国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

百度飛槳(PaddlePaddle)- 張量(Tensor)

這篇具有很好參考價(jià)值的文章主要介紹了百度飛槳(PaddlePaddle)- 張量(Tensor)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

張量(Tensor)、標(biāo)量(scalar)、向量(vector)、矩陣(matrix)

飛槳 使用張量(Tensor) 來(lái)表示神經(jīng)網(wǎng)絡(luò)中傳遞的數(shù)據(jù),Tensor 可以理解為多維數(shù)組,類似于 Numpy 數(shù)組(ndarray) 的概念。與 Numpy 數(shù)組相比,Tensor 除了支持運(yùn)行在 CPU 上,還支持運(yùn)行在 GPU 及各種 AI 芯片上,以實(shí)現(xiàn)計(jì)算加速;此外,飛槳基于 Tensor,實(shí)現(xiàn)了深度學(xué)習(xí)所必須的反向傳播功能和多種多樣的組網(wǎng)算子,從而可更快捷地實(shí)現(xiàn)深度學(xué)習(xí)組網(wǎng)與訓(xùn)練等功能。

Tensor 必須形如矩形,即在任何一個(gè)維度上,元素的數(shù)量必須相等,否則會(huì)拋出異常

Tensor 的創(chuàng)建

指定數(shù)據(jù)創(chuàng)建

import paddle 

# 創(chuàng)建類似向量(vector)的 1 維 Tensor:
ndim_1_Tensor = paddle.to_tensor([2.0, 3.0, 4.0])
print(ndim_1_Tensor)

# 創(chuàng)建類似矩陣(matrix)的 2 維 Tensor:
ndim_2_Tensor = paddle.to_tensor([[1.0, 2.0, 3.0],
                                  [4.0, 5.0, 6.0]])
print(ndim_2_Tensor)

# 創(chuàng)建 3 維 Tensor:
ndim_3_Tensor = paddle.to_tensor([[[1, 2, 3, 4, 5],
                                   [6, 7, 8, 9, 10]],
                                  [[11, 12, 13, 14, 15],
                                   [16, 17, 18, 19, 20]]])
print(ndim_3_Tensor)

輸出

"D:\Program Files\Python38\python.exe" D:/OpenSource/PaddlePaddle/Tensor.py
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
       [2., 3., 4.])
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
       [[1., 2., 3.],
        [4., 5., 6.]])
Tensor(shape=[2, 2, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
       [[[1 , 2 , 3 , 4 , 5 ],
         [6 , 7 , 8 , 9 , 10]],

        [[11, 12, 13, 14, 15],
         [16, 17, 18, 19, 20]]])

Process finished with exit code 0

百度飛槳(PaddlePaddle)- 張量(Tensor)

指定形狀創(chuàng)建

paddle.zeros([m, n])             # 創(chuàng)建數(shù)據(jù)全為 0,形狀為 [m, n] 的 Tensor
paddle.ones([m, n])              # 創(chuàng)建數(shù)據(jù)全為 1,形狀為 [m, n] 的 Tensor
paddle.full([m, n], 10)          # 創(chuàng)建數(shù)據(jù)全為 10,形狀為 [m, n] 的 Tensor

paddle.ones([2,3])
輸出

Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
       [[1., 1., 1.],
        [1., 1., 1.]])

指定區(qū)間創(chuàng)建

如果要在指定區(qū)間內(nèi)創(chuàng)建 Tensor,可以使用paddle.arange、 paddle.linspace 實(shí)現(xiàn)。

paddle.arange(start, end, step)  # 創(chuàng)建以步長(zhǎng) step 均勻分隔區(qū)間[start, end)的 Tensor
paddle.linspace(start, stop, num) # 創(chuàng)建以元素個(gè)數(shù) num 均勻分隔區(qū)間[start, stop)的 Tensor
paddle.arange(start=1, end=5, step=1)

輸出

Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
       [1, 2, 3, 4])

指定圖像、文本數(shù)據(jù)創(chuàng)建

