python - Keras TimeDistributed 层实际上是做什么的?

标签 python tensorflow keras lstm

给定一个时间序列,我有一个多步骤预测任务,我想在给定的时间序列序列中预测与时间步相同的次数。 如果我有以下模型:

input1 = Input(shape=(n_timesteps, n_channels))
lstm = LSTM(units=100, activation='relu')(input1)
outputs = Dense(n_timesteps, activation="softmax")(lstm)
model = Model(inputs=input1, outputs=outputs)
model.compile(loss="mse", optimizer="adam",
              metrics=["accuracy"])

密集层上的 n_timesteps 意味着我将有 n_timesteps 预测。但是,如果我将密集层包装在 TimeDistributed 中(或者等效地在 LSTM 层中设置 return_sequences=True ),单位数量是否仍然必须为 n_timesteps 还是 1,因为使用 TimeDistributed 我会将密集层应用到序列中的所有时间步骤。

最佳答案

根据您发布的示例,TimeDistributed本质上会将具有 softmax 激活函数的 Dense 层应用于每个时间步:

import tensorflow as tf

n_timesteps = 10
n_channels = 30
input1 = tf.keras.layers.Input(shape=(n_timesteps, n_channels))
lstm = tf.keras.layers.LSTM(units=100, activation='relu', return_sequences=True)(input1)
outputs = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(n_channels, activation="softmax"))(lstm)
model = tf.keras.Model(inputs=input1, outputs=outputs)

请注意,每个全连接层都等于 n_channels 的大小,以便为每个 channel 提供在时间步 n 进行预测的公平机会。

如果您正在解决多标签问题,您可以尝试如下操作:

import tensorflow as tf

n_timesteps = 10
features = 3
input1 = tf.keras.layers.Input(shape=(n_timesteps, features))
lstm = tf.keras.layers.LSTM(units=100, activation='relu', return_sequences=False)(input1)
outputs = tf.keras.layers.Dense(n_timesteps, activation="sigmoid")(lstm)
model = tf.keras.Model(inputs=input1, outputs=outputs)

x = tf.random.normal((1, n_timesteps, features))
y = tf.random.uniform((1, n_timesteps), dtype=tf.int32, maxval=2)

print(x)
print(y)
model.compile(optimizer='adam', loss='binary_crossentropy')
model.fit(x, y, epochs=2)

关于python - Keras TimeDistributed 层实际上是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71572843/

相关文章:

python - TensorFlow 模型获得零损失

python - Google Colab 可以使用本地资源吗?

python - 对两个列表进行排序——一个是列表的列表

python - 如何在 python 中弹出子列表的内容?

tensorflow - 如何将编码的 jpeg 作为字节写入 Tensorflow tfrecord 然后读取它?

python - 分类指标无法处理连续多输出和多标签指标目标的混合

r - 如何使用 keras 和 pad_sequences 在 R 中填充文本序列?

python - ValueError : Dimensions must be equal,,但对于 'loss/output_1_loss/mul' 来说是 3 和 3072 (op : 'Mul' ) with input shapes: [? ,3], [?,3072]

python - 如何在Python中合并多个缓冲区对象?

javascript - 在 python 服务器上从 Fabric.js JSON 构造图像