pytorch学习(一)基础入门

本文介绍了PyTorch的基础知识,包括为何选择PyTorch,Windows系统的安装步骤,以及PyTorch的核心特性:张量运算、自动求导。文章详细讲解了张量的创建、运算及与Numpy的转换,并演示了如何在PyTorch中实现自动求导,适合初学者入门。
摘要由CSDN通过智能技术生成

why pytorch?

pytorch是一个最近比较火的深度学习框架,但目前仅支持linux和osx系统,所以windows系统需要通过虚拟机去安装。
pytorch是一个提供两个强大功能的python包:

  • 具有强GPU加速度的张量计算,如numpy
  • 深层神经网络

pytorch的安装(windows系统)

配置安装环境

参考博文:Win7 配置Pytorch教程link
机器环境:win7 64位
anaconda 版本:4.3.30
python 版本 3.5

step1:利用anaconda创建虚拟环境
在conda prompt键入 conda create -n env_name [python=3.x] 其中env_name为自定义命名,[]里面可以指定python或者其他包版本,若不知指定python版本 则默认安装最新的python版本;创建虚拟环境后,用activate env_name指令激活
在这里插入图片描述

注:step1可以省略,创建虚拟环境后安装pytorch在调用时必须切换至虚拟环境中,并且要通过进一步配置才能在jupyter中展现,参考博客:如何在 Jupyter Notebook 中使用 PyTorch ==>link

step2:安装pytorch
进入链接:https://pytorch.org/get-started/locally/
根据自己的配置选择指令
在这里插入图片描述
由于博主未安装CUDA(一直安装失败),所以这一栏是none
选用指令conda install pytorch-cpu torchvision-cpu -c pytorch安装pytorch的CPU版本;根据提示安装一些package

step3:环境检测

import torch #检测pytorch是否存在
print(torch.cuda.is_available()) #检测pytorch的gpu版本(返回False,因为没有安装cuda)

Pytorch初入门

推荐一个pytorch入门教程(PyTorch 深度学习: 60 分钟极速入门),传送门===》link

教程目标:

  • 更高层次理解Pytorch的Tensor库以及神经网络
  • 训练一个小的神经网络模型用于分类图像
    注:确保安装torch和torchvision

什么是Pytorch

张量

torch创建的张量Tensor类似于Numpy的ndarray
1.创建张量(随机矩阵、零矩阵)

import torch

# 创建张量
x = torch.empty(5,3)  # 创建一个没有初始化的5*3矩阵
print(x) 

x = torch.rand(5,3) # 创建一个随机初始化的矩阵
print(x)

x = torch.zeros(5,3,dtype = torch.long) # 构造一个long型的零矩阵
print(x)

2.根据数据构建张量

## 根据数据构造张量
x = torch.tensor([5.5,3]) # 对照np.array([5,3])
print(x)

## 根据arange函数构建
torch.arange(5)## arange函数构建

## 根据已有的tensor建立新的tensor
x = x.new_ones(5,3,dtype=torch.double) 
print(x)
x = torch.randn_like(x,dtype=torch.float) # dtype属性被重载
print(x) # 除非用户提供新的值,否则这些方法将重用输入张量的属性,例如dtype

3.计算张量维度

## 计算形状(对照numpy.shape)
print(x.size()) # torch.size本质是tuple

x = torch.randn(4,4)
y = x.view(16) # 改变维数
z = x.view(-1,8) # -1表示从其他维度推断当前维数
print(x.size(), y.size(), z.size())

4.索引操作

print(x[:,1])

运算

1.加法运算(两种形式)

x = torch.rand(5,3)
y = torch.rand(5,3)
print(x+y)

print(torch.add(x,y))

注:可以将一个输出张量传递给输出参数作为输出

result = torch.empty(5,3)
torch.add(x,y. out=result)
print(result)

原位操作(in-place)

# add x to y and y changed
y.add_(x)
print(y)

任何一个in-place改变张量的操作后面都固定一个_,例如x.copy_(y)
pytorch的其他运算操作函数===》link

Numpy 与 torch的转化

torch张量和Numpy张量共享底层内存位置,更改一个另一个也发生变化

torch转化为numpy

a = torch.ones(5)
print(a) # 输出一个tensor

b = a.numpy() # 转化为numpy
print(b) # 输出一个数组

a.add_(1)
print(a)
print(b) # a与b均发生变化

output:
在这里插入图片描述
numpy转化为torch

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

output:
在这里插入图片描述

Autograd:自动求导

Pytorch中所有神经网络的核心是autograd包,autograd为张量上所有的操作提供了自动求导机制。

张量

torch.Tensor 是包的核心类,部分属性如下:

属性名用途
requires_grad=True追踪对于该张量的计算操作
backward()自动计算所有梯度;若tensor为多元素需指定gradient参数
grad()所有梯度的累计
detach()组织张量被追踪:隔离计算历史并阻止未来追踪
  • 设置requires_grad=True 追踪张量的计算操作
x = torch.ones(2,2, requires_grad = True)
print(x)

y = x+2
print(y) # y为计算结果,所以包含grad_fn属性

在这里插入图片描述

z = y * y * 3# 对y做更多操作
out = z.mean()
print(z, out) 

在这里插入图片描述

  • .requires_grad_(…) 可以改变requires_grad的值,默认为false
a = torch.randn(2,2)
a = ((a*3)/(a-1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a*a).sum()
print(b.grad_fn)

在这里插入图片描述

梯度

(torch.autograd)
autograd提供了对任意标量自动计算微分的函数和类,前提是在声明一个Tensor时使用关键词 requires_grad = True

torch.autograd.backward(tensors, grad_tensors=None, retain_graph=None, create_graph=False, grad_variables=None)

若tensor是非标量形式(多变量),需要额外声明 grad_tensors ;值得注意的是该函数计算的是累计梯度值,所以在使用前需要清零

举个例子:

import torch
x = torch.ones(2,2, requires_grad = True)
y = x+2
z = y*y*3
out = z.mean()

out.backward() # out是标量,等价于out.backward(torch.tensor(1.))
print(x.grad) # 输出导数d(out)/dx 

out:
在这里插入图片描述
在这里插入图片描述

  • torch.autograd 是计算雅克比向量(雅克比向量可将外部梯度输入到具有非标量输出的模型中)的“引擎”

tensor不是标量时,torch.autograd 不能直接计算完整的雅克比矩阵,但若是想要雅克比向量积,则将向量传递给backward即可

x = torch.randn(3, requires_grad=True)

y = x * 2
while y.data.norm() < 1000:
    y = y * 2
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)

print(x.grad)

out:
在这里插入图片描述

  • with torch.no_grad() 防止跟踪记录
    在评估模型时特别有用,requires_grad = True使得每一步都自动计算梯度并累计,但我们有时候不需要在过程中进行梯度计算

举个例子:

print(x.requires_grad) # output: True
print((x**2).requires_grad) # output: True

with torch.no_grad():
    print((x**2).requires_grad) # output:False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值