1、张量的创建和维度 2、张量的运算
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]]
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]])
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]])
(一般很少用到)
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]])
未完待续,将会在后续继续更新
原文:https://www.cnblogs.com/ASTHNONT/p/13294953.html