天天看點

PyTorch : 了解Tensor(張量)及其建立方法

本文已收錄于Pytorch系列專欄: ​​Pytorch入門與實踐​​ 專欄旨在詳解Pytorch,精煉地總結重點,面向入門學習者,掌握Pytorch架構,為資料分析,機器學習及深度學習的代碼能力打下堅實的基礎。免費訂閱,持續更新。

認識張量

張量是一個多元數組 ,它是标量、向量、矩陣的高維拓展。

PyTorch : 了解Tensor(張量)及其建立方法

比如說對于一張圖檔,它是3維張量,其中RGB就是其第三維張量。

Tensor與 Variable

Variable是Pytorch的0.4.0版本之前的一個重要的資料結構,但是從0.4.0開始,它已經并入了Tensor中了。

Variable是 torch.autograd 中的資料類型,主要用于封裝Tensor ,進行自動求導。

PyTorch : 了解Tensor(張量)及其建立方法
  • data: 被包裝的 Tensor
  • grad: data 的梯度
  • grad_fn: 建立 Tensor 的 Function ,是自動求導的關鍵。比如說是加法還是乘法之類的。
  • requires_grad: 訓示是否需要梯度,有些不需要梯度,設定為false可以節省記憶體。
  • is_leaf: 訓示是否是葉子結點(張量)

Tensor

PyTorch : 了解Tensor(張量)及其建立方法

PyTorch0.4.0版開始, Variable 并入 Tensor

  • dtype: 張量的資料類型,如 torch.FloatTensor FloatTensor, torch.cuda.FloatTensor(cuda表示資料放在了GPU上)
  • shape: 張量的形狀,如 (64, 3, 224, 224)
  • device: 張量所在裝置, GPU/CPU ,是加速的關鍵

張量的建立

一、直接建立

torch.tensor()
PyTorch : 了解Tensor(張量)及其建立方法

功能:從data 建立 tensor

  • data : 資料 , 可以是 list, numpy
  • dtype : 資料類型,預設與 data 的一緻
  • device 所在裝置 , cuda cpu
  • requires_grad :是否需要梯度
  • pin_memory :是否存于鎖頁記憶體

執行個體如下:

import torch
import numpy as np

# Create tensors via torch.tensor

flag = True

if flag:
    arr = np.ones((3, 3))
    print("type of data:", arr.dtype)

    t = torch.tensor(arr, device='cuda')
    print(t)      
type of data: float64
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], device='cuda:0', dtype=torch.float64)      

其中,cuda表示采用了gpu,0是gpu的标号,由于隻有一個gpu,是以是0。

torch.from_numpy(ndarray)

功能:從numpy 建立 tensor

注意事項:從 torch.from_numpy 建立的 tensor 于原 ndarray 共享記憶體 ,當修改其中一個的資料,另外一個也将會被改動。

PyTorch : 了解Tensor(張量)及其建立方法

執行個體代碼:

# Create tensors via torch.from_numpy(ndarray)
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    t = torch.from_numpy(arr)
    print("numpy array: ", arr)
    print("tensor : ", t)

    print("\n修改arr")
    arr[0, 0] = 0
    print("numpy array: ", arr)
    print("tensor : ", t)

    print("\n修改tensor")
    t[0, 0] = -1
    print("numpy array: ", arr)
    print("tensor : ", t)      

通過結果可見,指向相同。

numpy array:  [[1 2 3]
 [4 5 6]]
tensor :  tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)

修改arr
numpy array:  [[0 2 3]
 [4 5 6]]
tensor :  tensor([[0, 2, 3],
        [4, 5, 6]], dtype=torch.int32)

修改tensor
numpy array:  [[-1  2  3]
 [ 4  5  6]]
tensor :  tensor([[-1,  2,  3],
        [ 4,  5,  6]], dtype=torch.int32)      

二、依據數值建立

2.1 torch.zeros()

功能:依size 建立全 0 張量

  • size : 張量的形狀 , 如 (3,3),(3,224,224)
  • out : 輸出的張量
  • layout 記憶體中布局形式 , 有strided(預設), sparse_coo(這個通常稀疏矩陣時設定,提高讀取效率) 等
  • device 所在裝置 , gpu cpu
  • requires_grad :是否需要梯度
