keras中,TimeDistributed层在LSTM中的作用

@创建于: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实现一对多和多对多

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Keras的Attention来在LSTM加入注意力机制,具体实现可以参考以下代码: ```python from keras.layers import Input, LSTM, Dense, Dropout, TimeDistributed, Bidirectional, Concatenate, Dot, Activation from keras.layers import RepeatVector, Embedding, Flatten, Lambda, Permute, Multiply from keras.models import Model from keras.activations import softmax import keras.backend as K # 定义注意力机制的函数 def attention(a, b): a_reshape = Permute((2, 1))(a) score = Dot(axes=[2, 1])([b, a_reshape]) alignment = Activation('softmax')(score) context = Dot(axes=[2, 1])([alignment, a]) return context # 定义输入和输出的形状和维度 input_shape = (None,) output_shape = (None,) # 定义输入和嵌入 input_layer = Input(shape=input_shape) embedding_layer = Embedding(input_dim=vocab_size, output_dim=embedding_dim)(input_layer) # 定义双向LSTM lstm_layer = Bidirectional(LSTM(units=lstm_units, return_sequences=True))(embedding_layer) # 定义注意力 attention_layer = attention(lstm_layer, lstm_layer) # 将LSTM和注意力连接起来 concat_layer = Concatenate(axis=2)([lstm_layer, attention_layer]) # 定义全连接和输出 dense_layer = TimeDistributed(Dense(units=dense_units, activation='relu'))(concat_layer) output_layer = TimeDistributed(Dense(units=output_vocab_size, activation='softmax'))(dense_layer) # 构建模型 model = Model(inputs=[input_layer], outputs=[output_layer]) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ``` 注意,上述代码的函数`attention`就是实现注意力机制的关键。在模型,我们先将输入通过嵌入映射成词向量,然后经过双向LSTM,得到前向和后向的隐状态。接着,我们将这两个隐状态作为注意力机制的输入,计算得到注意力权重,然后根据这个权重计算出每个词对应的上下文向量。最后,我们将原始的LSTM输出和上下文向量拼接起来,再通过全连接和输出进行预测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值