I need to predict k values of a sequence of numbers. To do that, I decided to use a Fibonacci sequence mod 15 and build a model for each value to forecast (n+1,n+2,...n+k). Everything works fine except for this: when I predict the values using the feature test set, the model gives me the wrong shape. I want a the shape to be (20,1) but what I have is (20, 200, 1). Could you please help me? Here is my code:
# Importing all the required libraries
import pandas as pd
import numpy as np
from sklearn import metrics
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
nterms = 1000
fibonacci=[]
# Program to display the Fibonacci sequence up to n-th term
nterms = 10000
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
while count < nterms:
fibonacci.append(n1)
nth = (n1 + n2)%15
# update values
n1 = n2
n2 = nth
count += 1
df_fib=pd.DataFrame(fibonacci)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range = (0, 1))
df_fib_scaled = scaler.fit_transform(df_fib)
# Dictionary for storing generated models and values
models = {}
predicted_values={}
numbers_of_predictions=2
for k in range(0,numbers_of_predictions):
features_set = []
labels = []
for i in range(200, len(df_fib_scaled)-k-20):
features_set.append(df_fib_scaled[i-200:i, 0])
labels.append(df_fib_scaled[i+k, 0])
features_set, labels = np.array(features_set), np.array(labels)
features_set = np.reshape(features_set, (features_set.shape[0], features_set.shape[1], 1))
# Training the model
model = keras.Sequential()
model.add(layers.LSTM(units=50, return_sequences=True, input_shape=(features_set.shape[1], 1)))
model.add(layers.Dropout(0.2))
model.add(layers.LSTM(units=50, return_sequences=True))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(units = 1))
model.compile(optimizer = 'adam', loss = 'mean_squared_error')
model.fit(features_set, labels, epochs = 30, batch_size = 50)
models[k+1]=model
test_features = []
real_values=[]
for i in range(len(df_fib_scaled)-k-20, len(df_fib_scaled)-k):
test_features.append(df_fib_scaled[i-200:i, 0])
real_values.append(df_fib_scaled[i+k, 0])
test_features = np.array(test_features)
test_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1))
predictions = models[k+1].predict(test_features)
You prediction is the last sequence element. Add this line:
predictions = predictions[:, -1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.