在常見(jiàn)深度學(xué)習(xí)任務(wù)中,數(shù)據(jù)樣本可能是圖片(image)、文本(text)、語(yǔ)音(audio)等多種類型,在送入神經(jīng)網(wǎng)絡(luò)訓(xùn)練或推理前,這些數(shù)據(jù)和對(duì)應(yīng)的標(biāo)簽均需要?jiǎng)?chuàng)建為 Tensor。以下是圖像場(chǎng)景和 NLP 場(chǎng)景中手動(dòng)轉(zhuǎn)換 Tensor 方法的介紹。

  • 對(duì)于圖像場(chǎng)景,可使用 paddle.vision.transforms.ToTensor 直接將 PIL.Image 格式的數(shù)據(jù)轉(zhuǎn)為 Tensor,使用 paddle.to_tensor 將圖像的標(biāo)簽(Label,通常是 Python 或 Numpy 格式的數(shù)據(jù))轉(zhuǎn)為 Tensor。
  • 對(duì)于文本場(chǎng)景,需將文本數(shù)據(jù)解碼為數(shù)字后,再通過(guò) paddle.to_tensor 轉(zhuǎn)為 Tensor。不同文本任務(wù)標(biāo)簽形式不一樣,有的任務(wù)標(biāo)簽也是文本,有的則是數(shù)字,均需最終通過(guò) paddle.to_tensor 轉(zhuǎn)為 Tensor。
    下面以圖像場(chǎng)景為例介紹,以下示例代碼中將隨機(jī)生成的圖片轉(zhuǎn)換為 Tensor。
import numpy as np
from PIL import Image
import paddle.vision.transforms as T
import paddle.vision.transforms.functional as F

fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) # 創(chuàng)建隨機(jī)圖片
transform = T.ToTensor()
tensor = transform(fake_img) # 使用 ToTensor()將圖片轉(zhuǎn)換為 Tensor
print(tensor)

自動(dòng)創(chuàng)建 Tensor 的功能介紹

除了手動(dòng)創(chuàng)建 Tensor 外,實(shí)際在飛槳框架中有一些 API 封裝了 Tensor 創(chuàng)建的操作,從而無(wú)需用戶手動(dòng)創(chuàng)建 Tensor。例如 paddle.io.DataLoader 能夠基于原始 Dataset,返回讀取 Dataset 數(shù)據(jù)的迭代器,迭代器返回的數(shù)據(jù)中的每個(gè)元素都是一個(gè) Tensor。另外在一些高層 API,如 paddle.Model.fit 、paddle.Model.predict ,如果傳入的數(shù)據(jù)不是 Tensor,會(huì)自動(dòng)轉(zhuǎn)為 Tensor 再進(jìn)行模型訓(xùn)練或推理。

paddle.Model.fit、paddle.Model.predict 等高層 API 支持傳入 Dataset 或 DataLoader,如果傳入的是 Dataset,那么會(huì)用 DataLoader 封裝轉(zhuǎn)為 Tensor 數(shù)據(jù);如果傳入的是 DataLoader,則直接從 DataLoader 迭代讀取 Tensor 數(shù)據(jù)送入模型訓(xùn)練或推理。因此即使沒(méi)有寫將數(shù)據(jù)轉(zhuǎn)為 Tensor 的代碼,也能正常執(zhí)行,提升了編程效率和容錯(cuò)性。

以下示例代碼中,分別打印了原始數(shù)據(jù)集的數(shù)據(jù),和送入 DataLoader 后返回的數(shù)據(jù),可以看到數(shù)據(jù)結(jié)構(gòu)由 Python list 轉(zhuǎn)為了 Tensor。

import paddle

from paddle.vision.transforms import Compose, Normalize

transform = Compose([Normalize(mean=[127.5],
                               std=[127.5],
                               data_format='CHW')])

test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
print(test_dataset[0][1]) # 打印原始數(shù)據(jù)集的第一個(gè)數(shù)據(jù)的 label
loader = paddle.io.DataLoader(test_dataset)
for data in enumerate(loader):
    x, label = data[1]
    print(label) # 打印由 DataLoader 返回的迭代器中的第一個(gè)數(shù)據(jù)的 label
    break

Tensor 的屬性

在前文中,可以看到打印 Tensor 時(shí)有 shape、dtype、place 等信息,這些都是 Tensor 的重要屬性,想要了解如何操作 Tensor 需要對(duì)其屬性有一定了解,接下來(lái)分別展開(kāi)介紹 Tensor 的屬性相關(guān)概念。

Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
       [2., 3., 4.])

