【问题标题】:How to convert string to float32 in tensorflow如何在tensorflow中将字符串转换为float32
【发布时间】:2021-03-13 03:53:59
【问题描述】:

我是张量流的新用户。我有以下张量 A:

<tf.Tensor: shape=(3,), dtype=string, numpy=
array([b'1,2.0,32.29,42.1,16.0,0.60,46.0,0.0,26.0,0.0,-1.31,-0.9'],
  dtype=object)>

我想得到以下两个张量:

张量 B:将张量 A 转换为浮点张量并获取张量 A 的第一个元素:

<tf.Tensor: shape=(3,), dtype=float, numpy=
array([1],
  dtype=object)>

张量 C:将张量 A 转换为浮点张量并提取张量 B 的最后 4 个元素

<tf.Tensor: shape=(3,), dtype=float, numpy=
array([26.0,0.0,-1.31,-0.9],
  dtype=object)>

能否请您告诉我如何从张量 A 中获得张量 B 和张量 C?文档令人困惑。

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensor tensorflow-datasets


    【解决方案1】:
    temp_list = [1,2.0,32.29,42.1,16.0,0.60,46.0,0.0,26.0,0.0,-1.31,-0.9]
    temp_tensor = tf.convert_to_tensor(temp_list)
    temp_tensor[0]
    temp_tensor[-4:]
    

    您应该阅读https://www.tensorflow.org/guide/tensor 以进一步讨论。

    更新一:

    我试试

    temp_str = "1,2.0,32.29,42.1,16.0,0.60,46.0,0.0,26.0,0.0,-1.31,-0.9"
    temp_tensor = tf.convert_to_tensor(temp_str)
    tf.cast(tf.strings.split(temp_tensor, sep=","),dtype=tf.float32)
    

    它会引发错误:

    UnimplementedError: Cast string to float is not supported [Op:Cast]
    

    好像tensorflow不允许convert string to float。

    我不确定这是否能满足您的需求:

    tf.convert_to_tensor(np.array(tf.strings.split(temp_tensor, sep=",").numpy(),dtype="float32"))
    

    更新二:

    我找到了最好的答案:

    temp_str = "1,2.0,32.29,42.1,16.0,0.60,46.0,0.0,26.0,0.0,-1.31,-0.9"
    temp_tensor = tf.convert_to_tensor(temp_str)
    tf.strings.to_number(tf.strings.split(temp_tensor, sep=","))
    

    【讨论】:

    • 这并没有回答问题,因为 OP 似乎在询问如何将字符串张量转换为数字类型,您可以跳过。
    • 谢谢。但我的问题是我需要将字节类型张量转换为数字张量。您的临时张量不是字节类型
    • 谢谢@DachuanZhao。您的最后一行代码很有帮助
    • @xdurch0 我已经添加了~
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多