我試圖為構建神經網路建立一個最低限度的例子。我在 5 個不同的日期獲得了 5 個汽車的價格。無論我如何重新排列我的資料,我都會得到 2 種錯誤中的一種。
任何一個
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似乎沒有幫助。我需要做什么才能使這些尺寸匹配?它會奏效嗎?
uj5u.com熱心網友回復:
如keras 檔案中所述,所需的輸入形狀是(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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/346301.html
上一篇:如何列印Keras張量值?
