文本分类是自然语言处理中的一个基本任务,它涉及将文本数据分配到预定义的类别中。本教程将介绍如何使用 TensorFlow 实现文本分类。

简介

文本分类是将文本数据分配到预定义类别的过程。例如,你可以将新闻文章分类为“体育”、“政治”或“娱乐”等类别。

工具和库

  • TensorFlow
  • NumPy
  • Pandas

数据准备

在开始之前,你需要准备一些文本数据和相应的标签。以下是一个简单的例子:

texts = ["This is a sports news", "This is a political news", "This is an entertainment news"]
labels = [0, 1, 2]

模型构建

以下是一个简单的文本分类模型的示例:

import tensorflow as tf

model = tf.keras.Sequential([
    tf.keras.layers.Embedding(input_dim=10000, output_dim=16, input_length=100),
    tf.keras.layers.GlobalAveragePooling1D(),
    tf.keras.layers.Dense(24, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

训练模型

使用以下代码来训练模型:

model.fit(texts, labels, epochs=10)

验证模型

在训练完成后,你可以使用以下代码来验证模型的性能:

loss, accuracy = model.evaluate(texts, labels)
print("Accuracy:", accuracy)

扩展阅读

想要了解更多关于 TensorFlow 的信息,请访问我们的 TensorFlow 教程 页面。

相关资源

TensorFlow Logo