1. 程式人生 > 實用技巧 >Pytorch 張量部分小總結

Pytorch 張量部分小總結

Pytorch 張量學習小結

1、張量的建立和維度 2、張量的運算

一、建立張量有4中方法:1、由torch.tensor()方法建立 2、由Pytorch內建的函式建立 3、由已知的張量建立形狀一致的張量 4、由通過已知的張量建立形狀不一致的張量

1、由torch.tensor()方法建立

import torch 
import numpy as np

t1 = torch.tensor([1,2,3,4])
print(t1.dtype)
t2 = torch.tensor([1,2,3,4], dtype=torch.int32)
print(t2.dtype)
print(t1.to(torch.int32)) #可以使用to內建方法對張量進行型別轉換

t3 
= torch.tensor(np.arange(10)) print(t3) t4 = torch.tensor(range(10)) print("t4 is {}, dtype={}".format(t4, t4.dtype)) #pytorch的整型預設為int64,np的整型預設為in32 t5 = torch.tensor([1.0,2.0,3.0,4.0]) print("t5 is {}, dtype={}".format(t5, t5.dtype)) t6 = torch.tensor(np.array([1.0,2.0,3.0,4.0])) print("t6 is {}, dtype={}
".format(t6, t6.dtype)) #pytorch的預設浮點型別為float32(單精度),numpy預設為(float64)雙精度 t7 = torch.tensor([[1,2,3],[4,5,6]]) #列表巢狀建立 print(t7)

結果:

torch.int64
torch.int32
tensor([1, 2, 3, 4], dtype=torch.int32)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.int32)
t4 is tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), dtype=torch.int64
t5 
is tensor([1., 2., 3., 4.]), dtype=torch.float32 t6 is tensor([1., 2., 3., 4.], dtype=torch.float64), dtype=torch.float64 tensor([[1, 2, 3], [4, 5, 6]]

2、pytorch內建函式建立

torch.rand(), torch.randn(), torch.zeros(), torch.ones(), torch.eye(), torch.randint()等

n1 = torch.rand(3,3) #生成3x3的矩陣,服從[0,1)上的均勻分佈
print(n1)
n2 = torch.randn(2,3,3) #生成2x3x3的矩陣,服從標準正態分佈
print(n2)
n3 = torch.zeros(2,2) #全零
print(n3)
n4 = torch.ones(2,2,1)
print(n4)
n5 = torch.eye(3) #單位陣
print(n5)
n6 = torch.randint(0,10,(3,3)) #生成3x3矩陣,值從[0,10)均勻分佈
print(n6)

結果:

tensor([[0.4672, 0.0484, 0.0256],
        [0.4547, 0.8642, 0.9526],
        [0.4009, 0.2858, 0.3133]])
tensor([[[-0.1942, -1.8865,  0.3309],
         [ 0.8023,  0.1170, -0.1000],
         [ 0.1931,  0.0472,  1.8049]],

        [[ 0.4596,  0.2676,  0.2857],
         [-2.9891,  1.6126, -0.2666],
         [-0.5891, -2.4039, -0.9180]]])
tensor([[0., 0.],
        [0., 0.]])
tensor([[[1.],
         [1.]],

        [[1.],
         [1.]]])
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
tensor([[6, 5, 9],
        [7, 9, 2],
        [2, 2, 4]])

3、由已知張量建立形狀相同的張量

torch.zeros_like(), torch.ones_like(), torch.rand_like()

m = torch.zeros_like(n1)
print(m)
m1 = torch.ones_like(n2)
print(m1)
m2 = torch.rand_like(n3)
print(m2)

結果:

tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
tensor([[[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]],

        [[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]]])
tensor([[0.1613, 0.7150],
        [0.5519, 0.4913]])

4、由已知張量建立不同尺寸的張量

(一般很少用到)

print(t1.new_tensor([1,2,3]))
print(t1.new_zeros(2,3))
print(t1.new_ones(3,3))

結果:

tensor([1, 2, 3])
tensor([[0, 0, 0],
        [0, 0, 0]])
tensor([[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]])

未完待續,將會在後續繼續更新