【问题标题】:Error when checking target: expected dense_24 to have 3 dimensions, but got array with shape (3283, 1)检查目标时出错:预期 dense_24 有 3 个维度,但得到了形状为 (3283, 1) 的数组
【发布时间】:2019-08-22 01:23:24
【问题描述】:

我有一个 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: 检查目标时出错:预期dense_24 有3 维,但得到的数组形状为(3283, 1)

谁能告诉我该怎么办?

【问题讨论】:

    标签: python arrays lstm reshape


    【解决方案1】:

    在密集层之后,输出形状为(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'

    【讨论】:

    • 我已经编辑了这个问题。 y_train_pass 实际上是 y_train,它的形状是 (3283, 1)。我不知道如何纠正错误。如何重塑 y_train?
    猜你喜欢
    • 2019-01-16
    • 2018-03-28
    • 2019-09-11
    • 2019-01-03
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2019-03-25
    • 2019-03-02
    相关资源
    最近更新 更多