参考:https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#sphx-glr-beginner-blitz-tensor-tutorial-py

WHAT IS PYTORCH

这是一个基于python的实现两种功能的科学计算包:

  • 用于替换NumPy去使用GPUs的算力
  • 一个提供了最大化灵活度和速度的深度学习搜索平台

Getting Started

Tensors

Tensors与NumPy的ndarrays相似,不同在于Tensors能够使用在GPU上去加速计算能力

from __future__ import print_function
import torch

构造一个5*3的矩阵,不初始化

x = torch.empty(, )
print(x)

输出:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([[ 0.0000e+00, -2.5244e-29, 0.0000e+00],
[-2.5244e-29, 1.9618e-44, 9.2196e-41],
[ 0.0000e+00, 7.7050e+31, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 8.6499e-38]])

随机构造一个初始化矩阵:

x = torch.rand(, )
print(x)

输出:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([[0.4803, 0.5157, 0.9041],
[0.1619, 0.8994, 0.4302],
[0.6824, 0.6559, 0.9317],
[0.5558, 0.8311, 0.2492],
[0.8287, 0.1050, 0.7201]])

构建一个全为0的矩阵,并且设置类型为long:

x = torch.zeros(, , dtype=torch.long)
print(x)

输出:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([[, , ],
[, , ],
[, , ],
[, , ],
[, , ]])

直接使用数据来构造一个tensor:

x = torch.tensor([5.5, ])
print(x)

输出:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([5.5000, 3.0000])

或者基于存在的tensor去创建一个tensor。这些方法将重新使用输入tensor的特性,如dtype,除非用户提供新的值。默认的dtype为torch.float

#-*- coding: utf- -*-
from __future__ import print_function
import torch
x = torch.tensor([5.5, ])
print(x) x = x.new_ones(, , dtype=torch.double) # new_* methods take in sizes,就是新建一个矩阵,其与x无关
print(x) #设置dtype为torch.float64 x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # 会得到与x有相同大小的矩阵,dtype又从torch.float64变为torch.float

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([5.5000, 3.0000])
tensor([[., ., .],
[., ., .],
[., ., .],
[., ., .],
[., ., .]], dtype=torch.float64)
tensor([[-3.0480e-01, 1.5148e+00, -1.1507e+00],
[ 5.9181e-04, -8.0706e-01, 3.3035e-01],
[ 1.5499e+00, -6.1708e-01, 5.8211e-01],
[-9.1276e-02, -9.4747e-01, -1.8206e-01],
[-8.9208e-02, -1.5132e-01, 1.2374e+00]])

得到矩阵的大小:

print(x.size())

返回:

torch.Size([, ])

⚠️torch.Size实际上是一个元祖,它支持所有的元祖操作

Operations

这里有着多种操作的语法。如下面的例子,我们将看见的是加法操作:

#-*- coding: utf- -*-
from __future__ import print_function
import torch
x = torch.tensor([5.5, ])
print(x) x = x.new_ones(, ) # new_* methods take in sizes,就是新建一个矩阵,其与x无关
print(x) y = torch.rand(, )
print(y)
print(x + y)

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([5.5000, 3.0000])
tensor([[., ., .],
[., ., .],
[., ., .],
[., ., .],
[., ., .]])
tensor([[2.5123e-04, 9.8943e-01, 5.3585e-01],
[9.4955e-01, 1.3734e-01, 4.0120e-01],
[3.6199e-01, 1.5062e-01, 2.7033e-01],
[9.5025e-01, 6.3539e-01, 2.3759e-01],
[6.7833e-01, 4.3510e-01, 2.3747e-01]])
tensor([[1.0003, 1.9894, 1.5359],
[1.9496, 1.1373, 1.4012],
[1.3620, 1.1506, 1.2703],
[1.9502, 1.6354, 1.2376],
[1.6783, 1.4351, 1.2375]])

等价于:

print(torch.add(x,y))

还可以设置一个输出变量,然后使用变量输出:

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

还有内置加法函数:

y.add_(x)
print(y)

⚠️任何改变张量的内置操作都使用了_后缀。如x.copy_(y),x.t_()都会改变x的值

你也可以使用标准的类似于numpy的索引:

print(x[:, ])

调整:如果你想要调整/重塑tensor,你可以使用torch.view:

