Tensorflow如何使用Python将Illiad数据集中的标记化单词转换为整数?

Tensorflow是Google提供的一种机器学习框架。它是一个开放源代码框架,可与Python结合使用,以实现算法,深度学习应用程序等等。它用于研究和生产目的。

可以使用下面的代码行在Windows上安装'tensorflow'软件包-

pip install tensorflow

Tensor是TensorFlow中使用的数据结构。它有助于连接流程图中的边缘。该流程图称为“数据流程图”。张量不过是多维数组或列表。

可以使用三个主要属性来标识它们-

  • 等级-讲述张量的维数。可以理解为张量的顺序或已定义的张量中的维数。

  • 类型-它告诉与张量元素关联的数据类型。它可以是一维,二维或n维张量。

  • 形状-它是行和列的总数。

我们将使用Illiad的数据集,其中包含来自William Cowper,Edward(德比伯爵)和Samuel Butler的三本翻译作品的文本数据。当给出单行文本时,训练模型以识别翻译器。使用的文本文件已经过预处理。这包括删除文档的页眉和页脚,行号和章节标题。

我们正在使用Google合作实验室来运行以下代码。Google Colab或Colaboratory可以帮助通过浏览器运行Python代码,并且需要零配置和对GPU(图形处理单元)的免费访问。合作已建立在Jupyter Notebook的基础上。

示例

以下是代码片段-

keys = vocab
values = range(2, len(vocab) + 2) # 为填充保留0,为OOV保留1
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)令牌。

猜你喜欢