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

训练生成混淆矩阵遇AttributeError:'builtin_function_or_method'无index属性

问题解决:AttributeError: 'builtin_function_or_method' object has no attribute 'index'

错误根源

你的代码中这一行存在语法错误:

names = names.tolist

tolist()是NumPy数组的方法,必须加括号调用才能将NumPy数组转换为Python列表。如果不加括号,names会被赋值为这个方法本身(而非方法执行后的列表),后续调用names.index(name)时,自然会因为方法对象没有index属性而报错。

修正后的代码

def load_face_dataset(inputPath, net, minConfidence=0.5,
    minSamples=15):
    # grab the paths to all images in our input directory, extract
    # the name of the person (i.e., class label) from the directory
    # structure, and count the number of example images we have per
    # face
    imagePaths = list(paths.list_images(inputPath))
    names = [p.split(os.path.sep)[-2] for p in imagePaths]
    (names, counts) = np.unique(names, return_counts=True)
    names = names.tolist()  # 此处添加括号调用tolist方法
    # initialize lists to store our extracted faces and associated
    # labels
    faces = []
    labels = []
    # loop for the image paths
    for imagePath in imagePaths:
        # load the image from disk and extract the name of the person
        # from the subdirectory structure
        image = cv2.imread(imagePath)
        name = imagePath.split(os.path.sep)[-2]
        # only process images that have a sufficient number of
        # examples belonging to the class
        if counts[names.index(name)] < minSamples:
            continue
        # perform face detection
        boxes = detect_faces(net, image, minConfidence)
        # loop over the bounding boxes
        for (startX, startY, endX, endY) in boxes:
            try:
                # extract the face ROI, resize it, and convert it to
                # grayscale
                faceROI = image[startY:endY, startX:endX]
                faceROI = cv2.resize(faceROI, (47, 62))
                faceROI = cv2.cvtColor(faceROI, cv2.COLOR_BGR2GRAY)
                # update our faces and labels lists
                faces.append(faceROI)
                labels.append(name)
            except:
                continue
    # convert our faces and labels lists to NumPy arrays
    faces = np.array(faces)
    labels = np.array(labels)
    # return a 2-tuple of the faces and labels
    return (faces, labels)

补充说明

  • 修正后,names会被正确转换为Python列表,names.index(name)就能正常查找元素索引,进而通过counts[索引]获取对应类别的样本数量。
  • 调试时可在关键步骤打印变量类型(比如print(type(names))),快速定位这类方法调用遗漏括号的问题。

内容的提问来源于stack exchange,提问作者Bernardino Neil Brian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:20:25