#-*- coding: utf- -*-
from __future__ import print_function
import torch
x = torch.randn(, )
print(x)
y = x.view()
print(y)
z = x.view(-, ) # -1表示从其他维度推断,即后面设为8,那么前面就推断是2
print(z)
print(x.size(), y.size(), z.size())

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([[ 1.4353, -0.7081, 1.1953, -0.1438],
[-0.9198, -0.8695, -0.3122, -0.0882],
[ 0.5113, -1.3449, -0.9429, 1.7962],
[ 0.5734, 1.0710, -0.9295, -2.0507]])
tensor([ 1.4353, -0.7081, 1.1953, -0.1438, -0.9198, -0.8695, -0.3122, -0.0882,
0.5113, -1.3449, -0.9429, 1.7962, 0.5734, 1.0710, -0.9295, -2.0507])
tensor([[ 1.4353, -0.7081, 1.1953, -0.1438, -0.9198, -0.8695, -0.3122, -0.0882],
[ 0.5113, -1.3449, -0.9429, 1.7962, 0.5734, 1.0710, -0.9295, -2.0507]])
torch.Size([, ]) torch.Size([]) torch.Size([, ])

如果你有只有一个元素的tensor,那么就能够使用.item()去得到一个转换为python数字的值:

#-*- coding: utf- -*-
from __future__ import print_function
import torch
x = torch.randn()
print(x)
print(x.item())

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([-2.3159])
-2.3158915042877197

⚠️100+的张量运算,包括转置、标引、切片、数学运算、线性代数、随机数等,都计算在here

NumPy Bridge

将Torch Tensor转换为NumPy数组,反之亦然,是一件轻而易举的事。
Torch张量和NumPy数组将共享它们的底层内存位置,更改一个将更改另一个。

Converting a Torch Tensor to a NumPy Array

#-*- coding: utf- -*-
from __future__ import print_function
import torch
a = torch.ones()
print(a) b = a.numpy()
print(b) a.add_()
print(a)
print(b)

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py
tensor([., ., ., ., .])
[. . . . .]
tensor([., ., ., ., .])
[. . . . .]

从上面的结果可以看见,仅更改tensor a也会导致b被更改

Converting NumPy Array to Torch Tensor

查看如何改变np数组来自动改变torch张量

#-*- coding: utf- -*-
from __future__ import print_function
import torch
import numpy as np
a = np.ones()
b = torch.from_numpy(a)
np.add(a, , out=a)
print(a)
print(b)

返回:

(deeplearning) userdeMBP:pytorch user$ python test.py
[. . . . .]
tensor([., ., ., ., .], dtype=torch.float64)

CPU上除了Char Tensor以外的所有张量都支持转换成NumPy,或者反向转换

CUDA Tensors

Tensors可以被移到任意的设备,使用.to方法

#-*- coding: utf- -*-
from __future__ import print_function
import torch # let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
x = torch.randn(, )
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!

之前使用的机器中没有CUDA,换到另一台运行:

user@home:/opt/user$ python test.py
tensor([[0.6344, 1.7958, 2.3387, 2.0527],
[2.1517, 2.1555, 2.1645, 0.4499],
[2.2020, 1.7363, 3.1394, 0.1240],
[1.9541, 1.6115, 2.0081, 1.8911]], device='cuda:0')
tensor([[0.6344, 1.7958, 2.3387, 2.0527],
[2.1517, 2.1555, 2.1645, 0.4499],
[2.2020, 1.7363, 3.1394, 0.1240],
[1.9541, 1.6115, 2.0081, 1.8911]], dtype=torch.float64)

