pytorch基础知识

前言

本文转载于【pytorch基础知识】10分钟快速复习笔记|代码可直接运行|多实例 - 知乎

pytorch里的数据统称为张量(tensor),张量表示由⼀个数值组成的数组,这个数组可能有多个维度。具有一个轴的张量对应数学上的向量(vector)。 具有两个轴的张量对应数学上的矩阵(matrix)。具有两个轴以上的张量没有特殊的数学名称。 优点:张量(tensor)⽀持⾃动微分和GPU并行加速运算。

1 Tensor数据类型

  • 32位浮点型:torch.float、torch.float32。浮点型默认32位。
  • 64位整型:torch.long、troch.int64。整型默认64位。
  • 32位整型:http://torch.int、torch.int32。
  • 16位整型:torch.short、torch.float16。
  • 64位浮点型:torch.double、torch.float64。
b=[2.0,4]
b=torch.tensor(b).to(torch.float32)

2 Tensor的基本概念和操作

import torch

2.1 标量

a = torch.tensor(1.0)  #根据data生成不同类型tensor
# a = torch.Tensor(1.0)  会报错,应修改为 a = torch.Tensor([1.0]) 只生成torch.float类型。
print("标量:", a)

输出:标量: tensor(1.)

2.2 向量

b = torch.tensor([1, 0, 2])
print("向量:", b)

输出:向量: tensor([1, 0, 2])

2.3 矩阵

c = torch.tensor([[1, 2],[3, 4]])
print("矩阵:", c)

输出:矩阵: tensor([[1, 2],
                   [3, 4]])

2.4 多维张量

d = torch.tensor([[[1, 2],[3, 4]],[[5,6],[7,8]]])
print("多维张量:", d)

输出:多维矩阵: tensor([[[1, 2],
                       [3, 4]],

                      [[5, 6],
                       [7, 8]]])

2.5 创建一个大小为(3,4)空的tensor

e = torch.empty(3, 4)
print(e)

输出:tensor([[0., 0., 0., 0.],
             [0., 0., 0., 0.],
             [0., 0., 0., 0.]])

2.6 创建一个大小为(3,5)的tensor,元素随机产生

f = torch.rand(5, 3)
print(f)

输出:tensor([[0.4469, 0.3355, 0.8299, 0.5071, 0.3735],
             [0.2966, 0.8454, 0.7083, 0.7606, 0.8961],
             [0.2339, 0.1641, 0.9898, 0.1519, 0.0948]])

2.7 创建一个大小为(3,3)的tensor,元素全为0,类型为64位整型

g = torch.zeros(5, 3, dtype=torch.long)
print(g)

输出:tensor([[0, 0, 0],
             [0, 0, 0],
             [0, 0, 0]])

2.8 创建一个大小为(2,3)的tensor,元素全为1,类型为64位浮点型

h = torch.ones(5, 3, dtype=torch.double)
print(h)

输出:tensor([[1., 1., 1.],
             [1., 1., 1.]], dtype=torch.float64)

2.9 创建大小和h一样的tensor,元素随机

i = torch.rand_like(h, dtype=torch.float)
print(i)

输出:tensor([[0.5246, 0.4422, 0.5519],
             [0.3224, 0.6082, 0.2636]])

3 Tensor的基本运算

y = x + y 系统将取消引⽤ y 的地址,指向新地址。y指向地址不同。

y[:] = x + y 和 y += x 系统不再分配新空间,y指向的地址相同。

3.1 加法

j = torch.tensor([1, 2, 3])
k = torch.tensor([2, 3, 4])

## 加法1
print("Tensor 加法:", j + k)

## 加法2
print("Tensor 加法:", torch.add(j, k))

## 加法3 改变j的值
print("Tensor 加法:", j.add_(k))

输出:Tensor 加法: tensor([3, 5, 7])


##广播机制
j = torch.tensor([[1],[2]])
k = torch.tensor([2, 3, 4])

print("Tensor 加法:", j + k)
输出:tensor([[3, 4, 5],
              [4, 5, 6]])

3.2 乘法

## 向量乘法、对应坐标相乘相加
n = torch.tensor([1, 2])
p = torch.tensor([2, 3])
print("Tensor 乘法:", torch.dot(n, p))
输出:Tensor 乘法: tensor(8)

## 矩阵乘法
n = torch.ones(2, 3)
p = torch.ones(3, 2)
print("Tensor 乘法:", torch.mm(n, p))           # 只支持二维乘法
#print("Tensor 乘法:", torch.matmul(n, p))      # 支持三维乘法
#print("Tensor 乘法:", n.mm(p))
#print("Tensor 乘法:", n@p)
输出:Tensor 乘法: tensor([[3., 3.],
                          [3., 3.]])

