May 2025
Intermediate to advanced
864 pages
12h 32m
Chinese
在本附录中,除了常规的浮点或整数张量外,我们将快速了解 TensorFlow 支持的数据结构。其中包括字符串、锯齿张量、稀疏张量、张量数组、集合和队列。
张量可以保存字节字符串,,这对自然语言处理尤其有用(见第 16 章):
>>>tf.constant(b"hello world")<tf.Tensor: shape=(), dtype=string, numpy=b'hello world'>
如果尝试使用 Unicode 字符串构建张量,TensorFlow 会自动将其编码为 UTF-8:
>>>tf.constant("café")<tf.Tensor: shape=(), dtype=string, numpy=b'caf\xc3\xa9'>
还可以创建代表 Unicode 字符串的张量。只需创建一个 32 位整数数组,每个整数代表一个 Unicode 代码点。1
>>>u=tf.constant([ord(c)forcin"café"])>>>u<tf.Tensor: shape=(4,), [...], numpy=array([ 99, 97, 102, 233], dtype=int32)>
在tf.string 类型的张量中,字符串长度不是张量形状的一部分。换句话说,字符串被视为原子值。但是,在 Unicode 字符串张量(即 int32 张量)中,字符串的长度是张量形状的一部分。
tf.strings 软件包包含多个用于处理字符串张量的函数,例如length() 用于计算字节字符串中的字节数(如果设置了unit="UTF8_CHAR" ,则计算代码点数),unicode_encode() 用于将 Unicode 字符串张量(即 int32 张量)转换为字节字符串张量,以及unicode_decode() 用于反向操作:
>>>b=tf.strings.unicode_encode(u,"UTF-8")>>>b<tf.Tensor: shape=(), dtype=string, numpy=b'caf\xc3\xa9'>>>>tf.strings.length(b,unit="UTF8_CHAR")<tf.Tensor: shape=(), dtype=int32, numpy=4>>>>tf.strings.unicode_decode(b,"UTF-8")<tf.Tensor: shape=(4,), [...], numpy=array([ 99, 97, 102, 233], dtype=int32)>
您还可以操作包含多个字符串的张量:
>>>p=tf.constant(["Café","Coffee","caffè","咖啡"])>>>tf.strings.length(p,unit="UTF8_CHAR")<tf.Tensor: shape=(4,), dtype=int32, numpy=array([4, 6, 5, 2], dtype=int32)>>>>r=tf.strings.unicode_decode(p,"UTF8")>>>r<tf.RaggedTensor [[67, 97, 102, 233], [67, 111, 102, 102, 101, 101], [99, 97,102, 102, 232], [21654, 21857]]>
请注意,解码后的字符串存储在 ...
Read now
Unlock full access