industry_train_100.py 7.0 KB

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