## 点积、对应位置相乘
n = torch.ones(2, 3)
p = torch.ones(2, 3)
print("Tensor 乘法:", torch.mul(n, p))
#print("Tensor 乘法:", n*p)
输出:Tensor 乘法: tensor([[1., 1., 1.],
                            [1., 1., 1.]])

3.3 除法

l = torch.tensor([6, 9])
m = torch.tensor([3, 3])

## 除法1
print("Tensor 除法:", l // m)

## 除法2
print("Tensor 除法:", torch.true_divide(l, m))

输出:Tensor 除法: tensor([2., 3.])

3.4 幂运算

q = torch.tensor([2, 3])

## 方法1
print("Tensor 幂运算:", torch.pow(q, 2))

## 方法2
print("Tensor 幂运算:", q.pow(2))

## 方法3
print("Tensor 幂运算:", q**2)

输出:Tensor 幂运算: tensor([4, 9])

3.5 开根号

r = torch.tensor([4, 9])

## 方法1
print("Tensor 开根号运算:", r.sqrt())

## 方法2
print("Tensor 开根号运算:", torch.sqrt(r))

输出:Tensor 开根号运算: tensor([2., 3.])

3.6 对数运算

## 方法1
s1 = torch.tensor([2, 4, 8])
print("Tensor 对数运算:", torch.log2(s1))
输出:Tensor 对数运算: tensor([1., 2., 3.])

## 方法2
s2 = torch.tensor([10, 100])
print("Tensor 对数运算:", torch.log10(s2))
输出:Tensor 对数运算: tensor([1., 2.])

## 方法3
s3 = torch.tensor([3, 4, 5])
print("Tensor 对数运算:", torch.log(s3))
输出: Tensor 对数运算: tensor([0.6931, 1.0986, 1.3863])

3.7 取整

t = torch.tensor([1.4, 2.5, 3.6])

## 方法1
print("向下取整数 floor() :", t.floor())
输出:向下取整数 floor() : tensor([1., 2., 3.])

## 方法2
print("向上取整数 ceil() :", t.ceil())
输出:向上取整数 ceil() : tensor([2., 3., 4.])

## 方法3
print("四舍五入 round() :", t.round())
输出:四舍五入 round() : tensor([1., 2., 4.])

## 方法4
print("取整数部分 trunc() :", t.trunc())
输出:取整数部分 trunc() : tensor([1., 2., 3.])

3.8 取余

## 方法1
t = torch.tensor([1.4, 2.5, 3.6])
print("只取小数部分 frac() :", t.frac())
输出:只取小数部分 frac() : tensor([0.4000, 0.5000, 0.6000])

## 方法2
print("取余 % :", torch.tensor([5, 7]) % 3)
输出:取余 % : tensor([2, 1])

4 Tensor自带属性

4.1 查看tensor形状shape、改变形状resize、reshape、view

u = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])

print(u.shape)
print(u.size())
输出:torch.Size([2, 3])

## 方法1:resize
print("(2, 3) -> (3, 2):\n",u.resize(3, 2)) 
u.resize(2, 3)

## 方法2:reshape
print("(2,3) -> (3,2):\n", u.reshape(3, 2))
u.reshape(2, 3)

## 写法3:view (u的形状不改变)
print("(2,3) -> (3,2):\n", u.view(3, 2))

输出:(2, 3) -> (3, 2) : 
 tensor([[1, 2],
         [3, 4],
         [5, 6]])

## permute
a=np.array([[[1,2,3],[4,5,6]]]) 
unpermuted=torch.tensor(a)
print(unpermuted.size())  
print(unpermuted)
输出:
torch.Size([1, 2, 3])
tensor([[[1, 2, 3],
         [4, 5, 6]]], dtype=torch.int32)
 
permuted=unpermuted.permute(2,0,1)
print(permuted.size())  
print(permuted)

输出:
torch.Size([3, 1, 2])
tensor([[[1, 4]],
        [[2, 5]],
        [[3, 6]]], dtype=torch.int32)

4.2 获取tensor里的某个值和tensor元素个数

v = torch.tensor([2.3, 4.2, 3])
print("获取Tensor的值:item() : ", v[1].item())
输出:获取Tensor的值:item() :  4.199999809265137

print("获取Tensor的个数:numel() : ", v.numel())
输出:获取Tensor的个数:numel() :  4

