mix_train.py 5.6 KB

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