keras lstm 的输出形状错误
Wrong output shape with keras lstm
我需要预测数字序列的 k 个值。为此,我决定使用斐波那契数列 mod 15 并为每个要预测的值构建一个 model (n+1,n+2,...n+k)。除此以外一切正常:当我使用特征测试集预测值时,model 给了我错误的形状。我希望形状为 (20,1),但我拥有的是 (20, 200, 1)。请你帮助我好吗?这是我的代码:
# 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)
您预测的是最后一个序列元素。添加此行:
predictions = predictions[:, -1]
我需要预测数字序列的 k 个值。为此,我决定使用斐波那契数列 mod 15 并为每个要预测的值构建一个 model (n+1,n+2,...n+k)。除此以外一切正常:当我使用特征测试集预测值时,model 给了我错误的形状。我希望形状为 (20,1),但我拥有的是 (20, 200, 1)。请你帮助我好吗?这是我的代码:
# 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)
您预测的是最后一个序列元素。添加此行:
predictions = predictions[:, -1]