我有tuple numpy (使用len 4,5,6或更多),如何将tuple numpy转换为tuple tensor,输入如下:
import tensorflow as tf
import numpy as np
a = np.array([[20, 20], [40, 40]], dtype=np.int32)
b = np.array([[20, 20, 20], [40, 40, 40], [60, 60, 60]], dtype=np.int32)
c = np.array([[20, 20], [40, 40]], dtype=np.int32)
d = np.array([[20, 20, 20], [40, 40, 40], [60, 60, 60]], dtype=np.int32)
e = (a, b, c, d) # e is numpy tensor i want convert to tensor
tf_shapes = ((None, 2), (None, 3), (2, 2), (3, 3))
tf_types = (tf.int64, tf.float32, tf.int64, tf.float32)我必须编写一个生成器来将其转换为元组张量。
def data_generator():
for i in range(16):
yield a, b, c, d
dataset=tf.data.Dataset.from_generator(data_generator, tf_types, tf_shapes).batch(batch_size=4, drop_remainder=True)
for sample in dataset:
res = model(sample, training=False)如何不使用tfdata生成器直接获取样本。
发布于 2020-08-21 16:21:24
我不确定我是否正确理解了您的问题,但是您似乎只希望将a、b、c和d转换为tensorflow张量,而不必使用tf.data.Dataset.from_generator函数。在这种情况下,您可以简单地使用tf.convert_to_tensor
import tensorflow as tf
import numpy as np
a_tensor = tf.convert_to_tensor(a, np.int32)
b_tensor = tf.convert_to_tensor(b, np.int32)
c_tensor = tf.convert_to_tensor(c, np.int32)
d_tensor = tf.convert_to_tensor(d, np.int32)
# use the tensors however you want另外,如果你想在你的代码中有一个类似于e的张量,那么可以这样做:
e_tensor = tf.stack(e, axis=0)
# e_tensor[0] == a_tensor, e_tensor[1] == b_tensor, ...https://stackoverflow.com/questions/63518829
复制相似问题