mix_train_1.py 5.3 KB

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