一、什么是tensor?
scalar(标量):一个数值 2
vector(向量):一个数组 [2],[3]
matrix(矩阵):二维数组 [[2,3], [4,5]]
tensor(张量):大于二维的数组,即多维数组
tensor的类型
numpy.float64、numpy.float32、numpy.float16、numpy.int64、numpy.int32
numpy.int16、numpy.int8、numpy.uint8、numpy.bool
备注:pip 安装时使用清华源
-i https://pypi.tuna.tsinghua.edu.cn/simple
二、torch 操作tensor方法
import torch
import numpy as np
# 1.是否是tensor
x = [2, 9, 5, 16, 23, 35]
torch.is_tensor(x)
y = torch.rand(1, 2)
torch.is_tensor(y)
torch.numel(y) # 统计tensor中元素个数
# 2.创建全零的tensor
z = torch.zeros(3, 3)
z_num = torch.numel(z)
print('{} 数量为:{}'.format(z, z_num))
# 3.创建对角线为1的tensor
e = torch.eye(3, 3)
print(e)
# 4.将Numpy转换为tensor
x = np.array([3, 4, 5, 6, 7])
torch.from_numpy(x) # 将数组转换为tensor
# 5.切分linspace
x = torch.linspace(2, 10, steps=5) # 2~10之间切分为5份
print(x)
# 6.均匀分布,值在0到1之间
print(torch.rand(10))
# 7.正态分布,均值为0,方差为1
print(torch.randn(10))
# 8.选择随机数
print(torch.randperm(10))
# 9.生成一个区间的数
print(torch.arange(10, 30, 5)) # 开始,结尾,步长
# 10.获取行或列的最小值和最大值的索引
x = torch.randint(1, 99, (3, 3))
print(x)
print(torch.argmin(x, dim=0)) # 每一列中最小值索引
print(torch.argmax(x, dim=0)) # 每一列中最大值索引
# 11.连接
x = torch.randint(1, 10, (2, 3))
print(torch.cat((x, x)))
print(torch.cat((x, x), dim=1)) # 横向并排
# 12.chunk 切块
a = torch.randint(1, 10, (3, 3))
print(torch.chunk(a, 2, 0)) # 0 横向切
print(torch.chunk(a, 2, 1)) # 1 纵向切
# 13.index_select 根据索引选择
x = torch.randn(4, 4)
indices = torch.tensor([0, 2])
print(torch.index_select(x, 0, indices)) # 0,1 方向 indices索引 只输出下标是0和2的值
# 14.split 分割
x = torch.tensor([1, 2, 3, 4, 5, 6, 7])
print(torch.split(x, 3)) # 将tensor切分为3份
# 15. .t和.transpose 转置
x = torch.tensor([[1, 2], [3, 4]])
print(x.t())
print(x.transpose(1, 0))
# 16. tensor运算
x = torch.tensor([[1, 2], [3, 4]])
print(torch.add(x, 1))
print(torch.mul(x, 2))