未經允許,不得轉載,謝謝~~
PyTorch是一個深度學習的框架。
簡單記錄整理。
Pytorch是什么
基于Python的科學計算包:
- 代替numpy能使用GPU進行計算
- 靈活性很高的一個深度學習研究平臺
Tensor的基本用法
Tensor(張量)跟numpy的數組很像,但是它可以使用GPU來進行計算的加速。
import packet
from __future__ import print_function
import torch
Construct a 5x3 matrix, uninitialized:
x = torch.Tensor(5, 3)
print(x)
Construct a randomly initialized matrix
x = torch.rand(5, 3)
print(x)
Get its size
print(x.size())
torch.Size本質是元祖tuple
addition of Tensors
以下的運行結果都是一樣的。
x=torch.rand(5,3)
y=torch.rand(5,3)
# syntax 1
print(x + y)
# syntax 2
print(torch.add(x, y))
# syntax 3 - giving an output tensor
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)
# syntax 4 - in-place
y.add_(x)
print(y)
numpy-like indexing
像numpy一樣的用法來索引。
print(x[:, 1])
numpy array 與 torch Tensor的相互轉換
- 這里的轉換相對應的array與Tensor共享同一塊內存,改變一個也會改變另外一個。
- 所有還在CPU上運行的Tensor除了CharTensor之外都支持與numpy Array的相互轉化。
Tensor轉為array
a = torch.ones(5)
print(a)
# convert from tensor to Array
b = a.numpy()
print(b)
# share the same memory
a.add_(1)
print(a)
print(b)
Array 轉為 Tensor
import numpy as np
a = np.ones(5)
# convert from array to Tensor
b = torch.from_numpy(a)
np.add(a, 1, out=a)
# share the same memory
print(a)
print(b)
CUDA Tensors
用.cuda函數可以講張量移到GPU上
if torch.cuda.is_available():
print ("succ")
x = x.cuda()
y = y.cuda()
x + y
more
關于Tensor的操作,例如轉置, 索引,切片,數學計算等都可以在更多Tensor操作中找到。
基本就是對官網的getting started的一個小小翻譯,能力有限,權當自己做筆記吧~~~