我有一个X_train = [(4096,18464),(4097,43045),(4098,38948),(4099,2095),(4100,59432),(4101,55338),(4102,51245) ,(4103,26658),(4104,30755),....],形状为(3283,2),并且
y_train = [19189,19189,19189,...,1155085434105692417,1155120620365152513,...]形状为(3283,1)
我使用以下代码重塑了X_train:
X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
并成型(3283,1,2)
现在我建立一个lstm模型:
data_dim= 2
timesteps=1
num_classes=2
model_pass = Sequential()
model_pass.add(LSTM(units=64, return_sequences=True,
input_shape=(timesteps, data_dim)))
model_pass.add(Dense(2, activation='sigmoid'))
model_pass.compile(loss='binary_crossentropy', optimizer='adam',metrics=['accuracy'])
model_pass.summary()
model_pass.fit(X_train, y_train,batch_size=1, epochs = 1, verbose = 1)
但这给我一个错误: ValueError:检查目标时出错:预期density_24具有3维,但数组的形状为(3283,1)
有人可以告诉我该怎么办吗?
答案 0 :(得分:0)
在密集层之后,输出形状为(number of samples, timesteps, 2)
。数字2来自Dense(2,...)
。但是y_train_pass的形状可能为(number of samples, 1)
。那给出了一个错误。
以下是可能的代码示例,其中我将Dense(2,...)
更改为Dense(1,...)
并重塑了y_train
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
import numpy as np
X_train = np.random.randn(3283,2)
X_test = np.random.randn(1000,2)
y_train = np.random.randint(2, size=(3283,1))
print(y_train.shape)
X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
y_train = np.reshape(y_train, (y_train.shape[0],1, y_train.shape[1]))
data_dim= 2
timesteps=1
num_classes=2
model_pass = Sequential()
model_pass.add(LSTM(units=64, return_sequences=True,
input_shape=(timesteps, data_dim)))
model_pass.add(Dense(1, activation='sigmoid'))
model_pass.compile(loss='binary_crossentropy', optimizer='adam',metrics=['accuracy'])
model_pass.summary()
model_pass.fit(X_train, y_train,batch_size=1, epochs = 1, verbose = 1)
顺便说一句。奇怪的是,您的y_train值没有“二进制”值,而您使用loss='binary_crossentropy'
。