How can I predict the next elements in a dataset with LSTM in Keras, python?
This is my first time with Keras and LSTMs and I am working in a project in which I have many time series data to train with.
I have around 13000 rows of data (1 column) with numerical values regarding to a degradation level of a component ending in a failure; and on the other side I have multiple datasets of 100 rows (1 column) with data regarding to a degradation level of a component, but ending some points before a failure.
The challenge is to predict when those datasets will record a failure.
So what I have done, is the next:
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))
These line codes represents the training and the evaluation of the dataset, but how can I predict the next (for example) 50 elements of one dataset of 100 rows using that model?
python tensorflow keras lstm predict
add a comment |
This is my first time with Keras and LSTMs and I am working in a project in which I have many time series data to train with.
I have around 13000 rows of data (1 column) with numerical values regarding to a degradation level of a component ending in a failure; and on the other side I have multiple datasets of 100 rows (1 column) with data regarding to a degradation level of a component, but ending some points before a failure.
The challenge is to predict when those datasets will record a failure.
So what I have done, is the next:
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))
These line codes represents the training and the evaluation of the dataset, but how can I predict the next (for example) 50 elements of one dataset of 100 rows using that model?
python tensorflow keras lstm predict
add a comment |
This is my first time with Keras and LSTMs and I am working in a project in which I have many time series data to train with.
I have around 13000 rows of data (1 column) with numerical values regarding to a degradation level of a component ending in a failure; and on the other side I have multiple datasets of 100 rows (1 column) with data regarding to a degradation level of a component, but ending some points before a failure.
The challenge is to predict when those datasets will record a failure.
So what I have done, is the next:
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))
These line codes represents the training and the evaluation of the dataset, but how can I predict the next (for example) 50 elements of one dataset of 100 rows using that model?
python tensorflow keras lstm predict
This is my first time with Keras and LSTMs and I am working in a project in which I have many time series data to train with.
I have around 13000 rows of data (1 column) with numerical values regarding to a degradation level of a component ending in a failure; and on the other side I have multiple datasets of 100 rows (1 column) with data regarding to a degradation level of a component, but ending some points before a failure.
The challenge is to predict when those datasets will record a failure.
So what I have done, is the next:
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))
These line codes represents the training and the evaluation of the dataset, but how can I predict the next (for example) 50 elements of one dataset of 100 rows using that model?
python tensorflow keras lstm predict
python tensorflow keras lstm predict
asked Nov 16 '18 at 9:55
jartymcflyjartymcfly
5833727
5833727
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Try this:
model.predict(newX)
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335338%2fhow-can-i-predict-the-next-elements-in-a-dataset-with-lstm-in-keras-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try this:
model.predict(newX)
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
add a comment |
Try this:
model.predict(newX)
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
add a comment |
Try this:
model.predict(newX)
Try this:
model.predict(newX)
answered Nov 16 '18 at 9:57
artonaartona
71248
71248
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
add a comment |
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
But model.predict() will predict the next value. What if I want to predict the next 10 values?
– jartymcfly
Nov 19 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
If you give the same input to the trained model multiple times, the same value should occur - you do not train the model. If you want to do so, you need to train the model with model.fit(X).
– artona
Nov 20 '18 at 14:36
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335338%2fhow-can-i-predict-the-next-elements-in-a-dataset-with-lstm-in-keras-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown