概念解释
import torch
# 生成数组
x = torch.arange(12)
# tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
# 查看维度
x.shape
# torch.Size([12])
# 查看number of element(元素的总数)
x.numel()
# 12
# 改变张量的形状
X = x.reshape(3,4)
"""
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
"""
# 生成全0、全1、自己设定、随机的数字。需要自定维度
torch.zeros((2, 3, 4))
torch.ones((2, 3, 4))
torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) # 维度为[3,4]
torch.randn(3, 4) # 随机数
# tensor的加减乘除
x = torch.tensor([1.0, 2, 4, 8]) # 1.0为浮点数
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y # 加减乘除
"""
(tensor([ 3., 4., 6., 10.]),
tensor([-1., 0., 2., 6.]),
tensor([ 2., 4., 8., 16.]),
tensor([0.5000, 1.0000, 2.0000, 4.0000]),
tensor([ 1., 4., 16., 64.]))
"""
# 按元素做指数运算
torch.exp(x) # 做指数运算
# tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])
# 连结(concatenate)张量
X = torch.arange(12, dtype=torch.float32).reshape((3,4)) # 指定类型为float32
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1) # dim=0为按行合并(向下),dim=1为按列合并(向右)
"""
(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 2., 1., 4., 3.],
[ 1., 2., 3., 4.],
[ 4., 3., 2., 1.]]),
tensor([[ 0., 1., 2., 3., 2., 1., 4., 3.],
[ 4., 5., 6., 7., 1., 2., 3., 4.],
[ 8., 9., 10., 11., 4., 3., 2., 1.]]))
"""
# 判断张量是否相等
X == Y
"""
tensor([[False, True, False, True],
[False, False, False, False],
[False, False, False, False]])
"""
# 求和,获得单元素张量
X.sum()
# tensor(66.)
# 获得行、列元素
X[-1], X[1:3] # -1获得最后一行,[1:3]获得第1、2行
"""
(tensor([ 8., 9., 10., 11.]),
tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]))
"""
# 赋值
X[1, 2] = 9
X[0:2, :] = 12 # 对第0、1行的所有列赋值为12
# 广播机制
a = torch.arange(3).reshape((3, 1)) # 张量=数组,在数学上不一样
b = torch.arange(2).reshape((1, 2))
"""
(tensor([[0],
[1],
[2]]),
tensor([[0, 1]]))
"""
"""
a的维度变成(3,1->2),b的维度变成(1->3,2)
00 01 01
11 + 01 = 12
22 01 23
"""
a + b
"""
tensor([[0, 1],
[1, 2],
[2, 3]])
"""
before = id(Y)
Y = Y + X
id(Y) == before
# False。因为Y被新分配了内存
before = id(X)
X += Y # 这样操作没有分配新内存
id(X) == before
# True
A = X.numpy() # tensor->ndarray
B = torch.tensor(A) # ndarray->tensor
type(A), type(B)
# (numpy.ndarray, torch.Tensor)
# # tensor的标量获得值
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
# (tensor([3.5000]), 3.5, 3.5, 3)