TensorFlow v2 打印输出 “Hello World”

2022-08-10,,,,

本文使用Jupyter Notebook(python3)编写

TensorFlow版本为2.2.0



本程序使用TensorFlow v2 实现打印 “Hello World

import tensorflow as tf #创建一个Tensor字符串常量 hello = tf.constant("hello world ") print(hello) 

运行结果如下:
tf.Tensor(b'hello world', shape=(), dtype=string)

访问hello中的字符串,我们需要用到numpy()

#调用numpy(),来访问一个Tensor值 print(hello.numpy()) 

运行结果如下:
b'hello world'


本程序原期望的运行结果为hello world,而实际运行结果为b'hello world'

在网上查阅后,博主的理解:

b前缀的字符串为bytes类型的字符串
python语言中有两种不同的字符串,一个用于存储文本(unicode类型文本字符串u'hello world'),一个用于存储原始字节(byte类型字节字符串b'hello world'
在python3中,str变量默认采用unicode类型,因而省略了u前缀
字节型字符串和文本型字符串之间可以通过编码encode()和解码decode()相互转换。

那么既然hello.numpy()返回的是字节型字符串
我们对其进行decode()解码操作

#调用decode()解码,默认为utf-8解码 print(hello.numpy().decode()) 

运行结果为:
hello
这样就得到了期望的运行结果

对于含中文的字符串可以更明显地看到区别
我们可以定义一个含中文的Tensor字符串常量

test = tf.constant('hello 世界') print(test) print(test.numpy()) 

运行结果为:
tf.Tensor(b'hello \xe4\xb8\x96\xe7\x95\x8c', shape=(), dtype=string) b'hello \xe4\xb8\x96\xe7\x95\x8c'
可以看到字节型字符串中用3位16进制数来表示一个汉字

对test.numpy()解码

print(test.numpy().decode()) 

运行结果为:
hello 世界

上文中用到的编码方式称为utf-8,是python3中默认的编码方式
其他编码方式还有gbk等
其他前缀还有r,f,u等

有兴趣的朋友可以参考其他相关资料

本文地址:https://blog.csdn.net/m0_48796437/article/details/107126050

《TensorFlow v2 打印输出 “Hello World”.doc》

下载本文的Word格式文档,以方便收藏与打印。