【问题标题】:How to fit a 3D matrix in keras model?如何在 keras 模型中拟合 3D 矩阵?
【发布时间】:2017-05-11 03:58:26
【问题描述】:

我正在使用 keras 创建回归模型。我有 10 145 * 5 十位数的矩阵。我在 keras 模型中拟合 10 145 * 5 矩阵时遇到问题。

X 是输入矩阵

In: X.shape

Out: (10, 145, 5)

y 是目标矩阵

In: y.shape

Out: (10,)

对于每个145 * 5 矩阵,目标矩阵中都会有一个值

制作模型

In: model = Sequential([ Dense(32, input_dim=145), Activation('sigmoid'), Dense(output_dim=10) ])

虽然上一行没有抛出任何错误或警告,但我很确定在这种情况下它不是适合模型的正确方法。

In: model.compile(optimizer='sgd',loss='mse')

目前没有问题。但是当我试图拟合矩阵时

In: model.fit(X, y.reshape(-1, 1))

在这行之后,我得到了一个很长的 Traceback,它最终说

ValueError: Error when checking model input: expected dense_input_1 to have 2 dimensions, but got array with shape (10, 145, 5)

请帮助我正确拟合模型中的矩阵。谢谢!

【问题讨论】:

    标签: python-3.x neural-network keras


    【解决方案1】:

    使用input_shape 代替input_dim。此外,由于输出的维度数量正在变化,您需要使用FlattenReshape 作为维度之一。

    from keras.layers import Flatten
    
    model = Sequential([
        Dense(32, input_shape=(145,5)),
        Flatten(),
        Activation('sigmoid'),
        Dense(output_dim=10)
    ])
    
    model.summary()
    

    使用model.summary() 检查模型的结构以便更好地理解。

    【讨论】:

    • 在拟合模型时是否需要展平矩阵?
    • 我在试穿时得到了这个ValueError: Error when checking model target: expected dense_2 to have shape (None, 10) but got array with shape (10, 1)
    • 没有展平层会自动为您完成。您可以按原样使用输入。
    • 好的,这意味着你的 output_dim 是 1 使用 Dense(output_dim=1) 作为最后一层。
    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 2013-05-06
    • 2019-10-20
    • 2019-10-20
    • 2021-09-30
    • 2020-03-24
    • 2021-04-01
    • 1970-01-01
    相关资源
    最近更新 更多