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