PyTorch Tensor(张量)入门

import torch

# 张量tenser
# arange:类似range[start,end,step]
x = torch.arange(12)
print(x)

# .shape, .numel() 获取张量的形状和总数
print(x.shape, x.numel())

# reshape() 改变张量的形状. 缺省量可以用-1代替
X = x.reshape(3, 4)
print(X)

# .zeros, .ones 生成特殊张量
print(torch.zeros(2, 3, 4))

# .randn 生成随机的、服从标准正态分布N(0,1)的张量
print(torch.randn(3, 4))

# 给定数据生成张量:逐行输入。注意tenser数据类型为浮点数
print(torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4]]))


# 运算符
# 四则运算符与幂运算符视为按元素操作
x = torch.tensor([1, 2, 3, 4])
y = torch.tensor([1, 1, 1, 1])
print(x + y, x - y, x * y, x / y, x ** y)

# 幂运算函数也视为按元素操作
print(torch.exp(x))

# 利用cat()可将张量连结在一起, dim表示按第几个轴连结
X = torch.arange(12).reshape(3, 4)
Y = torch.arange(12, 24).reshape(3, 4)
print(torch.cat((X, Y), dim=0)) # 6*4张量
print(torch.cat((X, Y), dim=1)) # 3*8张量

# 逻辑运算符也逐元素操作,返回值为一同尺寸张量,每处的值为其运算结果
print(x == y)

# .sum()对所有元素求和,返回单元素张量
print(x.sum())

# 广播机制
# 以上运算均限制张量尺寸相同或者符合某些条件。当形状不同的张量运算时,会触发广播机制。
# 广播机制是指先复制元素来扩展这些运算的张量,在转换之后具有恰当的形状以便运算。
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
print(a, b, a + b)
# 以上运算中,a复制一列,b复制两行,按照得到的3*2矩阵运算

# 索引和切片
# 如同数组,张量中的元素可以通过索引访问,第一个为0,最后一个为-1
X = torch.arange(12).reshape(3, 4)
print(X[-1], X[1:3])

# 可以指定索引修改张量的值
X[1, 2] = 9
print(X)
X[0:2, :] = 100 # 同时修改多个索引位置的值
print(X)

# 节省内存
# 在torch的张量运算中,Y=Y+X会不必要地给Y分配新的内存
# 可以使用切片表示赋值以节省内存
Z = torch.zeros_like(Y) # zeros_like生成一个相同尺寸的零张量
print('id(Z) = ', id(Z)) # id(Z)表示Z的地址
Z[:] = X + Y # 切片法运算
print('id(Z) = ', id(Z)) # id(Z)表示Z的地址
# 使用X[:] = X + Y , X += Y也可以实现上述效果

# Tensor与NumPy的相互转换
A = X.numpy()
B = torch.tensor(A)
print(type(A), type(B))

# 调用item()或Python内置函数将单元素张量转化为标量
a = torch.tensor([2022.1])
print(a, a.item(), float(a), int(a))

    所属分类:Python     发表于2022-01-29