PyTorch随笔-5
一、
1.PyTorch簡(jiǎn)介
PyTorch是一個(gè)優(yōu)化的張量庫(kù),2017年1月,由Facebook人工智能研究院(FAIR)基于Torch推出,它是一個(gè)基于Python的可續(xù)計(jì)算包,可使用gpu和cpu進(jìn)行深度學(xué)習(xí),此外還支持動(dòng)態(tài)神經(jīng)網(wǎng)絡(luò)。
PyTorch具有以下優(yōu)點(diǎn):
(1)PyTorch是相當(dāng)簡(jiǎn)潔且高效快速的框架。
(2)設(shè)計(jì)追求最少的封裝。
(3)設(shè)計(jì)符合人類(lèi)思維,它讓用戶盡可能地專(zhuān)注于實(shí)現(xiàn)自己的想法。
(4)與google的Tensorflow類(lèi)似,FAIR的支持足以確保PyTorch獲得持續(xù)的開(kāi)發(fā)更新。
(5)PyTorch由作者親自維護(hù)其論壇,以供用戶交流和求教問(wèn)題。
(6)入門(mén)簡(jiǎn)單。
1.Torch
包 torch 包含了多維張量的數(shù)據(jù)結(jié)構(gòu)以及基于其上的多種數(shù)學(xué)操作。另外,它也提供了多種工具,其中一些可以更有效地對(duì)張量和任意類(lèi)型進(jìn)行序列化。
它有CUDA 的對(duì)應(yīng)實(shí)現(xiàn),可以在NVIDIA GPU上進(jìn)行張量運(yùn)算(計(jì)算能力>=2.0)。
1.1 張量 Tensors
1.torch.is_tensor(obj)
如果obj 是一個(gè)pytorch張量,則返回True
參數(shù): obj (Object) – 判斷對(duì)象
/usr/bin/env python3
-- coding: utf-8 --
import torch
shape=(3,2,)
x_data = torch.zeros(shape)
print(f"Tensor: \n {x_data} \n")
print(f"IsTensor: \n {torch.is_tensor(x_data)} \n")
Tensor:
tensor([[0., 0.],
[0., 0.],
[0., 0.]])
IsTensor:
True
2.torch.is_storage [source]
torch.is_storage(obj)
如何obj 是一個(gè)pytorch storage對(duì)象,則返回True
/usr/bin/env python3
-- coding: utf-8 --
import torch
shape=(3,2,)
x_data = torch.ones(shape)
print(f"Tensor: \n {x_data} \n")
print(f"is_storage: \n {torch.is_storage(x_data)} \n")
tensor([[1., 1.],
[1., 1.],
[1., 1.]])
is_storage:
False
3.
2.Tensor
2.1 概述
Tensor中文稱(chēng)為張量,張量(tensor)理論是數(shù)學(xué)的一個(gè)分支學(xué)科,張量在數(shù)學(xué)上定義為:它是矢量概念的推廣,向量(指具有大小和方向的量)是一階張量,是張量的特例,張量可表示的內(nèi)容比向量更豐富,它可用來(lái)表示向量、標(biāo)量(標(biāo)量只有大小,沒(méi)有方向)和其他張量之間的線性關(guān)系的多線性函數(shù)。
在PyTorch中,Tensor是一種特殊的數(shù)據(jù)結(jié)構(gòu),非常類(lèi)似于數(shù)組和矩陣,它被用來(lái)編碼模型的輸入和輸出,以及模型的參數(shù)。Tensor類(lèi)似于NumPy的ndarray,但比NumPy更強(qiáng)大,Tensor還可以在gpu或其他硬件加速器上運(yùn)行。事實(shí)上,Tensor和NumPy數(shù)組通常可以共享相同的底層內(nèi)存,從而消除了復(fù)制數(shù)據(jù)的需要。張量也被優(yōu)化為自動(dòng)微分。
2.2 張量定義
一、創(chuàng)建張量
在Pytorch中創(chuàng)建張量的方法取決于實(shí)際應(yīng)用場(chǎng)景,主要有以下幾種方法:
1、torch.tensor函數(shù)
用預(yù)先存在的數(shù)據(jù)創(chuàng)建張量,可使用torch.tensor函數(shù)。函數(shù)格式如下:
torch.tensor(data, , dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor
該函數(shù)有以下幾個(gè)參數(shù)。
(1)Data:表示要構(gòu)造張量的數(shù)據(jù),可以是list、tuple、NumPy ndarray、scalar和其他類(lèi)型。
(2)dtype (torch.dtype,可選參數(shù)) :期望返回張量的數(shù)據(jù)類(lèi)型。默認(rèn)參數(shù)值為None,即:從數(shù)據(jù)推斷數(shù)據(jù)類(lèi)型。
(3)device (torch.device,可選參數(shù)):用于CPU的CPU張量類(lèi)型或用于CUDA的CUDA張量類(lèi)型,參數(shù)值由設(shè)備類(lèi)型(‘cpu’或’cuda’)和可選的設(shè)備的序號(hào)組成(如果設(shè)備序號(hào)不存在,該對(duì)象將始終代表設(shè)備類(lèi)型的當(dāng)前設(shè)備),比如:
torch.device(‘cuda:0’)或torch.device(‘cuda’, 0)表示0號(hào)cuda設(shè)備。
torch.device(‘cpu:0’)或torch.device(‘cpu’, 0)表示0號(hào)cpu設(shè)備。
默認(rèn)參數(shù)值為None,即:使用當(dāng)前設(shè)備作為默認(rèn)張量類(lèi)型(參見(jiàn)torch.set_default_tensor_type())。
(4)requires_grad (bool,可選參數(shù)):autograd是否記錄返回張量的操作。默認(rèn)值:False。
(5)pin_memory (bool,可選參數(shù)) :返回的張量是否被分配到固定的內(nèi)存中。只適用于CPU張量。默認(rèn)值:False。
2、torch. tensor 函數(shù)創(chuàng)建具有特定大小的張量。
3、torch.like函數(shù)創(chuàng)建一個(gè)與另一個(gè)張量具有相同大小(和類(lèi)似類(lèi)型)的張量。
4、tensor.new 函數(shù)創(chuàng)建與另一個(gè)張量類(lèi)型相似但大小不同的張量。
5、torch.Tensor類(lèi)
這不是一個(gè)函數(shù),而是包含單一數(shù)據(jù)類(lèi)型元素的多維矩陣類(lèi),是默認(rèn)的tensor類(lèi)(torch.FloatTensor) 的簡(jiǎn)稱(chēng)。前述1-4方法調(diào)用成功后返回結(jié)果都是Tensor類(lèi)對(duì)象。
二、張量基本操作
下面以幾個(gè)例子具體講解張量的基本操作。
1、程序1-2-2-1.py創(chuàng)建了一個(gè)空tensor,為2*5的矩陣(空矩陣的元素值為未初始化狀態(tài),可理解為隨機(jī)值)。
#!/usr/bin/env python3
-- coding: utf-8 --
#1-2-2-1.py
import torch
x=torch.Tensor(2,5)
print(x)
程序輸出結(jié)果如下:
tensor([[3.8335e-40, 3.8338e-40, 9.1835e-41, 1.0691e+24, 4.1588e+21],
[1.8128e+34, 2.1565e+29, 8.6163e+09, 1.8004e+25, 1.8032e+22]])
2、程序1-2-2-2.py創(chuàng)建一個(gè)空tensor,為3*5的矩陣,并返回tensor矩陣元素?cái)?shù)據(jù)類(lèi)型為torch.float32和矩陣的類(lèi)型torch.FloatTensor。
#!/usr/bin/env python3
-- coding: utf-8 --
#1-2-2-2.py
import torch
x=torch.Tensor(3,5)
print(x.dtype)
print(x.type())
程序執(zhí)行結(jié)果如下:
torch.float32
torch.FloatTensor
3、程序1-2-2-3.py創(chuàng)建了幾個(gè)空tensor,都為3*5的矩陣,然后依次輸出它們?cè)財(cái)?shù)據(jù)類(lèi)型和矩陣數(shù)據(jù)類(lèi)型。
#!/usr/bin/env python3
-- coding: utf-8 --
#1-2-2-3.py
import torch
x=torch.DoubleTensor(3,5)
print(x.dtype)
print(x.type())
y=torch.BoolTensor(3,5)
print(y.dtype)
print(y.type())
程序執(zhí)行結(jié)果如下:
torch.float64
torch.DoubleTensor
torch.bool
torch.BoolTensor
觀察程序1-2-2-3.py及上述執(zhí)行結(jié)果,不難看出:x是雙精度浮點(diǎn)數(shù)(float64)類(lèi)矩陣DoubleTensor,而是y布爾(邏輯)類(lèi)矩陣BoolTensor。
4、程序1-2-2-4.py依次使用Python的列表和元組構(gòu)造Tensor。
#!/usr/bin/env python3
-- coding: utf-8 --
#1-2-2-4.py
import torch
x1=torch.tensor([[10,20],[2,4]])
print(x1)
print(x1.size())
y=((11,21),(11,66))
x2=torch.tensor(y)
print(x2)
執(zhí)行結(jié)果如下:
tensor([[10, 20],
[ 2, 4]])
torch.Size([2, 2])
tensor([[11, 21],
[11, 66]])
程序1-2-2-4.py首先傳入列表為參數(shù),調(diào)用torch.tensor函數(shù)定義FloatTensor類(lèi)矩陣x1,并輸出矩陣元素及其大小(2*2);然后傳入元組y作為參數(shù),調(diào)用torch.tensor函數(shù)定義FloatTensor類(lèi)矩陣x2,并輸出矩陣元素。
5、程序1-2-2-5.py依次定義雙精度矩陣和整數(shù)型矩陣。
#!/usr/bin/env python3
-- coding: utf-8 --
#1-2-2-5.py
import torch
a=[[10.2,20.6],[2,4]]
x=torch.DoubleTensor(a)
print(x)
y=torch.IntTensor(a)
print(y)
b=[[1,2],[3,4]]
z=torch.IntTensor(b)
print(z)
程序運(yùn)行結(jié)果如下:
tensor([[10.2000, 20.6000],
[ 2.0000, 4.0000]], dtype=torch.float64)
D:\pro\learnAIpy\src\1-2-2-5.py:8: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using int is deprecated, and may be removed in a future version of Python.
y=torch.IntTensor(a)
tensor([[10, 20],
[ 2, 4]], dtype=torch.int32)
tensor([[1, 2],
[3, 4]], dtype=torch.int32)
2.3 初始化張量
2.3.1 從數(shù)據(jù)中創(chuàng)建
張量可以直接從數(shù)據(jù)中創(chuàng)建,自動(dòng)判斷數(shù)據(jù)類(lèi)型。
import torch
data = [[11.0, 2],[3, 44.0]]
x_data = torch.tensor(data)
print(x_data)
data = [[11, 2],[3, 44]]
x_data = torch.tensor(data)
print(x_data)
運(yùn)行結(jié)果:
tensor([[11., 2.],
[ 3., 44.]])
tensor([[11, 2],
[ 3, 44]])
使用 torch.Tensor.item() 從包含單個(gè)值的張量中獲取Python數(shù),請(qǐng)執(zhí)行以下操作:
import torch
y=torch.tensor([[1,2],[3,4]])
print(y)
print(y[1,1].item())
tensor([[1, 2],
[3, 4]])
2.3.2 從NumPy 數(shù)組創(chuàng)建
import torch
import numpy as np
data = [[11.0, 2],[3, 44.0]]
np_array=np.array(data)
x_np = torch.from_numpy(np_array)
print(x_np)
運(yùn)行結(jié)果:
tensor([[11., 2.],
[ 3., 44.]], dtype=torch.float64)
如果有一個(gè)numpy數(shù)組并希望避免復(fù)制 ,可使用torch.as_tensor()。
import torch
import numpy as np
a = np.arange(8)
b = a.reshape(4,2)
print (b)
y=torch.torch.as_tensor(b)
print(y)
y[1][1]=55
print(y)
print(b)
[[0 1]
[2 3]
[4 5]
[6 7]]
tensor([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
tensor([[ 0, 1],
[ 2, 55],
[ 4, 5],
[ 6, 7]])
[[ 0 1]
[ 2 55]
[ 4 5]
[ 6 7]]
2.3.3 從其它tensor創(chuàng)建
import torch
import numpy as np
data = [[11.0, 2],[3, 44.0]]
x_data = torch.tensor(data)
print(f”Tensor: \n {x_data} \n")
運(yùn)行結(jié)果:
Tensor:
tensor([[11., 2.],
[ 3., 44.]])
2.3.4 隨機(jī)值創(chuàng)建tensor
import torch
import numpy as np
shape=(3,4,)
x_data = torch.rand(shape)
print(f"Tensor: \n {x_data} \n")
運(yùn)行結(jié)果:
Tensor:
tensor([[0.5137, 0.2523, 0.4290, 0.8971],
[0.6080, 0.6341, 0.3161, 0.1189],
[0.5905, 0.0437, 0.0408, 0.5235]])
2.3.5 零矩陣、單位矩陣等
import torch
import numpy as np
shape=(3,4,)
x_data = torch.zeros(shape)
print(f"Tensor: \n {x_data} \n")
x_data = torch.ones(shape)
print(f"Tensor: \n {x_data} \n")
運(yùn)行結(jié)果:
Tensor:
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
Tensor:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
單位矩陣
在線性代數(shù)中,n階單位矩陣,是一個(gè)n × n 的方形矩陣,其主對(duì)角線元素為1,其余元素為0。在矩陣的乘法中,起著特殊的作用,如同數(shù)的乘法中的1,根據(jù)單位矩陣的特點(diǎn),任何矩陣與單位矩陣相乘都等于本身。
print(torch.eye(5))#對(duì)象線為1,其余為0,單位矩陣
tensor([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
import torch
print(torch.zeros(2,3,2))
print(torch.ones(2,4))
print(torch.rand(2,3))#[0,1]隨機(jī)數(shù)
print(torch.arange(2,8))#序列
print(torch.arange(2,10,3))
tensor([[[0., 0.],
[0., 0.],
[0., 0.]],
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.]])
tensor([[0.2293, 0.5129, 0.2397],
[0.3889, 0.5081, 0.4054]])
tensor([2, 3, 4, 5, 6, 7])
tensor([2, 5, 8])
2.3.6 torch數(shù)據(jù)類(lèi)型
Pytorch的張量的數(shù)據(jù)類(lèi)型以數(shù)值類(lèi)型為主,定義了以下幾種CPU張量和對(duì)應(yīng)的GPU張量類(lèi)型,如下表所示。
數(shù)據(jù)類(lèi)型 dtype CPU張量 GPU張量
32-bit floating point torch.float32?or?torch.float torch.FloatTensor torch.cuda.FloatTensor
64-bit floating point torch.float64?or?torch.double torch.DoubleTensor torch.cuda.DoubleTensor
16-bit floating point?1 torch.float16?or?torch.half torch.HalfTensor torch.cuda.HalfTensor
16-bit floating point?2 torch.bfloat16 torch.BFloat16Tensor torch.cuda.BFloat16Tensor
32-bit complex torch.complex32
64-bit complex torch.complex64
128-bit complex torch.complex128?or?torch.cdouble
8-bit integer (unsigned) torch.uint8 torch.ByteTensor torch.cuda.ByteTensor
8-bit integer (signed) torch.int8 torch.CharTensor torch.cuda.CharTensor
16-bit integer (signed) torch.int16?or?torch.short torch.ShortTensor torch.cuda.ShortTensor
32-bit integer (signed) torch.int32?or?torch.int torch.IntTensor torch.cuda.IntTensor
64-bit integer (signed) torch.int64?or?torch.long torch.LongTensor torch.cuda.LongTensor
Boolean torch.bool torch.BoolTensor torch.cuda.BoolTensor
2.3.7 torch所在設(shè)備
torch.device是一個(gè)對(duì)象,它代表一個(gè)torch所在的設(shè)備,張量被分配在該設(shè)備里。device包含一個(gè)設(shè)備類(lèi)型(‘cpu’或’cuda’)和設(shè)備類(lèi)型的可選設(shè)備序號(hào)。 如果設(shè)備序號(hào)不存在,這個(gè)對(duì)象將始終代表設(shè)備類(lèi)型的當(dāng)前設(shè)備。
特定數(shù)據(jù)類(lèi)型的tensor可以被構(gòu)造,通過(guò) torch.dtype和/或torch.device,對(duì)于構(gòu)造函數(shù)或張量創(chuàng)建操作。
cuda0 = torch.device(‘cuda:0’)
torch.ones([2, 4], dtype=torch.float64, device=cuda0)
tensor([[ 1.0000, 1.0000, 1.0000, 1.0000],
[ 1.0000, 1.0000, 1.0000, 1.0000]], dtype=torch.float64, device=‘cuda:0’)
2.4 tensor訪問(wèn)與操作
2.4.1 索引和切片表示法
可以使用Python的索引和切片表示法訪問(wèn)和修改tensor的內(nèi)容:
import torch
y=torch.tensor([[1,2],[3,4]])
print(y)
print(y[1,:])
print(y[:,0])
print(y[:,1])
tensor([[1, 2],
[3, 4]])
tensor([3, 4])
tensor([1, 3])
tensor([2, 4])
2.4.2 記錄操作
可使用requires_grad=True創(chuàng)建張量,以便torch.autograd記錄對(duì)它們的操作以進(jìn)行自動(dòng)區(qū)分。
import torch
x = torch.tensor([[1., 2.], [3., 4.]], requires_grad=True)
out = x.pow(2).sum()
out.backward()
print(x.grad)
tensor([[2., 4.],
[6., 8.]])
2.4.3 tensor 數(shù)據(jù)保存
每個(gè) tensor 都有一個(gè)相關(guān)的 torch.Storage,,它保存數(shù)據(jù)。tensor類(lèi)還提供了存儲(chǔ)的多維、跨視圖,并定義了對(duì)存儲(chǔ)的數(shù)字操作。
改變tensor的方法用下劃線后綴標(biāo)記。例如,torch.FloatTensor.abs_()就地計(jì)算絕對(duì)值并返回修改后的張量,而torch.FloatTensor.abs_()以新的tensor張量計(jì)算結(jié)果。
改變現(xiàn)有的張量 torch.device 和/或torch.dtype,考慮對(duì)張量使用to()方法。
當(dāng)前執(zhí)行的 torch.Tensor 引入內(nèi)存開(kāi)銷(xiāo),因此在具有許多小張量tensor的應(yīng)用程序中可能會(huì)導(dǎo)致意外的高內(nèi)存使用率
二、
總結(jié)
以上是生活随笔為你收集整理的PyTorch随笔-5的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: MySQL 添加where 1= 1 是
- 下一篇: pytorch随笔-6