给定一个时间序列,我有一个多步骤预测任务,我想在给定的时间序列序列中预测与时间步相同的次数。 如果我有以下模型:
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/