函數 | 功能 |
---|---|
Tensor(*sizes) | 基礎構造函數 |
tensor(data,) | 相似np.array的構造函數 |
ones(*sizes) | 全1Tensor |
zeros(*sizes) | 全0Tensor |
eye(*sizes) | 對角線爲1,其餘爲0 |
arange(s,e,step) | 從s到e,步長爲step |
linspace(s,e,steps) | 從s到e,均勻切分紅steps份 |
rand/randn(*sizes) | 均勻/標準分佈 |
normal(mean,std)/uniform(from,to) | 正態分佈/均勻分佈 |
randperm(m) | 長度爲5隨機排列 |
這些建立方法均可以在建立的時候指定數據類型dtype和存放device(cpu/gpu)html
查看tensor的形狀,tensor.shape
等價於tensor.size()
python
import torch as t
# 用list的數據建立tensor
b = t.Tensor([[1,2,3],[4,5,6]])
b.tolist() # 把tensor轉爲list
b_size = b.size()
b.numel() # b中元素總個數,2*3,等價於b.nelement()
# 建立一個和b形狀同樣的tensor
c = t.Tensor(b_size)
# 建立一個元素爲2和3的tensor
d = t.Tensor((2, 3))
複製代碼
>>> torch.arange(0,10,1)
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> torch.range(0,10,1)
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
10.])
複製代碼
Data type | dtype | CPU tensor | GPU tensor |
---|---|---|---|
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 | torch.float16 or torch.half |
torch.HalfTensor |
torch.cuda.HalfTensor |
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 |
import torch as t
# 設置默認tensor,注意參數是字符串
t.set_default_tensor_type('torch.DoubleTensor')
a = t.Tensor(2,3)
a.dtype # 如今a是DoubleTensor,dtype是float64
# 恢復以前的默認設置
t.set_default_tensor_type('torch.FloatTensor')
t.zeros_like(a) #等價於t.zeros(a.shape,dtype=a.dtype,device=a.device)
t.zeros_like(a, dtype=t.int16) #能夠修改某些屬性
複製代碼
>>> c = torch.tensor([3,4,5], dtype=torch.long)
>>> c
tensor([3, 4, 5])
>>> c.dtype
torch.int64
>>> a = torch.Tensor([2,3])
>>> a.dtype
torch.float32
>>> a.requires_grad
False
>>> a.int()
tensor([2, 3], dtype=torch.int32)
>>> a.short()
tensor([2, 3], dtype=torch.int16)
>>> a.type(torch.FloatTensor)
tensor([2., 3.])
>>> a.dtype
torch.float32
>>> a.long()# 爲何修改失敗
tensor([2, 3])
>>> a.dtype
torch.float32
>>> a.double()
tensor([2., 3.], dtype=torch.float64)
>>> b=torch.LongTensor([4,5])
>>> b
tensor([4, 5])
>>> b.dtype
torch.int64
複製代碼
函數 | 功能 |
---|---|
abs/sqrt/div/exp/fmod/log/pow.. | 絕對值/平方根/除法/指數/求餘/求冪.. |
cos/sin/asin/atan2/cosh.. | 相關三角函數 |
ceil/round/floor/trunc | 上取整/四捨五入/下取整/只保留整數部分 |
clamp(input, min, max) | 超過min和max部分截斷 |
sigmod/tanh.. | 激活函數 |
Tensor---->Numpy 可使用 data.numpy(),data爲Tensor變量ide
Numpy ----> Tensor 可使用torch.from_numpy(data),data爲numpy變量函數
import numpy as np
a = np.ones([2, 3],dtype=np.float32)
b = t.from_numpy(a)
b = t.Tensor(a) # 也能夠直接將numpy對象傳入Tensor
c = b.numpy() # a, b, c三個對象共享內存
# 當numpy的數據類型和Tensor的類型不同的時候,數據會被複制,不會共享內存。
# 不論輸入的類型是什麼,t.tensor(a)都會進行數據拷貝,不會共享內存
複製代碼
自動求導須要指定,默認建立的tensor不能求導ui
#在建立tensor的時候指定requires_grad
a = t.randn(3,4, requires_grad=True)
# 或者
a = t.randn(3,4).requires_grad_()
# 或者
a = t.randn(3,4)
a.requires_grad=True
複製代碼
在tensor attributes中有三個類,分別爲torch.dtype, torch.device, 和 torch.layoutspa
其中, torch.dtype 是展現 torch.Tensor 數據類型的類,pytorch 有八個不一樣的數據類型,下表是完整的 dtype 列表.scala
Torch.device 是表現 torch.Tensor被分配的設備類型的類,其中分爲’cpu’ 和 ‘cuda’兩種,若是設備序號沒有顯示則表示此 tensor 被分配到當前設備, 好比: 'cuda' 等同於 'cuda': X , X 爲torch.cuda.current _device() 返回值3d
咱們能夠經過 tensor.device 來獲取其屬性,同時能夠利用字符或字符+序號的方式來分配設備code
經過字符串:
>>> torch.device('cuda:0')
device(type='cuda', index=0)
>>> torch.device('cpu')
device(type='cpu')
>>> torch.device('cuda') # 當前設備
device(type='cuda')
經過字符串和設備序號:
>>> torch.device('cuda', 0)
device(type='cuda', index=0)
>>> torch.device('cpu', 0)
device(type='cpu', index=0)
複製代碼
此外,cpu 和 cuda 設備的轉換使用 'to' 來實現:orm
>>> device_cpu = torch.device("cuda") #聲明cuda設備
>>> device_cuda = torch.device('cuda') #設備cpu設備
>>> data = torch.Tensor([1])
>>> data.to(device_cpu) #將數據轉爲cpu格式
>>> data.to(device_cuda) #將數據轉爲cuda格式
複製代碼
torch.layout 是表現 torch.Tensor 內存分佈的類,目前只支持 torch.strided
torch.tensor(data, dtype=None, device=None,requires_grad=False)
data - 能夠是list, tuple, numpy array, scalar或其餘類型
dtype - 能夠返回想要的tensor類型
device - 能夠指定返回的設備
requires_grad - 能夠指定是否進行記錄圖的操做,默認爲False
須要注意的是,torch.tensor 老是會複製 data, 若是你想避免複製,可使 torch.Tensor. detach(),若是是從 numpy 中得到數據,那麼你能夠用 torch.from_numpy(), 注from_numpy() 是共享內存的
>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
tensor([[ 0.1000, 1.2000],
[ 2.2000, 3.1000],
[ 4.9000, 5.2000]])
>>> torch.tensor([0, 1]) # Type inference on data
tensor([ 0, 1])
>>> torch.tensor([[0.11111, 0.222222, 0.3333333]],
dtype=torch.float64,
device=torch.device('cuda:0')) # creates a torch.cuda.DoubleTensor
tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0')
>>> torch.tensor(3.14159) # Create a scalar (zero-dimensional tensor)
tensor(3.1416)
>>> torch.tensor([]) # Create an empty tensor (of size (0,))
tensor([])
複製代碼
torch.from_numpy(ndarry)
注:生成返回的tensor會和ndarry共享數據,任何對tensor的操做都會影響到ndarry, 反之亦然
>>> a = numpy.array([1, 2, 3])
>>> t = torch.from_numpy(a)
>>> t
tensor([ 1, 2, 3])
>>> t[0] = -1
>>> a
array([-1, 2, 3])
複製代碼
根據數值要求:
torch.zeros(*sizes, out=None, ..)# 返回大小爲sizes的零矩陣
torch.zeros_like(input, ..) # 返回與input相同size的零矩陣
torch.ones(*sizes, out=None, ..) #f返回大小爲sizes的單位矩陣
torch.ones_like(input, ..) #返回與input相同size的單位矩陣
torch.full(size, fill_value, …) #返回大小爲sizes,單位值爲fill_value的矩陣
torch.full_like(input, fill_value, …) 返回與input相同size,單位值爲fill_value的矩陣
torch.arange(start=0, end, step=1, …) #返回從start到end, 單位步長爲step的1-d tensor.
torch.linspace(start, end, steps=100, …) #返回從start到end, 間隔中的插值數目爲steps的1-d tensor
torch.logspace(start, end, steps=100, …) #返回1-d tensor ,從10^start到10^end的steps個對數間隔
複製代碼
根據矩陣要求:
torch.eye(n, m=None, out=None,…) #返回2-D 的單位對角矩陣
torch.empty(*sizes, out=None, …) #返回被未初始化的數值填充,大小爲sizes的tensor
torch.empty_like(input, …) # 返回與input相同size,並被未初始化的數值填充的tensor
複製代碼
torch.normal(mean, std, out=None)
torch.rand(*size, out=None, dtype=None, …) #返回[0,1]之間均勻分佈的隨機數值
torch.rand_like(input, dtype=None, …) #返回與input相同size的tensor, 填充均勻分佈的隨機數值
torch.randint(low=0, high, size,…) #返回均勻分佈的[low,high]之間的整數隨機值
torch.randint_like(input, low=0, high, dtype=None, …) #
torch.randn(*sizes, out=None, …) #返回大小爲size,由均值爲0,方差爲1的正態分佈的隨機數值
torch.randn_like(input, dtype=None, …)
torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的數列的隨機排列
複製代碼
基本操做:
Joining ops:
torch.cat(seq,dim=0,out=None) # 沿着dim鏈接seq中的tensor, 全部的tensor必須有相同的size或爲empty, 其相反的操做爲 torch.split() 和torch.chunk()
torch.stack(seq, dim=0, out=None) #同上
#注: .cat 和 .stack的區別在於 cat會增長現有維度的值,能夠理解爲續接,stack會新加增長一個維度,能夠
理解爲疊加
>>> a=torch.Tensor([1,2,3])
>>> torch.stack((a,a)).size()
torch.size(2,3)
>>> torch.cat((a,a)).size()
torch.size(6)
複製代碼
torch.gather(input, dim, index, out=None) #返回沿着dim收集的新的tensor
>> t = torch.Tensor([[1,2],[3,4]])
>> index = torch.LongTensor([[0,0],[1,0]])
>> torch.gather(t, 0, index) #因爲 dim=0,因此結果爲
| t[index[0, 0] 0] t[index[0, 1] 1] |
| t[index[1, 0] 0] t[index[1, 1] 1] |
對於3-D 的張量來講,能夠做爲
out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
複製代碼
clicing ops:
torch.split(tensor, split_size_or_sections, dim=0) #將tensor 拆分紅相應的組塊
torch.chunk(tensor, chunks, dim=0) #將tensor 拆分紅相應的組塊, 最後一塊會小一些若是不能整除的話#
#注:split和chunk的區別在於:
split的split_size_or_sections 表示每個組塊中的數據大小,chunks表示組塊的數量
>>> a = torch.Tensor([1,2,3])
>>> torch.split(a,1)
(tensor([1.]), tensor([2.]), tensor([3.]))
>>> torch.chunk(a,1)
(tensor([ 1., 2., 3.]),)
複製代碼
Indexing ops:
torch.index_select(input, dim, index, out=None) #返回沿着dim的指定tensor, index需爲longTensor類型,不共用內存
torch.masked_select(input, mask, out=None) #根據mask來返回input的值其爲1-D tensor. Mask爲ByteTensor, true返回,false不返回,返回值不共用內存
>>> x = torch.randn(3, 4)
>>> x
tensor([[ 0.3552, -2.3825, -0.8297, 0.3477],
[-1.2035, 1.2252, 0.5002, 0.6248],
[ 0.1307, -2.0608, 0.1244, 2.0139]])
>>> mask = x.ge(0.5)
>>> mask
tensor([[ 0, 0, 0, 0],
[ 0, 1, 1, 1],
[ 0, 0, 0, 1]], dtype=torch.uint8)
>>> torch.masked_select(x, mask)
tensor([ 1.2252, 0.5002, 0.6248, 2.0139])
複製代碼
Mutation ops:
torch.transpose(input, dim0, dim1, out=None) #返回dim0和dim1交換後的tensor
torch.t(input, out=None) #專爲2D矩陣的轉置,是transpose的便捷函數
torch.squeeze(input, dim, out=None) #默認移除全部size爲1的維度,當dim指定時,移除指定size爲1的維度. 返回的tensor會和input共享存儲空間,因此任何一個的改變都會影響另外一個
torch.unsqueeze(input, dim, out=None) #擴展input的size, 如 A x B 變爲 1 x A x B
torch.reshape(input, shape) #返回size爲shape具備相同數值的tensor, 注意 shape=(-1,)這種表述,-1表示任意的。
#注 reshape(-1,)
>>> a=torch.Tensor([1,2,3,4,5]) #a.size 是 torch.size(5)
>>> b=a.reshape(1,-1) #表示第一維度是1,第二維度按a的size填充滿
>>> b.size()
torch.size([1,5])
torch.where(condition,x,y) #根據condition的值來相應x,y的值,true返回x的值,false返回y的值,造成新的tensor
torch.unbind(tensor, dim=0) #返回tuple 解除指定的dim的綁定,至關於按指定dim拆分
>>> a=torch.Tensor([[1,2,3],[2,3,4]])
>>> torch.unbind(a,dim=0)
(torch([1,2,3]),torch([2,3,4])) # 將一個(2,3) 分爲兩個(3)
torch.nonzero(input, out=None) # 返回非零值的索引, 每一行都是一個非零值的索引值
>>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]))
tensor([[ 0],
[ 1],
[ 2],
[ 4]])
>>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0],
[0.0, 0.4, 0.0, 0.0],
[0.0, 0.0, 1.2, 0.0],
[0.0, 0.0, 0.0,-0.4]]))
tensor([[ 0, 0],
[ 1, 1],
[ 2, 2],
[ 3, 3]])
複製代碼
三角函數:
torch.abs(input, out=None)
torch.acos(input, out=None)
torch.asin(input, out=None)
torch.atan(input, out=None)
torch.atan2(input, inpu2, out=None)
torch.cos(input, out=None)
torch.cosh(input, out=None)
torch.sin(input, out=None)
torch.sinh(input, out=None)
torch.tan(input, out=None)
torch.tanh(input, out=None)
複製代碼
基本運算,加減乘除
Torch.add(input, value, out=None)
.add(input, value=1, other, out=None)
.addcdiv(tensor, value=1, tensor1, tensor2, out=None)
.addcmul(tensor, value=1, tensor1, tensor2, out=None)
torch.div(input, value, out=None)
.div(input, other, out=None)
torch.mul(input, value, out=None)
.mul(input, other, out=None)
複製代碼
對數運算:
torch.log(input, out=None) # y_i=log_e(x_i)
torch.log1p(input, out=None) #y_i=log_e(x_i+1)
torch.log2(input, out=None) #y_i=log_2(x_i)
torch.log10(input,out=None) #y_i=log_10(x_i)
複製代碼
冪函數:
torch.pow(input, exponent, out=None) # y_i=input^(exponent)
複製代碼
指數運算
torch.exp(tensor, out=None) #y_i=e^(x_i)
torch.expm1(tensor, out=None) #y_i=e^(x_i) -1
複製代碼
截斷函數
torch.ceil(input, out=None) #返回向正方向取得最小整數
torch.floor(input, out=None) #返回向負方向取得最大整數
torch.round(input, out=None) #返回相鄰最近的整數,四捨五入
torch.trunc(input, out=None) #返回整數部分數值
torch.frac(tensor, out=None) #返回小數部分數值
torch.fmod(input, divisor, out=None) #返回input/divisor的餘數
torch.remainder(input, divisor, out=None) #同上
複製代碼
其餘運算
torch.erf(tensor, out=None)
torch.erfinv(tensor, out=None)
torch.sigmoid(input, out=None)
torch.clamp(input, min, max out=None) #返回 input<min,則返回min, input>max,則返回max,其他返回input
torch.neg(input, out=None) #out_i=-1*(input)
torch.reciprocal(input, out=None) # out_i= 1/input_i
torch.sqrt(input, out=None) # out_i=sqrt(input_i)
torch.rsqrt(input, out=None) #out_i=1/(sqrt(input_i))
torch.sign(input, out=None) #out_i=sin(input_i) 大於0爲1,小於0爲-1
torch.lerp(start, end, weight, out=None)
複製代碼
torch.argmax(input, dim=None, keepdim=False) #返回最大值排序的索引值
torch.argmin(input, dim=None, keepdim=False) #返回最小值排序的索引值
torch.cumprod(input, dim, out=None) #y_i=x_1 * x_2 * x_3 *…* x_i
torch.cumsum(input, dim, out=None) #y_i=x_1 + x_2 + … + x_i
torch.dist(input, out, p=2) #返回input和out的p式距離
torch.mean() #返回平均值
torch.sum() #返回總和
torch.median(input) #返回中間值
torch.mode(input) #返回衆數值
torch.unique(input, sorted=False) #返回1-D的惟一的tensor,每一個數值返回一次.
>>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
>>> output
tensor([ 2, 3, 1])
torch.std( #返回標準差)
torch.var() #返回方差
torch.norm(input, p=2) #返回p-norm的範式
torch.prod(input, dim, keepdim=False) #返回指定維度每一行的乘積
複製代碼
torch.eq(input, other, out=None) #按成員進行等式操做,相同返回1
torch.equal(tensor1, tensor2) #若是tensor1和tensor2有相同的size和elements,則爲true
>>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[ 1, 0],
[ 0, 1]], dtype=torch.uint8)
>>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[ 1, 0],
[ 0, 1]], dtype=torch.uint8)
torch.ge(input, other, out=None) # input>= other
torch.gt(input, other, out=None) # input>other
torch.le(input, other, out=None) # input=<other
torch.lt(input, other, out=None) # input<other
torch.ne(input, other, out=None) # input != other 不等於
torch.max() # 返回最大值
torch.min() # 返回最小值
torch.isnan(tensor) #判斷是否爲’nan’
torch.sort(input, dim=None, descending=False, out=None) #對目標input進行排序
torch.topk(input, k, dim=None, largest=True, sorted=True, out=None) #沿着指定維度返回最大k個數值及其索引值
torch.kthvalue(input, k, dim=None, deepdim=False, out=None) #沿着指定維度返回最小k個數值及其索引值
複製代碼
torch.fft(input, signal_ndim, normalized=False)
torch.ifft(input, signal_ndim, normalized=False)
torch.rfft(input, signal_ndim, normalized=False, onesided=True)
torch.irfft(input, signal_ndim, normalized=False, onesided=True)
torch.stft(signa, frame_length, hop, …)
複製代碼
torch.cross(input, other, dim=-1, out=None) #叉乘(外積)
torch.dot(tensor1, tensor2) #返回tensor1和tensor2的點乘
torch.mm(mat1, mat2, out=None) #返回矩陣mat1和mat2的乘積
torch.eig(a, eigenvectors=False, out=None) #返回矩陣a的特徵值/特徵向量
torch.det(A) #返回矩陣A的行列式
torch.trace(input) #返回2-d 矩陣的跡(對對角元素求和)
torch.diag(input, diagonal=0, out=None) #
torch.histc(input, bins=100, min=0, max=0, out=None) #計算input的直方圖
torch.tril(input, diagonal=0, out=None) #返回矩陣的下三角矩陣,其餘爲0
torch.triu(input, diagonal=0, out=None) #返回矩陣的上三角矩陣,其餘爲0
複製代碼
因爲pytorch 0.4後,python number的獲取統一經過 .item()方式實現:
>>> a = torch.Tensor([1,2,3])
>>> a[0] #直接取索引返回的是tensor數據
tensor(1.)
>>> a[0].item() #獲取python number
1
複製代碼
判斷:
torch.is_tensor() #若是是pytorch的tensor類型返回true
torch.is_storage() # 若是是pytorch的storage類型返回ture
複製代碼
這裏還有一個小技巧,若是須要判斷tensor是否爲空,能夠以下
>>> a=torch.Tensor()
>>> len(a)
0
>>> len(a) is 0
True
複製代碼
設置: 經過一些內置函數,能夠實現對tensor的精度, 類型,print打印參數等進行設置
torch.set_default_dtype(d) #對torch.tensor() 設置默認的浮點類型
torch.set_default_tensor_type() # 同上,對torch.tensor()設置默認的tensor類型
>>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32
torch.float32
>>> torch.set_default_dtype(torch.float64)
>>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
torch.float64
>>> torch.set_default_tensor_type(torch.DoubleTensor)
>>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
torch.float64
torch.get_default_dtype() #得到當前默認的浮點類型torch.dtype
torch.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, profile=None)#)
## 設置printing的打印參數
複製代碼