[英]TensorFlow: convert tf.Dataset to tf.Tensor
I want to generate windows of the range of 10:我想生成范围为 10 的窗口:
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices(tf.range(10))
dataset = dataset.window(5, shift=1, drop_remainder=True)
and would like to train my model on this dataset.并且想在这个数据集上训练我的模型。
To do so, those windows have to be converted to tensors.为此,必须将这些窗口转换为张量。 But the datatype of these windows cannot be converted via
tf.convert_to_tensor
to a tensor.但是这些窗口的数据类型不能通过
tf.convert_to_tensor
转换为张量。 It is possible to do tf.convert_to_tensor(list(window))
but this is quite inefficient.可以执行
tf.convert_to_tensor(list(window))
但这效率很低。
Does anyone know how to convert a tf.VariantDataset
efficiently to a tf.Tensor
?有谁知道如何将
tf.VariantDataset
有效地转换为tf.Tensor
?
Thank you for your help!感谢您的帮助!
If you want to create a tensor of sliding windows, doing it through a dataset is not really the best way, is far less efficient and flexible.如果你想创建一个滑动窗口的张量,通过数据集来做并不是最好的方法,效率和灵活性要低得多。 I don't think there is a proper operation for that, but there are two similar ones for 2D and 3D arrays,
tf.image.extract_patches
and tf.extract_volume_patches
.我认为没有合适的操作,但是对于 2D 和 3D 数组,有两个类似的操作,
tf.image.extract_patches
和tf.extract_volume_patches
。 You can reshape your 1D data to use them:您可以重塑一维数据以使用它们:
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.