How can I predict the next elements in a dataset with LSTM in Keras, python?












0















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?










share|improve this question



























    0















    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?










    share|improve this question

























      0












      0








      0


      1






      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?










      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 9:55









      jartymcflyjartymcfly

      5833727




      5833727
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Try this:
          model.predict(newX)






          share|improve this answer
























          • 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












          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
          });


          }
          });














          draft saved

          draft discarded


















          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









          0














          Try this:
          model.predict(newX)






          share|improve this answer
























          • 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
















          0














          Try this:
          model.predict(newX)






          share|improve this answer
























          • 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














          0












          0








          0







          Try this:
          model.predict(newX)






          share|improve this answer













          Try this:
          model.predict(newX)







          share|improve this answer












          share|improve this answer



          share|improve this answer










          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



















          • 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




















          draft saved

          draft discarded




















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine