如何使用 Python 和 TensorFlow 训练伊利亚特数据集?


TensorFlow 是 Google 提供的一个机器学习框架。它是一个开源框架,与 Python 结合使用可以实现算法、深度学习应用程序等等。它用于研究和生产目的。它具有优化技术,有助于快速执行复杂的数学运算。这是因为它使用了 NumPy 和多维数组。这些多维数组也称为“张量”。该框架支持与深度神经网络一起工作。

可以使用以下代码行在 Windows 上安装“tensorflow”包:

pip install tensorflow

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

我们将使用伊利亚特数据集,其中包含 William Cowper、Edward(Derby 伯爵)和 Samuel Butler 三个译本的文本数据。该模型经过训练,可以在给出单行文本时识别翻译者。所使用的文本文件已进行预处理。这包括删除文档页眉和页脚、行号和章节标题。

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

示例

以下是代码片段:

vocab_size += 2

print("Configure the dataset for better performance")
train_data = configure_dataset(train_data)
validation_data = configure_dataset(validation_data)

print("Train the model")
model = create_model(vocab_size=vocab_size, num_labels=3)
model.compile(
   optimizer='adam',
   loss=losses.SparseCategoricalCrossentropy(from_logits=True),
   metrics=['accuracy'])
print("Fit the training data to the model")
history = model.fit(train_data, validation_data=validation_data, epochs=3)

print("Finding the accuracy and loss associated with training")
loss, accuracy = model.evaluate(validation_data)

print("The loss is : ", loss)
print("The accuracy is : {:2.2%}".format(accuracy))

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

输出

Configure the dataset for better performance
Train the model
Fit the training data to the model
Epoch 1/3
697/697 [==============================] - 35s 17ms/step - loss: 0.6891 - accuracy: 0.6736 -
val_loss: 0.3718 - val_accuracy: 0.8404
Epoch 2/3
697/697 [==============================] - 8s 11ms/step - loss: 0.3149 - accuracy: 0.8713 -
val_loss: 0.3621 - val_accuracy: 0.8422
Epoch 3/3
697/697 [==============================] - 8s 11ms/step - loss: 0.2165 - accuracy: 0.9162 -
val_loss: 0.4002 - val_accuracy: 0.8404
Finding the accuracy and loss associated with training
79/79 [==============================] - 1s 2ms/step - loss: 0.4002 - accuracy: 0.8404
The loss is : 0.40021833777427673
The accuracy is : 84.04%

解释

  • 该模型在预处理的矢量化数据集上进行训练。

  • 完成后,将其编译并拟合到模型中。

  • 使用“evaluate”方法评估与模型相关的损失和准确性。

  • 此数据显示在控制台上。

更新于:2021年1月19日

86 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.