【发布时间】:2020-06-28 22:01:51
【问题描述】:
我正在 Tensorflow 2 中训练一个 LSTM 模型来预测两个输出,即水流和水温。
- 对于某些时间步,有一个流标签和一个温度标签,
- 对于某些只有水流标签或温度标签,
- 对于某些人来说,两者都没有。
所以损失函数需要在没有标签的情况下忽略温度和流量损失。我在 TF 文档中做了很多阅读,但我正在努力弄清楚如何最好地做到这一点。
到目前为止我已经尝试过
- 在编译模型时指定
sample_weight_mode='temporal',然后在调用fit时包含sample_weightnumpy 数组
当我这样做时,我收到一个错误,要求我传递一个二维数组。但这让我感到困惑,因为有 3 个维度:n_samples、sequence_length 和 n_outputs。
这是我基本上想要做的一些代码:
import tensorflow as tf
import numpy as np
# set up the model
simple_lstm_model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(8, return_sequences=True),
tf.keras.layers.Dense(2)
])
simple_lstm_model.compile(optimizer='adam', loss='mae',
sample_weight_mode='temporal')
n_sample = 2
seq_len = 10
n_feat = 5
n_out = 2
# random in/out
x = np.random.randn(n_sample, seq_len, n_feat)
y_true = np.random.randn(n_sample, seq_len, n_out)
# set the initial mask as all ones (everything counts equally)
mask = np.ones([n_sample, seq_len, n_out])
# set the mask so that in the 0th sample, in the 3-8th time step
# the 1th variable is not counted in the loss function
mask[0, 3:8, 1] = 0
simple_lstm_model.fit(x, y_true, sample_weight=mask)
错误:
ValueError: Found a sample_weight array with shape (2, 10, 2). In order to use timestep-wise sample weighting, you should
pass a 2D sample_weight array.
有什么想法吗?我一定不明白sample_weights 做了什么,因为对我来说,只有sample_weight 数组与输出具有相同的维度才有意义。我可以编写一个自定义损失函数并手动处理屏蔽,但似乎应该有一个更通用或内置的解决方案。
【问题讨论】:
标签: python numpy tensorflow keras lstm