如何使用Tensorflow和Python编码多个长度相同的字符串?


可以使用“tf.Tensor”作为输入值来编码多个长度相同的字符串。当需要编码多个长度不同的字符串时,应使用tf.RaggedTensor作为输入。如果张量包含以填充/稀疏格式存储的多个字符串,则需要将其转换为tf.RaggedTensor。然后,应该在其上调用unicode_encode方法。

阅读更多: 什么是TensorFlow以及Keras如何与TensorFlow一起创建神经网络?

让我们了解如何使用Python表示Unicode字符串,以及如何使用Unicode等价物来操作这些字符串。首先,我们借助标准字符串操作的Unicode等价物,根据脚本检测将Unicode字符串分成标记。

我们正在使用Google Colaboratory运行以下代码。Google Colab或Colaboratory帮助通过浏览器运行Python代码,无需任何配置,并且可以免费访问GPU(图形处理单元)。Colaboratory构建在Jupyter Notebook之上。

print("When encoding multiple strings of   same lengths, tf.Tensor is used as input")
tf.strings.unicode_encode([[99, 97, 116], [100, 111, 103], [ 99, 111, 119]],output_encoding='UTF-8')
print("When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:")
tf.strings.unicode_encode(batch_chars_ragged, output_encoding='UTF-8')
print("If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode")
tf.strings.unicode_encode(
   tf.RaggedTensor.from_sparse(batch_chars_sparse),
   output_encoding='UTF-8')
tf.strings.unicode_encode(
   tf.RaggedTensor.from_tensor(batch_chars_padded, padding=-1),
   output_encoding='UTF-8')

代码来源:https://tensorflowcn.cn/tutorials/load_data/unicode

输出

When encoding multiple strings of   same lengths, tf.Tensor is used as input
When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:
If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode

解释

  • 在编码多个长度相同的字符串时,可以使用tf.Tensor作为输入。
  • 在编码多个长度不同的字符串时,可以使用tf.RaggedTensor作为输入。
  • 如果存在一个包含以填充/稀疏格式存储的多个字符串的张量,则需要在对其调用unicode_encode之前将其转换为tf.RaggedTensor。

更新于: 2021年2月20日

214次查看

开启你的职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.