gpt4 book ai didi

python - tensorflow : how to feed a variable-time-step input to a RNN

转载 作者:行者123 更新时间:2023-12-05 05:37:11 24 4
gpt4 key购买 nike

我有一个简单的 X_train 和 Y_train 数据:

x_train = [
array([ 6, 1, 9, 10, 7, 7, 1, 9, 10, 3, 10, 1, 4]),
array([ 2, 8, 8, 1, 1, 4, 2, 5, 1, 2, 7, 2, 1, 1, 4, 5, 10, 4])
]
y_train = [23, 17]

数组是 numpy 数组。我现在正尝试使用 tf.data.Dataset 类将它们加载为张量。在我使用以下代码成功完成类似操作之前:

    dataset = data.Dataset.from_tensor_slices((x_train, y_train))

由于此输入被送入 RNN,我在第一个 RNN 层中使用了 expand_dims 方法(expand_dimension 作为函数传递以克服 tensorflow 中的一个明显错误:参见 https://github.com/keras-team/keras/issues/5298#issuecomment-281914537):

def expand_dimension(x):
from tensorflow import expand_dims
return expand_dims(x, axis=-1)

model = models.Sequential(
[
layers.Lambda(expand_dimension,
input_shape=[None]),
layers.LSTM(units=64, activation='tanh'),
layers.Dense(units=1)
]
)

这很有效,因为我有等长的数组。在我发布的示例中,第一个数组有 13 个数字,第二个数组有 18 个。在这种情况下,上面的方法不起作用,推荐的方法似乎是使用 tf.data.Dataset.from_generator。阅读此 How to use the Tensorflow Dataset Pipeline for Variable Length Inputs? , 接受的解决方案显示类似以下的内容可行(为简单起见,我在这里不关心 y_train ):

dataset = tf.data.Dataset.from_generator(lambda: x_train, 
tf.as_dtype(x_train[0].dtype),
tf.TensorShape([None, ]))

但是,自此答案以来,tensorflow 中的语法发生了变化,现在它需要使用 output_signature 参数(参见 https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator)。

我尝试了不同的方法,但我发现很难从 tensorflow 文档中理解 output_signature 在我的情况下究竟应该是什么。任何帮助将不胜感激。

最佳答案

简短的回答是,您可以按如下方式定义 output_signature

import tensorflow as tf
import numpy as np
x_train = [
np.array([ 6, 1, 9, 10, 7, 7, 1, 9, 10, 3, 10, 1, 4]),
np.array([ 2, 8, 8, 1, 1, 4, 2, 5, 1, 2, 7, 2, 1, 1, 4, 5, 10, 4])
]
y_train = [23, 17]

dataset = tf.data.Dataset.from_generator(
lambda: x_train,
output_signature=tf.TensorSpec(
[None, ],
dtype=tf.as_dtype(x_train[0].dtype)
)
)

我还将扩展和改进您在这里所做的一些事情,以改进您的管道。

同时使用输入和标签

dataset = tf.data.Dataset.from_generator(
lambda: zip(x_train, y_train),
output_signature=(
tf.TensorSpec([None, ], dtype=tf.as_dtype(x_train[0].dtype)),
tf.TensorSpec([], dtype=tf.as_dtype(y_train.dtype))
)
)

for x in dataset:
print(x)

哪个会输出,

(<tf.Tensor: shape=(13,), dtype=int64, numpy=array([ 6,  1,  9, 10,  7,  7,  1,  9, 10,  3, 10,  1,  4])>, <tf.Tensor: shape=(), dtype=int64, numpy=23>)
(<tf.Tensor: shape=(18,), dtype=int64, numpy=
array([ 2, 8, 8, 1, 1, 4, 2, 5, 1, 2, 7, 2, 1, 1, 4, 5, 10,
4])>, <tf.Tensor: shape=(), dtype=int64, numpy=17>)

警告:如果您尝试 tf.data.Dataset.batch() 项目,这可能会稍微复杂一些。那么你需要使用 RaggedTensorSpec 而不是 TensorSpec。此外,我还没有对将参差不齐的张量输入 RNN 进行过太多实验。但我认为这些超出了您提出的问题的范围。

关于python - tensorflow : how to feed a variable-time-step input to a RNN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73165980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com