- 基本操作
import torch
# 创建一个向量
x = torch.arange(12)
# 形状
x.shape
# 大小(元素的个数)
x.numel()
# 改变形状
x.reshape(3,4) #指定为-1的维度会自动计算
# 全0矩阵
torch.zeros((3,4))
#全1矩阵
torch.ones((3,4))
#高斯分布矩阵
torch.randn(3,4)
# 从列表创建张量
torch.tensor([[1,2,3],[4,5,6],[5,6,2]])
- 数据运算
# 基本运算
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y  # **运算符是求幂运算
torch.exp(x)
# 形状拼接
# dim=0,按行拼接,dim=1,按列拼接
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
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)
# 逻辑运算
X == Y #元素相等位置为1,否则为0
# 求和
X.sum()
# 广播,沿着数组中长度为1的轴进行广播
# a会被扩展成3*2张量,b会被扩展为3*2张量,进而计算
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
- 索引和切片
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
X[-1]
X[1:3]
X[1:2] = 9
X[0:2,:]=1
# 使用切片赋值不会分配新的内存,提高性能
Z = torch.zeros_like(Y)
print('id(Z):', id(Z))
Z[:] = X + Y
print('id(Z):', id(Z))
- 与numpy的转换
A = X.numpy()
B = torch.tensor(A)
type(A), type(B)  #(numpy.ndarray, torch.Tensor)
# 将大小为1的张量转换为标量
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)  #(tensor([3.5000]), 3.5, 3.5, 3)
- 与pandas转换
# inputs为pd.DataFrame
X = torch.tensor(inputs.to_numpy(dtype=float))