1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
| import os import random import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from sklearn import metrics from sklearn.metrics import r2_score from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import Reshape from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import LSTM, Bidirectional, Dense from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten from tensorflow.keras.layers import Add
def check_tensorflow_gpu(): print("TensorFlow 版本:", tf.__version__) if tf.test.is_gpu_available(): print("GPU is available") else: print("GPU is not available, using CPU")
def normalize_dataframe(DFTrain, DFTest): scaler = MinMaxScaler() scaler.fit(DFTrain) train_data = pd.DataFrame(scaler.transform(DFTrain), columns = DFTrain.columns, index = DFTrain.index) test_data = pd.DataFrame(scaler.transform(DFTest), columns = DFTest.columns, index = DFTest.index) return train_data, test_data
def prepare_data(data, win_size): X = [] y = []
for i in range(len(data) - win_size): temp_x = data[i:i + win_size] temp_y = data[i + win_size] X.append(temp_x) y.append(temp_y)
X = np.asarray(X) y = np.asarray(y) return X, y
if __name__ == '__main__': win_size = 30 tra_val_ratio = 0.7 epoch_size = 10 batch_size = 32 verbose = 0 wkdir = 'E:/BaiduSyncdisk/005.Bioinformatics/Bioinformatics/src/250508_multiple_timeseries_model' os.chdir(wkdir) SEED = 42 random.seed(SEED) np.random.seed(SEED) tf.set_random_seed(SEED) os.environ['TF_DETERMINISTIC_OPS'] = '1' os.environ['TF_CUDNN_DETERMINISTIC'] = '1'
DF = pd.read_excel('data/data.xlsx', index_col = 0, parse_dates = ['日期']) DF = DF[['平均氣溫']] DFTrain = DF[DF.index < '2020-01-01'] DFTest = DF[DF.index >= '2020-01-01']
plt.figure(figsize = (15, 5)) plt.subplot(1, 2, 1) plt.plot(DFTrain['平均氣溫'], color = 'b', alpha = 0.5) plt.title('Train Data') plt.xticks(rotation = 0) plt.grid(True) plt.subplot(1, 2, 2) plt.plot(DFTest['平均氣溫'], color = 'r', alpha = 0.5) plt.title('Test Data') plt.grid(True) plt.xticks(rotation = 0) plt.show()
data_train, data_test = normalize_dataframe(DFTrain, DFTest) X, y = prepare_data(data_train.values, win_size) train_size = int(len(X) * tra_val_ratio) X_train, X_val = X[:train_size], X[train_size:] y_train, y_val = y[:train_size], y[train_size:] X_test, y_test = prepare_data(data_test.values, win_size) print("训练集形状:", X_train.shape, y_train.shape) print("验证集形状:", X_val.shape, y_val.shape) print("测试集形状:", X_test.shape, y_test.shape)
if False: model = Sequential() model.add(Bidirectional(LSTM(128, activation = 'relu'), input_shape = (X_train.shape[1], X_train.shape[2]))) model.add(Dense(64, activation = 'relu')) model.add(Dense(32, activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(1, activation = 'sigmoid')) elif False: model = Sequential() model.add(Conv1D(filters = 64, kernel_size = 7, activation = 'relu', input_shape = (X_train.shape[1], X_train.shape[2]))) model.add(MaxPooling1D(pool_size = 2)) model.add(Flatten()) model.add(Dense(32, activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(1, activation = 'sigmoid')) elif False: model = Sequential() model.add(Bidirectional(LSTM(128, activation = 'relu'), input_shape = (X_train.shape[1], X_train.shape[2]))) model.add(Reshape((256, 1))) model.add(Conv1D(filters = 64, kernel_size = 7, activation = 'relu')) model.add(MaxPooling1D(pool_size = 2)) model.add(Flatten()) model.add(Dense(32, activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(1, activation = 'sigmoid')) else: def residual_block(input_layer, filters, kernel_size): residual = Conv1D(filters = filters, kernel_size = kernel_size, activation = 'relu', padding = 'same')(input_layer) residual = Conv1D(filters = filters, kernel_size = kernel_size, activation = 'relu', padding = 'same')(residual) residual = Add()([input_layer, residual]) return residual
model = Sequential() model.add(Bidirectional(LSTM(128, activation = 'relu'), input_shape = (X_train.shape[1], X_train.shape[2]))) model.add(Reshape((256, 1))) model.add(Conv1D(filters = 64, kernel_size = 7, activation = 'relu')) model.add(MaxPooling1D(pool_size = 2)) intermediate_output = model.layers[-1].output residual_output = residual_block(model.layers[-1].output, filters = 64, kernel_size = 7) residual_output = MaxPooling1D(pool_size = 2)(residual_output) residual_output = Flatten()(residual_output) residual_output = Dense(32, activation = 'relu')(residual_output) residual_output = Dense(16, activation = 'relu')(residual_output) output_layer = Dense(1, activation = 'sigmoid')(residual_output) model = Model(inputs = model.input, outputs = output_layer) model.compile(optimizer = 'adam', loss = 'mse') history = model.fit(X_train, y_train, epochs = epoch_size, batch_size = batch_size, validation_data = (X_val, y_val), verbose = verbose) plt.figure() plt.plot(history.history['loss'], c = 'b', label = 'loss') plt.plot(history.history['val_loss'], c = 'g', label = 'val_loss') plt.legend() plt.show() y_pred = model.predict(X_test) mse = metrics.mean_squared_error(y_test, np.array([i for arr in y_pred for i in arr])) rmse = np.sqrt(mse) mae = metrics.mean_absolute_error(y_test, np.array([i for arr in y_pred for i in arr])) r2 = r2_score(y_test, np.array([i for arr in y_pred for i in arr])) print("均方误差 (MSE):", mse) print("均方根误差 (RMSE):", rmse) print("平均绝对误差 (MAE):", mae) print("拟合优度:", r2) model.summary()
import sys import platform import pkg_resources def session_info(): print("Python Session Information") print("==========================") print(f"Python Version: {sys.version}") print(f"Python Implementation: {platform.python_implementation()}") print(f"Python Build: {platform.python_build()}") print("\nOperating System Information") print(f"OS: {platform.system()}") print(f"OS Release: {platform.release()}") print(f"OS Version: {platform.version()}") print(f"Machine: {platform.machine()}") print(f"Processor: {platform.processor()}") print("\nInstalled Packages") print("------------------") installed_packages = sorted( [(dist.key, dist.version) for dist in pkg_resources.working_set], key=lambda x: x[0].lower() ) for package, version in installed_packages: print(f"{package}: {version}") session_info()
|