- 数字转字符串 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']
- 字符串转数字 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则会报错。