Tensor 的形狀(shape)

(1)形狀的介紹

形狀是 Tensor 的一個(gè)重要的基礎(chǔ)屬性,可以通過(guò) Tensor.shape 查看一個(gè) Tensor 的形狀,以下為相關(guān)概念:

  • shape:描述了 Tensor 每個(gè)維度上元素的數(shù)量。
  • ndim: Tensor 的維度數(shù)量,例如向量的維度為 1,矩陣的維度為 2,Tensor 可以有任意數(shù)量的維度。
  • axis 或者 dimension:Tensor 的軸,即某個(gè)特定的維度。
  • size:Tensor 中全部元素的個(gè)數(shù)。

創(chuàng)建 1 個(gè)四維 Tensor ,并通過(guò)圖形來(lái)直觀表達(dá)以上幾個(gè)概念之間的關(guān)系:

ndim_4_Tensor = paddle.ones([2, 3, 4, 5])
print("Data Type of every element:", ndim_4_Tensor.dtype)
print("Number of dimensions:", ndim_4_Tensor.ndim)
print("Shape of Tensor:", ndim_4_Tensor.shape)
print("Elements number along axis 0 of Tensor:", ndim_4_Tensor.shape[0])
print("Elements number along the last axis of Tensor:", ndim_4_Tensor.shape[-1])

百度飛槳(PaddlePaddle)- 張量(Tensor)

(2)重置 Tensor 形狀(Reshape) 的方法

重新設(shè)置 Tensor 的 shape 在深度學(xué)習(xí)任務(wù)中比較常見(jiàn),如一些計(jì)算類 API 會(huì)對(duì)輸入數(shù)據(jù)有特定的形狀要求,這時(shí)可通過(guò) paddle.reshape 接口來(lái)改變 Tensor 的 shape,但并不改變 Tensor 的 size 和其中的元素?cái)?shù)據(jù)。
以下示例代碼中,創(chuàng)建 1 個(gè) shape=[3] 的一維 Tensor,使用 reshape 功能將該 Tensor 重置為 shape=[1, 3] 的二維 Tensor。這種做法經(jīng)常用在把一維的標(biāo)簽(label)數(shù)據(jù)擴(kuò)展為二維,由于飛槳框架中神經(jīng)網(wǎng)絡(luò)通常需要傳入一個(gè) batch 的數(shù)據(jù)進(jìn)行計(jì)算,因此可將數(shù)據(jù)增加一個(gè) batch 維,方便后面的數(shù)據(jù)計(jì)算。

ndim_1_Tensor = paddle.to_tensor([1, 2, 3])
print("the shape of ndim_1_Tensor:", ndim_1_Tensor.shape)

reshape_Tensor = paddle.reshape(ndim_1_Tensor, [1, 3])
print("After reshape:", reshape_Tensor.shape)

在指定新的 shape 時(shí)存在一些技巧:

  • -1 表示這個(gè)維度的值是從 Tensor 的元素總數(shù)和剩余維度自動(dòng)推斷出來(lái)的。因此,有且只有一個(gè)維度可以被設(shè)置為 -1。
  • 0 表示該維度的元素?cái)?shù)量與原值相同,因此 shape 中 0 的索引值必須小于 Tensor 的維度(索引值從 0 開(kāi)始計(jì),如第 1 維的索引值是 0,第二維的索引值是 1)。
origin:[3, 2, 5] reshape:[3, 10]      actual: [3, 10] # 直接指定目標(biāo) shape
origin:[3, 2, 5] reshape:[-1]         actual: [30] # 轉(zhuǎn)換為 1 維,維度根據(jù)元素總數(shù)推斷出來(lái)是 3*2*5=30
origin:[3, 2, 5] reshape:[-1, 5]      actual: [6, 5] # 轉(zhuǎn)換為 2 維,固定一個(gè)維度 5,另一個(gè)維度根據(jù)元素總數(shù)推斷出來(lái)是 30÷5=6
origin:[3, 2, 5] reshape:[0, -1]         actual: [3, 6] # reshape:[0, -1]中 0 的索引值為 0,按照規(guī)則,轉(zhuǎn)換后第 0 維的元素?cái)?shù)量與原始 Tensor 第 0 維的元素?cái)?shù)量相同,為 3;第 1 維的元素?cái)?shù)量根據(jù)元素總值計(jì)算得出為 30÷3=10。
origin:[3, 2] reshape:[3, 1, 0]          error: # reshape:[3, 1, 0]中 0 的索引值為 2,但原 Tensor 只有 2 維,無(wú)法找到與第 3 維對(duì)應(yīng)的元素?cái)?shù)量,因此出錯(cuò)。

