keras中,TimeDistributed层在LSTM中的作用

本文详细介绍了Keras中的TimeDistributed层,该层用于将同一个层应用到3D输入的每个时间片。通过示例代码展示了在LSTM网络中使用TimeDistributed进行序列预测的不同模式,包括一对一、多对一和多对多。同时,讨论了使用该层时的注意事项,如输入和输出的维度要求。此外,还提供了LSTM中参数计算的公式,并给出了相关资源链接供进一步学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@创建于:20210414

1、TimeDistributed官网介绍

keras.layers.TimeDistributed(layer)

  • (1)这个封装器将一个层应用于输入的每个时间片。
  • (2)输入至少为3D,且第一个维度应该是时间所表示的维度。
    • 例如:32 个样本的一个batch,其中每个样本是10 个16 维向量的序列。那么这个batch 的输入尺寸为(32, 10, 16),而input_shape 不包含样本数量的维度,为(10, 16)。
    • 使用TimeDistributed 来将Dense 层独立地应用到这10 个时间步中的每一个。

即:TimeDistributed(Dense) 将同样的Dense(全连接)层操作应用到3D张量的每一个时间间隔上。

【我的理解】:TimeDistributed主要作用于每一步向量长度(即:属性大小);可以实现每一步结束后直接进行计算,而不是全部序列结束后进行计算;不改变数据的尺寸,改变数据尺寸的是TimeDistributed的层对象。

2、注意事项

利用TimeDistributed层来处理LSTM隐藏层的输出,在运用TimeDistributed包装层的时候需要记住两个关键点:
(1)输入必须(至少)是三维的。这就意味着需要在TimeDistributed包装密集层前配置最后一个LSTM层以便返回序列(例如将“return_sequences”参数设置为“True”);
(2)输出将也是三维的。如果TimeDistributed包装密集层是输出层,并且是用于预测序列,那么就得将y数组的大小调整成三维的向量。

3、TimeDistributed的测试代码

# -*- coding:UTF-8 -*- 

# author:
# contact: 
# datetime:2021/4/14 13:19
# software: PyCharm

"""
 文件说明:
 TimeDistributed的使用测试
 """

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, TimeDistributed

length = 5
seq = np.array([i*1.0/length for i in range(length)])



def one_to_one():
    X = seq.reshape(len(seq), 1, 1)
    X_test = np.arange(start=1, stop=3, step=0.2)
    X_test = X_test.reshape(X_test.shape[0], 1, 1)
    y = seq.reshape(len(seq), 1)

    print('X={}'.format(X))
    print('X_test={}'.format(X_test))
    print('y={}'.format(y))

    n_neurons = length
    n_batch = length
    n_epoch = 1000

    model = Sequential()
    model.add(LSTM(units=n_neurons, input_shape=(1, 1)))
    model.add(Dense(1))
    model.compile(loss='mean_squared_error', optimizer='adam')
    print(model.summary())
    model.fit(X, y, epochs=n_epoch, batch_size=n_batch, verbose=0)
    result = model.predict(X, batch_size=n_batch, verbose=0)
    # result = model.predict(X_test, batch_size=X_test.shape[0], verbose=0)
    for value in result:
        print('%.2f' % value)


def many_to_one():
    X = seq.reshape(1, length, 1)
    X_test = np.arange(start=1, stop=2, step=0.2)
    X_test = X_test.reshape(1, X_test.shape[0],  1)
    y = seq.reshape(1, length)

    n_neurons = length
    n_batch = 1
    n_epoch = 1000

    model = Sequential()
    model.add(LSTM(units=n_neurons, input_shape=(length, 1)))
    model.add(Dense(length))
    model.compile(loss='mean_squared_error', optimizer='adam')
    print(model.summary())
    model.fit(X, y, epochs=n_epoch, batch_size=n_batch, verbose=0)
    result = model.predict(X, batch_size=n_batch, verbose=0)
    # result = model.predict(X_test, batch_size=n_batch, verbose=0)
    for value in result[0, :]:
        print('%.2f' % value)


def many_to_many():
    X = seq.reshape(1, length, 1)
    X_test = np.arange(start=1, stop=2, step=0.2)
    X_test = X_test.reshape(1, X_test.shape[0], 1)
    y = seq.reshape(1, length)

    n_neurons = length
    n_batch = 1
    n_epoch = 1000

    model = Sequential()
    model.add(LSTM(units=n_neurons, return_sequences=True, input_shape=(length, 1)))
    model.add(TimeDistributed(Dense(1)))
    model.compile(loss='mean_squared_error', optimizer='adam')
    print(model.summary())
    model.fit(X, y, epochs=n_epoch, batch_size=n_batch, verbose=0)
    result = model.predict(X, batch_size=n_batch, verbose=0)
    # result = model.predict(X_test, batch_size=n_batch, verbose=0)
    for value in result[0, :]:
        print('%.2f' % value)


def main():
    # one_to_one()
    # many_to_one()
    many_to_many()


if __name__ == '__main__':
    main()

4、lstm中Param的计算

4 * [(inputs + 1) * outputs + outputs^2]
inputs是指lstm输入的数据n_features,
output是指lstm的隐藏层units的个数。

5、参考链接

How to Use the TimeDistributed Layer in Keras

如何在长短期记忆(LSTM)网络中利用TimeDistributed层—python语言

keras中使用LSTM实现一对多和多对多

### 双向长短期记忆网络在命名实体识别任务中的角色 #### BiLSTM 的工作原理及其优势 双向长短期记忆网络(BiLSTM)是一种特殊的循环神经网络结构,能够捕捉序列数据的时间依赖关系。与传统的单向 LSTM 不同的是,BiLSTM 同时考虑了输入序列的正向和反向信息[^3]。 对于给定的一个词语,在进行命名实体识别时,不仅当前词本身的信息很重要,其上下文环境同样起着决定性的作用。而 BiLSTM 正好可以通过两个方向上的隐藏状态来获取完整的语境信息: - **前向传递**:从前到后的顺序处理文本片段; - **后向传递**:从后往前的方向分析句子成分; 最终将这两个过程的结果组合起来作为该位置处单词的表征形式。 #### 结合 CNN 和 CRF 提升效果 为了进一步提高模型的表现力,通常会把 BiLSTM 与其他组件联合使用。例如,在字符级别引入卷积神经网络(CNN),从而更好地理解每个字内部结构以及形态学特性[^2]。另外,条件随机场(CRF)也被广泛应用在基于 BiLSTM 的 NER 系统中,因为它可以在解码阶段考虑到标签之间的转移概率,使得预测更加合理连贯。 ```python import tensorflow as tf from tensorflow.keras.layers import Input, Embedding, Bidirectional, LSTM, Dense, TimeDistributed, Conv1D, concatenate from tensorflow_addons.text.crf import crf_log_likelihood def build_model(vocab_size, embedding_dim, num_classes): input_word = Input(shape=(None,)) # Word embeddings layer embed_layer = Embedding(input_dim=vocab_size, output_dim=embedding_dim)(input_word) # Character-based features using CNN can be added here bilstm_output = Bidirectional(LSTM(units=100, return_sequences=True))(embed_layer) dense_output = TimeDistributed(Dense(num_classes))(bilstm_output) model_input = [input_word] logits = dense_output # Add CRF Layer for better sequence tagging performance log_likelihood, transition_params = crf_log_likelihood(logits, ...) model = tf.keras.Model(inputs=model_input, outputs=[logits]) return model ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值