
663
附录 F
特殊数据结构
在本附录中,我们将快速浏览 TensorFlow 支持的数据结构,而不仅仅是常规的浮点或整
数张量。这包括字符串、不规则张量、稀疏张量、张量数组、集合和队列。
F.1 字符串
张量可以容纳字节串,这对于自然语言处理特别有用(见第 16 章 ):
>>>
tf.constant(b"hello world")
<tf.Tensor: id=149, shape=(), dtype=string, numpy=b'hello world'>
如果你使用 Unicode 字符串来构建一个张量,则 TensorFlow 会自动将其编码为 UTF-8:
>>>
tf.constant("café")
<tf.Tensor: id=138, shape=(), dtype=string, numpy=b'caf\xc3\xa9'>
也可以创建表示 Unicode 字符串的张量。只需创建一个 32 位整数的数组,每个整数代
表一个 Unicode 代码点
注 1
:
1
>>>
tf.constant([ord(c)
for
c
in
"café"])
<tf.Tensor: id=211, shape=(4,), dtype=int32,
numpy=array([ 99, 97, 102, 233], dtype=int32)>
在类型为 tf.string 的张量中,字符串长度不是张量形状的一部分。换句话说,字符串被
视为原子值。但是,在 Unicode 字符串张量(即 int32 张量)中,字符串的长度是张量形 ...