学习材料:Pytorch 入门到精通全教程 卷积神经网络 循环神经网络_哔哩哔哩_bilibili
1.创建tensor
(1)使用列表或者数组创建tensor
#使用列表为参数
torch.Tensor([[1,2,3],[4,5,6]])
#使用array作为参数
torch.Tensor(np.array([[1,2,3],[4,5,6]]))
(2)使用torch自带的api创建tensor
torch.ones([3,4]) #创建3行4列值为1的tensor
torch.zeros([3,4]) #创建3行4列值为0的tensor
torch.empty(3,4) #创建3行4列的tensor,使用无意义的值填充
torch.rand([3,4]) #创建3行4列值为随机数的tensor,随机数范围[0,1)
2.tensor中的方法
(1)tensor转为numpy
t=torch.Tensor([[1,2,3],[4,5,6]])
t.numpy()
'''
array([[1., 2., 3.],
[4., 5., 6.]], dtype=float32)
'''
(2)获取tensor的维度信息
t=torch.Tensor([[1,2,3],[4,5,6]])
t.size()
#torch.Size([2, 3])
t.size(0) #获取某一维度的size
#2
(3)改变tensor形状
t=torch.Tensor([[1,2,3],[4,5,6]])
t.view(3,2) #类似reshape函数
'''
tensor([[1., 2.],
[3., 4.],
[5., 6.]])
'''
t.view(1,-1) #-1表示随着前面维度的变化而变化
'''
tensor([[1., 2., 3., 4., 5., 6.]])
'''
(4)转置
t=torch.Tensor(np.arange(24).reshape(2,3,4))
t
'''
tensor([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]],
[[12., 13., 14., 15.],
[16., 17., 18., 19.],
[20., 21., 22., 23.]]])
'''
#t.permute(1,0,2)
t.transpose(0,1) #第1个维度和第2个维度的转置
'''
tensor([[[ 0., 1., 2., 3.],
[12., 13., 14., 15.]],
[[ 4., 5., 6., 7.],
[16., 17., 18., 19.]],
[[ 8., 9., 10., 11.],
[20., 21., 22., 23.]]])
'''
(5)tensor相加
t1=torch.Tensor(np.arange(24).reshape(2,3,4))
t2=torch.Tensor(np.arange(24).reshape(2,3,4))
t1.add(t2) #tensor相加
t1.add_(t2) #相加后对t1就地修改