文章目录
- # 1. 创建虚拟环境 conda create -n nlp python=3.11 -y conda activate nlp # 2. 安装核心库(2026 年推荐组合) pip install torch torchvision torchaudio –index-url https://download.pytorch.org/whl/cpu # CPU版(有GPU换cuda版本) pip install transformers datasets accelerate evaluate pandas scikit-learn
- from datasets import load_dataset # 加载中文情感分析数据集(Seamew/ChnSentiCorp) dataset = load_dataset(“seamew/ChnSentiCorp”) print(dataset) # 输出:DatasetDict({ # train: Dataset({…}), # validation: Dataset({…}), # test: Dataset({…}) # }) # 查看前3条数据 print(dataset[“train”][0:3])
- from transformers import AutoTokenizer model_name = “bert-base-chinese” # 中文预训练模型 tokenizer = AutoTokenizer.from_pretrained(model_name) def preprocess_function(examples): return tokenizer(examples[“text”], truncation=True, # 超长自动截断 padding=”max_length”, # 统一长度 max_length=128) # 应用到整个数据集 tokenized_datasets = dataset.map(preprocess_function, batched=True)
- from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer import evaluate import numpy as np # 加载模型(2分类:正面/负面) model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2) # 评估指标(准确率 + F1) accuracy = evaluate.load(“accuracy”) f1 = evaluate.load(“f1″) def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) acc = accuracy.compute(predictions=predictions, references=labels) f1_score = f1.compute(predictions=predictions, references=labels, average=”macro”) return {“accuracy”: acc[“accuracy”], “f1”: f1_score[“f1″]} # 训练参数(可根据显存调整) training_args = TrainingArguments( output_dir=”./results”, # 输出目录 eval_strategy=”epoch”, # 每轮评估 save_strategy=”epoch”, learning_rate=2e-5, per_device_train_batch_size=16, per_device_eval_batch_size=16, num_train_epochs=3, # 建议 3-5 轮 weight_decay=0.01, logging_dir=”./logs”, report_to=”none”, # 不上传 wandb load_best_model_at_end=True, metric_for_best_model=”f1″ )
- trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_datasets[“train”], eval_dataset=tokenized_datasets[“validation”], compute_metrics=compute_metrics, tokenizer=tokenizer, # 自动保存 tokenizer ) print(“开始训练…”) trainer.train() # 训练结束后在测试集上评估 test_results = trainer.evaluate(tokenized_datasets[“test”]) print(“测试集结果:”, test_results)
- # 保存模型 trainer.save_model(“./my_chinese_sentiment_model”) tokenizer.save_pretrained(“./my_chinese_sentiment_model”) # 加载推理(最常用方式) from transformers import pipeline sentiment_pipeline = pipeline( “sentiment-analysis”, model=”./my_chinese_sentiment_model”, tokenizer=”./my_chinese_sentiment_model” ) # 测试 texts = [ “这家餐厅的服务态度非常好,菜也超级美味!”, “完全是浪费钱,东西难吃还贵,差评!”, “一般般吧,没什么特别的。” ] results = sentiment_pipeline(texts) for text, res in zip(texts, results): label = “正面” if res[“label”] == “LABEL_1” else “负面” print(f”文本: {text}n预测: {label} (置信度: {res[‘score’]:.4f})n”)
目录
- 一、推荐学习路径(建议顺序)
- 二、完整步骤 + 可复制代码
- 步骤 1:环境准备(推荐新建虚拟环境)
- 步骤 2:准备数据(使用公开中文数据集)
- 步骤 3:数据预处理(Tokenizer)
- 步骤 4:加载模型 + 设置训练参数
- 步骤 5:开始训练(核心代码)
- 步骤 6:保存模型 & 推理测试
- 三、完整项目结构推荐(中型项目)
- 四、常见问题 & 优化建议(2026 经验)
- 五、下一步建议
你好!“NPL模型”我理解为 NLP(Natural Language Processing,自然语言处理)模型 的笔误(非常常见),如果不是请立刻告诉我。
下面给你一套从 0 到 1 可直接运行的完整教程,2026 年最推荐的方案是 Hugging Face Transformers,因为:
- 代码最简洁(几行就能跑通)
- 支持中文极好
- 自动处理分词、训练、评估、部署
- 社区模型最丰富
- 先用 pipeline 零代码跑通(5 分钟见效果)
- 再完整微调一个模型(掌握全流程)
- 最后部署成 API(可选)
我们今天直接走 第 2 步:完整微调中文情感分析模型(基于 bert-base-chinese)
# 1. 创建虚拟环境
conda create -n nlp python=3.11 -y
conda activate nlp
# 2. 安装核心库(2026 年推荐组合)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu # CPU版(有GPU换cuda版本)
pip install transformers datasets accelerate evaluate pandas scikit-learn
from datasets import load_dataset
# 加载中文情感分析数据集(Seamew/ChnSentiCorp)
dataset = load_dataset("seamew/ChnSentiCorp")
print(dataset)
# 输出:DatasetDict({
# train: Dataset({...}),
# validation: Dataset({...}),
# test: Dataset({...})
# })
# 查看前3条数据
print(dataset["train"][0:3])
from transformers import AutoTokenizer
model_name = "bert-base-chinese" # 中文预训练模型
tokenizer = AutoTokenizer.from_pretrained(model_name)
def preprocess_function(examples):
return tokenizer(examples["text"],
truncation=True, # 超长自动截断
padding="max_length", # 统一长度
max_length=128)
# 应用到整个数据集
tokenized_datasets = dataset.map(preprocess_function, batched=True)
from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
import evaluate
import numpy as np
# 加载模型(2分类:正面/负面)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)
# 评估指标(准确率 + F1)
accuracy = evaluate.load("accuracy")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
acc = accuracy.compute(predictions=predictions, references=labels)
f1_score = f1.compute(predictions=predictions, references=labels, average="macro")
return {"accuracy": acc["accuracy"], "f1": f1_score["f1"]}
# 训练参数(可根据显存调整)
training_args = TrainingArguments(
output_dir="./results", # 输出目录
eval_strategy="epoch", # 每轮评估
save_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=3, # 建议 3-5 轮
weight_decay=0.01,
logging_dir="./logs",
report_to="none", # 不上传 wandb
load_best_model_at_end=True,
metric_for_best_model="f1"
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["validation"],
compute_metrics=compute_metrics,
tokenizer=tokenizer, # 自动保存 tokenizer
)
print("开始训练...")
trainer.train()
# 训练结束后在测试集上评估
test_results = trainer.evaluate(tokenized_datasets["test"])
print("测试集结果:", test_results)
# 保存模型
trainer.save_model("./my_chinese_sentiment_model")
tokenizer.save_pretrained("./my_chinese_sentiment_model")
# 加载推理(最常用方式)
from transformers import pipeline
sentiment_pipeline = pipeline(
"sentiment-analysis",
model="./my_chinese_sentiment_model",
tokenizer="./my_chinese_sentiment_model"
)
# 测试
texts = [
"这家餐厅的服务态度非常好,菜也超级美味!",
"完全是浪费钱,东西难吃还贵,差评!",
"一般般吧,没什么特别的。"
]
results = sentiment_pipeline(texts)
for text, res in zip(texts, results):
label = "正面" if res["label"] == "LABEL_1" else "负面"
print(f"文本: {text}n预测: {label} (置信度: {res['score']:.4f})n")
nlp_sentiment_project/
├── data/ # 原始数据
├── models/ # 保存的模型
├── results/ # 训练输出
├── logs/
├── main.py # 训练主文件
├── inference.py # 推理脚本
├── requirements.txt
└── README.md
| 问题 | 解决方案 |
|---|---|
| 显存不够 | 改小 batch_size=8 或用 torch.cuda.empty_cache() |
| 中文效果差 | 换用 hfl/chinese-bert-wwm-ext 或 chinese-roberta-wwm-ext |
| 想更快训练 | 加 --fp16(混合精度)或用 unsloth 加速微调 |
| 部署成 API | 用 FastAPI + pipeline(下节课可讲) |
| 多分类/多标签 | 把 num_labels 改成对应类别数即可 |
- 今天就把上面代码跑通(CPU 也只需要 10–30 分钟)
- 换成你自己的数据集(电商评论、电影短评等)
- 尝试其他任务:文本分类、命名实体识别、机器翻译
到此这篇关于Python搭建 NLP模型的详细步骤的文章就介绍到这了,更多相关Python搭建NLP模型内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- Python搭建NLP模型的步骤和代码详解
- Python机器学习NLP自然语言处理基本操作词向量模型
- Python机器学习NLP自然语言处理基本操作词袋模型