(3)原位(Inplace)操作和非原位操作的區(qū)別

飛槳框架的 API 有原位(Inplace)操作和非原位操作之分,原位操作即在原 Tensor 上保存操作結(jié)果,輸出 Tensor 將與輸入 Tensor 共享數(shù)據(jù),并且沒(méi)有 Tensor 數(shù)據(jù)拷貝的過(guò)程。非原位操作則不會(huì)修改原 Tensor,而是返回一個(gè)新的 Tensor。通過(guò) API 名稱區(qū)分兩者,如 paddle.reshape 是非原位操作,paddle.reshape_ 是原位操作。

Tensor 的數(shù)據(jù)類型(dtype)

(1)指定數(shù)據(jù)類型的介紹

Tensor 的數(shù)據(jù)類型 dtype 可以通過(guò) Tensor.dtype 查看,支持類型包括:bool、float16、float32、float64、uint8、int8、int16、int32、int64、complex64、complex128。
同一 Tensor 中所有元素的數(shù)據(jù)類型均相同,通常通過(guò)如下方式指定:

(2)修改數(shù)據(jù)類型的方法

飛槳框架提供了paddle.cast 接口來(lái)改變 Tensor 的 dtype:

float32_Tensor = paddle.to_tensor(1.0)

float64_Tensor = paddle.cast(float32_Tensor, dtype='float64')
print("Tensor after cast to float64:", float64_Tensor.dtype)

int64_Tensor = paddle.cast(float32_Tensor, dtype='int64')
print("Tensor after cast to int64:", int64_Tensor.dtype)

Tensor 的設(shè)備位置(place)

Tensor 的名稱(name)

Tensor 的 stop_gradient 屬性

Tensor 的操作

索引和切片

索引或切片的第一個(gè)值對(duì)應(yīng)第 0 維,第二個(gè)值對(duì)應(yīng)第 1 維,依次類推,如果某個(gè)維度上未指定索引,則默認(rèn)為 :
Python Numpy 切片

import paddle

# 創(chuàng)建 3 維 Tensor:
ndim_3_Tensor = paddle.to_tensor([[[[1, 2, 3, 4, 5],
                                    [6, 7, 8, 9, 10],
                                    [11, 12, 13, 14, 15]],
                                   [[21, 22, 23, 24, 25],
                                    [26, 27, 28, 29, 30],
                                    [31, 32, 33, 34, 35]]],

                                  [[[1, 2, 3, 4, 5],
                                    [6, 7, 8, 9, 10],
                                    [11, 12, 13, 14, 15]],
                                   [[29, 22, 23, 24, 25],
                                    [26, 57, 28, 29, 30],
                                    [31, 32, 33, 34, 59]]]])


print("Origin Tensor:", ndim_3_Tensor.ndim)
print("Tensor Shape:", ndim_3_Tensor.shape) # [2, 2, 3, 5]
print("Slice:", ndim_3_Tensor[1, 1, 2, 4].numpy()) # 對(duì)應(yīng) shape


print("First row:", ndim_3_Tensor[0].numpy())
print("First row:", ndim_3_Tensor[1, 1, 2, 4].numpy())
print("First column:", ndim_3_Tensor[:, 0].numpy())
print("Last column:", ndim_3_Tensor[:, -1].numpy())
print("All element:", ndim_3_Tensor[:].numpy())
print("First row and second column:", ndim_3_Tensor[1, 0].numpy())

運(yùn)算

Tensor 的廣播機(jī)制

飛槳 Tensor 的廣播機(jī)制
Python NumPy 廣播(Broadcast)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-438594.html

到了這里,關(guān)于百度飛槳(PaddlePaddle)- 張量(Tensor)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包