【问题标题】:keras SimpleRNN model data shape interpretationkeras SimpleRNN 模型数据形状解释
【发布时间】:2020-04-11 17:22:13
【问题描述】:

我有一个非常简单的 keras 顺序模型:

model = keras.models.Sequential([
    keras.layers.SimpleRNN(1, input_shape=[None, 1], return_sequences=True),
])
model.compile(loss='mse')

我的(玩具)数据如下所示:

X = np.array([[1,2],[3,4],[5,6], [7,8]])[...,np.newaxis]
y = np.array([3,5,7,9])[..., np.newaxis]

X.shape -> (4,2,1)
y.shape -> (4,1)

因为我return_sequences,我希望我的输出形状是(4,2,1)
这也是model.predict(X)返回的内容。
我的问题:当模型预测输出的形状与y 的形状不匹配时,如何在拟合中计算损失?
keras.layers.mse(model.predict(X), y) 引发形状不匹配..

要试验的完整代码:

from tensorflow import keras
import numpy as np

X = np.array([[1,2],[3,4],[5,6], [7,8]])[...,np.newaxis]
y = np.array([3,5,7,9])[..., np.newaxis]
print(X.shape)
print(y.shape)


model = keras.models.Sequential([
    keras.layers.SimpleRNN(1, input_shape=[None, 1], return_sequences=True),
])

model.compile(loss='mse', optimizer='adam')
model.summary()

model.fit(X, y, epochs = 1)
print(model.predict(X).shape)

# this fails as expected
# keras.losses.mse(model.predict(X), y)

版本:keras 2.2.4-tf 和 tensorflow 2.1.0

【问题讨论】:

    标签: python keras recurrent-neural-network


    【解决方案1】:

    你已经设置了return_sequences=False

    model = keras.models.Sequential([
        keras.layers.SimpleRNN(1, input_shape=[None, 1], return_sequences=False),
    ])
    model.compile(loss='mse',optimizer='sgd')
    model.fit(X,y)
    

    【讨论】:

    • 不过,这不是我的问题。我对我的代码为什么(以及如何)工作很感兴趣。我希望它会失败
    • 你确定吗?对我来说确实失败了InvalidArgumentError: Incompatible shapes: [4,2,1] vs. [4,1] [[{{node loss_5/simple_rnn_loss/SquaredDifference}}]]
    • 有趣,哪个 tf/keras 版本?我正在使用带有 keras 2.2.4-tf 的 tf 2.1.0。我说的是合身,对吧?因为在我的例子的最后一行,它对我来说也失败了
    • haa tf 1.14.0 和 keras 2.2.4-tf
    • 这是功能还是错误? :D
    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 2020-04-13
    • 2019-09-21
    • 1970-01-01
    • 2022-10-18
    • 2018-11-09
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多