基于Google Cloud Platform训练数据分析师项目的文本分类实战教程

基于Google Cloud Platform训练数据分析师项目的文本分类实战教程

training-data-analyst Labs and demos for courses for GCP Training (http://cloud.google.com/training). training-data-analyst 项目地址: https://gitcode.com/gh_mirrors/tr/training-data-analyst

概述

本教程将带领读者从零开始构建一个情感分析模型,使用TensorFlow框架对IMDB电影评论数据集进行二分类(正面/负面评价)。我们将完整覆盖从数据准备到模型评估的整个机器学习流程。

学习目标

通过本教程,您将掌握以下核心技能:

  1. 文本数据的标准化处理方法
  2. 使用TensorFlow构建文本分类模型
  3. 模型训练与评估技巧
  4. 实际应用中的最佳实践

环境准备

首先确保已安装TensorFlow 2.x版本。我们推荐使用2.6或更高版本以获得最佳性能。

import tensorflow as tf
from tensorflow.keras import layers, losses
import matplotlib.pyplot as plt
import os
import re
import string

print(tf.__version__)  # 确认TensorFlow版本

数据集介绍

我们将使用斯坦福大学提供的大型电影评论数据集,包含来自IMDB的50,000条电影评论,其中25,000条用于训练,25,000条用于测试。数据集已经平衡,包含等量的正面和负面评价。

数据加载与探索

下载数据集

url = "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
dataset = tf.keras.utils.get_file("aclImdb_v1", url, untar=True, cache_dir='.')
dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')

数据集结构

数据集目录包含:

  • train/pos: 正面评价文本文件
  • train/neg: 负面评价文本文件
  • test: 对应的测试集
train_dir = os.path.join(dataset_dir, 'train')
print(os.listdir(train_dir))  # 查看训练目录内容

查看样本数据

sample_file = os.path.join(train_dir, 'pos/1181_9.txt')
with open(sample_file) as f:
    print(f.read())  # 打印一个正面评价样本

数据预处理

创建TensorFlow数据集

使用text_dataset_from_directory工具从目录结构创建标记数据集:

batch_size = 32
seed = 42

# 创建训练集(80%)和验证集(20%)
raw_train_ds = tf.keras.utils.text_dataset_from_directory(
    'aclImdb/train',
    batch_size=batch_size,
    validation_split=0.2,
    subset='training',
    seed=seed)

raw_val_ds = tf.keras.utils.text_dataset_from_directory(
    'aclImdb/train',
    batch_size=batch_size,
    validation_split=0.2,
    subset='validation',
    seed=seed)

# 创建测试集
raw_test_ds = tf.keras.utils.text_dataset_from_directory(
    'aclImdb/test',
    batch_size=batch_size)

数据标准化

我们需要自定义标准化函数处理HTML标签等特殊字符:

def custom_standardization(input_data):
    lowercase = tf.strings.lower(input_data)  # 转为小写
    stripped_html = tf.strings.regex_replace(lowercase, '<br />', ' ')  # 移除HTML标签
    return tf.strings.regex_replace(stripped_html,
                                  '[%s]' % re.escape(string.punctuation),
                                  '')  # 移除标点符号

构建文本向量化层

使用TextVectorization层将文本转换为数值表示:

max_features = 10000  # 词汇表大小
sequence_length = 250  # 序列长度

vectorize_layer = layers.TextVectorization(
    standardize=custom_standardization,
    max_tokens=max_features,
    output_mode='int',
    output_sequence_length=sequence_length)

适配词汇表

# 只使用训练文本生成词汇表
train_text = raw_train_ds.map(lambda x, y: x)
vectorize_layer.adapt(train_text)

构建模型

我们使用嵌入层+全局平均池化+全连接层的经典结构:

model = tf.keras.Sequential([
    vectorize_layer,  # 文本向量化层
    layers.Embedding(max_features, 16),  # 嵌入层
    layers.GlobalAveragePooling1D(),  # 全局平均池化
    layers.Dense(16, activation='relu'),  # 全连接层
    layers.Dense(1)  # 输出层
])

model.compile(
    optimizer='adam',
    loss=losses.BinaryCrossentropy(from_logits=True),
    metrics=['accuracy'])

模型训练

epochs = 10
history = model.fit(
    raw_train_ds,
    validation_data=raw_val_ds,
    epochs=epochs)

模型评估

loss, accuracy = model.evaluate(raw_test_ds)
print("Test Accuracy:", accuracy)

可视化训练过程

history_dict = history.history
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

epochs = range(1, len(acc) + 1)

# 绘制准确率曲线
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

# 绘制损失曲线
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

模型导出与应用

训练完成后,我们可以导出模型用于生产环境:

export_model = tf.keras.Sequential([
    vectorize_layer,
    model,
    layers.Activation('sigmoid')
])

export_model.compile(
    loss=losses.BinaryCrossentropy(from_logits=False),
    optimizer="adam",
    metrics=['accuracy'])

# 测试导出模型
examples = [
    "The movie was great!",
    "The movie was okay.",
    "The movie was terrible..."
]

print(export_model.predict(examples))

总结

本教程完整展示了使用TensorFlow进行文本分类的流程,从数据准备到模型部署。关键点包括:

  1. 文本数据的标准化处理
  2. 使用TextVectorization层进行高效文本处理
  3. 简单的神经网络结构即可获得良好效果
  4. 注意训练-验证-测试集的分割

这种技术可广泛应用于客户评论分析、社交媒体监控等各种文本分类场景。

training-data-analyst Labs and demos for courses for GCP Training (http://cloud.google.com/training). training-data-analyst 项目地址: https://gitcode.com/gh_mirrors/tr/training-data-analyst

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黎纯俪Forest

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值