PyTorch是什么?

2022-06-09 09:00 更新

PyTorch是什么?

原文: https://///pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html
譯者: bat67
驗證者: FontTian

作者: Soumith Chintala

PyTorch 是一個基于 python 的科學計算包,主要針對兩類人群:

  • 作為 NumPy 的替代品,可以利用 GPU 的性能進行計算
  • 作為一個高靈活性,速度快的深度學習平臺

入門

張量

Tensor(張量),NumPyndarray ,但還可以在 GPU 上使用來加速計算

from __future__ import print_function
import torch

創(chuàng)建一個沒有初始化的 5 * 3 矩陣:

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

輸出:

tensor([[2.2391e-19, 4.5869e-41, 1.4191e-17],
        [4.5869e-41, 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, 0.0000e+00, 0.0000e+00]])

創(chuàng)建一個隨機初始化矩陣:

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

輸出:

tensor([[0.5307, 0.9752, 0.5376],
        [0.2789, 0.7219, 0.1254],
        [0.6700, 0.6100, 0.3484],
        [0.0922, 0.0779, 0.2446],
        [0.2967, 0.9481, 0.1311]])

構(gòu)造一個填滿 0 且數(shù)據(jù)類型為 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]])

直接從數(shù)據(jù)構(gòu)造張量:

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

輸出:

tensor([5.5000, 3.0000])

或根據(jù)現(xiàn)有的 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)    # 重載 dtype!
print(x)                                      # 結(jié)果size一致

輸出:

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[ 1.6040, -0.6769,  0.0555],
        [ 0.6273,  0.7683, -0.2838],
        [-0.7159, -0.5566, -0.2020],
        [ 0.6266,  0.3566,  1.4497],
        [-0.8092, -0.6741,  0.0406]])

獲取張量的形狀:

print(x.size())

輸出:

torch.Size([5, 3])

注意:torch.Size 本質(zhì)上還是 tuple ,所以支持 tuple 的一切操作。

運算

一種運算有多種語法。在下面的示例中,我們將研究加法運算。

加法:形式一

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

輸出:

tensor([[ 2.5541,  0.0943,  0.9835],
        [ 1.4911,  1.3117,  0.5220],
        [-0.0078, -0.1161,  0.6687],
        [ 0.8176,  1.1179,  1.9194],
        [-0.3251, -0.2236,  0.7653]])

加法:形式二

print(torch.add(x, y))

輸出:

tensor([[ 2.5541,  0.0943,  0.9835],
        [ 1.4911,  1.3117,  0.5220],
        [-0.0078, -0.1161,  0.6687],
        [ 0.8176,  1.1179,  1.9194],
        [-0.3251, -0.2236,  0.7653]])

加法:給定一個輸出張量作為參數(shù)

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

輸出:

tensor([[ 2.5541,  0.0943,  0.9835],
        [ 1.4911,  1.3117,  0.5220],
        [-0.0078, -0.1161,  0.6687],
        [ 0.8176,  1.1179,  1.9194],
        [-0.3251, -0.2236,  0.7653]])

加法:原位/原地操作(in-place)

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

輸出:

tensor([[ 2.5541,  0.0943,  0.9835],
        [ 1.4911,  1.3117,  0.5220],
        [-0.0078, -0.1161,  0.6687],
        [ 0.8176,  1.1179,  1.9194],
        [-0.3251, -0.2236,  0.7653]])

注意:任何一個就地改變張量的操作后面都固定一個 _ 。例如 x.copy_(y), x.t_()將更改x

也可以使用像標準的 NumPy 一樣的各種索引操作:

print(x[:, 1])

輸出:

tensor([-0.6769,  0.7683, -0.5566,  0.3566, -0.6741])

改變形狀:如果想改變形狀,可以使用 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())

輸出:

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

如果是僅包含一個元素的 tensor,可以使用 .item() 來得到對應的 python 數(shù)值

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

輸出:

tensor([0.0445])
0.0445479191839695

后續(xù)閱讀: 超過100種 tensor的運算操作,包括轉(zhuǎn)置,索引,切片,數(shù)學運算,線性代數(shù),隨機數(shù)等,具體訪問 這里

橋接NumPy

將一個 Torch 張量轉(zhuǎn)換為一個 NumPy 數(shù)組是輕而易舉的事情,反之亦然。

Torch 張量和 NumPy數(shù)組將共享它們的底層內(nèi)存位置,因此當一個改變時,另外也會改變。

將 torch 的 Tensor 轉(zhuǎn)換為 NumPy 數(shù)組

輸入:

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 數(shù)組轉(zhuǎn)化為Torch張量

看改變 NumPy 分配是如何自動改變 Torch 張量的:

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)

CPU上的所有張量( CharTensor 除外)都支持與 Numpy 的相互轉(zhuǎn)換。

CUDA上的張量

張量可以使用 .to 方法移動到任何設(shè)備(device)上:

## 當GPU可用時,我們可以運行以下代碼
## 我們將使用`torch.device`來將tensor移入和移出GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # 直接在GPU上創(chuàng)建tensor
    x = x.to(device)                       # 或者使用`.to("cuda")`方法
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # `.to`也能在移動時改變dtype

輸出:

tensor([1.0445], device='cuda:0')
tensor([1.0445], dtype=torch.float64)
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號