【问题标题】:how can i covert tuple numpy to tuple tensor in tensorflow easily如何轻松地将元组 numpy 转换为 tensorflow 中的元组张量
【发布时间】:2020-12-10 14:27:16
【问题描述】:

我有 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 生成器直接获取样本。

【问题讨论】:

    标签: numpy tensorflow tensorflow-datasets


    【解决方案1】:

    我不确定我是否正确理解了您的问题,但您似乎只想将 abcd 转换为 tensorflow 张量,而无需使用 @ 987654325@ 功能。 在这种情况下,您可以简单地使用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, ...
    

    【讨论】:

    • a, b, c, d 不是同一个形状,我在问题中改变了 a,b,c,d 的形状。
    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 2016-03-09
    • 2021-10-13
    • 2021-04-28
    • 2021-01-08
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多