日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

pytorch方法,Tensor及其基本操作_重点

發(fā)布時間:2023/11/28 生活经验 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pytorch方法,Tensor及其基本操作_重点 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

由于之前的草稿都沒了,現(xiàn)在只有重寫…. 我好痛苦

本章只是對pytorch的常規(guī)操作進行一個總結(jié),大家看過有腦子里有印象就好,知道有這么個東西,需要的時候可以再去詳細的看,另外也還是需要在實戰(zhàn)中多運用。

?

本章導視圖

Tensor attributes:

在tensor attributes中有三個類,分別為torch.dtype, torch.device, 和 torch.layout

其中, torch.dtype 是展示 torch.Tensor 數(shù)據(jù)類型的類,pytorch 有八個不同的數(shù)據(jù)類型,下表是完整的 dtype 列表.

?

?

Torch.device 是表現(xiàn) torch.Tensor被分配的設備類型的類,其中分為’cpu’ 和 ‘cuda’兩種,如果設備序號沒有顯示則表示此 tensor 被分配到當前設備, 比如: 'cuda' 等同于 'cuda': X , X 為torch.cuda.current _device() 返回值

我們可以通過 tensor.device 來獲取其屬性,同時可以利用字符或字符+序號的方式來分配設備

通過字符串:
>>> 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 設備的轉(zhuǎn)換使用 'to' 來實現(xiàn):

>>> device_cpu = torch.device("cuda")  #聲明cuda設備
>>> device_cuda = torch.device('cuda')  #設備cpu設備
>>> data = torch.Tensor([1])
>>> data.to(device_cpu)  #將數(shù)據(jù)轉(zhuǎn)為cpu格式
>>> data.to(device_cuda)   #將數(shù)據(jù)轉(zhuǎn)為cuda格式

?

torch.layout 是表現(xiàn) torch.Tensor 內(nèi)存分布的類,目前只支持 torch.strided

?

創(chuàng)建tensor

  • 直接創(chuàng)建

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 中獲得數(shù)據(jù),那么你可以用 torch.from_numpy(), 注from_numpy() 是共享內(nèi)存的

?

>>> 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([])

?

  • 從numpy中獲得數(shù)據(jù)

torch.from_numpy(ndarry)

注:生成返回的tensor會和ndarry共享數(shù)據(jù),任何對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])

?

  • 創(chuàng)建特定的tensor

根據(jù)數(shù)值要求:

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, 間隔中的插值數(shù)目為steps的1-d tensortorch.logspace(start, end, steps=100, …) #返回1-d tensor ,從10^start到10^end的steps個對數(shù)間隔

根據(jù)矩陣要求:

torch.eye(n, m=None, out=None,…) #返回2-D 的單位對角矩陣torch.empty(*sizes, out=None, …) #返回被未初始化的數(shù)值填充,大小為sizes的tensortorch.empty_like(input, …) # 返回與input相同size,并被未初始化的數(shù)值填充的tensor

?

  • 隨機采用生成:
torch.normal(mean, std, out=None)torch.rand(*size, out=None, dtype=None, …) #返回[0,1]之間均勻分布的隨機數(shù)值torch.rand_like(input, dtype=None, …) #返回與input相同size的tensor, 填充均勻分布的隨機數(shù)值torch.randint(low=0, high, size,…) #返回均勻分布的[low,high]之間的整數(shù)隨機值torch.randint_like(input, low=0, high, dtype=None, …) #torch.randn(*sizes, out=None, …) #返回大小為size,由均值為0,方差為1的正態(tài)分布的隨機數(shù)值torch.randn_like(input, dtype=None, …)torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的數(shù)列的隨機排列

?

?

?

操作tensor

