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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值