使用keras实现的卷积神经网络训练和预测自己的数据

from keras import optimizers
from keras.models import Model
from keras.layers import Input,Convolution1D,Activation,Dense,Lambda
import numpy as np
import pandas as pd
import eleceval
###bulid load###
def CNN():
    input_layer = Input(name='input_layer',shape=(150,1))
    x = input_layer
    x = Convolution1D(32,8,padding='same',name='conv_1')(x)
    x = Activation('relu')(x)
    
    x = Convolution1D(64,8,padding='same',name='conv_2')(x)
    x = Activation('relu')(x)
    
    x = Convolution1D(64,8,padding='same',name='conv_3')(x)
    x = Activation('relu')(x)
    
    x = Lambda(lambda tt: tt[:,-1,:])(x)
    x = Dense(1)(x)
    output_layer = x
    model = Model(input_layer,output_layer)
    return model
###chuli data###
def chuli(datafile,data_size,steps):
    data = pd.read_csv(datafile)
    X = []
    Y = []
    for i in range(data_size-steps):
        x = data.loc[i:i+steps-1,['load']].values.tolist()
        y = data.loc[i+steps,['load']].tolist()
        X.append(x)
        Y.append(y)
    return X,Y
###load data###
datafile = 'pretrate_31.csv'
data_size = 1000
train_size = 600
train_val_size = 800
steps = 150

x_raw,y_raw = chuli(datafile,data_size,steps)
xtrain = x_raw[0:train_size]
ytrain = y_raw[0:train_size]
x_train = np.array(xtrain)
y_train = np.array(ytrain)

xval = x_raw[train_size:train_val_size]
yval = y_raw[train_size:train_val_size]
x_val = np.array(xval)
y_val = np.array(yval)

xtest = x_raw[train_val_size:data_size]
ytest = y_raw[train_val_size:data_size]
x_test = np.array(xtest)
y_test = np.array(ytest)

model = CNN()
model.summary()
adam = optimizers.Adam(lr=0.002,clipnorm=1.)
model.compile(adam,loss='mse')
model.fit(x_train,y_train,validation_data=(x_val,y_val),epochs=50,batch_size=100)
pred = model.predict(x_test)

pred_all = pred.flatten()
truth_all = y_test.flatten()

mape = eleceval.mape(truth_all,pred_all)
print(mape)

运行结果如下所示: 

使用keras实现的卷积神经网络训练和预测自己的数据_第1张图片

使用keras实现的卷积神经网络训练和预测自己的数据_第2张图片使用keras实现的卷积神经网络训练和预测自己的数据_第3张图片 

你可能感兴趣的:(深度学习)