ValueError: Input 0 of layer "sequential_1" is incompatible with the layer: expected shape=(None, 60, 1), found shape=(None, 59, 1)

ValueError: Input 0 of layer "sequential_1" is incompatible with the layer: expected shape=(None, 60, 1), found shape=(None, 59, 1)

嗨,我有以下错误:

 ValueError                                Traceback (most recent call 
 last)
 C:\Users\COOKET~1\AppData\Local\Temp/ipykernel_10332/793675004.py in 
 <module>
 2 real_data =  np.array(real_data)
 3 real_data = np.reshape(real_data, (real_data.shape[0], 
 real_data.shape[1], 1))
 ----> 4 prediction = model.predict(real_data)
 5 prediction = scaler.inverse_transform(prediction)
 6 print(f"Tomorrow's {company} share price: {prediction}")

~\anaconda3\envs\PYTHON\lib\site-packages\keras\utils\traceback_utils.py 
in 
error_handler(*args, **kwargs)
65     except Exception as e:  # pylint: disable=broad-except
66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
68     finally:
69       del filtered_tb

~\anaconda3\envs\PYTHON\lib\site- 
packages\tensorflow\python\framework\func_graph.py in 
autograph_handler(*args, **kwargs)
1127           except Exception as e:  # pylint:disable=broad-except
1128             if hasattr(e, "ag_error_metadata"):
->  1129               raise e.ag_error_metadata.to_exception(e)
1130             else:
1131               raise

ValueError: in user code:

File "C:\Users\Cooketaker\anaconda3\envs\PYTHON\lib\site- 
packages\keras\engine\training.py", line 1621, in predict_function  *
return step_function(self, iterator)
File "C:\Users\Cooketaker\anaconda3\envs\PYTHON\lib\site- 
packages\keras\engine\training.py", line 1611, in step_function  **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\Cooketaker\anaconda3\envs\PYTHON\lib\site- 
packages\keras\engine\training.py", line 1604, in run_step  **
outputs = model.predict_step(data)
File "C:\Users\Cooketaker\anaconda3\envs\PYTHON\lib\site- 
packages\keras\engine\training.py", line 1572, in predict_step
return self(x, training=False)
File "C:\Users\Cooketaker\anaconda3\envs\PYTHON\lib\site- 
packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Cooketaker\anaconda3\envs\PYTHON\lib\site- 
packages\keras\engine\input_spec.py", line 263, in 
assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

ValueError: Input 0 of layer "sequential" is incompatible with the 
layer: expected shape=(None, 60, 1), found shape=(None, 59, 1)

我不知道如何修复下一个错误,错误只发生在我想预测第二天的最后一部分:

prediction = model.predict(real_data)
prediction = scaler.inverse_transform(prediction)

我的完整代码是这样的:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader as web
import datetime as dt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Dropout,LSTM

#Ticker symbol of the company
company = 'FB'
#Date from which we are collecting the data (year, month, date)
start = dt.datetime(2012,1,1)
end = dt.datetime(2021,1,1)
data = web.DataReader(company, 'yahoo', start, end)

scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))

#How many past days of data we want to use to predict the next day price
prediction_days = 60

#Preparing the Training data
X_train = []
y_train = []

for x in range(prediction_days, len(scaled_data)):
X_train.append(scaled_data[x-prediction_days:x, 0]) 
y_train.append(scaled_data[x,0])

X_train, y_train = np.array(X_train), np.array(y_train)
#Reshaping so that it will work in Neural net
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))


model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1)) 

model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, y_train, epochs=100, batch_size=32)

test_start = dt.datetime(2021,1,1)
test_end = dt.datetime.now()
test_data = web.DataReader(company, 'yahoo', test_start, test_end)
actual_prices = test_data['Close'].values

total_dataset = pd.concat((data['Close'],test_data['Close']), axis=0)
model_inputs = total_dataset[len(total_dataset) - len(test_data) - prediction_days: ].values
model_inputs = model_inputs.reshape(-1,1)
model_inputs = scaler.transform(model_inputs)

X_test = []
for x in range(prediction_days, len(model_inputs)):
X_test.append(model_inputs[x-prediction_days:x, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))

predicted_price = model.predict(X_test)
predicted_price = scaler.inverse_transform(predicted_price)

plt.plot(actual_prices, color='black',label='Actual Share price')
plt.plot(predicted_price, color='green',label='Predicted Share price')
plt.title(f"{company} Share Price prediction")
plt.xlabel('Time')
plt.ylabel(f'{company} Share Price')
plt.legend()
plt.show()

real_data = [model_inputs[len(model_inputs) + 1 - prediction_days : len(model_inputs)+1, 0]]
real_data =  np.array(real_data)
real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1], 1))
prediction = model.predict(real_data)
prediction = scaler.inverse_transform(prediction)
print(f"Tomorrow's {company} share price: {prediction}")

这是我尝试的解决方案。我对 ML 的东西不是很熟悉,但我只是将其作为使维度一致的问题来处理。

因此,我将行(大约第 76 行)从:

real_data = [model_inputs[len(model_inputs) + 1 - prediction_days : len(model_inputs)+1, 0]

real_data = [model_inputs[len(model_inputs) - prediction_days : len(model_inputs)+1, 0]]

我认为第 61 行左右某处存在缩进问题,更改为:

for x in range(prediction_days, len(model_inputs)):
    X_test.append(model_inputs[x-prediction_days:x, 0])

然后,经过这次调整后,我收到了下图和最后的输出:

Tomorrow's FB share price: [[331.90765]]

图表: