深度学习训练八股

一、模型中的函数的定义

1.torchmetrics.AUROC

(1).binary
复制代码
>>> from torch import tensor
>>> preds = tensor([0.13, 0.26, 0.08, 0.19, 0.34])
>>> target = tensor([0, 0, 1, 1, 1])
>>> auroc = AUROC(task="binary")
>>> auroc(preds, target)
tensor(0.5000)
(2).multiclass
复制代码
>>> preds = tensor([[0.90, 0.05, 0.05],
...                       [0.05, 0.90, 0.05],
...                       [0.05, 0.05, 0.90],
...                       [0.85, 0.05, 0.10],
...                       [0.10, 0.10, 0.80]])
>>> target = tensor([0, 1, 1, 2, 2])
>>> auroc = AUROC(task="multiclass", num_classes=3)
>>> auroc(preds, target)
tensor(0.7778)

注意函数中average参数的默认值为"macro"。

二、test_k_fold_test_copy.py---.logs_k_fold/result_draw

复制代码
# Test script
def test(model, test_loader, writer, device,criterion,roc_path,fold):
    model.eval()
    accuracy = Accuracy(task='multiclass', num_classes=2).to(device)
    precision = Precision(task='multiclass', average='macro', num_classes=2).to(device)
    recall = Recall(task='multiclass', average='macro', num_classes=2).to(device)
    auroc = AUROC(task='multiclass',num_classes=2).to(device)
    f1 = F1Score(num_classes=2, task='multiclass', average='macro').to(device)
    specificity=Specificity(num_classes=2, task='multiclass', average='macro').to(device)

    pred_scores = [] 
    true_labels = []
    pred_labels = []
    

    fold_results={}
    with torch.no_grad():
        for images, coords, labels, _, _  in test_loader:
            images = images.to(device)
            labels = labels.to(device) 
            outputs = model(images,coords)
            _, predicted = torch.max(outputs.data, 1)
                    
            accuracy(predicted, labels.data)
            precision(predicted, labels.data)
            recall(predicted, labels.data)
            f1(predicted, labels.data)
            #auroc(predicted, labels.data)
            specificity(predicted, labels.data)
            auroc(outputs, labels.data)
            pred_labels.extend(predicted.cpu().numpy())
            pred_scores.extend(outputs.cpu().numpy()) 
            true_labels.extend(labels.cpu().numpy())

    acc = accuracy.compute().item() 
    prec = precision.compute().item() 
    rec = recall.compute().item() 
    f1_score = f1.compute().item()
    auroc_score = auroc.compute().item()
    spec=specificity.compute().item()

    fold_results['fold']=fold
    fold_results['accuracy'] = acc
    fold_results['precision'] = prec
    fold_results['recall'] = rec
    fold_results['f1_score'] = f1_score
    fold_results['auroc_score'] = auroc_score
    fold_results['specificity'] = spec
    
    logging.info(f"Test Accuracy: {acc:.4f}, Test precision: {prec:.4f}, Test recall: {rec:.4f}, Test f1: {f1_score:.4f}, Test auroc: {auroc_score:4f},Test specificity:{spec:.4f}")
    logging.error("This is a fatal log!")   
    
    roc = MulticlassROC(num_classes=2, thresholds=None)
    pred_scores = torch.Tensor(pred_scores).to(device)
    true_labels = torch.Tensor(true_labels).int().to(device)
    fpr, tpr, thresholds = roc(pred_scores, true_labels)
    
    draw_fold_path = Path(os.path.join(fprs_tprs_path, f'fold_{fold}'))
    draw_fold_path.mkdir(parents=True, exist_ok=True)
    torch.save(tpr,os.path.join(draw_fold_path,"tpr.pt"))
    torch.save(fpr,os.path.join(draw_fold_path,"fpr.pt"))
   
    return fold_results, fpr, tpr
相关推荐
HelloGitHub4 分钟前
开源新旗舰 GLM-4.5:不想刷榜,只想干活儿
人工智能·开源·github
虹科数字化与AR8 分钟前
安宝特案例丨AR+AI赋能轨道交通制造:破解人工装配难题的创新实践
人工智能·ar·制造·轨道交通·工业ar·ai辅助·ar工业
陈敬雷-充电了么-CEO兼CTO8 分钟前
字节跳动开源Coze,开启AI Agent开发新时代?
人工智能·gpt·chatgpt·开源·大模型·agi·coze
说私域12 分钟前
基于开源AI智能名片链动2+1模式与S2B2C商城小程序的微商品牌规范化运营研究
人工智能·小程序·开源
强德亨上校15 分钟前
2025年7月21–28日AI开发周报:新模型、新战略与开源亮点
人工智能·科技·gpt·chatgpt·开源·aigc
亚马逊云开发者16 分钟前
Amazon Bedrock Runtime API集成指南——从Invoke Model API迁移到Converse API,简化生成式AI应用开发
人工智能·api
算家计算17 分钟前
FLUX.1 Kontext LoRA专用炼丹炉使用教程:加快训练进程,减少实例费用消耗!
人工智能·开源·aigc
江山如画,佳人北望18 分钟前
pytorch常用函数
人工智能·pytorch·python
DM今天肝到几点?27 分钟前
【7.26-7.28胜算云AI日报:首个开源3D世界生成模型腾讯混元、微软预示 8 月 GPT-5 发布、Nemotron推理、商汤悟能、DM夺金】
人工智能·vscode·microsoft·3d·ai·chatgpt
学术小八34 分钟前
第六届物联网、人工智能与机械自动化国际学术会议 (IoTAIMA 2025)
运维·人工智能·自动化