4.3 分离计算图

#方法1
with torch.no_grad():
...
#方法2
tensor.detach()

4.4 tensor 转 numpy ,numpy 转 tensor

w = torch.tensor([4, 5, 6])

## tensor 转 numpy
print("Tensor 转 Numpy :", w.numpy())
输出:Tensor 转 Numpy : [1 2 3]
#------------------------------------------------------

import numpy as np
w2 = np.ones(3)

## numpy 转 tensor
#方法1  转换前后共享内存
print("Numpy 转 Tensor :\n", torch.from_numpy(w2))  
print("Numpy 转 Tensor :\n", torch.as_tensor(w2)) 

#方法2 开辟新内存
print("Numpy 转 Tensor :\n", torch.tensor(w2))
print("Numpy 转 Tensor :\n", torch.Tensor(w2))
输出:Numpy 转 Tensor : tensor([1., 1., 1.], dtype=torch.float64)

4.5 判断是否有GPU,把数据放在GPU上

device = ""
if torch.cuda.is_available():
    device = torch.device('cuda')
else:
    device = torch.device('cpu')
#方法1
x = torch.tensor([2, 3])
x.to(device)

#方法2
x1 = torch.tensor([2, 3], device=device)

5 pytorch常用函数

5.1 求tensor第1维度的均值

a = torch.tensor([[1., 2.], [3., 4.]])
print(torch.mean(a, dim = 1))

输出:tensor([1.5000, 3.5000])

5.2 求tensor第1维度的和

print(torch.sum(a, dim = 1))
#a.cumsum(axis=0) 第0轴累积和

输出:tensor([3., 7.])

5.3 求tensor第1维度的积

print(torch.prod(a, dim = 1))

输出:tensor([ 2., 12.])

5.4 求tensor第1维度的最大值和最小值

##最大值
print(torch.max(a, dim = 1))
输出:torch.return_types.max(
                values=tensor([2., 4.]),
               indices=tensor([1, 1]))

##最小值
print(torch.min(a, dim = 1))
torch.return_types.min(
                values=tensor([1., 3.]),
               indices=tensor([0, 0]))

5.5 求tensor第1维度的最大值下标和最小值下标

##最大值下标
print(torch.argmax(a, dim = 1))
输出:tensor([1, 1])

##最小值下标
print(torch.argmin(a, dim = 1))
输出:tensor([0, 0])

5.6 求tensor第1维度标准差std和方差var

##标准差
print(torch.std(a, dim = 1))
输出:tensor([0.7071, 0.7071])

##方差
print(torch.var(e, dim = 1))
输出:tensor([0.5000, 0.5000])

5.7 求tensor第1维度中位数和众数

##中位数
b = torch.tensor([[2., 3., 4], [3., 4., 5]])
print(torch.median(b, dim = 1))
输出:torch.return_types.median(
                 values=tensor([3., 4.]),
                indices=tensor([1, 1]))

##众数
b = torch.tensor([[2., 3., 3], [4., 4., 5]])
print(torch.mode(b, dim = 1))
输出:torch.return_types.mode(
               values=tensor([3., 4.]),
              indices=tensor([2, 1]))

5.8 随机种子

torch.manual_seed(222)

5.9 改变tensor形状

c = torch.tensor([[1,2,3],
                  [4,5,6]])
print(torch.reshape(c, (3, 2)))

输出:tensor([[1, 2],
             [3, 4],
             [5, 6]])

5.10 tensor转置

c = torch.tensor([[1,2,3],
                  [4,5,6]])
print(torch.t(c))

输出:tensor([[1, 4],
             [2, 5],
             [3, 6]])

5.11 交换tensor两个维度

c = torch.tensor([[1,2,3],
                  [4,5,6]])
print(torch.transpose(c, 1, 0))

输出:tensor([[1, 4],
             [2, 5],
             [3, 6]])

5.12 压缩tensor维度

e = torch.tensor([[1],[1]])
print(torch.squeeze(e))

输出:tensor([1, 1])

5.13 扩充矩阵维度

f = torch.tensor([1,2,3,4])
torch.unsqueeze(f, 1)

输出:tensor([[1],
             [2],
             [3],
             [4]])

5.14 去除某个维度,返回多个tensor

g = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])
print(torch.unbind(g, dim=0))

输出:(tensor([1, 2, 3]), tensor([4, 5, 6]))

5.15 按照给定维度翻转张量

h = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])
print(torch.flip(h, [0,1]))

