mix_train_2.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. epochs= 100
  19. size = 440000
  20. file_path = 'D:\\data\\quantization\\stock160_18d_train.log'
  21. model_path = '170_18d_mix_5D_ma5_s_seq.h5'
  22. def read_data(path):
  23. lines = []
  24. with open(path) as f:
  25. i = 0
  26. for x in range(size): #610000
  27. line = eval(f.readline().strip())
  28. lines.append(line)
  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. train_x,train_y,test_x,test_y=read_data(file_path)
  42. train_x_tmp = train_x[:,:18*24]
  43. train_x_a = train_x_tmp.reshape(train_x.shape[0], 18, 24, 1)
  44. train_x_b = train_x_tmp.reshape(train_x.shape[0], 18, 24)
  45. train_x_c = train_x[:,18*24:]
  46. def create_mlp(dim, regress=False):
  47. # define our MLP network
  48. model = Sequential()
  49. model.add(Dense(128, input_dim=dim, activation="relu"))
  50. # model.add(Dense(128, activation="relu"))
  51. # check to see if the regression node should be added
  52. if regress:
  53. model.add(Dense(1, activation="linear"))
  54. # return our model
  55. return model
  56. def create_lstm(sample, timesteps, input_dim, output):
  57. inputShape = (timesteps, input_dim)
  58. # define the model input
  59. inputs = Input(shape=inputShape)
  60. x = inputs
  61. x = LSTM(units = 64, input_shape=(timesteps, input_dim), dropout=0.2
  62. )(x)
  63. # x = LSTM(16*16, return_sequences=False)
  64. # x = Activation("relu")(x)
  65. x = Dense(output)(x)
  66. x = Dropout(0.2)(x)
  67. x = Activation("relu")(x)
  68. # construct the CNN
  69. model = Model(inputs, x)
  70. # return the CNN
  71. return model
  72. def create_cnn(width, height, depth, filters=(4, 6), kernel_size=(5, 6), regress=False, output=24):
  73. # initialize the input shape and channel dimension, assuming
  74. # TensorFlow/channels-last ordering
  75. inputShape = (width, height, 1)
  76. chanDim = -1
  77. # define the model input
  78. inputs = Input(shape=inputShape)
  79. x = inputs
  80. # CONV => RELU => BN => POOL
  81. x = Conv2D(32, kernel_size, strides=2, padding="same")(x)
  82. x = Activation("relu")(x)
  83. x = BatchNormalization(axis=chanDim)(x)
  84. # x = MaxPooling2D(pool_size=(2, 2))(x)
  85. # if width > 2:
  86. # x = Conv2D(32, (10, 6), padding="same")(x)
  87. # x = Activation("relu")(x)
  88. # x = BatchNormalization(axis=chanDim)(x)
  89. # flatten the volume, then FC => RELU => BN => DROPOUT
  90. x = Flatten()(x)
  91. x = Dense(output)(x)
  92. x = Activation("relu")(x)
  93. # x = BatchNormalization(axis=chanDim)(x)
  94. x = Dropout(0.2)(x)
  95. # apply another FC layer, this one to match the number of nodes
  96. # coming out of the MLP
  97. x = Dense(output)(x)
  98. x = Activation("relu")(x)
  99. # check to see if the regression node should be added
  100. if regress:
  101. x = Dense(1, activation="linear")(x)
  102. # construct the CNN
  103. model = Model(inputs, x)
  104. # return the CNN
  105. return model
  106. # create the MLP and CNN models
  107. mlp = create_mlp(train_x_c.shape[1], regress=False)
  108. cnn_0 = create_cnn(18, 24, 1, kernel_size=(6, 6), regress=False, output=128)
  109. lstm = create_lstm(train_x_a.shape[1], 18, 24, output=128)
  110. # create the input to our final set of layers as the *output* of both
  111. # the MLP and CNN
  112. combinedInput = concatenate([mlp.output, cnn_0.output, lstm.output])
  113. # our final FC layer head will have two dense layers, the final one
  114. # being our regression head
  115. x = Dense(1024, activation="relu", kernel_regularizer=regularizers.l1(0.002))(combinedInput)
  116. x = Dropout(0.2)(x)
  117. x = Dense(1024, activation="relu")(x)
  118. # x = Dense(512, activation="relu")(x)
  119. # 在建设一层
  120. x = Dense(5, activation="softmax")(x)
  121. # our final model will accept categorical/numerical data on the MLP
  122. # input and images on the CNN input, outputting a single value (the
  123. # predicted price of the house)
  124. model = Model(inputs=[mlp.input, cnn_0.input, lstm.input], outputs=x)
  125. print("Starting training ")
  126. # h = model.fit(train_x, train_y, batch_size=4096*2, epochs=500, shuffle=True)
  127. # compile the model using mean absolute percentage error as our loss,
  128. # implying that we seek to minimize the absolute percentage difference
  129. # between our price *predictions* and the *actual prices*
  130. opt = Adam(lr=1e-3, decay=1e-3 / 200)
  131. model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=['accuracy'])
  132. # train the model
  133. print("[INFO] training model...")
  134. model.fit(
  135. [train_x_c, train_x_a, train_x_b], train_y,
  136. # validation_data=([testAttrX, testImagesX], testY),
  137. # epochs=int(3*train_x_a.shape[0]/1300),
  138. epochs=epochs,
  139. batch_size=2048, shuffle=True)
  140. test_x_tmp = test_x[:,:18*24]
  141. test_x_a = test_x_tmp.reshape(test_x.shape[0], 18, 24, 1)
  142. test_x_b = test_x_tmp.reshape(test_x.shape[0], 18, 24)
  143. test_x_c = test_x[:,18*24:]
  144. # make predictions on the testing data
  145. print("[INFO] predicting house prices...")
  146. score = model.evaluate([test_x_c, test_x_a, test_x_b], test_y)
  147. print(score)
  148. print('Test score:', score[0])
  149. print('Test accuracy:', score[1])
  150. model.save(model_path)