PyTorch : 了解Tensor(張量)及其建立方法

code:

out_t = torch.tensor([1])

    t = torch.zeros((3, 3), out=out_t)

    print(t, '\n', out_t)
    print(id(t), id(out_t), id(t) == id(out_t))      

可見,該out的值與t相同,是以out是一個輸出的作用,将張量生成的資料指派給另一個變量。

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
2211683380904 2211683380904 True      
2.2 torch.zeros_like()

功能:依據input 形狀建立全 0 張量

  • intput : 建立與 input 同形狀的全 0 張量
  • dtype : 資料類型
  • layout 記憶體中布局形式
2.3 torch. ones()
2.4 torch. ones_like()

功能:input 形狀建立全 1 張量

其他參數一樣同上。

PyTorch : 了解Tensor(張量)及其建立方法
2.5 torch. full()
2.6 torch.full_like()

功能:依據input 形狀建立指定資料的張量

  • size : 張量的形狀 , 如 (3,3)
  • fill_value : 張量的值
PyTorch : 了解Tensor(張量)及其建立方法

code

t = torch.full((3, 3), 5)
    print(t)      
tensor([[5, 5, 5],
        [5, 5, 5],
        [5, 5, 5]])      
2.7 torch. arange

功能:建立等差的1 維張量

注意事項:數值區間為[start,end)

  • start : 數列起始值
  • end : 數列“結束值”
  • step : 數列公差,預設為 1

code

t = torch.arange(2, 10, 2)
    print(t)      
tensor([2, 4, 6, 8])      
2.8 torch. linspace

功能:建立均分的1 維張量

注意事項:數值區間為[start,end)

  • start : 數列起始值
  • end : 數列結束值
  • steps : 數列長度,注意是長度。

它的步長就是(end - start)/ steps。

t = torch.linspace(2, 10, 6)
    print(t)      
tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])      
2.9 torch. logspace
PyTorch : 了解Tensor(張量)及其建立方法

功能:建立對數均分的1 維張量

注意事項:長度為steps, 底為 base

  • start : 數列起始值
  • end : 數列結束值
  • steps : 數列長度
  • base : 對數函數的底,預設為 10
2.10 torch. eye()

功能:建立機關對角矩陣(2 維張量)

注意事項:預設為方陣

  • n : 矩陣行數
  • m : 矩陣列數

三、依機率分布建立張量

3.1 torch. normal()

功能:生成正态分布(高斯分布)

  • mean : 均值
  • std : 标準差

四種模式:

mean為标量, std為标量

mean為标量, std為張量

mean為張量, std為标量

mean為張量, std為張量

後三種基本用法相同,都是根據不同的維數進行

code:

# the mean and std both are tensors
    mean = torch.arange(1, 5, dtype=torch.float)
    std = torch.arange(1, 5, dtype=torch.float)
    t_normal = torch.normal(mean, std)
    print("mean:{}\nstd:{}".format(mean, std))
    print(t_normal)      

由結果可知,其生成的tensor是上面每一次元的參數生成的。

mean:tensor([1., 2., 3., 4.])
std:tensor([1., 2., 3., 4.])
tensor([1.6614, 2.5338, 3.1850, 6.4853])      

需要注意的是,對于mean和std都是标量的情況下,需要指定生成的size。

# mean: scalar std: scalar
    t_normal = torch.normal(0., 1., size=(4,))
    print(t_normal)      
tensor([0.6614, 0.2669, 0.0617, 0.6213])      
3.2 torch. randn ()
3.3 torch. randn_like ()

功能:生成标準正态分布(均值為0,方差為1)

size : 張量的形狀。

PyTorch : 了解Tensor(張量)及其建立方法
3.4 torch. rand()
3.5 torch. rand_like

功能:在區間[0,1) 上,生成均勻分布

3.6 torch. randint ()
3.7 torch. randint_like ()

功能:區間[low, high) 生成整數均勻分布

size : 張量的形狀

PyTorch : 了解Tensor(張量)及其建立方法
3.8 torch. randperm ()

功能:生成生成從0 到 n-1 的随機排列

n : 張量的長度

PyTorch : 了解Tensor(張量)及其建立方法
3.9 torch. bernoulli ()

繼續閱讀