Pytorch框架之one hot編碼函式

2021-10-10 07:12:33 字數 1476 閱讀 5451

在乙個給定的向量中,按照設定的最值–可以是向量中包含的最大值(作為最高分類數),有也可以是自定義的最大值,設計one_hot編碼的長度:最大值+1【詳見舉的例子吧】。

然後按照最大值建立乙個1*(最大值+1)的維度大小的全零零向量:[0, 0, 0, …] => 共最大值+1對應的個數

接著按照向量中的值,從第0位開始索引,將向量中值對應的位置設定為1,其他保持為0.

eg:假設設定one_hot長度為4(最大值) –

且當前向量中值為1對應的one_hot編碼:

[0, 1, 0, 0]

當前向量中值為2對應的one_hot編碼:

[0, 0, 1, 0]

eg:假設設定one_hot長度為6(等價最大值+1) –

且當前向量中值為4對應的one_hot編碼:

[0, 0, 0, 0, 1, 0]

當前向量中值為2對應的one_hot編碼:

[0, 0, 1, 0, 0, 0]

eg:targets = [4, 1, 0, 3] => max_value=4=>one_hot的長度為(4+1)

假設設定one_hot長度為5(最大值) –

且當前向量中值為4對應的one_hot編碼:

[0, 0, 0, 0, 1]

當前向量中值為1對應的one_hot編碼:

[0, 1, 0, 0, 0]

import torch

targets = torch.tensor(

[5, 3, 2, 1]

)targets_to_one_hot = torch.nn.functional.one_hot(targets)

# 預設按照targets其中的最大值+1作為one_hot編碼的長度

# result:

# tensor(

# [0, 0, 0, 0, 0, 1],

# [0, 0, 0, 1, 0, 0],

# [0, 0, 1, 0, 0, 0],

# [0, 1, 0, 0, 0, 0]

#)targets_to_one_hot = torch.nn.functional.one_hot(targets, num_classes=7) 3# 指定one_hot編碼長度為7

# result:

# tensor(

# [0, 0, 0, 0, 0, 1, 0],

# [0, 0, 0, 1, 0, 0, 0],

# [0, 0, 1, 0, 0, 0, 0],

# [0, 1, 0, 0, 0, 0, 0]

#)

總結:one_hot編碼主要用於分類時,作為乙個類別的編碼–方便判別與相關計算;

【1. 如同類別數統計,只需要將one_hot編碼相加得到乙個一維向量就知道了一批資料中所有類別的**或真實的分布情況;

2. 相比於**出具體的類別數–43等,用向量可以使用向量相關的演算法進行時間上的優化等等】

pytorch 深度學習框架

定義網路 net net 定義資料 資料預處理,1.轉為tensor,2.歸一化 transform transforms.compose transforms.totensor transforms.normalize 0.5 0.5 0.5 0.5 0.5 0.5 訓練集 trainset to...

Pytorch框架貓狗大戰之資料預處理

資料預處理階段,dataset.py中主要定義了dogcat類,並定義了 init getitem len 三個類方法,話不多說直接上 具體解讀都在每一行後面的注釋中。coding utf8 import os from pil import image from torch.utils impor...

在Anaconda安裝pytorch框架

首先檢視自己電腦能夠支援cuda的version 在桌面隨便乙個地方右擊 nvidia控制面板 幫助 系統資訊 元件 nvidia cuda後面是數字就是cuda version 能夠安裝的最高版本 然後進入cuda官網 根據你之前的那個數字選擇合適的version 然後直接download然後安裝...