什么是pyTorch

pyTorch是一个基于python的计算包,主要有两个目的:

  • 代替Numpy以发挥出GPU的优势
  • 是一个深度学习的研究平台,提供最大化的灵活性和速度

开始

Tensors

Tensors与Numpy的ndarray非常相似,但它可以被用在GPU上以加速计算。

from __future__ import print_function
import torch

注意:一个没有被初始化的矩阵被申明后,在使用之前是不包含任何特定的值的。当一个没有初始化的矩阵被创建时,分配的内存中当时储存的值会成为初始值。

创建一个5x3的矩阵,不初始化它:

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

Out:

tensor([[ 1.8918e-16,  4.5644e-41, -3.0675e-26],
        [ 3.0773e-41,  0.0000e+00,  1.4013e-45],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00]])

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

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

Out:

tensor([[0.5524, 0.8042, 0.8140],
        [0.2944, 0.1345, 0.2921],
        [0.3099, 0.3343, 0.7377],
        [0.0685, 0.1461, 0.9683],
        [0.8908, 0.4492, 0.9506]])

创建一个矩阵,用0元素填满,元素类型为long:

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

Out:

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)

Out:

tensor([5.5000, 3.0000])

或者基于现有的tensor创建一个tensor。这些方法会重复使用输入tensor的性质,比如dtype,除非使用者提供新的值:

x = x.new_ones(5, 3, dtype=torch.double)   # new_* methods take in sizes
print(x)

x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x)                                   # result has the same size

Out:

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[-1.9325,  1.2030, -2.1360],
        [-0.1392,  1.2079,  1.3194],
        [-1.0496,  0.9343,  2.4428],
        [-0.3567, -0.5195, -0.0276],
        [ 1.8236,  0.1193, -0.5549]])

获取它的size:

print(x.size())

Out:

torch.Size([5, 3])

注意torch.Size实际上是一个元组,所以它支持所有的元组操作。

操作

Tensor操作有多种语法。在接下的例子中,我们会看一下加法操作。

加法:语法1

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

Out:

tensor([[-1.8346,  1.6518, -1.2673],
        [ 0.1698,  1.8538,  2.2153],
        [-0.0803,  0.9863,  3.2740],
        [-0.0906, -0.3752,  0.8960],
        [ 1.8271,  0.8586, -0.0483]])

加法:语法2

print(torch.add(x, y))

Out:

tensor([[-1.8346,  1.6518, -1.2673],
        [ 0.1698,  1.8538,  2.2153],
        [-0.0803,  0.9863,  3.2740],
        [-0.0906, -0.3752,  0.8960],
        [ 1.8271,  0.8586, -0.0483]])

加法:提供一个输出tensor作为参数

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

Out:

tensor([[-1.8346,  1.6518, -1.2673],
        [ 0.1698,  1.8538,  2.2153],
        [-0.0803,  0.9863,  3.2740],
        [-0.0906, -0.3752,  0.8960],
        [ 1.8271,  0.8586, -0.0483]])

加法:in-place

# adds x to y
y.add_(x)
print(y)

Out:

tensor([[-1.8346,  1.6518, -1.2673],
        [ 0.1698,  1.8538,  2.2153],
        [-0.0803,  0.9863,  3.2740],
        [-0.0906, -0.3752,  0.8960],
        [ 1.8271,  0.8586, -0.0483]])

注意:任何的会改变一个tensor的in-place操作都有一个后缀_。例如:x.copy_(y)x.t_(),会改变x的值。

你可以使用标准的类似于Numpy的指标。

print(x[:, 1])

Out:

tensor([ 1.2030,  1.2079,  0.9343, -0.5195,  0.1193])

Resizing:如果你想reshape一个tensor,你可以使用torch.view

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())

Out:

torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

如果你有一个只有一个元素的tensor,使用.item()来获取它的值作为一个Python数字。

x = torch.randn(1)
print(x)
print(x.item())

Out:

tensor([-0.7521])
-0.7521063685417175

延伸阅读:关于更多的tensor操作,可以查看这里

Numpy桥梁

把一个Torch Tensor转化为Numpy array和反过来是非常容易的。

Torch Tensor和Numpy array会共享它们的内存位置(如果Torch Tensor在CPU上),因此改变一个也会改变另一个。

将Torch Tensor转化为Numpy array

a = torch.ones(5)
print(a)

Out:

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

Out:

[1. 1. 1. 1. 1.]

注意numpy array的值是如何变化的。

a.add_(1)
print(a)
print(b)

Out:

tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

将Numpy Array转化为Torch Tensor

观察改变np array是如何自动改变Torch Tensor的。

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

Out:

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

所有的CPU上的Tensors除了CharTensor都支持转化成Numpy再转化回来。

CUDA Tensors

使用.to方法,Tensors可以被移动到任何设备。

# 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
    y = torch.ones_lke(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!

Out:

tensor([0.2479], device='cuda:0')
tensor([0.2479], dtype=torch.float64)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Tensors #Tensors#Tensors和numpy中的ndarrays较为相似,因此Tensor也能够使...
    MiracleJQ阅读 1,775评论 0 1
  • pytorch torch包 torch 包含了多维张量的数据结构以及基于其上的多种数学操作。 函数 torch....
    NJUST江波阅读 1,194评论 0 0
  • 我是个无论怎样做都爱后悔的人,人生应该怎样过才算没有遗憾呢? 后来看了一本书,把一句影响过我的话与...
    时光里的人儿啊阅读 666评论 0 1
  • 从小,我的父母,爷爷奶奶就没有对我给我很多的宠溺。因为他们清楚,男孩子要是娇生惯养以后一定难以独当一面。当然这不...
    DominickWang阅读 475评论 0 1
  • 踩着灰黑色的地砖,步入通幽小径,只闻其声未见其影的潺潺流水声,从何而来?赶紧往前走,哦,被茂密的竹林遮挡了,原来是...
    飞柔阅读 313评论 0 10

友情链接更多精彩内容