文章目录
因为想用TCN进行时间序列预测,所以我打算研究一下怎么写代码。
从官网机翻来的。
这是个不成熟的坑,先挖再说。
API
https://pypi.org/project/keras-tcn/
pip install keras-tcn
中文:https://www.cnpython.com/pypi/keras-tcn
https://github.com/philipperemy/keras-tcn/tree/master/tasks
TCN优势
在大量任务上优于LSTM
并行性、灵活的接受 field 大小、稳定的梯度、训练时的低记忆要求、可变长度输入
API参数
TCN(
nb_filters=64,
kernel_size=2,
nb_stacks=1,
dilations=[1, 2, 4, 8, 16, 32],
padding=‘causal’,
use_skip_connections=True,
dropout_rate=0.0,
return_sequences=True,
activation=‘linear’,
kernel_initializer=‘he_normal’
, use_batch_norm=False, **kwargs)
nb_filters: Integer
在卷积层中使用的过滤器的数量,类似于LSTM。
kernel_size
整数,在每个卷积层中使用的内核kernel的大小。
dilations
列表。扩张的列表的一个例子是 : [1, 2, 4, 8, 16, 32, 64].
nb_stacks
整数。要使用的剩余块的堆栈( stacks of residual blocks)数量。
padding
String. The padding to use in the convolutions. ‘causal’ for a causal network (as in the original implementation) and ‘same’ for a non-causal network.
字符串。在卷积中使用的填充。
在因果网络中使用“因果”(如同最初的实现),而在非因果网络中使用“相同”。
use_skip_connections
Boolean. If we want to add skip connections from input to each residual block.
布尔。如果我们想要添加从输入到每个剩余块的跳过连接。
return_sequences
Boolean. Whether to return the last output in the output sequence, or the full sequence.
布尔。
是返回输出序列中的最后一个输出,还是返回完整序列。
dropout_rate
Float between 0 and 1. Fraction of the input units to drop.
在0和1之间浮动。要下降的输入单位的分数。
activation
The activation used in the residual blocks o = activation(x + F(x)).
剩余块中使用的激活o =激活(x + F(x))。
kernel_initializer
Initializer for the kernel weights matrix (Conv1D).
核权值矩阵(Conv1D)的初始化式。
use_batch_norm
Whether to use batch normalization in the residual layers or not.
是否在剩余层中使用批处理规范化。
kwargs
Any other arguments for configuring parent class Layer. For example “name=str”, Name of the model. Use unique names when using multiple TCN.
用于配置父类层的任何其他参数。
例如"name=str",模型的名称。使用多个TCN时使用唯一名称。
Input shape
三维张量形状(batch_size, timesteps, input_dim)。
具有形状的三维张量(批量大小、时间步长、输入维度)
如果每个序列都有不同的长度,这可能很有用:多个长度序列的例子。
Output shape
shape (batch_size, timesteps, nb_filters).
如果return_sequences=true:具有形状的三维张量(批量大小、时间步长、nb_过滤器)
如果return_sequences=false:具有形状的2d张量(批量大小,nb_过滤器)
TCN支持的任务类型
回归(多对一),例如添加问题
分类(多对多),例如复制内存任务
分类(多对一),例如顺序任务
对于多对多回归,目前一个廉价的解决方案是更改最终密集层的单元数。
代码示例
①载入模块
from tensorflow.keras.layers import Dense
from tensorflow.keras import Input, Model
from tcn import TCN, tcn_full_summary
②确定batch的大小,时间步,输入维度
batch_size, timesteps, input_dim = None, 20, 1
③得到训练集
def get_x_y(size=1000):
import numpy as np
pos_indices = np.random.choice(size, size=int(size // 2), replace=False)
x_train = np.zeros(shape=(size, timesteps, 1))
y_train = np.zeros(shape=(size, 1))
x_train[pos_indices, 0] = 1.0
y_train[pos_indices, 0] = 1.0
return x_train, y_train
④搭建网络(没太懂这步,有待研究,备注瞎标)
仿佛它不用 sequential
#i是输入,读入之前设置的参数
i = Input(batch_shape=(batch_size, timesteps, input_dim))
#TCN层
o = TCN(return_sequences=False)(i) # The TCN layers are here.
#全连接层
o = Dense(1)(o)
#模型实例
m = Model(inputs=[i], outputs=[o])
在上面的例子中,tcn也可以像这样堆叠在一起
o = TCN(return_sequences=True)(i)
o = TCN(return_sequences=False)(o)
⑤配置训练方法,选择优化器和损失函数
m.compile(optimizer='adam', loss='mse')
⑥打印网络结构
tcn_full_summary(m, expand_residual_blocks=False)
⑦拟合
x, y = get_x_y()
m.fit(x, y, epochs=10, validation_split=0.2)
现成的TCN使用
完整代码见 cf. tasks/
from tcn import compiled_tcn
model = compiled_tcn(...)
model.fit(x, y) # Keras model.
本文介绍了Keras-TCN库的API用法,包括关键参数如nb_filters, kernel_size, dilations等,并强调了TCN在多个任务上的优势,如并行性、可变长度输入。此外,提供了代码示例展示如何搭建和训练TCN模型。"
113511688,10544488,Python一键生成九宫格短视频教程,"['Python编程', '视频编辑', '图像处理', '朋友圈分享', '自动化工具']
435





