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., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])

创建一个随机初始化的矩阵:

x = torch.rand(5, 3)
print(x)
tensor([[0.9150, 0.7657, 0.8546],
[0.3395, 0.7662, 0.0313],
[0.7757, 0.0178, 0.3521],
[0.3413, 0.9466, 0.1630],
[0.8141, 0.1705, 0.0776]])

创建一个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([[ 1.1297, 0.1577, -0.7850],
[ 0.5521, 1.1847, 0.6533],
[ 1.0695, -0.6460, 0.1133],
[ 0.1926, -0.5291, -0.7003],
[ 0.4813, -1.7848, -1.0248]])

获取 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([[ 1.2431,  0.5113, -0.1128],
[ 0.5706, 1.3514, 0.7406],
[ 1.1418, 0.2117, 0.6874],
[ 0.9976, -0.1778, -0.5245],
[ 1.1259, -1.3210, -0.4456]])

加法2

print(torch.add(x, y))
tensor([[ 1.2431,  0.5113, -0.1128],
[ 0.5706, 1.3514, 0.7406],
[ 1.1418, 0.2117, 0.6874],
[ 0.9976, -0.1778, -0.5245],
[ 1.1259, -1.3210, -0.4456]])

提供输出tensor作为参数

result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
tensor([[ 1.2431,  0.5113, -0.1128],
[ 0.5706, 1.3514, 0.7406],
[ 1.1418, 0.2117, 0.6874],
[ 0.9976, -0.1778, -0.5245],
[ 1.1259, -1.3210, -0.4456]])

替换

# adds x to y
y.add_(x)
print(y)
tensor([[ 1.2431,  0.5113, -0.1128],
[ 0.5706, 1.3514, 0.7406],
[ 1.1418, 0.2117, 0.6874],
[ 0.9976, -0.1778, -0.5245],
[ 1.1259, -1.3210, -0.4456]])

Note

任何 以``_`` 结尾的操作都会用结果替换原变量. 例如: ``x.copy_(y)``, ``x.t_()``, 都会改变 ``x``.

你可以使用与NumPy索引方式相同的操作来进行对张量的操作

print(x[:, 1])
tensor([ 0.1577,  1.1847, -0.6460, -0.5291, -1.7848])

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([2.3180])
2.317981481552124

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 转换

将一个Torch Tensor转换为NumPy数组是一件轻松的事,反之亦然。

Torch Tensor与NumPy数组共享底层内存地址,修改一个会导致另一个的变化。

将一个Torch Tensor转换为NumPy数组

a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[1. 1. 1. 1. 1.]

观察numpy数组的值是如何改变的。

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`` 也会对变量的类型做更改

