python機(jī)器學(xué)習(xí)pytorch?張量基礎(chǔ)教程
正文
張量是一種特殊的數(shù)據(jù)結(jié)構(gòu),與數(shù)組和矩陣非常相似。在 PyTorch 中,我們使用張量對(duì)模型的輸入和輸出以及模型的參數(shù)進(jìn)行編碼。
張量類似于NumPy 的ndarray,除了張量可以在 GPU 或其他硬件加速器上運(yùn)行。事實(shí)上,張量和 NumPy 數(shù)組通??梢怨蚕硐嗤牡讓觾?nèi)存,從而無(wú)需復(fù)制數(shù)據(jù)(請(qǐng)參閱Bridge with NumPy)。張量也針對(duì)自動(dòng)微分進(jìn)行了優(yōu)化(我們將在稍后的Autograd 部分中看到更多相關(guān)內(nèi)容)。如果您熟悉 ndarrays,那么您對(duì) Tensor API 會(huì)很快熟悉。
# 導(dǎo)入需要的包 import torch import numpy as np
1.初始化張量
張量可以以各種方式初始化。請(qǐng)看以下示例:
1.1 直接從列表數(shù)據(jù)初始化
張量可以直接從列表數(shù)據(jù)中創(chuàng)建。數(shù)據(jù)類型是自動(dòng)推斷的。
# 創(chuàng)建python list 數(shù)據(jù) data = [[1, 2],[3, 4]] # 初始化張量 x_data = torch.tensor(data)
1.2 用 NumPy 數(shù)組初始化
張量可以從 NumPy 數(shù)組創(chuàng)建(反之亦然 - 請(qǐng)參閱Bridge with NumPy)。
# 創(chuàng)建numpy 數(shù)組 np_array = np.array(data) # from_numpy初始化張量 x_np = torch.from_numpy(np_array)
1.3 從另一個(gè)張量初始化
新張量保留原張量的屬性(形狀shape、數(shù)據(jù)類型datatype),除非顯式覆蓋。
# 創(chuàng)建和x_data (形狀shape、數(shù)據(jù)類型datatype)一樣的張量并全部初始化為1 x_ones = torch.ones_like(x_data) # retains the properties of x_data print(f"Ones Tensor: \n {x_ones} \n") # 創(chuàng)建和x_data (形狀shape)一樣的張量并隨機(jī)初始化,覆蓋其數(shù)據(jù)類型datatype 為torch.float x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor: tensor([[1, 1], [1, 1]]) Random Tensor: tensor([[0.5001, 0.2973], [0.8085, 0.9395]])
1.4 使用隨機(jī)值或常量值初始化
shape
是張量維度的元組。在下面的函數(shù)中,它決定了輸出張量的維度。
# 定義形狀元組 shape = (2,3,) # 隨機(jī)初始化 rand_tensor = torch.rand(shape) # 全部初始化為1 ones_tensor = torch.ones(shape) # 全部初始化為0 zeros_tensor = torch.zeros(shape) print(f"Random Tensor: \n {rand_tensor} \n") print(f"Ones Tensor: \n {ones_tensor} \n") print(f"Zeros Tensor: \n {zeros_tensor}")
Random Tensor: tensor([[0.0032, 0.5302, 0.2832], [0.0826, 0.3679, 0.8727]]) Ones Tensor: tensor([[1., 1., 1.], [1., 1., 1.]]) Zeros Tensor: tensor([[0., 0., 0.], [0., 0., 0.]])
2.張量的屬性
張量屬性描述了它們的形狀Shape、數(shù)據(jù)類型Datatype和存儲(chǔ)它們的設(shè)備Device。
tensor = torch.rand(3,4) print(f"Shape of tensor: {tensor.shape}") print(f"Datatype of tensor: {tensor.dtype}") print(f"Device tensor is stored on: {tensor.device}")
Shape of tensor: torch.Size([3, 4]) Datatype of tensor: torch.float32 Device tensor is stored on: cpu
3.張量運(yùn)算
這里全面介紹了超過(guò) 100 種張量運(yùn)算,包括算術(shù)、線性代數(shù)、矩陣操作(轉(zhuǎn)置、索引、切片)、采樣等。
這些操作中的每一個(gè)都可以在 GPU 上運(yùn)行(通常以比 CPU 更高的速度)。
默認(rèn)情況下,張量是在 CPU 上創(chuàng)建的。我們需要使用 .to
方法明確地將張量移動(dòng)到 GPU(在檢查 GPU 可用性之后)。請(qǐng)記住,跨設(shè)備復(fù)制大張量在時(shí)間和內(nèi)存方面可能會(huì)很昂貴!
# We move our tensor to the GPU if available if torch.cuda.is_available(): tensor = tensor.to("cuda")
嘗試列表中的一些操作。如果您熟悉 NumPy API,您會(huì)發(fā)現(xiàn) Tensor API 使用起來(lái)輕而易舉。
3.1 標(biāo)準(zhǔn)的類似 numpy 的索引和切片:
tensor = torch.ones(4, 4) print(f"First row: {tensor[0]}") print(f"First column: {tensor[:, 0]}") print(f"Last column: {tensor[..., -1]}") tensor[:,1] = 0 print(tensor)
First row: tensor([1., 1., 1., 1.]) First column: tensor([1., 1., 1., 1.]) Last column: tensor([1., 1., 1., 1.]) tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]])
3.2 連接張量
您可以用來(lái)torch.cat
沿給定維度連接一系列張量。另請(qǐng)參閱torch.stack,另一個(gè)與torch.cat
.
t1 = torch.cat([tensor, tensor, tensor], dim=1) print(t1)
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.], [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.], [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.], [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
3.3 算術(shù)運(yùn)算
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value y1 = tensor @ tensor.T y2 = tensor.matmul(tensor.T) y3 = torch.rand_like(y1) torch.matmul(tensor, tensor.T, out=y3) # This computes the element-wise product. z1, z2, z3 will have the same value z1 = tensor * tensor z2 = tensor.mul(tensor) z3 = torch.rand_like(tensor) torch.mul(tensor, tensor, out=z3)
tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]])
3.4單元素張量 Single-element tensors
如果您有一個(gè)單元素張量,例如通過(guò)將張量的所有值聚合為一個(gè)值,您可以使用以下方法將其轉(zhuǎn)換為 Python 數(shù)值item()
:
agg = tensor.sum() agg_item = agg.item() print(agg_item, type(agg_item))
12.0 <class 'float'>
3.5 In-place 操作
將結(jié)果存儲(chǔ)到操作數(shù)中的操作稱為In-place操作。它們由_
后綴表示。例如:x.copy_(y)
, x.t_()
, 會(huì)變x
。
print(f"{tensor} \n") tensor.add_(5) print(tensor)
tensor([[1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.], [1., 0., 1., 1.]]) tensor([[6., 5., 6., 6.], [6., 5., 6., 6.], [6., 5., 6., 6.], [6., 5., 6., 6.]])
注意:
In-place 操作可以節(jié)省一些內(nèi)存,但在計(jì)算導(dǎo)數(shù)時(shí)可能會(huì)出現(xiàn)問(wèn)題,因?yàn)闀?huì)立即丟失歷史記錄。因此,不鼓勵(lì)使用它們。
4. 張量和NumPy 橋接
CPU 和 NumPy 數(shù)組上的張量可以共享它們的底層內(nèi)存位置,改變一個(gè)會(huì)改變另一個(gè)。
4.1 張量到 NumPy 數(shù)組
t = torch.ones(5) print(f"t: {t}") n = t.numpy() print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.]) n: [1. 1. 1. 1. 1.]
張量的變化反映在 NumPy 數(shù)組中。
t.add_(1) print(f"t: {t}") print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.]) n: [2. 2. 2. 2. 2.]
4.2 NumPy 數(shù)組到張量
n = np.ones(5) t = torch.from_numpy(n)
NumPy 數(shù)組的變化反映在張量中。
np.add(n, 1, out=n) print(f"t: {t}") print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64) n: [2. 2. 2. 2. 2.]
以上就是python機(jī)器學(xué)習(xí)pytorch 張量基礎(chǔ)教程的詳細(xì)內(nèi)容,更多關(guān)于python機(jī)器學(xué)習(xí)pytorch張量的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Python機(jī)器學(xué)習(xí)應(yīng)用之基于天氣數(shù)據(jù)集的XGBoost分類篇解讀
- python機(jī)器學(xué)習(xí)庫(kù)xgboost的使用
- Python機(jī)器學(xué)習(xí)特征重要性分析的8個(gè)常用方法實(shí)例探究
- python taipy庫(kù)輕松地將數(shù)據(jù)和機(jī)器學(xué)習(xí)模型轉(zhuǎn)為功能性Web應(yīng)用
- Python BentoML構(gòu)建部署和管理機(jī)器學(xué)習(xí)模型技巧掌握
- Python機(jī)器學(xué)習(xí)性能度量利用鳶尾花數(shù)據(jù)繪制P-R曲線
- Python機(jī)器學(xué)習(xí)利用鳶尾花數(shù)據(jù)繪制ROC和AUC曲線
- Python梯度提升庫(kù)XGBoost解決機(jī)器學(xué)習(xí)問(wèn)題使用探究
相關(guān)文章
淺談PyQt5中異步刷新UI和Python多線程總結(jié)
今天小編就為大家分享一篇淺談PyQt5中異步刷新UI和Python多線程總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12淺談使用Python變量時(shí)要避免的3個(gè)錯(cuò)誤
這篇文章主要介紹了淺談使用Python變量時(shí)要避免的3個(gè)錯(cuò)誤,還是比較不錯(cuò)的,涉及部分代碼分析,以及字典的創(chuàng)建等相關(guān)內(nèi)容,需要的朋友可以參考下。2017-10-10Python3開(kāi)發(fā)環(huán)境搭建詳細(xì)教程
這篇文章主要介紹了Python3開(kāi)發(fā)環(huán)境搭建詳細(xì)教程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06Matplotlib animation模塊實(shí)現(xiàn)動(dòng)態(tài)圖
這篇文章主要介紹了Matplotlib animation模塊實(shí)現(xiàn)動(dòng)態(tài)圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02全面掌握Python?JSON庫(kù)函數(shù)與方法學(xué)會(huì)JSON數(shù)據(jù)處理
Python提供了內(nèi)置的JSON庫(kù),允許在Python中解析和序列化JSON數(shù)據(jù),本文將深入研究Python中JSON庫(kù)的各種函數(shù)和方法,為你提供豐富的示例代碼來(lái)幫助掌握J(rèn)SON處理的方方面面2024-01-01Python 批量驗(yàn)證和添加手機(jī)號(hào)碼為企業(yè)微信聯(lián)系人
你是否也有過(guò)需要添加很多微信好友的時(shí)候,一個(gè)個(gè)輸入添加太麻煩了,本篇文章手把手教你用Python替我們完成這繁瑣的操作,大家可以在過(guò)程中查缺補(bǔ)漏,看看自己掌握程度怎么樣2021-10-10python計(jì)算數(shù)字或者數(shù)組的階乘的實(shí)現(xiàn)
本文主要介紹了python計(jì)算數(shù)字或者數(shù)組的階乘,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08