惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
腾讯CDC
IT之家
IT之家
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
U
Unit 42
爱范儿
爱范儿
博客园 - 聂微东
F
Fortinet All Blogs
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
L
LangChain Blog
雷峰网
雷峰网
B
Blog RSS Feed
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Engineering at Meta
Engineering at Meta
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - VipSoft

FastAPI 全局 HTTP 异常处理器 + 统一响应封装 SpringBoot 心跳日志不记录 access.log Qdrant Linux 安装(非Docker) LangChain — RAG 知识库(实操) LangChain — RAG 构建知识库(理论) LangChain — RAG 构建知识库(实操) Python PyCharm 运行,取不到 .env 文件中的值 Qdrant 安装(Windows) LangChain — RAG 构建知识库 Python 项目简单部署(Linux) MinerU - 将非结构化文档(PDF、图片、Office 文件等)转换为机器可读的 Markdown 和 JSON LangChain 入门 服务端部署-FastAPI LangChain 入门 LangSmith LangChain 入门 实战 - 食谱推荐 LangChain 入门 Memory 会话记忆 LangChain 入门 Tools 工具 LangChain 入门 Tools 工具 LangChain 入门 Prompts 提示词 LangChain 入门 Message 消息 LangChain 入门 Model 的初始化和调用 LangChain 入门 Agent 的基本运行机制 AI 0基础学习,名词解析 LangChain 和 LangGraph AI大模型知识体系 Dify — Workflow - 数据可视化 Dify — 连接MySQL配置 Dify — Chatflow - 数据库智能查询 Dify — Chatflow - 文档知识库 Dify — Agent 智能体 高安全券码、注册码生成
跟着AI学AI - 诊断结论信息抽取 - 模型评估与调试
VipSoft · 2026-05-11 · via 博客园 - VipSoft
# 设置镜像源的环境变量
(vippython) PS D:\OpenSource\Python\VipPython> $env:HF_ENDPOINT = "https://hf-mirror.com"
# 添加依赖
(vippython) PS D:\OpenSource\Python\VipPython\information_extraction> uv add pandas
# 切换下目录,否则会报文件不存在
(vippython) PS D:\OpenSource\Python\VipPython> cd D:\OpenSource\Python\VipPython\information_extraction
(vippython) PS D:\OpenSource\Python\VipPython\information_extraction> uv run .\evaluate_model.py

evaluate_model.py

# 模型评估和测试
import json
import os
import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification
from seqeval.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score
import pandas as pd


def evaluate_model(model_dir, test_file):
    """评估模型性能"""
    print("=" * 60)
    print("模型评估")
    print("=" * 60)

    # 1. 加载模型和tokenizer
    tokenizer = AutoTokenizer.from_pretrained(model_dir)
    model = AutoModelForTokenClassification.from_pretrained(model_dir)
    model.eval()

    # 2. 加载测试数据
    with open(test_file, 'r', encoding='utf-8') as f:
        test_data = json.load(f)

    # 3. 加载标签映射
    with open(os.path.join(model_dir, 'id2label.json'), 'r', encoding='utf-8') as f:
        id2label = json.load(f)
        id2label = {int(k): v for k, v in id2label.items()}

    label2id = {v: k for k, v in id2label.items()}

    # 4. 预测
    predictions = []
    references = []

    with torch.no_grad():
        for item in test_data[:50]:  # 测试前50个
            input_ids = torch.tensor(item['input_ids']).unsqueeze(0)
            attention_mask = torch.tensor(item['attention_mask']).unsqueeze(0)

            outputs = model(input_ids, attention_mask=attention_mask)
            preds = torch.argmax(outputs.logits, dim=2)

            # 转换预测
            pred_labels = [id2label[p.item()] for p in preds[0]]
            true_labels = [id2label[l] for l in item['labels'] if id2label[l] != 'O'][:len(pred_labels)]

            # 过滤特殊token
            pred_filtered = []
            true_filtered = []
            for p, l, attn in zip(pred_labels, item['labels'], attention_mask[0]):
                if attn == 1 and l != label2id['O']:
                    pred_filtered.append(p)
                    true_filtered.append(id2label[l])
                    break

            predictions.append(pred_filtered)
            references.append(true_filtered)

    # 5. 计算指标
    print("\n分类报告:")
    print(classification_report(references, predictions))

    print(f"准确率: {accuracy_score(references, predictions):.4f}")
    print(f"F1分数: {f1_score(references, predictions):.4f}")
    print(f"精确率: {precision_score(references, predictions):.4f}")
    print(f"召回率: {recall_score(references, predictions):.4f}")

    return predictions, references

if __name__ == "__main__":
    evaluate_model('./ecg_ner_model', 'data/out/bert_training_data.json')

image