哪里有做網(wǎng)站服務(wù)商seo研究學(xué)院
目錄
1.張量的定義
2.張量的分類
3.張量的創(chuàng)建
3.1 根據(jù)已有數(shù)據(jù)創(chuàng)建張量
3.2?根據(jù)形狀創(chuàng)建張量
3.3 創(chuàng)建指定類型的張量
1.張量的定義
張量(Tensor)是機器學(xué)習(xí)的基本構(gòu)建模塊,是以數(shù)字方式表示數(shù)據(jù)的形式。PyTorch就是將數(shù)據(jù)封裝成張量來進行運算的。PyTorch中的張量就是元素為同一種數(shù)據(jù)類型的多維數(shù)組。在PyTorch中,張量以"類"的形式封裝起來,對張量的一些運算、處理的方法被封裝在類中。
2.張量的分類
2.1 0維張量
?將標(biāo)量轉(zhuǎn)化為張量得到的就是0維張量
import torch
#0維張量:標(biāo)量(scalar)
scalar=torch.tensor(7)
print(scalar.ndim)#0
2.2 1維張量
將向量轉(zhuǎn)化為張量得到的就是1維張量
import torch
#1維張量:向量(vector)
vector=torch.tensor([7,7])
print(vector.ndim)#1
2.3 2維張量
將矩陣轉(zhuǎn)化為張量得到的就是2維張量
import torch
#2維張量:矩陣(matrix)
matrix=torch.tensor([[7,8],[9,10]])
print(matrix.ndim)#2
2.4 多維張量
將多維數(shù)組轉(zhuǎn)化為張量得到的就是多維張量
import torch
#多維張量
tensor=torch.tensor([[[1,2,3],[3,6,9],[2,4,5]]])
print(tensor.ndim)#3
3.張量的創(chuàng)建
3.1 根據(jù)已有數(shù)據(jù)創(chuàng)建張量
利用torch.tensor可以實現(xiàn)根據(jù)已有數(shù)據(jù)創(chuàng)建張量
import torch
import numpy as np
def test01():#1.1創(chuàng)建標(biāo)量張量data=torch.tensor(10)print(data)#1.2numpy數(shù)組,由于data為float64,下面代碼也使用該類型data=np.random.randn(2,3)#2行3列data=torch.tensor(data)print(data)#1.3列表,下面代碼使用默認元素類型float32data=[[10.,20.,30.],[40.,50.,60.]]data=torch.tensor(data)print(data)
if __name__=='__main__':test01()
3.2?根據(jù)形狀創(chuàng)建張量
利用torch.Tensor可以根據(jù)形狀創(chuàng)建張量,也可用來創(chuàng)建指定數(shù)據(jù)的張量
import torch
def test02():#2.1創(chuàng)建2行3列的張量,默認dtype為float32data=torch.Tensor(2,3)print(data)#2.2注意:如果傳遞列表,則創(chuàng)建包含指定元素的張量data=torch.Tensor([10])print(data)data=torch.Tensor([10,20])print(data)
if __name__=='__main__':test02()
3.3 創(chuàng)建指定類型的張量
利用 torch.IntTensor、torch.FloatTensor、torch.DoubleTensor可以創(chuàng)建指定類型的張量
def test03():#3.1創(chuàng)建2行3列,dtype為int32的張量data=torch.IntTensor(2,3)print(data)#3.2注意:如果傳遞的元素類型不正確,則會進行類型轉(zhuǎn)換data=torch.IntTensor([2.5,3.3])print(data)#3.3其他的類型#int16data=torch.ShortTensor()#int64data=torch.LongTensor()#float32data=torch.FloatTensor()#float64data=torch.DoubleTensor()
if __name__ =='__main__':test03()
?