【问题标题】:How to convert tensorflow tensor to bytes?如何将张量流张量转换为字节?
【发布时间】:2021-04-13 14:09:46
【问题描述】:

在 numpy 中,将 np 张量转换为字节可以如下完成:

import tensorflow as tf
import numpy as np

b = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.uint8)
bytesArr = b.tobytes()
print(bytesArr)

在 tensorflow 中,您可以这样做来创建张量,但是如何将结果转换为字节数组?

a = tf.cast(tf.constant([[1.0, 2.0], [3.0, 4.0]]), tf.uint8)

#Do conversion here

另外:我也在处理一个包裹在@tf.function 中的 tf 模型,所以没有启用急切执行,这意味着我不能在张量上使用 .numpy() 方法。

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:
    tensorByteProto = tf.io.serialize_tensor(a)
    

    要从 TensorProto 中提取字节,请使用 tensorByteProto.tensor_content

    【讨论】:

    • 第二个(tf.io.serialize_tensor)工作
    • (tf.io.serialize_tensor) 似乎没有给出与 numpy .tobytes() 命令相同的值。字节看起来不正确。
    • 查看 tf.io.serialize(a).tensor_content 是否有效
    • 究竟是什么是不可接受的,因为如果你看到使用 Python type(val2test) 的数据类型,那么它将显示为字节
    猜你喜欢
    • 2018-02-13
    • 2022-09-29
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2020-12-21
    相关资源
    最近更新 更多