pytorch evaluate model(torch.no_grad() and model.eval())

  • 使用 torch.no_grad():这是一个上下文管理器(context manager),用于暂时禁用在其作用域内的所有计算的梯度计算。这在模型评估阶段非常有用,因为它可以减少内存消耗并提高计算效率,因为验证过程中不需要计算梯度信息。

  • 调用 model.eval():这将模型设置为评估模式。在这种模式下,模型中的某些层(如批量归一化层 BatchNorm 和 dropout 层)会改变其行为,以适应评估(例如,BatchNorm 层会使用在训练时收集的运行时统计数据,而 dropout 层会关闭)。

py 复制代码
import torch
from torch.utils.data import DataLoader
from sklearn.metrics import accuracy_score

def evaluate_model(model, data_loader, device):
    """
    对给定的模型和数据加载器进行验证。
    
    参数:
    - model: 要验证的PyTorch模型。
    - data_loader: 数据的PyTorch DataLoader。
    - device: 用于模型和数据的设备('cuda' 或 'cpu')。
    """
    # 将模型设置为评估模式,这会关闭dropout和batch normalization层的训练行为
    model.eval()
    
    # 初始化度量指标
    total_correct = 0
    total_samples = 0
    
    # 使用torch.no_grad()上下文管理器来禁用梯度计算
    with torch.no_grad():
       # 遍历数据加载器中的所有批次
        for inputs, targets in data_loader:
            # 将数据移动到指定的设备
            inputs, targets = inputs.to(device), targets.to(device)
            
            # 前向传播,获取模型输出
            outputs = model(inputs)
            
            # 计算预测结果
            _, predicted = torch.max(outputs, 1)
            
            # 计算准确度
            correct = (predicted == targets).sum().item()
            
            total_correct += correct
            total_samples += targets.size(0)
    
    # 计算总体准确度
    accuracy = total_correct / total_samples
    
    return accuracy
相关推荐
m4Rk_43 分钟前
【论文阅读】Agent 记忆机制(83):Inside Out——用可演化 PersonaTree 构建 Agent 的核心长期记忆
论文阅读·人工智能·学习·开源·github
运行时异常1 小时前
【WMS 仓储系统集成 AI Agent 实战】第 8 讲(终篇):生产部署与并发安全——Semaphore 放进 Flux.defer 的坑,压测抓了一晚上
人工智能·安全
杨杨杨大侠1 小时前
Jev、Kev、Laya:决策模型怎么选,什么时候需要微调?
人工智能·python·agent
代码方舟1 小时前
零信任架构实战:基于天远人企关联构建自动化供应链金融网关
运维·人工智能·架构·自动化
虹科网络安全1 小时前
“顶会”看安全(十八):超越越狱:揭示由能力边界模糊引发的 LLM 应用安全风险
人工智能·安全
LOVE️YOU1 小时前
Python 在定义函数时,究竟定义的是什么?
python
Maiko Star2 小时前
* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性
java·人工智能·langchain
段一凡-华北理工大学2 小时前
大模型应用开发 100 天:Python + LLM 从入门到精通 day26~Prompt 调试与优化——A/B 测试与效果评估
windows·python·大模型·prompt·智能体·提示词工程·高炉智能化
Minecraft红客2 小时前
以撒的结合
python·游戏·电脑·娱乐
鬓戈2 小时前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust