mix_kmeans_train_1.py 6.0 KB

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