mix_train_400.py 7.2 KB

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