[Pytorch框架] 1.3、张量的更多相关文章

  1. 小白学习之pytorch框架(1)-torch.nn.Module+squeeze(unsqueeze)

    我学习pytorch框架不是从框架开始,从代码中看不懂的pytorch代码开始的 可能由于是小白的原因,个人不喜欢一些一下子粘贴老多行代码的博主或者一些弄了一堆概念,导致我更迷惑还增加了畏惧的情绪(个 ...

  2. PyTorch框架+Python 3面向对象编程学习笔记

    一.CNN情感分类中的面向对象部分 sparse.py super(Embedding, self).__init__() 表示需要父类初始化,即要运行父类的_init_(),如果没有这个,则要自定义 ...

  3. 手写数字识别 卷积神经网络 Pytorch框架实现

    MNIST 手写数字识别 卷积神经网络 Pytorch框架 谨此纪念刚入门的我在卷积神经网络上面的摸爬滚打 说明 下面代码是使用pytorch来实现的LeNet,可以正常运行测试,自己添加了一些注释, ...

  4. 全面解析Pytorch框架下模型存储,加载以及冻结

    最近在做试验中遇到了一些深度网络模型加载以及存储的问题,因此整理了一份比较全面的在 PyTorch 框架下有关模型的问题.首先咱们先定义一个网络来进行后续的分析: 1.本文通用的网络模型 import ...

  5. 小白学习之pytorch框架(2)-动手学深度学习(begin-random.shuffle()、torch.index_select()、nn.Module、nn.Sequential())

    在这向大家推荐一本书-花书-动手学深度学习pytorch版,原书用的深度学习框架是MXNet,这个框架经过Gluon重新再封装,使用风格非常接近pytorch,但是由于pytorch越来越火,个人又比 ...

  6. 小白学习之pytorch框架(4)-softmax回归(torch.gather()、torch.argmax()、torch.nn.CrossEntropyLoss())

    学习pytorch路程之动手学深度学习-3.4-3.7 置信度.置信区间参考:https://cloud.tencent.com/developer/news/452418 本人感觉还是挺好理解的 交 ...

  7. 【chainer框架】【pytorch框架】

    教程: https://bennix.github.io/ https://bennix.github.io/blog/2017/12/14/chain_basic/ https://bennix.g ...

  8. 搭建 pytorch框架

    Pytorch 发布了1.0,对windows的支持效果更好,因此,今天试了一下安装Pytorch.安装速度确实很快,安装也很方便. 进入pytorch的官网,选择对应的版本 根据版本输入相应命令 注 ...

  9. NLP使用pytorch框架,pytorch安装

    pytorch的安装方法及出现问题的解决方案: 安装pytorch,使用pip 安装,在运行代码的时候会报错,但是导包的时候不会报错,因此要采用conda的方式安装   1.找到miniconda的网 ...

  10. PyToune:一款类Keras的PyTorch框架

    PyToune is a Keras-like framework for PyTorch and handles much of the boilerplating code needed to t ...

随机推荐

  1. 解决VUE中document.documentElement.scrollTop为0(转)

    原文地址:https://blog.csdn.net/WDCCSDN/article/details/82107374 Vue中document.documentElement.scrollTop的值 ...

  2. CVE-2016-2183(SSL/TLS)漏洞的办法

    运行gpedit.msc,打开"本地组策略编辑器" 启用"SSL密码套件顺序" TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_ ...

  3. 搭建rust开发环境

    1.打开https://www.rust-lang.org/tools/install 下载64位安装器 选择第一项默认安装 安装器会下载安装rust 相关工具链,并添加path C:\Users\z ...

  4. linux修改用户密码期限

    1. https://www.cnblogs.com/wwwcf1982603555/p/15474557.html 设置密码复杂度: http://events.jianshu.io/p/533d3 ...

  5. [picoCTF]Insp3ct0r write up

    根据提示,需要检查浏览器上的Web代码(动手翻译一下啦) (漫不经心的瞅瞅页面,curl+UUUUUUU(一只U就行)一下下,微微瞄一瞄,where is flag? fn+f12(或其它)打开源代码 ...

  6. Map遍历增加key报错如何解决

    public static void main(String[] args) throws Exception{ Map<String,Object> aa=new HashMap< ...

  7. AttributeError: module 'torchvision' has no attribute 'transforms'

    代码:maskrcnn-benchmark Python 3.6.13 |Anaconda, Inc Traceback (most recent call last): File "too ...

  8. RPA现阶段的问题

    RPA(Robotic Process Automation)全称机器人流程自动化,作为"自动化为先"时代的翘楚和先驱,被广泛地用来代替人类自动执行任务,越来越多的领域.企业和人开 ...

  9. 如何在 Apinto 实现 HTTP 与gRPC 的协议转换 (上)

    什么是 gRPC 像gRPC是由google开发的一个高性能.通用的开源 RPC 框架,主要面向移动应用开发且基于HTTP/2协议标准而设计,同时支持大多数流行的编程语言. gRPC基于 HTTP/2 ...

  10. 【转载】谈谈GIS三维渲染引擎

    > 原文地址:https://zhuanlan.zhihu.com/p/419667971 三维引擎 minemap: 是我们公司的产品,主要以earth的形态展示,支持矢量切片+倾斜数据(这一 ...