python搭建NPL模型的详细步骤和代码

Python 搭建 NLP 模型完整详细教程(2026 保姆级)
—— 以“中文情感分析模型”为例

你好!“NPL模型”我理解为 NLP(Natural Language Processing,自然语言处理)模型 的笔误(非常常见),如果不是请立刻告诉我。

下面给你一套从 0 到 1 可直接运行的完整教程,2026 年最推荐的方案是 Hugging Face Transformers,因为:

  • 代码最简洁(几行就能跑通)
  • 支持中文极好
  • 自动处理分词、训练、评估、部署
  • 社区模型最丰富

一、推荐学习路径(建议顺序)

  1. 先用 pipeline 零代码跑通(5 分钟见效果)
  2. 再完整微调一个模型(掌握全流程)
  3. 最后部署成 API(可选)

我们今天直接走 第 2 步完整微调中文情感分析模型(基于 bert-base-chinese)

二、完整步骤 + 可复制代码

步骤 1:环境准备(推荐新建虚拟环境)

# 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

步骤 2:准备数据(使用公开中文数据集)

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])

步骤 3:数据预处理(Tokenizer)

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)

步骤 4:加载模型 + 设置训练参数

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"
)

步骤 5:开始训练(核心代码)

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)

步骤 6:保存模型 & 推理测试

# 保存模型
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

四、常见问题 & 优化建议(2026 经验)

问题解决方案
显存不够改小 batch_size=8 或用 torch.cuda.empty_cache()
中文效果差换用 hfl/chinese-bert-wwm-extchinese-roberta-wwm-ext
想更快训练--fp16(混合精度)或用 unsloth 加速微调
部署成 API用 FastAPI + pipeline(下节课可讲)
多分类/多标签num_labels 改成对应类别数即可

五、下一步建议

  1. 今天就把上面代码跑通(CPU 也只需要 10–30 分钟)
  2. 换成你自己的数据集(电商评论、电影短评等)
  3. 尝试其他任务:文本分类、命名实体识别、机器翻译

你现在最想继续哪一步?

A. 完整 FastAPI 部署代码(把模型变成网页接口)
B. 用自己的 Excel/CSV 数据集微调
C. 换成更强的模型(Qwen2.5、DeepSeek 等)
D. 从零手写一个简单 Transformer(原理向)
E. 其他任务(命名实体、文本生成、问答等)

回复字母或直接告诉我你的需求,我立刻给你对应完整代码~ 😄

文章已创建 4758

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部