pytorch学习-WHAT IS PYTORCH的更多相关文章

  1. 【pytorch】pytorch学习笔记(一)

    原文地址:https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html 什么是pytorch? pytorch是一个基于p ...

  2. 【深度学习】Pytorch学习基础

    目录 pytorch学习 numpy & Torch Variable 激励函数 回归 区分类型 快速搭建法 模型的保存与提取 批训练 加速神经网络训练 Optimizer优化器 CNN MN ...

  3. Pytorch学习之源码理解:pytorch/examples/mnists

    Pytorch学习之源码理解:pytorch/examples/mnists from __future__ import print_function import argparse import ...

  4. Pytorch学习记录-torchtext和Pytorch的实例( 使用神经网络训练Seq2Seq代码)

    Pytorch学习记录-torchtext和Pytorch的实例1 0. PyTorch Seq2Seq项目介绍 1. 使用神经网络训练Seq2Seq 1.1 简介,对论文中公式的解读 1.2 数据预 ...

  5. Pytorch学习--编程实战:猫和狗二分类

    Pytorch学习系列(一)至(四)均摘自<深度学习框架PyTorch入门与实践>陈云 目录: 1.程序的主要功能 2.文件组织架构 3. 关于`__init__.py` 4.数据处理 5 ...

  6. 新手必备 | 史上最全的PyTorch学习资源汇总

    目录: PyTorch学习教程.手册 PyTorch视频教程 PyTorch项目资源      - NLP&PyTorch实战      - CV&PyTorch实战 PyTorch论 ...

  7. [深度学习] Pytorch学习(一)—— torch tensor

    [深度学习] Pytorch学习(一)-- torch tensor 学习笔记 . 记录 分享 . 学习的代码环境:python3.6 torch1.3 vscode+jupyter扩展 #%% im ...

  8. [PyTorch 学习笔记] 1.1 PyTorch 简介与安装

    PyTorch 的诞生 2017 年 1 月,FAIR(Facebook AI Research)发布了 PyTorch.PyTorch 是在 Torch 基础上用 python 语言重新打造的一款深 ...

  9. 计算机视觉2-> 深度学习 | anaconda+cuda+pytorch环境配置

    00 想说的 深度学习的环境我配置了两个阶段,暑假的时候在一个主攻视觉的实验室干活,闲暇时候就顺手想给自己的Ubuntu1804配置一个深度学习的环境.这会儿配到了anaconda+pytorch+c ...

随机推荐

  1. 详解纯css实现瀑布流(multi-column多列及flex布局)

    瀑布流的布局自我感觉还是很吸引人的,最近又看到实现瀑布流这个做法,在这里记录下,特别的,感觉flex布局实现瀑布流还是有点懵的样子,不过现在就可以明白它的原理了 1.multi-column多列布局实 ...

  2. 学习 Docker 操作系统版本选择

    近来有时间一直在捣鼓 Docker.因为服务器选择的是 CentOS 版本,所以实验的环境选择的一直是 CentOS.如果是个人玩 Docker,优先选择 ubuntu.如果需要选择 CentOS 的 ...

  3. 洛谷P4841 城市规划(生成函数 多项式求逆)

    题意 链接 Sol Orz yyb 一开始想的是直接设\(f_i\)表示\(i\)个点的无向联通图个数,枚举最后一个联通块转移,发现有一种情况转移不到... 正解是先设\(g(n)\)表示\(n\)个 ...

  4. 照葫芦画瓢系列之Java --- Maven的介绍和安装

    一.Maven是什么? Maven 是一个项目管理工具.它负责管理项目开发过程中的几乎所有的东西. 版本 maven有自己的版本定义和规则 构建 maven支持许多种的应用程序类型,对于每一种支持的应 ...

  5. Spring IOC/DI

    IOC:反转控制(资源获取),之前开发是要什么就 new 什么,现在只需创建 IOC 容器,你要什么 IOC 都会给你,你只管接收.反转控制的对象是 Bean,也就是对象 DI:依赖注入,依赖容器把资 ...

  6. 【Wyn Enterprise BI知识库】 什么是商业智能 ZT

    商业智能(Business Intelligence,BI),又称商务智能,指用现代数据仓库技术.在线分析处理技术.数据挖掘和数据展现技术进行数据分析以实现商业价值. 图1:商业智能(BI)系统 商业 ...

  7. Android Studio 无法预览xml布局视图:failed to load AppCompat ActionBar with unkNown error

    问题如下: 解决方法: 找到res-->values-->styles.xml 文件 可以看到主题Them设置如下: 修改为: 界面预览可以正常显示

  8. IDEA基于Maven Struts2搭建配置及示例

    1.web.xml加载struts框架即过滤器,要注意struts版本不同过滤器配置也不同. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems ...

  9. 深入理解Java虚拟机02--Java内存区域与内存溢出异常

    一.概述 我们在进行 Java 开发的时候,很少关心 Java 的内存分配等等,因为这些活都让 JVM 给我们做了.不仅自动给我们分配内存,还有自动的回收无需再占用的内存空间,以腾出内存供其他人使用. ...

  10. MySQL 约束、表连接、表关联、索引

    一.外键: 1.什么是外键 2.外键语法 3.外键的条件 4.添加外键 5.删除外键 1.什么是外键: 主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性. 外键:是另一表的唯一性 ...