one hot编码及torch.Tensor.scatter_()函数详解

one hot 编码

One Hot编码,又称为一位有效编码,主要是采用N位状态寄存器来对N个状态进行编码,每个状态都由他独立的寄存器位,并且在任意时候只有一位有效。
One Hot编码是分类变量作为二进制向量的表示。这首先要求将分类值映射到整数值。然后,每个整数值被表示为二进制向量,除了整数的索引之外,它都是零值,它被标记为1。
在这里插入图片描述

  • 应用实例

在这里插入图片描述
在这里插入图片描述

  • torch.Tensor.scatter_()函数

在这里插入图片描述

  • 示例

  • dim=0

import torch

x = torch.tensor([[0.9413, 0.9476, 0.1104, 0.9898, 0.6443],
            [0.6913, 0.8924, 0.7530, 0.8874, 0.0557]])

result = torch.zeros(3, 5)
indices = torch.tensor([[0, 1, 2, 0, 0], 
                        [2, 0, 0, 1, 2]])
result.scatter_(0, indices, x)

# 输出
tensor([[0.9413, 0.8924, 0.7530, 0.9898, 0.6443],
        [0.0000, 0.9476, 0.0000, 0.8874, 0.0000],
        [0.6913, 0.0000, 0.1104, 0.0000, 0.0557]])


上例中,dim=0,所以根据这个规则来self[ index[i][j] ] [j] = src[i][j]来确定替换规则
index中的值决定了src中的值在result中的放置位置

dim=0时,则将列固定起来,先看第0列:

对于第0行,首先找到x的第0列第0行的值为0.9413,然后在用index[0][0]的值来找将要在result中放置的位置。

在这个例子中,index[0][0]=0, 所以0.9413将放置在result[0][0]这个位置。

对于result中的各项,他们的寻址过程如下:

x[0][1] = 0.9476 -> indices[0][1]=1 -> result[ index = 1 ][1] = 0.9476

x[1][3] = 0.8874 -> indices[1][3]=1 -> result[ index = 1 ][3] = 0.8874

依此类推。
!](https://img-blog.csdnimg.cn/85327e8283164757b176c4b27c020aa8.png)

  • dim=1

x = torch.tensor([[0.9413, 0.9476, 0.1104, 0.9898, 0.6443],
                        [0.6913, 0.8924, 0.7530, 0.8874, 0.0557]])
result = torch.zeros(3, 5)
indices = torch.tensor([[0, 1, 2, 0, 0], 
                        [2, 0, 0, 1, 2]])
result.scatter_(1, indices, x)
            
# 输出
tensor([[0.6443, 0.9476, 0.1104, 0.0000, 0.0000],
        [0.7530, 0.8874, 0.0557, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])

x[0][0] = 0.9413 -> indices[0][0]=0 -> result[0][index = 0] = 0.9413

x[0][3] = 0.9898 -> indices[0][3]=0 -> result[0][index = 0] = 0.9898 ## 将上一步的值覆盖了

x[0][4] = 0.6443 -> indices[0][4]=0 -> result[0][index = 0] = 0.6443 ## 再次将上一步的值覆盖了

因此result[0][0]的值为0.6443.

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值