参考: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. @RequestBody Spring MVC 示例

    1.前端的访问请求 <script type="text/javascript"> $(document).ready(function(){ var saveData ...

  2. CSS单位【记录】

    1.长度 2.角度 3.时间 4.分辨率 5.颜色 6.函数 7.生成内容 8.图像 9.数字 1.长度 <length>:数字和单位之间没有空格,0之后的长度单位是可选的 相对长度单位 ...

  3. 洛谷P3966 [TJOI2013]单词(AC自动机)

    题目描述 小张最近在忙毕设,所以一直在读论文.一篇论文是由许多单词组成但小张发现一个单词会在论文中出现很多次,他想知道每个单词分别在论文中出现了多少次. 输入输出格式 输入格式: 第一行一个整数N,表 ...

  4. Python运维开发:运算符与数据类型(二)

    python对象的相关术语: python程序中保存的所有数据都是围绕对象这个概念展开的: 程序中存储的所有数据都是对象 每个对象都有一个身份.一个类型和一个值 例如,school='MaGe Lin ...

  5. OkHttp3源码详解(五) okhttp连接池复用机制

    1.概述 提高网络性能优化,很重要的一点就是降低延迟和提升响应速度. 通常我们在浏览器中发起请求的时候header部分往往是这样的 keep-alive 就是浏览器和服务端之间保持长连接,这个连接是可 ...

  6. Java虚拟机(四)垃圾收集算法

    前言 在本系列上一篇文章中我讲到了垃圾标记算法,垃圾被标记后,GC就会对垃圾进行收集,垃圾收集有很多种算法,这篇文章就来介绍常用的垃圾收集算法的思想. 1.标记-清除算法 标记-清除算法(Mark-S ...

  7. 分组统计SQL

    Itpub上遇到一个求助写SQL的帖子,感觉很有意思,于是写出来看看,要求如下: 有个计划表1, 记录物料的年度计划量 有个实际使用情况表2,记录实际使用情况. 最后要出个统计表,把计划和实际的数据结 ...

  8. hive笔记:时间格式的统一

    一.string类型,年月日部分包含的时间统一格式: 原数据格式(时间字段为string类型) 取数时间和格式的语法  2018-11-01 00:12:49.0 substr(regexp_repl ...

  9. sql生成连续日期(年份、月份、日期)

    此随笔主在分享日常可能用到的sql函数,用于生成连续日期(年份.月份.日期) 具体的看代码及效果吧! -- ============================================= ...

  10. Linux学习历程——Centos 7 man命令

    一.man命令介绍 man,为单词manual的缩写,是linux下的帮助指令. 二.实例 以man命令为例,输入 man  man  获取man命令的帮助文档 可以看出,使用man命令查询到的帮助信 ...