You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

糖尿病视网膜检测项目中utils.get_roc_curve属性错误解决问询

问题排查:utils模块缺少get_roc_curve函数导致AttributeError

问题场景

我在基于视网膜PSD图像的糖尿病检测项目中,执行了以下代码:
导入utils模块:

import utils

调用函数计算ROC曲线下面积并绘制ROC曲线:

auc_rocs = utils.get_roc_curve(labels, predicted_vals, test_generator)

运行时抛出错误:

AttributeError: module 'utils' has no attribute 'get_roc_curve'

我的utils.py文件内容

import colorsys
from os import replace
import random
import numpy as np
import pandas as pd
import skimage.draw as drw


def _fix_df(df):
    """Prepare the Data Frame to be readable
    """
    df_new = df.drop(['ID'], axis=0)
    df_new.columns = df_new.iloc[0,:]
    df_new.drop([np.nan], axis=0, inplace=True)
    df_new.columns.name = 'ID'
    return df_new
    

# contour_to_mask() and apply_mask() functions adapted from Mask RCNN implementation
def contour_to_mask(cont, img_shape, abs_path='../'):
    """Return mask given a contour and the shape of image
    """
    c = np.loadtxt(abs_path + "ExpertsSegmentations/Contours/" + cont)
    mask = np.zeros(img_shape[:-1], dtype=np.uint8)
    rr, cc = drw.polygon(c[:,1], c[:,0])
    mask[rr, cc] = 1
    return mask

def apply_mask(image, mask, color, alpha=0.5):
    """Apply the given mask to the image.
    """
    for c in range(3):
        image[:, :, c] = np.where(mask == 1,
                                  image[:, :, c] *
                                  (1 - alpha) + alpha * color[c] * 255,
                                  image[:, :, c])
    return image


def read_clinical_data(abs_path='../'):
    """Return excel data as pandas Data Frame
    """
    df_od = pd.read_excel(abs_path + 'ClinicalData/patient_data_od.xlsx', index_col=[0])
    df_os = pd.read_excel(abs_path + 'ClinicalData/patient_data_os.xlsx', index_col=[0])
    return _fix_df(df=df_od), _fix_df(df=df_os)

def get_diagnosis(abs_path='../'):
    """Return three arrays of shape 488 with the diagnosis tag, eye ID (od, os)
    and patient ID
    """
    df_od, df_os = read_clinical_data(abs_path=abs_path)
        
    index_od = np.ones(df_od.iloc[:,2].values.shape, dtype=np.int8)
    index_os = np.zeros(df_os.iloc[:,2].values.shape, dtype=np.int8)

    eyeID = np.array(list(zip(index_od, index_os))).reshape(-1)
    tag = np.array(list(zip(df_od.iloc[:,2].values, df_os.iloc[:,2].values))).reshape(-1)
    patID = np.array([[int(i.replace('#', ''))] * 2 for i in df_od.index]).reshape(-1)
    
    return tag, eyeID, patID

排查结论与解决方案

你的utils.py中确实没有定义get_roc_curve函数,这就是报错的直接原因,需要在utils.py中添加该函数来实现ROC曲线计算与绘制功能。

下面是适配该项目场景的get_roc_curve示例实现,可根据实际需求调整:

import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
import numpy as np

def get_roc_curve(labels, predicted_vals, test_generator):
    # 多分类任务需先将标签二值化
    n_classes = len(test_generator.class_indices)
    if n_classes > 2:
        labels = label_binarize(labels, classes=range(n_classes))
        predicted_vals = predicted_vals.reshape(-1, n_classes)
    
    # 计算每类的ROC曲线和AUC值
    fpr = dict()
    tpr = dict()
    roc_auc = dict()
    for i in range(n_classes):
        fpr[i], tpr[i], _ = roc_curve(labels[:, i], predicted_vals[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])
    
    # 绘制ROC曲线
    plt.figure()
    colors = ['blue', 'red', 'green']  # 多分类时可扩展颜色列表
    class_names = list(test_generator.class_indices.keys())
    for i, color in zip(range(n_classes), colors):
        plt.plot(fpr[i], tpr[i], color=color, lw=2,
                 label='ROC curve of class {0} (area = {1:0.2f})'
                 ''.format(class_names[i], roc_auc[i]))
    
    plt.plot([0, 1], [0, 1], 'k--', lw=2)
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver Operating Characteristic')
    plt.legend(loc="lower right")
    plt.show()
    
    return roc_auc

注意事项

  • 确保环境已安装scikit-learn和matplotlib库,未安装可执行:
pip install scikit-learn matplotlib
  • 若为二分类任务,可删除多分类相关处理代码,简化函数逻辑。
  • 根据test_generator的实际结构调整类标签获取方式,确保与数据集匹配。

内容的提问来源于stack exchange,提问作者Awab Elkhair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:35:39