You need to enable JavaScript to run this app. 实现Omniglot孪生网络时调用make_pairs生成样本对报KeyError
优惠活动
大模型
产品
解决方案
定价
更多

实现Omniglot孪生网络时调用make_pairs生成样本对报KeyError

孪生神经网络配对样本生成KeyError问题解决

问题背景

基于Omniglot数据集实现单样本图像识别的孪生神经网络时,需要生成同类别/不同类别的配对样本,调整现有代码调用时触发KeyError。

相关代码

数据加载代码

import requests
import io
import numpy as np

def load_numpy_arr_from_url(url):
    """
    从指定链接加载numpy数组
    输入:
    url: 数据集下载链接
    输出:
    dataset: 存储特征或标签的numpy数组
    """
    response = requests.get(url)
    response.raise_for_status()
    return np.load(io.BytesIO(response.content)) 

# 下载数据集,耗时可能较长
train_x = load_numpy_arr_from_url('https://surfdrive.surf.nl/files/index.php/s/tvQmLyY7MhVsADb/download')
# 布尔类型转整数
train_data = train_x * 1
train_y = load_numpy_arr_from_url('https://surfdrive.surf.nl/files/index.php/s/z234AHrQqx9RVGH/download')

存在错误的配对生成代码

import torch
import random
def make_pairs(data, labels, num=1000):
    digits = {}
    for i, j in enumerate(labels):
        if not j in digits:
            digits[j] = []
        digits[j].append(i)

    pairs, labels_ = [], []
    for i in range(num):
        if np.random.rand() >= .5: # 同类别配对
            digit = random.choice(range(len(labels+1)))
            d1, d2 = random.choice(digits[digit], size=2, replace=False)
            labels_.append(1)
        else: # 不同类别配对
            digit1, digit2 = np.random.choice(range(len(labels+1)), size=2, replace=False)
            d1, d2 = random.choice(digits[digit1]), np.random.choice(digits[digit2])
            labels_.append(0)
        pairs.append(torch.from_numpy(np.concatenate([data[d1,:], data[d2,:]])).view(1, 56, 28))
    return torch.cat(pairs), torch.LongTensor(labels_)

触发错误的调用命令

make_pairs(train_data,train_y, 5)

错误回溯信息

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-30-7d53181e46ef> in <module>()
     25 
     26     return torch.cat(pairs), torch.LongTensor(labels_)
---> 27 make_pairs(train_data,train_y, 5)
     28 #print(a)

<ipython-input-30-7d53181e46ef> in make_pairs(data, labels, num)
     14         if np.random.rand() >= .5: # same digit
     15             digit = random.choice(range(len(labels+1)))
---> 16             print(random.choice(digits[digit], replace=False))
     17             d1, d2 = random.choice(digits[digit], size=2, replace=False)
     18             labels_.append(1)

KeyError: 12803

错误原因

  1. 类别取值逻辑错误:digits字典的键是数据集实际的类别标签值,并非0到样本总数的连续整数。代码中用range(len(labels+1))生成的随机数大量不存在于digits的键中,直接触发KeyError。
  2. 括号书写错误:原本想获取样本总数加1的范围,错误写成len(labels+1),实际是对标签数组每个元素加1后取长度,等价于len(labels),完全不符合预期。
  3. 库调用规则错误:Python标准库的random.choice不支持size和replace参数,只有numpy.random.choice支持该用法,即使解决KeyError后续也会触发参数错误。

修复方案

首先获取所有实际存在的类别标签列表,直接从该列表中随机选择类别,不要自行生成连续整数范围,同时替换对应的随机选择接口:

修复后的完整代码

import torch
def make_pairs(data, labels, num=1000):
    digits = {}
    for i, j in enumerate(labels):
        if not j in digits:
            digits[j] = []
        digits[j].append(i)
    # 提取所有合法的类别标签
    valid_classes = list(digits.keys())
    pairs, labels_ = [], []
    for i in range(num):
        if np.random.rand() >= .5: # 同类别配对
            digit = np.random.choice(valid_classes)
            d1, d2 = np.random.choice(digits[digit], size=2, replace=False)
            labels_.append(1)
        else: # 不同类别配对
            digit1, digit2 = np.random.choice(valid_classes, size=2, replace=False)
            d1 = np.random.choice(digits[digit1])
            d2 = np.random.choice(digits[digit2])
            labels_.append(0)
        pairs.append(torch.from_numpy(np.concatenate([data[d1,:], data[d2,:]])).view(1, 56, 28))
    return torch.cat(pairs), torch.LongTensor(labels_)

内容的提问来源于stack exchange,提问作者ChengLong Deng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 15:36:03