基本操作:

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的區(qū)別在于 cat會增加現(xiàn)有維度的值,可以理解為續(xù)接,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,所以結(jié)果為
| 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的區(qū)別在于:
split的split_size_or_sections 表示每一個組塊中的數(shù)據(jù)大小,chunks表示組塊的數(shù)量
>>> 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類型,不共用內(nèi)存torch.masked_select(input, mask, out=None) #根據(jù)mask來返回input的值其為1-D tensor. Mask為ByteTensor, true返回,false不返回,返回值不共用內(nèi)存
>>> 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矩陣的轉(zhuǎn)置,是transpose的便捷函數(shù)torch.squeeze(input, dim, out=None)  #默認移除所有size為1的維度,當dim指定時,移除指定size為1的維度. 返回的tensor會和input共享存儲空間,所以任何一個的改變都會影響另一個
torch.unsqueeze(input, dim, out=None) #擴展input的size, 如 A x B 變?yōu)?1 x A x B torch.reshape(input, shape) #返回size為shape具有相同數(shù)值的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) #根據(jù)condition的值來相應x,y的值,true返回x的值,false返回y的值,形成新的tensortorch.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]])

?

Tensor操作

  • 點對點操作

三角函數(shù):

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)

?

對數(shù)運算:

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)

?

冪函數(shù):

torch.pow(input, exponent, out=None)  # y_i=input^(exponent)

?

指數(shù)運算

torch.exp(tensor, out=None)    #y_i=e^(x_i)
torch.expm1(tensor, out=None)   #y_i=e^(x_i) -1

?

截斷函數(shù)

torch.ceil(input, out=None)   #返回向正方向取得最小整數(shù)
torch.floor(input, out=None)  #返回向負方向取得最大整數(shù)torch.round(input, out=None)  #返回相鄰最近的整數(shù),四舍五入torch.trunc(input, out=None)  #返回整數(shù)部分數(shù)值
torch.frac(tensor, out=None)  #返回小數(shù)部分數(shù)值torch.fmod(input, divisor, out=None)  #返回input/divisor的余數(shù)
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,其余返回inputtorch.neg(input, out=None) #out_i=-1*(input)torch.reciprocal(input, out=None)  # out_i= 1/input_itorch.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為-1torch.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_itorch.dist(input, out, p=2)       #返回input和out的p式距離
torch.mean()                      #返回平均值
torch.sum()                       #返回總和
torch.median(input)               #返回中間值
torch.mode(input)                 #返回眾數(shù)值
torch.unique(input, sorted=False) #返回1-D的唯一的tensor,每個數(shù)值返回一次.
>>> 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個數(shù)值及其索引值
torch.kthvalue(input, k, dim=None, deepdim=False, out=None) #沿著指定維度返回最小k個數(shù)值及其索引值

?

  • 頻譜操作
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)  #返回矩陣的下三角矩陣,其他為0torch.triu(input, diagonal=0, out=None) #返回矩陣的上三角矩陣,其他為0

?

Tips:

  • 獲取python number:

由于pytorch 0.4后,python number的獲取統(tǒng)一通過 .item()方式實現(xiàn):

>>> a = torch.Tensor([1,2,3])
>>> a[0]   #直接取索引返回的是tensor數(shù)據(jù)
tensor(1.)
>>> a[0].item()  #獲取python number
1

?

  • tensor設置

判斷:

torch.is_tensor()  #如果是pytorch的tensor類型返回true
torch.is_storage() # 如果是pytorch的storage類型返回ture

?

這里還有一個小技巧,如果需要判斷tensor是否為空,可以如下

>>> a=torch.Tensor()
>>> len(a)
0
>>> len(a) is 0
True

?

設置: 通過一些內(nèi)置函數(shù),可以實現(xiàn)對tensor的精度, 類型,print打印參數(shù)等進行設置

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.float64torch.get_default_dtype() #獲得當前默認的浮點類型torch.dtypetorch.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, profile=None)#)
## 設置printing的打印參數(shù)

總結(jié)

以上是生活随笔為你收集整理的pytorch方法,Tensor及其基本操作_重点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。