基于pytorch_bert的中文多标签分类运行bug笔记

发布于:2025-02-27 ⋅ 阅读:(29) ⋅ 点赞:(0)

项目地址:https://github.com/taishan1994/pytorch_bert_multi_classification/tree/main
在这里插入图片描述

编码解释设置错误

Traceback (most recent call last):
  File "main.py", line 192, in <module>
    labels = fp.read().strip().split('\n')
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa5 in position 233: illegal multibyte sequence

修改文件读取时的编码方式(已解决)

在 main.py 中找到读取标签文件或数据文件的代码(第 192 行附近),添加 encoding=‘utf-8’ 参数

# 修改前(可能没有指定编码)
with open(label_path, 'r') as fp:
    labels = fp.read().strip().split('\n')

# 修改后(强制使用 UTF-8 编码)
with open(label_path, 'r', encoding='utf-8') as fp:  # 关键修改
    labels = fp.read().strip().split('\n')

下载装入Bert模型

步骤一:访问 HuggingFace 模型页面
打开浏览器,访问 bert-base-chinese 模型页面:
https://huggingface.co/bert-base-chinese/tree/main
📥 步骤二:下载必需文件
在模型页面中找到以下三个文件,逐个下载:

  1. vocab.txt
    点击文件列表中的 vocab.txt → 点击右侧的 ↓ Download 按钮。
    保存文件到本地。
  2. config.json
    点击文件列表中的 config.json → 点击右侧的 ↓ Download 按钮。
    保存文件到本地。
  3. pytorch_model.bin
    点击文件列表中的 pytorch_model.bin → 点击右侧的 ↓ Download 按钮。
    保存文件到本地。
    步骤三:创建模型目录并保存文件
    创建目录结构:
    根据你的项目参数 --bert_dir="../model_hub/bert-base-chinese/",模型文件需存放在 上级目录的 model_hub 文件夹 中。
    假设你的项目根目录是 E:\PyProject\pytorch_bert_multi_classification-main,则模型目录应为:
E:\PyProject\model_hub\bert-base-chinese\  # 注意是上级目录!

移动下载的文件:
将下载的三个文件(vocab.txt, config.json, pytorch_model.bin)复制到 E:\PyProject\model_hub\bert-base-chinese\ 目录中。

E:\PyProject
├─pytorch_bert_multi_classification-main  # 项目根目录
│  ├─main.py
│  ├─data/
│  └─...
│
└─model_hub                                # 上级目录中的 model_hub
   └─bert-base-chinese
      ├─vocab.txt
      ├─config.json
      └─pytorch_model.bin

🚀 最终运行命令

python main.py --bert_dir="../model_hub/bert-base-chinese/" --data_dir="./data/final_data/" --log_dir="./logs/" --output_dir="./checkpoints/" --num_tags=65 --seed=123 --gpu_ids="0" --max_seq_len=128 --lr=3e-5 --other_lr=3e-4 --train_batch_size=32 --train_epochs=5 --eval_batch_size=32