一次热编码期间出现 RunTimeError

2024-04-14

我有一个数据集,其中类值以 1 步从 -2 到 2(i.e., -2,-1,0,1,2)其中 9 标识未标记的数据。 使用一种热编码

self._one_hot_encode(labels)

我收到以下错误:RuntimeError: index 1 is out of bounds for dimension 1 with size 1

due to

self.one_hot_labels = self.one_hot_labels.scatter(1, labels.unsqueeze(1), 1)

错误应该从[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 1, 1, 1, 1, 1, 1],我在映射设置中有 9 等于索引 9 到 1。即使在浏览了过去的问题和类似问题的答案之后(例如,索引 1 超出尺寸 1 的维度 0 的范围 https://stackoverflow.com/questions/67185851/index-1-is-out-of-bounds-for-dimension-0-with-size-1)。 涉及错误的部分代码如下:

def _one_hot_encode(self, labels):
    # Get the number of classes
    classes = torch.unique(labels)
    classes = classes[classes != 9] # unlabelled 
    self.n_classes = classes.size(0)

    # One-hot encode labeled data instances and zero rows corresponding to unlabeled instances
    unlabeled_mask = (labels == 9)
    labels = labels.clone()  # defensive copying
    labels[unlabeled_mask] = 0
    self.one_hot_labels = torch.zeros((self.n_nodes, self.n_classes), dtype=torch.float)
    self.one_hot_labels = self.one_hot_labels.scatter(1, labels.unsqueeze(1), 1)
    self.one_hot_labels[unlabeled_mask, 0] = 0

    self.labeled_mask = ~unlabeled_mask

def fit(self, labels, max_iter, tol):
    
    self._one_hot_encode(labels)

    self.predictions = self.one_hot_labels.clone()
    prev_predictions = torch.zeros((self.n_nodes, self.n_classes), dtype=torch.float)

    for i in range(max_iter):
        # Stop iterations if the system is considered at a steady state
        variation = torch.abs(self.predictions - prev_predictions).sum().item()
        

        prev_predictions = self.predictions
        self._propagate()

数据集示例:

ID  Target  Weight  Label   Score   Scale_Cat   Scale_num
0   A   D   65.1    1   87  Up  1
1   A   X   35.8    1   87  Up  1
2   B   C   34.7    1   37.5    Down    -2
3   B   P   33.4    1   37.5    Down    -2
4   C   B   33.1    1   37.5    Down    -2
5   S   X   21.4    0   12.5    NA  9

我用作参考的源代码在这里:https://mybinder.org/v2/gh/thibaudmartinez/label-propagation/master?filepath=notebook.ipynb https://mybinder.org/v2/gh/thibaudmartinez/label-propagation/master?filepath=notebook.ipynb

错误的完整跟踪:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-126-792a234f63dd> in <module>
      4 label_propagation = LabelPropagation(adj_matrix_t)
----> 6 label_propagation.fit(labels_t) # causing error
      7 label_propagation_output_labels = label_propagation.predict_classes()
      8 

<ipython-input-115-54a7dbc30bd1> in fit(self, labels, max_iter, tol)
    100 
    101     def fit(self, labels, max_iter=1000, tol=1e-3):
--> 102         super().fit(labels, max_iter, tol)
    103 
    104 ## Label spreading

<ipython-input-115-54a7dbc30bd1> in fit(self, labels, max_iter, tol)
     58             Convergence tolerance: threshold to consider the system at steady state.
     59         """
---> 60         self._one_hot_encode(labels)
     61 
     62         self.predictions = self.one_hot_labels.clone()

<ipython-input-115-54a7dbc30bd1> in _one_hot_encode(self, labels)
     42         labels[unlabeled_mask] = 0
     43         self.one_hot_labels = torch.zeros((self.n_nodes, self.n_classes), dtype=torch.float)
---> 44         self.one_hot_labels = self.one_hot_labels.scatter(1, labels.unsqueeze(1), 1)
     45         self.one_hot_labels[unlabeled_mask, 0] = 0
     46 

RuntimeError: index 1 is out of bounds for dimension 1 with size 1


我浏览了你的笔记本(我认为你将 9 更改为 -1 以便运行)并看到这部分代码:

# Learn with Label Propagation
label_propagation = LabelPropagation(adj_matrix_t)
print("Label Propagation: ", end="")
label_propagation.fit(labels_t)
label_propagation_output_labels = label_propagation.predict_classes()

最终调用:

self.one_hot_labels = self.one_hot_labels.scatter(1, labels.unsqueeze(1), 1)

是出了问题的地方。

请花一点时间阅读有关 scatter 的 pytorch 手册:火炬分散 https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html我们了解到,对于分散来说,了解暗淡、索引、src 和自身矩阵很重要。对于一种热编码,dim=1 或 0 并不重要,我们的 src 矩阵是 1(稍后我们将对此进行更多研究)。您现在在维度 1 上调用 scatter,索引矩阵为 [40,1],结果(自身)矩阵为 [40,5]。

我在这里看到两个问题:

  1. 您正在使用文字类别虚拟变量 (-2,-1,0,1,2) 作为索引矩阵中的编码索引。这将导致 scatter 在 src 矩阵中搜索这些索引。这是索引越界的地方
  2. 您提到有 6 个类 -2、-1、0、1、2 和 9 为未标记的,但您是 5 个类的热门编码。 (是的,我知道您希望未标记的类全部为零,但这用分散实现有点困难。我稍后会解释)。

那么我们该如何解决这个问题呢?

问题一:让我们从一个小例子开始:

index = torch.tensor([[5],[0],[3],[5],[1],[4]]); print(index.shape); print(index)
result = torch.zeros(6, 6, dtype=src.dtype).scatter_(1, index, src); print(result.shape); print(result)

这会给我们

torch.Size([6, 1])
tensor([[5],
        [0],
        [3],
        [5],
        [1],
        [4]])
torch.Size([6, 6])
tensor([[0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 1],
        [0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]])

索引矩阵是 6 个观测值和 1 个观测值(类别) 自矩阵是 6 个观测值,具有 6 类一热编码向量 scatter(dim=1) 创建 self 矩阵的方式是 torch 首先检查行(观察),然后将该行的值更改为存储在 src 矩阵中同一行但列的值存储在索引中的值。

self[i][index[i][j][k]][k] = src[i][j][k]

因此,在您的情况下,您试图将 1 的值应用到 self[40,1] 中索引 [0] 列(等于 1)的行中。给你问题中的错误。虽然我检查了你的笔记本,错误是 索引 -1 超出了尺寸为 5 的维度 1 的范围。它们都是相同的根本原因。

问题 2:One-hot 编码

在这种情况下,使用冷编码进行完整的one-hot 比one-hot 更容易。原因是,对于单热冷编码,您需要在 src 矩阵中为每个未标记的观察创建一个 0 值。这比仅仅使用 1 作为 src 更痛苦。另请阅读此链接:OHE 全零是否有效? https://stats.stackexchange.com/questions/408626/is-it-valid-to-have-all-zeroes-in-a-one-hot-encoded-categorical-feature我认为对每个类别都使用 one-hot 更有意义。

因此,对于第二个问题,我们只需要简单地将类别映射到结果/自身矩阵的索引中。由于我们有 6 个类别,我们只需将它们映射到 0,1,2,3,4,5 即可。一个简单的 lambda 函数就可以解决这个问题。我使用随机采样器从类列表中获取数据标签,如下所示:(我从 6 个类中随机创建了 40 个观察值)

classes = list([-2,-1,0,1,2,9])

labels = list()
for i in range(0,40):
    labels.append(list([(lambda x: x+2 if x !=9 else 5)(random.sample(classes,1)[0])]))

index_aka_labels = torch.tensor(labels)
print(index_aka_labels)
print(index_aka_labels.shape)
torch.zeros(40, 6, dtype=src.dtype).scatter_(1, index_aka_labels, 1)

最终,我们达到了我们想要的OHE结果:

tensor([[0, 0, 0, 0, 0, 1],
        [0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 1, 0],
        ... (40 observations)
        [0, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 1],
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一次热编码期间出现 RunTimeError 的相关文章

  • 在函数内的 for 循环上使用 tqdm 来检查进度

    我正在使用 for 循环迭代目录树内的一大组文件 这样做时 我想通过控制台中的进度条来监视进度 因此 我决定使用 tqdm 来实现此目的 目前 我的代码如下所示 for dirPath subdirList fileList in tqdm
  • docker 容器中的“(pygame parachute)分段错误”

    尝试在 docker 容器中使用 pygame 时出现以下错误 我想从容器中获取显示 Fatal Python error pygame parachute Segmentation Fault 重现 Docker已安装 docker ru
  • DynamodB:如何更新排序键?

    该表有两个键 filename 分区键 和eventTime 排序键 我要更新eventTime对于某些filename Tried put item and update item 发送相同的filename与新的eventTime但这些
  • 使用 Python 和 lmfit 拟合复杂模型?

    我想适合椭偏仪 http en wikipedia org wiki Ellipsometry使用 LMFit 将数据转换为复杂模型 两个测量参数 psi and delta 是复杂函数中的变量rho 我可以尝试将问题分离为实部和虚部共享参
  • Scrapy 文件管道不下载文件

    我的任务是构建一个可以下载所有内容的网络爬虫 pdfs 在给定站点中 Spider 在本地计算机和抓取集线器上运行 由于某种原因 当我运行它时 它只下载一些但不是全部的 pdf 通过查看输出中的项目可以看出这一点JSON 我已经设定MEDI
  • Python 内置对象的 __enter__() 和 __exit__() 在哪里定义?

    我读到每次使用 with 时都会调用该对象的 enter 和 exit 方法 我知道对于用户定义的对象 您可以自己定义这些方法 但我不明白这对于 打开 等内置对象 函数甚至测试用例是如何工作的 这段代码按预期工作 我假设它使用 exit 关
  • 使用 Pandas 从 csv 文件读取标题信息

    我有一个包含 14 行标题的数据文件 在标头中 有经纬度坐标和时间的元数据 我目前正在使用 pandas read csv filename delimiter header 14 读取文件 但这只是获取数据 我似乎无法获取元数据 有人知道
  • 会话数据库表清理

    该表是否需要清除或者由 Django 自动处理 Django 不提供自动清除功能 然而 有一个方便的命令可以帮助您手动完成此操作 Django 文档 清除会话存储 https docs djangoproject com en dev to
  • 在 django 中导入设置时出现奇怪的错误

    我有很多项目在 ubuntu 中使用 python2 7 和 virtualenv virtualenvwrapper 工作 在我的工作中 一些开发人员使用 macosx 和 windows 通常我像往常一样创建项目 django admi
  • 使用 ElementTree 在 python 中解析 xml

    我对 python 很陌生 我需要解析一些脏的 xml 文件 这些文件需要先清理 我有以下 python 代码 import arff import xml etree ElementTree import re totstring wit
  • 哪种方式最适合Python工厂注册?

    这是一个关于这些方法中哪一种被认为是最有效的问题 Pythonic 我不是在寻找个人意见 而是在寻找惯用的观点 我的背景不是Python 所以这会对我有帮助 我正在开发一个可扩展的 Python 3 项目 这个想法类似于工厂模式 只不过它是
  • Python:导入模块一次然后与多个文件共享

    我有如下文件 file1 py file2 py file3 py 假设这三个都使用 lib7 py lib8 py lib9 py 目前 这三个文件中的每一个都有以下行 import lib7 import lib8 import lib
  • 获取多个同名请求参数

    我的问题是给定的代码 from flask import Flask request app Flask name app route def hello return str request values get param None a
  • AttributeError: 'super' 对象没有属性 '__getattr__' 在 Kivy 中使用带有多个 kv 文件的 BoxLayout 时出错

    我很清楚 这个问题已经被问过好几次了 但尝试以下解决方案后 Python Kivy AttributeError 尝试获取 self ids 时 super 对象没有属性 getattr https stackoverflow com qu
  • 数据损坏 C++ 和 Python 之间的管道

    我正在编写一些代码 从 Python 获取二进制数据 将其通过管道传输到 C 对数据进行一些处理 在本例中计算互信息度量 然后将结果通过管道传输回 Python 在测试时 我发现如果我发送的数据是一组尺寸小于 1500 X 1500 的 2
  • 如何检测一个二维数组是否在另一个二维数组内?

    因此 在堆栈溢出成员的帮助下 我得到了以下代码 data needle s which is a png image base64 code goes here decoded data decode base64 f cStringIO
  • 从给定的项目列表创建子列表

    我首先要说的是以下问题不是为了家庭作业目的即使因为我几个月前就完成了软件工程师的工作 无论如何 今天我正在工作 一位朋友向我询问了这个奇怪的排序问题 我有一个包含 1000 行的列表 每行代表一个数字 我想创建 10 个子列表 每个子列表都
  • 如何将两列 pandas Dataframe 移动并堆叠为一列?

    我有一个下面提到的数据框 ETHNIC SEX USUBJID 0 HISPANIC OR LATINO F 16 1 HISPANIC OR LATINO M 8 2 HISPANIC OR LATINO Total 24 3 NOT H
  • 用 pandas DataFrame 替换 mysql 数据库表中的行

    Python 版本 2 7 6 熊猫版本 0 17 1 MySQLdb 版本 1 2 5 在我的数据库中 PRODUCT 我有一张桌子 XML FEED 表 XML FEED 很大 数百万条记录 我有一个 pandas DataFrame
  • py2exe ImportError:没有名为 的模块

    我已经实现了一个名为 myUtils 的包 它由文件夹 myUtils 文件 组成 init py 和许多名称为 myUtils 的 py 文件 该包包含在 myOtherProject py 中 当我从 Eclipse 运行它们时可以找到

随机推荐