industry_train_100.py 6.6 KB

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