输出:tensor([[6, 5, 4],
             [3, 2, 1]])

5.16 逆时针旋转tensor

a = torch.tensor([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
print(torch.rot90(a, 1, [0,1]))

输出:tensor([[3, 6, 9],
             [2, 5, 8],
             [1, 4, 7]])

5.17 tensor 组合拼接

a1 = torch.tensor([1, 2, 3], dtype=torch.float)
a2 = torch.tensor([4, 5, 6], dtype=torch.float)

##方法1
print(torch.cat([a1, a2], dim=0))
输出:tensor([1., 2., 3., 4., 5., 6.])

##方法2
print(torch.stack([a1, a2], dim=1))
输出:tensor([[1., 4.],
             [2., 5.],
             [3., 6.]])

5.18 从tensor中挑选出满足条件的元素

= torch.tensor([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
print(torch.where(x < 5)) 

输出:(tensor([0, 0, 0, 1]), tensor([0, 1, 2, 0])) #输出对应维度的索引值

5.19 gather按照索引输出tensor

b = torch.Tensor([[1,2,3],[4,5,6]])
index_1 = torch.LongTensor([[0,2],[1,0]])
print(torch.gather(b, dim=1, index=index_1))

#torch.gather(input, dim, index, out=None)
输出:tensor([[1., 3.],
             [5., 4.]])

5.20 index_select指定索引输出tensor

a  = torch.Tensor([[1,2,3],[4,5,6]])
print(torch.index_select(a, dim = 0, torch.tensor([0])))

输出:tensor([[1., 2., 3.]])

5.21 eq、ne、gt、lt、ge、le

eq 等于,ne不等于,gt大于,lt小于,ge,大于等于,le小于等于

x = torch.tensor([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
mask = x.gt(5)
print(x.gt(5))
输出:tensor([[False, False, False],
             [False, False,  True],
             [ True,  True,  True]])

5.22 masked_select选择标记索引

##x和mask见5.21
print(torch.masked_select(x, mask))

输出:tensor([6, 7, 8, 9])

5.23 将tensor看成1维

src = torch.tensor([[4,3,5],
                    [6,7,8]])
print(torch.take(src, torch.tensor([0, 2, 5])))

输出:tensor([4, 5, 8])

5.24 tensor 切片

a = torch.Tensor([[1,2,3],
                  [4,5,6],
                  [7,8,9],
                  [10,11,12]])
print(torch.chunk(a, 2, dim=0))
print(torch.split(a, 2, dim=0))
输出:(tensor([[1., 2., 3.],[4., 5., 6.]]), 
       tensor([[ 7.,  8.,  9.],[10., 11., 12.]]))

print(torch.split(a, [1, 2, 1], dim=0))
输出:(tensor([[1., 2., 3.]]), 
       tensor([[4., 5., 6.],[7., 8., 9.]]), 
       tensor([[10., 11., 12.]]))

print(a[1:2, 0:1])
输出:(tensor([[4,5],
               [7,8]]))

5.23 tensor 排序

w = torch.tensor([2, 1, 5, 9, 4, 8, 3])
print("Tensor 升序:", torch.sort(w,descending=False))

输出:Tensor 升序: torch.return_types.sort(
       values=tensor([1, 2, 3, 4, 5, 8, 9]),
      indices=tensor([1, 0, 6, 4, 2, 5, 3]))

5.24 返回指定维度最大最小k个数和索引值

x = torch.tensor([2, 1, 5, 9, 4, 8, 3])
print("Tensor 最大4个元素:", torch.topk(x, k=4, dim=0, largest=True, sorted=True, out=None))

输出:Tensor 最大4个元素: torch.return_types.topk(
                            values=tensor([9, 8, 5, 4]),
                            indices=tensor([3, 5, 2, 4]))

5.25 第k个最小值和索引值

x = torch.tensor([2, 1, 5, 9, 4, 8, 3])
print("Tensor 返回第k个最小值和索引值:", torch.kthvalue(x, 5, dim=0))

输出:Tensor 沿着指定纬度返回第k个最小值及其索引值: torch.return_types.kthvalue(
       values=tensor(5),
       indices=tensor(2))

5.26 判断是否为nan、inf、finite

y = torch.tensor([2, 3, 4])

print(torch.isnan(y)) # 检查是否是无穷大
输出:tensor([False, False, False])

print(torch.isfinite(y))# 参数有效返回true
输出:tensor([True, True, True])

print(torch.isinf(y)) # 检查是否是无穷大
输出:tensor([False, False, False])
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值