PyTorch深度学习(16)tensor张量

43 篇文章 16 订阅
34 篇文章 7 订阅

一、什么是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))

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值