无法匹配 Keras LSTM 模型所需的维数
Posted
技术标签:
【中文标题】无法匹配 Keras LSTM 模型所需的维数【英文标题】:Failing to match the required number of dimensions for Keras LSTM model 【发布时间】:2021-12-16 10:12:13 【问题描述】:我试图建立一个构建神经网络的最小示例。我得到了超过 5 个不同日期的 5 个汽车价格。无论我如何重新排列我的数据,我都会遇到两种错误中的一种。
要么
ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (1, 1)
或
ValueError: Data cardinality is ambiguous:
x sizes: 5
y sizes: 1
Make sure all arrays contain the same number of samples.
我开始怀疑,无论我如何安排这些数据,它都不会起作用。我是否需要添加其他维度(例如价格和税额)?
完整代码:
import numpy as np
from keras.models import Sequential #, LSTM
from keras.layers.core import Dense;
from keras.layers import LSTM
import tensorflow as tf
time_list = [ 1296000.0, 19350000.0, 29635200.0, 48294000.0, 45961200.0] # my sample data
price_list = [ 0.05260218,0.05260218,0.0,0.96769388,1.0 ]
these_dates = np.array(time_list)
prices = np.array(price_list)
#these_dates = these_dates.reshape(-1, 1) # ive tried every variery of dimensions, nothing works.
#prices = prices.reshape(-1, 1)
model = Sequential()
model.add(LSTM(10 , return_sequences = True , input_shape =(len(prices) , 1) ,input_dim=2))
model.compile(optimizer = 'adam' , loss = 'mean_squared_error')
model.fit( prices ,these_dates , batch_size = 1 , epochs =1)
指定input_ndim
似乎没有帮助。我需要做什么才能使这些尺寸匹配?它会起作用吗?
【问题讨论】:
【参考方案1】:如keras documentation 中所述,所需的输入形状为(batch, timesteps, features)
。在您的情况下,这是 (5, 1, 1)
,因为 batch=5
、timesteps=1
和 features=1
,请参见下面的示例。
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, LSTM
tf.random.set_seed(0)
# generate the features
X = np.array([1296000.0, 19350000.0, 29635200.0, 48294000.0, 45961200.0])
# generate the target
y = np.array([0.05260218, 0.05260218, 0.0, 0.96769388, 1.0])
# rescale the features
X = (X - np.min(X)) / (np.max(X) - np.min(X))
# reshape the features
X = X.reshape(len(X), 1, 1)
print(X.shape)
# (5, 1, 1)
# define the model
model = Sequential()
model.add(LSTM(10, return_sequences=False, input_shape=(X.shape[0], X.shape[1])))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
model.fit(X, y, batch_size=1, epochs=10)
# generate the model predictions
model.predict(X)
# array([[0.05585098],
# [0.0940358 ],
# [0.11524458],
# [0.152216 ],
# [0.14772224]], dtype=float32)
【讨论】:
以上是关于无法匹配 Keras LSTM 模型所需的维数的主要内容,如果未能解决你的问题,请参考以下文章