lstm_kmeans_train.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import keras
  2. # -*- encoding:utf-8 -*-
  3. import numpy as np
  4. from keras.models import Sequential
  5. # 优化方法选用Adam(其实可选项有很多,如SGD)
  6. from keras.optimizers import Adam
  7. import random
  8. from keras.models import load_model
  9. from imblearn.over_sampling import RandomOverSampler
  10. from keras.utils import np_utils
  11. # 用于模型初始化,Conv2D模型初始化、Activation激活函数,MaxPooling2D是池化层
  12. # Flatten作用是将多位输入进行一维化
  13. # Dense是全连接层
  14. from keras.layers import Conv2D, Activation, MaxPool2D, Flatten, Dense,Dropout,Input,MaxPooling2D,BatchNormalization,concatenate
  15. from keras.layers import LSTM
  16. from keras import regularizers
  17. from keras.models import Model
  18. from keras.callbacks import EarlyStopping
  19. early_stopping = EarlyStopping(monitor='accuracy', patience=5, verbose=2)
  20. epochs= 330
  21. model_path = '161_18d_lstm_5D_ma5_s_seq.h5'
  22. data_dir = 'D:\\data\\quantization\\dmi\\'
  23. args = 'stock160_18d_train_A_'
  24. def read_data(path):
  25. lines = []
  26. with open(path) as f:
  27. for line in f.readlines()[:]:
  28. lines.append(eval(line.strip()))
  29. random.shuffle(lines)
  30. print('读取数据完毕')
  31. d=int(0.7*len(lines))
  32. train_x=[s[:-2] for s in lines[0:d]]
  33. train_y=[s[-1] for s in lines[0:d]]
  34. test_x=[s[:-2] for s in lines[d:]]
  35. test_y=[s[-1] for s in lines[d:]]
  36. print('转换数据完毕')
  37. ros = RandomOverSampler(random_state=0)
  38. X_resampled, y_resampled = ros.fit_sample(np.array(train_x), np.array(train_y))
  39. print('数据重采样完毕')
  40. return X_resampled,y_resampled,np.array(test_x),np.array(test_y)
  41. def mul_train(name="10_18d"):
  42. for x in range(0, 12):
  43. score = train(data_dir + name + str(x) + ".log", x) # stock160_18d_trai_0
  44. with open(data_dir + name + '_lstm.log', 'a') as f:
  45. f.write(str(x) + ':' + str(score[1]) + '\n')
  46. def train(file_path, idx):
  47. train_x,train_y,test_x,test_y=read_data(file_path)
  48. train_x_a = train_x[:,:18*24]
  49. train_x_a = train_x_a.reshape(train_x.shape[0], 18, 24)
  50. # train_x_b = train_x[:, 18*24:18*16+10*18]
  51. # train_x_b = train_x_b.reshape(train_x.shape[0], 18, 10, 1)
  52. train_x_c = train_x[:,18*24:]
  53. # create the MLP and CNN models
  54. mlp = create_mlp(train_x_c.shape[1], regress=False)
  55. cnn_0 = create_lstm(train_x_a.shape[1], 18, 24)
  56. # cnn_1 = create_cnn(18, 10, 1, kernel_size=(3, 5), filters=32, regress=False, output=120)
  57. # create the input to our final set of layers as the *output* of both
  58. # the MLP and CNN
  59. combinedInput = concatenate([mlp.output, cnn_0.output,])
  60. # our final FC layer head will have two dense layers, the final one
  61. # being our regression head
  62. x = Dense(256, activation="relu", kernel_regularizer=regularizers.l1(0.003))(combinedInput)
  63. x = Dropout(0.2)(x)
  64. x = Dense(256, activation="relu")(x)
  65. x = Dense(512, activation="relu")(x)
  66. # 在建设一层
  67. x = Dense(5, activation="softmax")(x)
  68. # our final model will accept categorical/numerical data on the MLP
  69. # input and images on the CNN input, outputting a single value (the
  70. # predicted price of the house)
  71. model = Model(inputs=[mlp.input, cnn_0.input,], outputs=x)
  72. print("Starting training ")
  73. # h = model.fit(train_x, train_y, batch_size=4096*2, epochs=500, shuffle=True)
  74. # compile the model using mean absolute percentage error as our loss,
  75. # implying that we seek to minimize the absolute percentage difference
  76. # between our price *predictions* and the *actual prices*
  77. opt = Adam(lr=1e-3, decay=1e-3 / 200)
  78. model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=['accuracy'],
  79. )
  80. # train the model
  81. print("[INFO] training model...")
  82. model.fit(
  83. [train_x_c, train_x_a, ], train_y,
  84. # validation_data=([testAttrX, testImagesX], testY),
  85. # epochs=int(3*train_x_a.shape[0]/1300),
  86. epochs=epochs,
  87. batch_size=4096, shuffle=True,
  88. callbacks=[early_stopping]
  89. )
  90. test_x_a = test_x[:,:18*24]
  91. test_x_a = test_x_a.reshape(test_x.shape[0], 18, 24)
  92. # test_x_b = test_x[:, 18*16:18*16+10*18]
  93. # test_x_b = test_x_b.reshape(test_x.shape[0], 18, 10, 1)
  94. test_x_c = test_x[:,18*24:]
  95. # make predictions on the testing data
  96. print("[INFO] predicting house prices...")
  97. score = model.evaluate([test_x_c, test_x_a], test_y)
  98. print(score)
  99. print('Test score:', score[0])
  100. print('Test accuracy:', score[1])
  101. model.save(model_path.split('.')[0] + '_' + str(idx) + '.h5')
  102. return score
  103. def create_mlp(dim, regress=False):
  104. # define our MLP network
  105. model = Sequential()
  106. model.add(Dense(64, input_dim=dim, activation="relu"))
  107. model.add(Dense(64, activation="relu"))
  108. # check to see if the regression node should be added
  109. if regress:
  110. model.add(Dense(1, activation="linear"))
  111. # return our model
  112. return model
  113. def create_cnn(width, height, depth, filters=32, kernel_size=(5, 6), regress=False, output=24):
  114. # initialize the input shape and channel dimension, assuming
  115. # TensorFlow/channels-last ordering
  116. inputShape = (width, height, 1)
  117. chanDim = -1
  118. # define the model input
  119. inputs = Input(shape=inputShape)
  120. x = inputs
  121. # CONV => RELU => BN => POOL
  122. x = Conv2D(filters, kernel_size, strides=(2,2), padding="same",
  123. # data_format='channels_first'
  124. )(x)
  125. x = Activation("relu")(x)
  126. x = BatchNormalization(axis=chanDim)(x)
  127. # x = MaxPooling2D(pool_size=(2, 2))(x)
  128. # if width > 2:
  129. # x = Conv2D(32, (10, 6), padding="same")(x)
  130. # x = Activation("relu")(x)
  131. # x = BatchNormalization(axis=chanDim)(x)
  132. # flatten the volume, then FC => RELU => BN => DROPOUT
  133. x = Flatten()(x)
  134. x = Dense(output)(x)
  135. x = Activation("relu")(x)
  136. x = BatchNormalization(axis=chanDim)(x)
  137. x = Dropout(0.2)(x)
  138. # apply another FC layer, this one to match the number of nodes
  139. # coming out of the MLP
  140. x = Dense(output)(x)
  141. x = Activation("relu")(x)
  142. # check to see if the regression node should be added
  143. if regress:
  144. x = Dense(1, activation="linear")(x)
  145. # construct the CNN
  146. model = Model(inputs, x)
  147. # return the CNN
  148. return model
  149. def create_lstm(sample, timesteps, input_dim):
  150. inputShape = (timesteps, input_dim)
  151. # define the model input
  152. inputs = Input(shape=inputShape)
  153. x = inputs
  154. x = LSTM(units = 64, input_shape=(timesteps, input_dim), dropout=0.2
  155. )(x)
  156. # x = LSTM(16*16, return_sequences=False)
  157. # x = Activation("relu")(x)
  158. x = Dense(64)(x)
  159. x = Dropout(0.2)(x)
  160. x = Activation("relu")(x)
  161. # construct the CNN
  162. model = Model(inputs, x)
  163. # return the CNN
  164. return model
  165. if __name__ == '__main__':
  166. mul_train(args)