mix_train_180.py 6.6 KB

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