PyTorch Tutorials 1 PyTorch是什么?
%matplotlib inline
PyTorch是什么?
基于Python的科学计算包,服务于以下两种场景:
- 作为NumPy的替代品,可以使用GPU的强大计算能力
- 提供最大的灵活性和高速的深度学习研究平台
开始
Tensors(张量)
^^^^^^^
Tensors与Numpy中的 ndarrays类似,但是在PyTorch中
Tensors 可以使用GPU进行计算.
from __future__ import print_function
import torch
创建一个 5x3 矩阵, 但是未初始化:
x = torch.empty(5, 3)
print(x)
tensor([[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]])
创建一个随机初始化的矩阵:
x = torch.rand(5, 3)
print(x)
tensor([[0.6972, 0.0231, 0.3087],
[0.2083, 0.6141, 0.6896],
[0.7228, 0.9715, 0.5304],
[0.7727, 0.1621, 0.9777],
[0.6526, 0.6170, 0.2605]])
创建一个0填充的矩阵,数据类型为long:
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
创建tensor并使用现有数据初始化:
x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])
根据现有的张量创建张量。 这些方法将重用输入张量的属性,例如, dtype,除非设置新的值进行覆盖
x = x.new_ones(5, 3, dtype=torch.double) # new_* 方法来创建对象
print(x)
x = torch.randn_like(x, dtype=torch.float) # 覆盖 dtype!
print(x) # 对象的size 是相同的,只是值和类型发生了变化
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.5691, -2.0126, -0.4064],
[-0.0863, 0.4692, -1.1209],
[-1.1177, -0.5764, -0.5363],
[-0.4390, 0.6688, 0.0889],
[ 1.3334, -1.1600, 1.8457]])
获取 size
译者注:使用size方法与Numpy的shape属性返回的相同,张量也支持shape属性,后面会详细介绍
print(x.size())
torch.Size([5, 3])
Note
``torch.Size`` 返回值是 tuple类型, 所以它支持tuple类型的所有操作.
操作
^^^^^^^^^^
操作有多种语法。
我们将看一下加法运算。
加法1:
y = torch.rand(5, 3)
print(x + y)
tensor([[ 0.7808, -1.4388, 0.3151],
[-0.0076, 1.0716, -0.8465],
[-0.8175, 0.3625, -0.2005],
[ 0.2435, 0.8512, 0.7142],
[ 1.4737, -0.8545, 2.4833]])
加法2
print(torch.add(x, y))
tensor([[ 0.7808, -1.4388, 0.3151],
[-0.0076, 1.0716, -0.8465],
[-0.8175, 0.3625, -0.2005],
[ 0.2435, 0.8512, 0.7142],
[ 1.4737, -0.8545, 2.4833]])
提供输出tensor作为参数
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 0.7808, -1.4388, 0.3151],
[-0.0076, 1.0716, -0.8465],
[-0.8175, 0.3625, -0.2005],
[ 0.2435, 0.8512, 0.7142],
[ 1.4737, -0.8545, 2.4833]])
替换
# adds x to y
y.add_(x)
print(y)
tensor([[ 0.7808, -1.4388, 0.3151],
[-0.0076, 1.0716, -0.8465],
[-0.8175, 0.3625, -0.2005],
[ 0.2435, 0.8512, 0.7142],
[ 1.4737, -0.8545, 2.4833]])
Note
任何 以``_`` 结尾的操作都会用结果替换原变量.
例如: ``x.copy_(y)``, ``x.t_()``, 都会改变 ``x``.
你可以使用与NumPy索引方式相同的操作来进行对张量的操作
print(x[:, 1])
tensor([-2.0126, 0.4692, -0.5764, 0.6688, -1.1600])
torch.view: 可以改变张量的维度和大小
译者注:torch.view 与Numpy的reshape类似
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # size -1 从其他维度推断
print(x.size(), y.size(), z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
如果你有只有一个元素的张量,使用.item()来得到Python数据类型的数值
x = torch.randn(1)
print(x)
print(x.item())
tensor([-0.2368])
-0.23680149018764496
Read later:
100+ Tensor operations, including transposing, indexing, slicing,
mathematical operations, linear algebra, random numbers, etc.,
are described
here <https://pytorch.org/docs/torch>_.
NumPy 转换
Converting a Torch Tensor to a NumPy array and vice versa is a breeze.
The Torch Tensor and NumPy array will share their underlying memory
locations, and changing one will change the other.
Converting a Torch Tensor to a NumPy Array
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[1. 1. 1. 1. 1.]
See how the numpy array changed in value.
a.add_(1)
print(a)
print(b)
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
NumPy Array 转化成 Torch Tensor
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
使用from_numpy自动转化
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
所有的 Tensor 类型默认都是基于CPU, CharTensor 类型不支持到
NumPy 的转换.
CUDA 张量
使用.to 方法 可以将Tensor移动到任何设备中
# is_available 函数判断是否有cuda可以使用
# ``torch.device``将张量移动到指定的设备中
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA 设备对象
y = torch.ones_like(x, device=device) # 直接从GPU创建张量
x = x.to(device) # 或者直接使用``.to("cuda")``将张量移动到cuda中
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` 也会对变量的类型做更改
tensor([0.7632], device='cuda:0')
tensor([0.7632], dtype=torch.float64)
PyTorch Tutorials 1 PyTorch是什么?的更多相关文章
- 对比学习:《深度学习之Pytorch》《PyTorch深度学习实战》+代码
PyTorch是一个基于Python的深度学习平台,该平台简单易用上手快,从计算机视觉.自然语言处理再到强化学习,PyTorch的功能强大,支持PyTorch的工具包有用于自然语言处理的Allen N ...
- NLP使用pytorch框架,pytorch安装
pytorch的安装方法及出现问题的解决方案: 安装pytorch,使用pip 安装,在运行代码的时候会报错,但是导包的时候不会报错,因此要采用conda的方式安装 1.找到miniconda的网 ...
- PyTorch Tutorials 5 数据并行(选读)
%matplotlib inline 数据并行(选读) Authors: Sung Kim and Jenny Kang 在这个教程里,我们将学习如何使用 DataParallel 来使用多GPU. ...
- PyTorch Tutorials 4 训练一个分类器
%matplotlib inline 训练一个分类器 上一讲中已经看到如何去定义一个神经网络,计算损失值和更新网络的权重. 你现在可能在想下一步. 关于数据? 一般情况下处理图像.文本.音频和视频数据 ...
- PyTorch Tutorials 3 Neural Networks
%matplotlib inline Neural Networks 使用torch.nn包来构建神经网络. 上一讲已经讲过了autograd,nn包依赖autograd包来定义模型并求导. 一个nn ...
- PyTorch Tutorials 2 AUTOGRAD: AUTOMATIC DIFFERENTIATION
%matplotlib inline Autograd: 自动求导机制 PyTorch 中所有神经网络的核心是 autograd 包. 我们先简单介绍一下这个包,然后训练第一个简单的神经网络. aut ...
- pytorch系列 -- 9 pytorch nn.init 中实现的初始化函数 uniform, normal, const, Xavier, He initialization
本文内容:1. Xavier 初始化2. nn.init 中各种初始化函数3. He 初始化 torch.init https://pytorch.org/docs/stable/nn.html#to ...
- [pytorch学习]1.pytorch ubuntu安装
看完了Deep Learning with Python,尝试了部分Keras的demo代码. 感觉Keras虽然容易上手,能够快速搭建出一个通用的模型,但是缺乏对底层的控制. 同时,在使用了自己编译 ...
- 【pytorch 代码】pytorch 网络结构可视化
部分内容转载自 http://blog.csdn.net/GYGuo95/article/details/78821617,在此表示由衷感谢. 此方法需要安装python-graphviz: con ...
随机推荐
- spring data 入门
提出问题 我是Sping Data,是程序员的春天,因为我提供很多接口给开发人员, 减少程序员重复的写CRUD和分页等方法,你们也可以叫我春D,或者春帝,因为我很酷 解决问题 在Spring Data ...
- django 常用 详解
Django 1 django框架介绍 是一个开源框架,2005年发布,采用Python语言编写的,早期时主要做新闻和内容管理的网站 Django本身提供了非常强大的后台管理系统 看中文说明文档 百度 ...
- insert buffer/change buffer double write buffer,双写 adaptive hash index(AHI) innodb的crash recovery innodb重要参数 innodb监控
https://yq.aliyun.com/articles/41000 http://blog.itpub.net/22664653/viewspace-1163838/ http://www.cn ...
- Flutter——AspectRatio组件
AspectRatio 的作用是根据设置调整子元素 child 的宽高比. AspectRatio 首先会在布局限制条件允许的范围内尽可能的扩展,widget 的高度是由宽度和比率决定的,类似于 Bo ...
- ARP、Proxy ARP、Gratuitous ARP
Proxy ARP 什么是Proxy ARP? 一个主机A(通常是路由器)有意应答另一个主机B的ARP请求(ARP requests).主机A通过伪装其身份,承担起将分组路由到真实目的地的责任.代理A ...
- Windows10关闭自动更新方法
你在为windows10自动更新而烦恼吗?下面教你一招如何关闭自动更新
- 测试某网站的SMS验证码
to=18911121211&sms_type=sms_registration&captcha_num=9JCMw4yN5EjI6ISYoNGdwF2YiwiIw5WNwlmb3xm ...
- idou老师教你学Istio 24:如何在Istio使用Prometheus进行监控
使用Prometheus进行监控是Istio提供的监控能力之一.Istio提供丰富的监控能力,为网格中的服务收集遥测数据.Mixer是负责提供策略控制和遥测收集的Istio组件. Istio通过Mix ...
- Java基础 线程的通信的三个方法/ 交替数数线程 / 生产者&消费者线程问题
线程通讯笔记: /** 线程通信 三个方法: * wait(): 调用该方法 是该调用的方法的线程释放共享资源的锁,进入等待状态,直至被唤醒 * notify() : 可以唤醒队列中的第一个等待同一共 ...
- JQuery中 text()、html() 以及 val()以及innerText、innerHTML和value
设置内容 - text().html() 以及 val() 我们将使用前一章中的三个相同的方法来设置内容: text() - 设置或返回所选元素的文本内容 html() - 设置或返回所选元素的内容( ...