如何使用Python将Illiad数据集中的标记化单词转换为整数?
Tensorflow是谷歌提供的机器学习框架。它是一个开源框架,与Python一起使用来实现算法、深度学习应用等等。它被用于研究和生产目的。
下面的代码可以在Windows上安装’tensorflow’包 –
pip install tensorflow
Tensor是TensorFlow中使用的数据结构。它帮助连接流程图中的边缘。这个流程图被称为”Data flow graph”。张量只是一个多维数组或列表。
它们可以用三个主要属性来确定 –
- 排名(Rank) - 它告诉张量的维度。它可以被理解为定义的张量的阶数或维数的数量。
-
类型(Type) - 它告诉与张量元素相关联的数据类型。可以是一维张量,二维张量或n维张量。
-
形状(Shape) - 它是行和列的数量总和。
我们将使用Illiad数据集,该数据集包含三部翻译作品的文本数据,译者分别为William Cowper,Edward (Earl of Derby)和Samuel Butler。该模型被训练为在给定单行文本时识别翻译者。已对使用的文本文件进行了预处理。这包括删除文档标题和页脚、行号和章节标题。
我们使用Google Colaboratory来运行以下代码。Google Colab或Colaboratory可以在浏览器上运行Python代码,且无需任何配置和免费访问GPU(图形处理单元)。Colaboratory是在Jupyter笔记本之上构建的。
更多Python相关文章,请阅读:Python 教程
示例
以下是代码片段 –
keys = vocab
values = range(2, len(vocab) + 2) # reserve 0 for padding, 1 for OOV
print("Map the tokens to integers")
init = tf.lookup.KeyValueTensorInitializer(
keys, values, key_dtype=tf.string, value_dtype=tf.int64)
num_oov_buckets = 1
vocab_table = tf.lookup.StaticVocabularyTable(init, num_oov_buckets)
print("A function has been defined to standardize, tokenize and vectorize the dataset using tokenizer and lookup table")
def preprocess_text(text, label):
standardized = tf_text.case_fold_utf8(text)
tokenized = tokenizer.tokenize(standardized)
vectorized = vocab_table.lookup(tokenized)
return vectorized, label
代码来源:https://www.tensorflow.org/tutorials/load_data/text
输出
Map the tokens to integers
A function has been defined to standardize, tokenize and vectorize the dataset using tokenizer and lookup table
解释
-
使用vocab集创建StaticVocabularyTable。
-
标记被映射到范围内的整数[2,vocab_size + 2]。
-
数字0用于表示填充,1用于表示词汇表中没有的标记(OOV)。