Tensor的基本操作

一、张量的创建与类型

张量最基本创建方法和Numpy中创建Array的格式一致,都是创建函数的格式。

1.1 通过列表创建

t = torch.tensor([1, 2])
print(t)
# tensor([1, 2])

1.2 通过元组创建

t = torch.tensor((1, 2))
print(t)
# tensor([1, 2])

1.3 通过Numpy创建

import numpy as np
n = np.array([1, 2])
t = torch.tensor(n)
print(t)
# tensor([1, 2])

1.4 张量的类型

i = torch.tensor([1, 2])
f = torch.tensor([1.0, 2.0])
print(type(i), i.dtype, sep = ' , ')
print(type(f), f.dtype, sep = ' , ')
# <class 'torch.Tensor'> , torch.int64
# <class 'torch.Tensor'> , torch.float32

1.5 张量类型的转化方法

t = torch.tensor([1, 2])
f = t.float()
print(f)
print(t)
# tensor([1., 2.])
# tensor([1, 2])

二、张量的维度

# 一维向量
t1 = torch.tensor((1, 2))
# 二维向量
t2 = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 三维向量
t3 = torch.tensor([[[1, 2], [3, 4]],[[5, 6], [7, 8]]])

2.1 ndim查看张量维度

print(t1.ndim, t2.ndim, t3.ndim, sep = ', ')

# 1, 2, 3

# t1为1维向量

# t2为2维矩阵

# t3为3维张量

2.2 shape&size查看向量的形状

  1. print(t1.shape, t2.shape, t3.shape, sep = ', ')

  2. # torch.Size([2]), torch.Size([2, 3]), torch.Size([2, 2, 2])

  3. print(t1.size(), t2.size(), t3.size(), sep = ', ')

  4. # torch.Size([2]), torch.Size([2, 3]), torch.Size([2, 2, 2])

t1向量torch.Size([2])的理解:向量的形状是1行2列。

t2矩阵torch.Size([2, 3])的理解:包含两个一维向量,每个一维向量的形状是1行3列。

t3矩阵torch.Size([2, 2, 2])的理解:包含两个二维矩阵,每个二维矩阵的形状是2行2列。

2.3 numel查看张量中的元素个数

print(t1.numel(), t2.numel(), t3.numel(), sep = ', ')
# 2, 6, 8
# t1向量中共有2个元素
# t2矩阵中共有6个元素
# t3张量中共有8个元素

2.4 flatten将任意维度张量转为一维张量

t2.flatten()
# tensor([1, 2, 3, 4, 5, 6])
 
t3.flatten()
# tensor([1, 2, 3, 4, 5, 6, 7, 8])

2.5 reshape任意变形

形变维度的乘积需要等于张量元素的个数。

# 将`t3`变成2×4的矩阵
t3.reshape(2, 4)
#tensor([[1, 2, 3, 4],[5, 6, 7, 8]])
 
# 将`t3`变成1×4×2的矩阵
t3.reshape(1, 4, 2)
# tensor([[[1, 2], [3, 4], [5, 6], [7, 8]]])

2.6 squeeze&unsqueeze

  • squeeze的作用是压缩张量,去掉维数为1位置的维度

# 将t3的维度变为2×1×4
t_214 = t3.reshape(2, 1, 4)
print(t_214)
# tensor([[[1, 2, 3, 4]], [[5, 6, 7, 8]]])
 
# 使用squeeze将其变成2×4,去掉维度为1位置的维度
t_24 = t_214.squeeze(1)
print(t_24)
# tensor([[1, 2, 3, 4], [5, 6, 7, 8]])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值