簡體   English   中英

ValueError: 層“sequential_1”的輸入 0 與層不兼容:預期形狀=(None, 60, 1),發現形狀=(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])

然后,經過這次調整,我收到了下圖和最后的output:

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

在此處輸入圖像描述

圖表: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM