如何在Keras,python中使用LSTM预测数据集中的下一个元素?

时间:2018-11-16 09:55:04

标签: python tensorflow keras lstm predict

这是我第一次使用Keras和LSTM,并且我正在从事一个项目,该项目中有许多时间序列数据需要培训。

我有大约13000行数据(1列),这些数据具有有关以故障结束的组件的退化水平的数值;另一方面,我有100行(1列)的多个数据集,其中包含有关组件降级级别的数据,但是在出现故障之前会结束一些点。

面临的挑战是预测这些数据集何时记录故障。

接下来我要做的是

from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from math import sqrt
from matplotlib import pyplot
from numpy import array


# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back):
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back), 0]
        dataX.append(a)
        dataY.append(dataset[i + look_back, 0])
    return numpy.array(dataX), numpy.array(dataY)


look_back = 600
epochs = 500
batch_size = 50




data = np.array(data).reshape(-1,1)
data = data.astype('float32')

# Scale the data
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(data)

# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]

trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)


# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))


# create and fit the LSTM network
model = Sequential()
model.add(LSTM(100, activation = 'tanh', inner_activation = 'hard_sigmoid', return_sequences=True))
model.add(LSTM(50, activation = 'tanh', inner_activation = 'hard_sigmoid'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=epochs, batch_size=batch_size, verbose=2)



# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)


# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])





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

这些行代码代表数据集的训练和评估,但是我如何使用该模型预测100行的一个数据集中的下一个(例如)50个元素?

1 个答案:

答案 0 :(得分:0)

尝试一下:     model.predict(newX)