如何使用Tensorflow和Python从单词列表中构建不规则张量?
通过使用句子中单词的起始偏移量可以构建RaggedTensor。首先,构建句子中每个单词中每个字符的代码点。接下来,打印出它们。确定该特定句子中的单词数量和偏移量。
使用Python表示Unicode字符串,并使用Unicode等效物来操作这些字符串。首先,我们将Unicode字符串根据脚本检测分成标记,使用标准字符串操作的Unicode等效物来获取。
我们使用Google Colaboratory来运行下面的代码。 Google Colab或Colaboratory可以在浏览器上运行Python代码,不需要任何配置,并且可以免费访问GPU(图形处理器)。 Colaboratory是基于Jupyter Notebook构建的。
print(“获取每个单词中每个字符的代码点”)
word_char_codepoint = tf.RaggedTensor.from_row_starts(
values=sentence_char_codepoint.values,
row_starts=word_starts)
print(word_char_codepoint)
print(“获取特定句子中的单词数量”)
sentence_num_words = tf.reduce_sum(tf.cast(sentence_char_starts_word, tf.int64), axis=1)
代码来源: https://www.tensorflow.org/tutorials/load_data/unicode
更多Python相关文章,请阅读:Python 教程
输出
获取每个单词中每个字符的代码点
<tf.RaggedTensor [[72, 101, 108, 108, 111], [44, 32], [116, 104, 101, 114, 101], [46], [19990, 30028], [12371, 12435, 12395, 12385, 12399]]>
获取特定句子中的单词数量
解释
- 构建了每个单词中每个字符的代码点。
- 将它们打印出来。
- 确定该特定句子中的单词数量。
极客教程