欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python機(jī)器學(xué)習(xí)pytorch?張量基礎(chǔ)教程

 更新時間:2022年10月12日 15:49:58   作者:xuejianxinokok  
這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)pytorch?張量基礎(chǔ)教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

張量是一種特殊的數(shù)據(jù)結(jié)構(gòu),與數(shù)組和矩陣非常相似。在 PyTorch 中,我們使用張量對模型的輸入和輸出以及模型的參數(shù)進(jìn)行編碼。

張量類似于NumPy 的ndarray,除了張量可以在 GPU 或其他硬件加速器上運行。事實上,張量和 NumPy 數(shù)組通??梢怨蚕硐嗤牡讓觾?nèi)存,從而無需復(fù)制數(shù)據(jù)(請參閱Bridge with NumPy)。張量也針對自動微分進(jìn)行了優(yōu)化(我們將在稍后的Autograd 部分中看到更多相關(guān)內(nèi)容)。如果您熟悉 ndarrays,那么您對 Tensor API 會很快熟悉。

# 導(dǎo)入需要的包
import torch
import numpy as np

1.初始化張量

張量可以以各種方式初始化。請看以下示例:

1.1 直接從列表數(shù)據(jù)初始化

張量可以直接從列表數(shù)據(jù)中創(chuàng)建。數(shù)據(jù)類型是自動推斷的。

# 創(chuàng)建python list 數(shù)據(jù)
data = [[1, 2],[3, 4]]
# 初始化張量
x_data = torch.tensor(data)

1.2 用 NumPy 數(shù)組初始化

張量可以從 NumPy 數(shù)組創(chuàng)建(反之亦然 - 請參閱Bridge with NumPy)。

# 創(chuàng)建numpy 數(shù)組
np_array = np.array(data)
# from_numpy初始化張量
x_np = torch.from_numpy(np_array)

1.3 從另一個張量初始化

新張量保留原張量的屬性(形狀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和存儲它們的設(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.張量運算

這里全面介紹了超過 100 種張量運算,包括算術(shù)、線性代數(shù)、矩陣操作(轉(zhuǎn)置、索引、切片)、采樣等。

這些操作中的每一個都可以在 GPU 上運行(通常以比 CPU 更高的速度)。

默認(rèn)情況下,張量是在 CPU 上創(chuàng)建的。我們需要使用 .to方法明確地將張量移動到 GPU(在檢查 GPU 可用性之后)。請記住,跨設(shè)備復(fù)制大張量在時間和內(nèi)存方面可能會很昂貴!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

嘗試列表中的一些操作。如果您熟悉 NumPy API,您會發(fā)現(xiàn) Tensor API 使用起來輕而易舉。

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 連接張量

您可以用來torch.cat沿給定維度連接一系列張量。另請參閱torch.stack,另一個與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ù)運算

# 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

如果您有一個單元素張量,例如通過將張量的所有值聚合為一個值,您可以使用以下方法將其轉(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é)果存儲到操作數(shù)中的操作稱為In-place操作。它們由_后綴表示。例如:x.copy_(y)x.t_(), 會變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)存,但在計算導(dǎo)數(shù)時可能會出現(xiàn)問題,因為會立即丟失歷史記錄。因此,不鼓勵使用它們。

4. 張量和NumPy 橋接

CPU 和 NumPy 數(shù)組上的張量可以共享它們的底層內(nèi)存位置,改變一個會改變另一個。

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張量的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 淺談PyQt5中異步刷新UI和Python多線程總結(jié)

    淺談PyQt5中異步刷新UI和Python多線程總結(jié)

    今天小編就為大家分享一篇淺談PyQt5中異步刷新UI和Python多線程總結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • python清除字符串前后空格函數(shù)的方法

    python清除字符串前后空格函數(shù)的方法

    今天小編就為大家分享一篇python清除字符串前后空格函數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • 淺談使用Python變量時要避免的3個錯誤

    淺談使用Python變量時要避免的3個錯誤

    這篇文章主要介紹了淺談使用Python變量時要避免的3個錯誤,還是比較不錯的,涉及部分代碼分析,以及字典的創(chuàng)建等相關(guān)內(nèi)容,需要的朋友可以參考下。
    2017-10-10
  • Python讀寫yaml文件

    Python讀寫yaml文件

    這篇文章主要介紹了Python讀寫yaml文件,yaml?是專門用來寫配置文件的語言,非常簡潔和強(qiáng)大,之前用ini也能寫配置文件,有點類似于json格式,下面關(guān)于Python讀寫yaml文件的詳細(xì)資料,需要的小伙伴可以參考一下
    2022-03-03
  • python3獲取url文件大小示例代碼

    python3獲取url文件大小示例代碼

    這篇文章主要介紹了python3獲取url文件大小,本文通過示例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-09-09
  • Python3開發(fā)環(huán)境搭建詳細(xì)教程

    Python3開發(fā)環(huán)境搭建詳細(xì)教程

    這篇文章主要介紹了Python3開發(fā)環(huán)境搭建詳細(xì)教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • Matplotlib animation模塊實現(xiàn)動態(tài)圖

    Matplotlib animation模塊實現(xiàn)動態(tài)圖

    這篇文章主要介紹了Matplotlib animation模塊實現(xiàn)動態(tài)圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • 全面掌握Python?JSON庫函數(shù)與方法學(xué)會JSON數(shù)據(jù)處理

    全面掌握Python?JSON庫函數(shù)與方法學(xué)會JSON數(shù)據(jù)處理

    Python提供了內(nèi)置的JSON庫,允許在Python中解析和序列化JSON數(shù)據(jù),本文將深入研究Python中JSON庫的各種函數(shù)和方法,為你提供豐富的示例代碼來幫助掌握J(rèn)SON處理的方方面面
    2024-01-01
  • Python 批量驗證和添加手機(jī)號碼為企業(yè)微信聯(lián)系人

    Python 批量驗證和添加手機(jī)號碼為企業(yè)微信聯(lián)系人

    你是否也有過需要添加很多微信好友的時候,一個個輸入添加太麻煩了,本篇文章手把手教你用Python替我們完成這繁瑣的操作,大家可以在過程中查缺補(bǔ)漏,看看自己掌握程度怎么樣
    2021-10-10
  • python計算數(shù)字或者數(shù)組的階乘的實現(xiàn)

    python計算數(shù)字或者數(shù)組的階乘的實現(xiàn)

    本文主要介紹了python計算數(shù)字或者數(shù)組的階乘,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08

最新評論