本文目录导读:

我将为你提供一个完整的 FastText 文本分类 Python 案例,FastText 是 Facebook 开发的一个高效文本分类工具。
环境安装
pip install fasttext pip install pandas pip install scikit-learn
完整代码实现
数据准备与预处理
import pandas as pd
import numpy as np
import fasttext
import fasttext.util
import re
import jieba
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score
# 设置随机种子
np.random.seed(42)
class FastTextClassifier:
def __init__(self):
self.model = None
def clean_text(self, text):
"""文本清洗"""
# 移除特殊字符和数字
text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z\s]', '', text)
# 转换为小写
text = text.lower()
# 去除多余空格
text = ' '.join(text.split())
return text
def tokenize_chinese(self, text):
"""中文分词"""
return ' '.join(jieba.cut(text))
def preprocess_data(self, texts, labels=None, is_chinese=True):
"""数据预处理"""
processed_texts = []
for text in texts:
# 清洗文本
text = self.clean_text(text)
# 如果是中文,进行分词
if is_chinese:
text = self.tokenize_chinese(text)
processed_texts.append(text)
# 如果有标签,返回标签和文本
if labels is not None:
return processed_texts, labels
return processed_texts
def prepare_fasttext_data(self, texts, labels, output_file='train.txt'):
"""准备FastText训练数据"""
with open(output_file, 'w', encoding='utf-8') as f:
for text, label in zip(texts, labels):
# FastText格式:__label__标签 文本
line = f'__label__{label} {text}\n'
f.write(line)
print(f"数据已保存到 {output_file}")
return output_file
# 创建示例数据集
def create_sample_data():
"""创建示例数据集"""
texts = [
"这部电影太精彩了,剧情紧凑,演员演技出色",
"产品性价比很高,值得购买",
"服务质量很差,客服态度不好",
"这个手机电池续航能力很强",
"今天天气真不错,适合出去游玩",
"这家餐厅的菜品味道一般,价格偏贵",
"学习编程可以提高逻辑思维能力",
"这个软件操作简单,功能强大",
"快递速度很快,包装也很完好",
"这篇文章内容空洞,没有什么实质内容"
]
labels = [
"positive",
"positive",
"negative",
"positive",
"positive",
"negative",
"neutral",
"positive",
"positive",
"negative"
]
return texts, labels
# 生成数据
texts, labels = create_sample_data()
# 创建分类器实例
classifier = FastTextClassifier()
# 预处理数据
processed_texts, processed_labels = classifier.preprocess_data(texts, labels)
# 分割数据集
train_texts, test_texts, train_labels, test_labels = train_test_split(
processed_texts, processed_labels, test_size=0.2, random_state=42
)
# 准备FastText训练数据
classifier.prepare_fasttext_data(train_texts, train_labels, 'train.txt')
classifier.prepare_fasttext_data(test_texts, test_labels, 'test.txt')
训练模型
# 训练FastText模型
print("开始训练模型...")
classifier.model = fasttext.train_supervised(
input='train.txt',
lr=1.0, # 学习率
epoch=25, # 训练轮数
wordNgrams=2, # 词N-gram
dim=100, # 词向量维度
loss='softmax', # 损失函数
minCount=1, # 最小词频
minn=1, # 字符n-gram的最小长度
maxn=6, # 字符n-gram的最大长度
bucket=2000000, # 字符n-gram的哈希桶数
thread=4, # 线程数
verbose=1 # 是否显示训练信息
)
# 保存模型
classifier.model.save_model("fasttext_model.bin")
print("模型训练完成并保存!")
模型评估
# 计算训练集准确率
train_result = classifier.model.test('train.txt')
print(f"训练集准确率: {train_result[1]:.4f}")
# 计算测试集准确率
test_result = classifier.model.test('test.txt')
print(f"测试集准确率: {test_result[1]:.4f}")
# 测试单个文本
def predict_text(classifier, text):
"""预测单个文本的情感"""
processed_text = classifier.clean_text(text)
processed_text = classifier.tokenize_chinese(processed_text)
if classifier.model is None:
raise ValueError("模型未加载")
# 预测
prediction = classifier.model.predict(processed_text, k=3)
labels, probabilities = prediction
print(f"\n文本: {text}")
print("预测结果:")
for label, prob in zip(labels, probabilities):
print(f" {label.replace('__label__', '')}: {prob:.4f}")
return labels[0].replace('__label__', ''), probabilities[0]
# 测试预测
test_sentences = [
"这个产品非常好用,强烈推荐",
"服务太差了,再也不来了",
"一般般吧,没什么特别"
]
for sentence in test_sentences:
predict_text(classifier, sentence)
批量预测与混淆矩阵
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
def batch_predict(classifier, texts, true_labels):
"""批量预测并生成报告"""
predictions = []
probabilities = []
for text in texts:
pred_label, prob = predict_text(classifier, text)
predictions.append(pred_label)
probabilities.append(prob)
# 生成分类报告
print("\n分类报告:")
print(classification_report(true_labels, predictions))
# 计算准确率
accuracy = accuracy_score(true_labels, predictions)
print(f"准确率: {accuracy:.4f}")
# 绘制混淆矩阵
cm = confusion_matrix(true_labels, predictions, labels=['positive', 'negative', 'neutral'])
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['positive', 'negative', 'neutral'],
yticklabels=['positive', 'negative', 'neutral'])
plt.title('混淆矩阵')
plt.xlabel('预测标签')
plt.ylabel('真实标签')
plt.show()
return predictions, probabilities
# 执行批量预测
batch_predict(classifier, test_texts, test_labels)
参数调优
def parameter_tuning(train_file, test_file):
"""FastText参数调优"""
best_accuracy = 0
best_params = {}
# 测试不同参数组合
learning_rates = [0.1, 0.5, 1.0]
dimensions = [50, 100, 200]
epochs = [10, 25, 50]
for lr in learning_rates:
for dim in dimensions:
for epoch in epochs:
print(f"测试参数: lr={lr}, dim={dim}, epoch={epoch}")
model = fasttext.train_supervised(
input=train_file,
lr=lr,
dim=dim,
epoch=epoch,
wordNgrams=2,
loss='softmax'
)
result = model.test(test_file)
accuracy = result[1]
print(f"准确率: {accuracy:.4f}")
if accuracy > best_accuracy:
best_accuracy = accuracy
best_params = {
'lr': lr,
'dim': dim,
'epoch': epoch
}
print(f"\n最佳参数: {best_params}")
print(f"最佳准确率: {best_accuracy:.4f}")
return best_params
# 执行参数调优(可选,数据量大时执行)
# best_params = parameter_tuning('train.txt', 'test.txt')
完整使用示例
# 完整的FastText分类器使用示例
def main():
# 1. 创建数据
texts, labels = create_sample_data()
# 2. 初始化分类器
classifier = FastTextClassifier()
# 3. 预处理数据
processed_texts, processed_labels = classifier.preprocess_data(texts, labels)
# 4. 分割数据
train_texts, test_texts, train_labels, test_labels = train_test_split(
processed_texts, processed_labels, test_size=0.3, random_state=42
)
# 5. 准备训练数据
classifier.prepare_fasttext_data(train_texts, train_labels, 'train.txt')
classifier.prepare_fasttext_data(test_texts, test_labels, 'test.txt')
# 6. 训练模型
print("训练模型...")
classifier.model = fasttext.train_supervised(
input='train.txt',
lr=1.0,
epoch=50,
wordNgrams=3,
dim=100
)
# 7. 评估模型
print("\n模型评估结果:")
print(f"测试集准确率: {classifier.model.test('test.txt')[1]:.4f}")
# 8. 使用模型进行预测
new_texts = [
"这次购物体验非常愉快",
"产品做工粗糙,不值得这个价格",
"内容还不错,但需要改进"
]
print("\n新文本预测:")
for text in new_texts:
predict_text(classifier, text)
# 9. 保存和加载模型
classifier.model.save_model("final_model.bin")
print("\n模型已保存为 final_model.bin")
# 重新加载模型
loaded_model = fasttext.load_model("final_model.bin")
print("模型加载成功!")
if __name__ == "__main__":
main()
重要参数说明
| 参数 | 说明 | 推荐值 |
|---|---|---|
| lr | 学习率 | 1-1.0 |
| dim | 词向量维度 | 100-300 |
| epoch | 训练轮数 | 10-50 |
| wordNgrams | 词N-gram | 2-3 |
| minCount | 最小词频 | 1-5 |
| loss | 损失函数 | 'softmax', 'ns' |
注意事项
- 数据质量:确保训练数据质量,标签准确
- 中文分词:中文文本需要进行分词处理
- 模型优化:根据数据集大小调整参数
- 硬件要求:大数据集需要较好的硬件支持
这个完整的 FastText 分类案例可以直接使用,你可以根据实际需求调整数据和参数。