Pytorch 基础知识

学习目标:

  • 掌握Pytorch基本语法
    Pytorch的一些语法和numpy中的一些语法十分相似,本文只总结其中相对比较难以理解的内容

学习内容:

1. 张量的定义:

几何代数中定义的张量是基于向量和矩阵的推广,比如我们可以将标量视为零阶张量,矢量可以视 为一阶张量,矩阵就是二阶张量。

  • 零维张量表示一个数字,也可以称之为标量
  • 一维张量表示一个向量
  • 二维张量表示一个矩阵
  • 三维张量 可以用来表示图片(RGB)

2. pytorch索引

需要注意的是:索引出来的结果与原数据共享内存,修改一个,另一个会跟着修改。
x=torch.ones(4,3,dtype=torch.double)
print(x)
y=x[0,:]
y+=1
print(y)
print(x)

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

2. Pytorch的unsqueeze和squeeze使用:

目的是用于扩展或压缩tensor的维度,使其与目标数据格式一致

2.1 unsqueeze 用法

import torch
x=torch.arange(0,6)
x=x.view(2,3)
print(x)
#第二维增加一个维度
b=x.unsqueeze(1)
print(b)
print(b.shape)

输出结果:
tensor([[0, 1, 2],
        [3, 4, 5]])
tensor([[[0, 1, 2]],

        [[3, 4, 5]]])   #增加了1维
torch.Size([2, 1, 3])

2.2 squeeze使用:

#在第0行增加一维
b=x.unsqueeze(0)
print(b)
print(b.shape)
c=b.squeeze(-3)   #去除第1维度 ,填0也可以
print(c)
print(c.shape)
输出结果:
tensor([[[0, 1, 2],
         [3, 4, 5]]])  #多了一个方框 [],第0维增加了
torch.Size([1, 2, 3])
tensor([[0, 1, 2],
        [3, 4, 5]])
torch.Size([2, 3])

你可能感兴趣的:(Pytorch,pytorch,python,深度学习)