mix_train_300.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 import regularizers
  16. from keras.models import Model
  17. from keras.callbacks import EarlyStopping
  18. early_stopping = EarlyStopping(monitor='accuracy', patience=5, verbose=2)
  19. epochs= 77
  20. size = 440000 #共68W
  21. file_path = 'D:\\data\\quantization\\stock324_28d_train2.log'
  22. model_path = '324_28d_mix_5D_ma5_s_seq.h5'
  23. file_path1='D:\\data\\quantization\\stock324_28d_test.log'
  24. file_path2='D:\\data\\quantization\\stock324_28d_train1.log'
  25. row = 28
  26. col = 18
  27. '''
  28. 30d+ma5+流通市值>40
  29. 0 ROC 30*18 38,100,17
  30. 1 DMI 30*20 39,101,13
  31. 2 MACD 30*19 34,100,19
  32. 3 RSI 30*17
  33. 28d+ma5+流通市值>5
  34. 10 ROC 28*18 36,100,18
  35. 11 DMI 28*20 37,101,16
  36. 12 MACD 28*19
  37. 28d+ma5+5+流通市值>10
  38. 21 DMI 28*20 43,102,9 非常好 46,102,8
  39. 22 MACD 28*19 46,102,9
  40. 1d close
  41. 23 DMI 28*20 34,97,36
  42. 3d close 去掉ma的两个字段
  43. 24 DMI 28*18 41,96,42-13
  44. 30d+close
  45. 4 ROC 30*18
  46. 5 DMI 30*20
  47. 6 MACD 30*19 32,96,44
  48. 7 RSI 30*17 31,96,42
  49. 24d+close
  50. 14 ROC 24*18 31,95,52
  51. '''
  52. def read_data(path, path1=file_path1):
  53. lines = []
  54. with open(path) as f:
  55. for x in range(size): #680000
  56. line = eval(f.readline().strip())
  57. lines.append(line)
  58. with open(path1) as f:
  59. for x in range(50000): #6w
  60. line = eval(f.readline().strip())
  61. lines.append(line)
  62. # with open(file_path2) as f:
  63. # for x in range(60000): #6w
  64. # line = eval(f.readline().strip())
  65. # lines.append(line)
  66. random.shuffle(lines)
  67. print('读取数据完毕')
  68. d=int(0.85*len(lines))
  69. length = len(lines[0])
  70. train_x=[s[:length - 2] for s in lines[0:d]]
  71. train_y=[s[-1] for s in lines[0:d]]
  72. test_x=[s[:length - 2] for s in lines[d:]]
  73. test_y=[s[-1] for s in lines[d:]]
  74. print('转换数据完毕')
  75. ros = RandomOverSampler(random_state=0)
  76. X_resampled, y_resampled = ros.fit_sample(np.array(train_x), np.array(train_y))
  77. print('数据重采样完毕')
  78. return X_resampled,y_resampled,np.array(test_x),np.array(test_y)
  79. train_x,train_y,test_x,test_y=read_data(file_path)
  80. train_x_a = train_x[:,:row*col]
  81. train_x_a = train_x_a.reshape(train_x.shape[0], row, col, 1)
  82. # train_x_b = train_x[:, 9*26:18*26]
  83. # train_x_b = train_x_b.reshape(train_x.shape[0], 9, 26, 1)
  84. train_x_c = train_x[:,row*col:]
  85. def create_mlp(dim, regress=False):
  86. # define our MLP network
  87. model = Sequential()
  88. model.add(Dense(256, input_dim=dim, activation="relu"))
  89. model.add(Dropout(0.2))
  90. model.add(Dense(256, activation="relu"))
  91. model.add(Dense(256, activation="relu"))
  92. model.add(Dense(128, activation="relu"))
  93. # check to see if the regression node should be added
  94. if regress:
  95. model.add(Dense(1, activation="linear"))
  96. # return our model
  97. return model
  98. def create_cnn(width, height, depth, size=48, kernel_size=(5, 6), regress=False, output=24):
  99. # initialize the input shape and channel dimension, assuming
  100. # TensorFlow/channels-last ordering
  101. inputShape = (width, height, 1)
  102. chanDim = -1
  103. # define the model input
  104. inputs = Input(shape=inputShape)
  105. # x = inputs
  106. # CONV => RELU => BN => POOL
  107. x = Conv2D(size, kernel_size, strides=2, padding="same")(inputs)
  108. x = Activation("relu")(x)
  109. x = BatchNormalization(axis=chanDim)(x)
  110. # y = Conv2D(24, (2, 8), strides=2, padding="same")(inputs)
  111. # y = Activation("relu")(y)
  112. # y = BatchNormalization(axis=chanDim)(y)
  113. # flatten the volume, then FC => RELU => BN => DROPOUT
  114. x = Flatten()(x)
  115. x = Dense(output)(x)
  116. x = Activation("relu")(x)
  117. x = BatchNormalization(axis=chanDim)(x)
  118. x = Dropout(0.2)(x)
  119. # apply another FC layer, this one to match the number of nodes
  120. # coming out of the MLP
  121. x = Dense(output)(x)
  122. x = Activation("relu")(x)
  123. # check to see if the regression node should be added
  124. if regress:
  125. x = Dense(1, activation="linear")(x)
  126. # construct the CNN
  127. model = Model(inputs, x)
  128. # return the CNN
  129. return model
  130. # create the MLP and CNN models
  131. mlp = create_mlp(train_x_c.shape[1], regress=False)
  132. # cnn_0 = create_cnn(18, 20, 1, kernel_size=(3, 3), size=90, regress=False, output=96) # 31 97 46
  133. cnn_0 = create_cnn(row, col, 1, kernel_size=(6, col), size=96, regress=False, output=96) # 29 98 47
  134. # cnn_0 = create_cnn(18, 20, 1, kernel_size=(9, 9), size=90, regress=False, output=96) # 28 97 53
  135. # cnn_0 = create_cnn(18, 20, 1, kernel_size=(3, 20), size=90, regress=False, output=96)
  136. # cnn_1 = create_cnn(18, 20, 1, kernel_size=(18, 10), size=80, regress=False, output=96)
  137. # cnn_1 = create_cnn(9, 26, 1, kernel_size=(2, 14), size=36, regress=False, output=64)
  138. # create the input to our final set of layers as the *output* of both
  139. # the MLP and CNN
  140. combinedInput = concatenate([mlp.output, cnn_0.output, ])
  141. # our final FC layer head will have two dense layers, the final one
  142. # being our regression head
  143. x = Dense(1024, activation="relu", kernel_regularizer=regularizers.l1(0.003))(combinedInput)
  144. x = Dropout(0.2)(x)
  145. x = Dense(1024, activation="relu")(x)
  146. x = Dense(1024, activation="relu")(x)
  147. # 在建设一层
  148. x = Dense(4, activation="softmax")(x)
  149. # our final model will accept categorical/numerical data on the MLP
  150. # input and images on the CNN input, outputting a single value (the
  151. # predicted price of the house)
  152. model = Model(inputs=[mlp.input, cnn_0.input, ], outputs=x)
  153. print("Starting training ")
  154. # h = model.fit(train_x, train_y, batch_size=4096*2, epochs=500, shuffle=True)
  155. # compile the model using mean absolute percentage error as our loss,
  156. # implying that we seek to minimize the absolute percentage difference
  157. # between our price *predictions* and the *actual prices*
  158. opt = Adam(lr=1e-3, decay=1e-3 / 200)
  159. model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=['accuracy'])
  160. # train the model
  161. print("[INFO] training model...")
  162. model.fit(
  163. [train_x_c, train_x_a, ], train_y,
  164. # validation_data=([testAttrX, testImagesX], testY),
  165. # epochs=int(3*train_x_a.shape[0]/1300),
  166. epochs=epochs,
  167. batch_size=2048, shuffle=True,
  168. callbacks=[early_stopping]
  169. )
  170. model.save(model_path)
  171. test_x_a = test_x[:,:row*col]
  172. test_x_a = test_x_a.reshape(test_x.shape[0], row, col, 1)
  173. # test_x_b = test_x[:, 9*26:9*26+9*26]
  174. # test_x_b = test_x_b.reshape(test_x.shape[0], 9, 26, 1)
  175. test_x_c = test_x[:,row*col:]
  176. # make predictions on the testing data
  177. print("[INFO] predicting house prices...")
  178. score = model.evaluate([test_x_c, test_x_a,], test_y)
  179. print(score)
  180. print('Test score:', score[0])
  181. print('Test accuracy:', score[1])