简体   繁体   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)

Hi i have the following error:您好我有以下错误:

 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)

I don´t know how fix the next error, the error happens only in the last part when i want to predict the next day:我不知道如何修复下一个错误,当我想预测第二天时,错误仅发生在最后一部分:

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

My full code is this:我的完整代码是这样的:

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

Here is my attempt at a solution.这是我的解决方案尝试。 I am not very familiar with the ML stuff but I just approached it as an issue of making the dimensions consistent.我对 ML 的东西不是很熟悉,但我只是把它作为一个使尺寸保持一致的问题来处理。

Thus, I changed the line (approximately line 76) from:因此,我将行(大约第 76 行)从:

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

to

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

I think there was an indentation issue somewhere on line 61 or so, changed to:我认为第 61 行左右的某个地方存在缩进问题,改为:

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

Then, after this adjustment, I received the following graph and the following output at the end:然后,经过这次调整,我收到了下图和最后的output:

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

在此处输入图像描述

The graph:图表: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:“顺序”层的输入 0 与该层不兼容:预期形状 =(None, 60, 5),找到的形状 =(None, 60, 7) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 60, 5), found shape=(None, 60, 7) ValueError:layersequential_1 的输入 0 与 layer 不兼容::预期 min_ndim=4,发现 ndim=3。 收到的完整形状:[无、256、256] - ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, 256, 256] ValueError:“顺序”层的输入 0 与层不兼容:预期形状 =(无,223461,5),找到形状 =(无,5) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 223461, 5), found shape=(None, 5) ValueError:层“顺序”的输入0与层不兼容:预期形状=(无,90),发现形状=(无,2,90) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 90), found shape=(None, 2, 90) ValueError:“顺序”层的输入 0 与该层不兼容:预期形状 =(None, 455, 30),找到的形状 =(None, 30) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 455, 30), found shape=(None, 30) ValueError:“顺序”层的输入 0 与该层不兼容:预期形状 =(无,33714,12),找到形状 =(无,12) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 33714, 12), found shape=(None, 12) | ValueError:“顺序”层的输入 0 与该层不兼容:预期形状 =(None, 28, 28),找到的形状 =(None, 28, 3) - | ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 28, 28), found shape=(None, 28, 3) ValueError:“顺序”层的输入 0 与该层不兼容:预期形状=(无,256、256、3),找到的形状=(无,33) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 256, 256, 3), found shape=(None, 33) 层“sequential_3”的输入0与层不兼容:预期形状=(无,60),找到形状=(5,174) - Input 0 of layer "sequential_3" is incompatible with the layer: expected shape=(None, 60), found shape=(5, 174) ValueError:层“顺序”的输入 0 与层不兼容:预期形状=(无,32,32,3),找到形状=(32,32,3) - ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 32, 32, 3), found shape=(32, 32, 3)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM