1. 程式人生 > 其它 >pytorch-張量-張量的生成

pytorch-張量-張量的生成

技術標籤:深度學習深度學習機器學習pytorch

張量的生成:

import torch
import numpy as np

# 使用tensor.tensor()函式構造張量
a = torch.tensor([[1.0, 1.0], [2., 2.]])
print(a)

# 獲取張量的維度
print("張量的維度", a.shape)

# 獲取張量的形狀大小
print("張量的大小", a.size())

# 獲取張量中元素的個數
print("張量的元素個數", a.numel())

# 使用tensor.tensor()函式構造張量時
# 可以使用引數dtype修改張量的資料型別 # 使用requires_grad來指定張量是否需要計算梯度 b = torch.tensor((1, 2, 3), dtype=torch.float32, requires_grad=True) print(b) # 對於張量b計算sum(b^2)在每個元素上的梯度 y = b.pow(2).sum() y.backward() # 梯度求解的方法 # https://blog.csdn.net/huyaoyu/article/details/81059315 print("梯度為", b.grad) # 注意只有浮點型別的張量可以計算梯度
# torch.Tensor()函式生成張量 c = torch.Tensor([1., 2., 3., 4.]) print(c) # 根據形狀引數構建特定尺寸的張量 d = torch.Tensor(2, 3) print("2*3的形狀張量:\n", d) # 根據已經生成的張量可以使用torch.like()系列函式生成與指定張量維度相同,性質類似的張量 print("建立一個與d相同大小和型別的全1張量", torch.ones_like(d)) print("建立一個與d維度相同的全0張量", torch.zeros_like(
d)) print("建立一個與d維度相同的隨機張量", torch.rand_like(d)) e = [[1., 2.], [3., 4.]] e = d.new_tensor(e) print("將e列表轉換為與d型別相似但尺寸不同的張量", d.new_tensor(e)) print(e.dtype) print(d.dtype) print("3*3使用1填充的張量:", d.new_full((3, 3), fill_value=1)) print("3*3的全0的張量:", d.new_zeros((3, 3))) print("建立一個3*3的空張量", d.new_empty((3, 3))) print("建立一個3*3的全一張量:", d.new_ones((3, 3))) # 張量和numpy資料型別的轉換 # 利用numpy陣列生成張量 f = np.ones((3, 3)) ftensor = torch.as_tensor(f) print(ftensor) ftensor = torch.from_numpy(f) print(ftensor) # 使用numpy生成的陣列預設就是64位浮點型陣列 # 使用torch.numpy()函式可轉換為numpy陣列 print(ftensor.numpy()) # 隨機生成張量 torch.manual_seed(123) # 通過指定均值和標準差來生成隨機數 a = torch.normal(mean=0, std=torch.tensor(1.0)) print(a) # 如果mean引數和std引數有多個,那麼則生成多個隨機數 a = torch.normal(mean=0, std=torch.arange(1, 5.0)) print(a) a = torch.normal(mean=torch.arange(1, 5.0), std=torch.arange(1, 5.0)) print(a) # 使用torch.rand()函式,在區間[0,1]生成均勻分佈的張量 b = torch.rand(3, 4) print(b) # 使用torch.rand_like()函式,可根據其他張量的維度,生成與其維度相同的隨機張量 c = torch.ones(2, 3) d = torch.rand_like(c) print(d) # 使用torch.randn()和torch.rand_like()函式則可生成服從標準正態分佈的隨機張量 print(torch.randn(3, 3)) print(torch.rand_like(c)) # 使用torch.randperm(n)函式則可將0~n(包含0,不包含n)之間的中的整數隨機排序後輸出 print(torch.randperm(10)) # 其他生成張量的函式 # start指定開始,end指定結束,step指定步長 print(torch.arange(start=0, end=10, step=2)) # torch.linspace()函式在範圍內生成固定數量的等間隔張量 print(torch.linspace(start=0, end=10, steps=10)) # torch.logspace()函式生成一對數為間隔的張量 print(torch.logspace(start=0, end=10, steps=10)) # 生成全0張量 print(torch.zeros(3, 3)) # 生成全1張量 print(torch.ones(3, 3)) # 生成單位張量 print(torch.eye(3, 3)) # 生成用0.25填充的張量 print(torch.full((3, 3), fill_value=0.25))