mix_train_200.py 7.5 KB

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