TensorFlow 字符串 与数字 互相转换

  1. 数字转字符串 tf.as_string()
    数据类型只能取 int32, int64, complex64, float32, float64, bool, int8 中的一种
import tensorflow as tf

A_tf = tf.constant([1, 2, 3, 4, 5, 6], dtype=tf.float32)
A_str_tf = tf.as_string(A_tf)

with tf.Session() as sess:
    bytes_v = sess.run(A_str_tf)
    A_str = [v.decode() for v in bytes_v]
    print(A_str)

# 输出为:
# ['1.000000', '2.000000', '3.000000', '4.000000', '5.000000', '6.000000']

  1. 字符串转数字 tf.string_to_number
    可转换的数字类型有: int32, int64, float32, float64,
    默认为 float32
import tensorflow as tf

A_tf = tf.constant(['1.3', '2.8', '3.5', '4.7', '5.6'], dtype=tf.string)
A_float_tf = tf.string_to_number(A_tf, out_type=tf.float32)

with tf.Session() as sess:
    print(sess.run(A_float_tf))

# 输出为:
# [1.3 2.8 3.5 4.7 5.6]

tf.string 转为Number 类型时,必须保证tf.string存储的数据能正确转为指定的Number 数据类型。 如上面例子, 只能转为浮点数,若转为int则会报错。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Enzo 想砸电脑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值