淘先锋技术网

首页 1 2 3 4 5 6 7

# -*- coding: utf-8 -*-importnumpyasnpimportnumpyimportmatplotlib.pyplotaspltimportpandasimportmathfromkeras.modelsimportSequentialfromkeras.layersimportDense,LSTM,Dropoutfromsklearn.preprocessingimportMinMaxScalerfromsklearn.metricsimportmean_squared_error# convert an array of values into a dataset matrixdefcreate_dataset(dataset,look_back=1):dataX,dataY=[],[]foriinrange(len(dataset)-look_back-1):a=dataset[i:(i+look_back):]dataX.append(a)dataY.append(dataset[i+look_back,:])returnnumpy.array(dataX),numpy.array(dataY)# fix random seed for reproducibilitynumpy.random.seed(7)# load the datasetdataframe=pandas.read_csv('v77.csv',engine='python',skiprows=0)dataset=dataframe.valuesprintdataset# normalize the datasetscaler=MinMaxScaler(feature_range=(0,1))dataset=scaler.fit_transform(dataset)# split into train and test setstrain_size=10test_size=10train,test=dataset[0:train_size,:],dataset[train_size:train_size+test_size,:]print(train_size,test_size)# reshape into X=t and Y=t+1look_back=3trainX,trainY=create_dataset(train,look_back)testX,testY=create_dataset(test,look_back)printtrainX# reshape input to be [samples, time steps, features]#trainX = numpy.reshape(trainX, (trainX.shape[0], look_back, 3))#testX = numpy.reshape(testX, (testX.shape[0],look_back, 3))# create and fit the LSTM networkmodel=Sequential()model.add(LSTM(32,input_shape=(3,3)))model.add(Dense(3))model.compile(loss='mean_squared_error',optimizer='adam')history=model.fit(trainX,trainY,validation_split=0.33,nb_epoch=10,batch_size=16)# make predictionstrainPredict=model.predict(trainX)testPredict=model.predict(testX)# print testPredict# print np.shape(testPredict)# Get something which has as many features as datasettrainPredict_extended=numpy.zeros((len(trainPredict),3))printtrainPredict_extendedprintnp.shape(trainPredict_extended[:,2])printnp.shape(trainPredict[:,0])# Put the predictions theretrainPredict_extended[:,2]=trainPredict[:,0]# Inverse transform it and select the 3rd coumn.trainPredict=scaler.inverse_transform(trainPredict_extended)[:,2]# print(trainPredict)# Get something which has as many features as datasettestPredict_extended=numpy.zeros((len(testPredict),3))# Put the predictions theretestPredict_extended[:,2]=testPredict[:,0]# Inverse transform it and select the 3rd column.testPredict=scaler.inverse_transform(testPredict_extended)[:,2]# print testPredict_extendedtrainY_extended=numpy.zeros((len(trainY),3))trainY_extended[:,2]=trainY

trainY=scaler.inverse_transform(trainY_extended)[:,2]testY_extended=numpy.zeros((len(testY),3))testY_extended[:,2]=testY

testY=scaler.inverse_transform(testY_extended)[:,2]# print# print testY# calculate root mean squared errortrainScore=math.sqrt(mean_squared_error(trainY,trainPredict))print('Train Score: %.2f RMSE'%(trainScore))testScore=math.sqrt(mean_squared_error(testY,testPredict))print('Test Score: %.2f RMSE'%(testScore))