mix_train_600.py 6.5 KB

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