gpt4 book ai didi

python - TensorFlow:将 tf.Dataset 转换为 tf.Tensor

转载 作者:行者123 更新时间:2023-12-04 03:50:25 28 4
gpt4 key购买 nike

我想生成范围为 10 的窗口:

import tensorflow as tf

dataset = tf.data.Dataset.from_tensor_slices(tf.range(10))
dataset = dataset.window(5, shift=1, drop_remainder=True)
并且想在这个数据集上训练我的模型。
为此,必须将这些窗口转换为张量。但是这些窗口的数据类型不能通过 tf.convert_to_tensor 转换到张量。可以做 tf.convert_to_tensor(list(window))但这效率很低。
有谁知道如何转换 tf.VariantDataset有效地到 tf.Tensor ?
感谢您的帮助!

最佳答案

如果你想创建一个滑动窗口的张量,通过数据集来做并不是最好的方法,效率和灵活性要低得多。我认为没有合适的操作,但是对于 2D 和 3D 数组有两个类似的操作, tf.image.extract_patches tf.extract_volume_patches .您可以 reshape 一维数据以使用它们:

import tensorflow as tf

a = tf.range(10)
win_size = 5
stride = 1
# Option 1
a_win = tf.image.extract_patches(tf.reshape(a, [1, -1, 1, 1]),
sizes=[1, win_size, 1, 1],
strides=[1, stride, 1, 1],
rates=[1, 1, 1, 1],
padding='VALID')[0, :, 0]
# Option 2
a_win = tf.extract_volume_patches(tf.reshape(a, [1, -1, 1, 1, 1]),
ksizes=[1, win_size, 1, 1, 1],
strides=[1, stride, 1, 1, 1],
padding='VALID')[0, :, 0, 0]
# Print result
print(a_win.numpy())
# [[0 1 2 3 4]
# [1 2 3 4 5]
# [2 3 4 5 6]
# [3 4 5 6 7]
# [4 5 6 7 8]
# [5 6 7 8 9]]

关于python - TensorFlow:将 tf.Dataset 转换为 tf.Tensor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64497977/

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