PyTorch?Tensor創(chuàng)建實(shí)現(xiàn)
使用已有數(shù)據(jù)
torch.tensor(data)
>>> import torch >>> import numpy as np # 標(biāo)量 >>> torch.tensor(0) tensor(0) # 列表/元組 >>> torch.tensor([[1.0]]) tensor([[1.]]) # ndarray >>> n = np.arange(3) >>> torch.tensor(n) tensor([0, 1, 2])
可以額外指定數(shù)據(jù)類型和設(shè)備, 默認(rèn)情況下由數(shù)據(jù)本身自動(dòng)推斷出類型, 整數(shù)使用 torch.int64 類型, 浮點(diǎn)數(shù)使用 torch.float32 類型
>>> torch.tensor([1.0, 2.0], dtype=torch.float16, device='cuda') tensor([1., 2.], device='cuda:0', dtype=torch.float16)
使用 torch.tensor 創(chuàng)建 Tensor 時(shí), 總是完全拷貝, 不會(huì)共享底層數(shù)據(jù)
# 不與 ndarray 共享內(nèi)存數(shù)據(jù) >>> n = np.array([1, 2]) >>> t = torch.tensor(n) >>> t[0] = 0 >>> t tensor([0, 2]) >>> n array([1, 2])
torch.as_tensor(data)
與 torch.tensor 不同, 該函數(shù)會(huì)盡量共享內(nèi)存, 當(dāng)然只有 data 是 np.ndarray 或 torch.Tensor 類型時(shí)才能共享, data 是列表或元組時(shí)沒(méi)法共享內(nèi)存
# 與 ndarray 共享內(nèi)存數(shù)據(jù) >>> n = np.array([1, 2]) # 底層調(diào)用 torch.from_numpy(n) >>> t = torch.as_tensor(n) >>> t[0] = 0 >>> t tensor([0, 2]) >>> n array([0, 2])
同樣可以指定數(shù)據(jù)類型和設(shè)備, 當(dāng)指定的類型與 data 的數(shù)據(jù)類型不一致時(shí)不共享數(shù)據(jù)
>>> d = torch.arange(3) >>> t = torch.as_tensor(d, dtype=torch.int16) >>> t[0] = -1 >>> t tensor([-1, 1, 2], dtype=torch.int16) >>> d tensor([0, 1, 2])
torch.Tensor(sequence)
相當(dāng)于直接實(shí)例化一個(gè) torch.Tensor 類型的對(duì)象, 默認(rèn)是 torch.float32 的數(shù)據(jù)類型, 設(shè)備位于 CPU
# 不支持標(biāo)量 >>> torch.Tensor(1.0) ----------------------------------------------------------- TypeError ? ? ? ? ? ? ? ? Traceback (most recent call last) Input In [40], in <cell line: 1>() ----> 1 torch.Tensor(1.0) TypeError: new(): data must be a sequence (got float) >>> n = np.array([0, 1]) # 整型被自動(dòng)轉(zhuǎn)為 torch.float32 >>> torch.Tensor(n) tensor([0., 1.])
除了 torch.Tensor 還有其他的類型, 也可以這樣實(shí)例化, 例如 torch.IntTensor, torch.FloatTensor 等 CPU 張量類型, torch.cuda.IntTensor, torch.cuda.FloatTensor 等 GPU 張量類型
torch.Tensor 默認(rèn)是 torch.FloatTensor 類型即默認(rèn)張量類型, 這個(gè)可以被全局修改
# 使用 CPU 張量類型進(jìn)行實(shí)例化 >>> torch.DoubleTensor([1, 2]) tensor([1., 2.], dtype=torch.float64) # 使用 GPU 張量類型進(jìn)行實(shí)例化 >>> torch.cuda.IntTensor([1, 2]) tensor([1, 2], device='cuda:0', dtype=torch.int32)
數(shù)據(jù)未初始化
數(shù)據(jù)未初始化, 直接使用存儲(chǔ)設(shè)備中的原有數(shù)據(jù)
torch.empty(*sizes) # 注意與 torch.Tensor(sequence) 的區(qū)別 # 這里也可以替換為 torch.IntTensor(*sizes) 等 Tensor 類型 torch.Tensor(*sizes)
示例
>>> torch.empty(1, 2) tensor([[2.9386e+29, 7.1104e-04]]) >>> torch.cuda.IntTensor(2, 3) tensor([[0, 0, 0], ? ? ? ? [0, 0, 0]], device='cuda:0', dtype=torch.int32)
特殊張量
# 全 0 torch.zeros(*size) # 全 1 torch.ones(*size) # 指定全值 torch.full(size, fill_value) # n 行 m 列單位對(duì)角矩陣 torch.eye(n, m=None) # 對(duì)角矩陣, 參數(shù) tensor 為一維張量, 指定對(duì)角線元素 torch.diag(tensor)
除了末尾兩個(gè)函數(shù)生成的是二維張量, 其余的函數(shù)不限張量維度
代碼示例:
# 默認(rèn)數(shù)據(jù)類型為 torch.float32 >>> torch.zeros(2) tensor([0., 0.]) # 2 行 1 列 >>> torch.ones(2, 1, dtype=torch.int32) tensor([[1], ? ? ? ? [1]], dtype=torch.int32) # 指定全值 >>> torch.full([2, 2], 3) tensor([[3, 3], ? ? ? ? [3, 3]]) # 主對(duì)角線元素均為 1, 其余元素為 0 >>> torch.eye(2, 3) tensor([[1., 0., 0.], ? ? ? ? [0., 1., 0.]]) >>> torch.diag(torch.tensor([1, 3, 5])) tensor([[1, 0, 0], ? ? ? ? [0, 3, 0], ? ? ? ? [0, 0, 5]])
數(shù)列
torch.arange(start=0, end, step=1)
torch.linspace(start, end, steps=100) 間隔相等的張量

torch.logspace(start, end, steps=100, base=10.0) 以對(duì)數(shù)為間隔的張量

代碼示例
>>> torch.arange(3) tensor([0, 1, 2]) >>> torch.arange(1, 3.1, 1.0) tensor([1., 2., 3.]) >>> torch.linspace(-2, 2, 5) tensor([-2., -1., ?0., ?1., ?2.]) # 從 2^(-2) 至 2^2 >>> torch.logspace(-2, 2, steps=5, base=2) tensor([0.2500, 0.5000, 1.0000, 2.0000, 4.0000])
可以看出對(duì)于相同的 start, end 和 steps 參數(shù), logspace = base ^ linspace
隨機(jī)生成
正態(tài)分布
# 標(biāo)準(zhǔn)正態(tài)分布 torch.randn(*size) # 指定均值與標(biāo)準(zhǔn)差 torch.normal(mean, std, size)
示例
# 指定隨機(jī)數(shù)種子, 保證隨機(jī)數(shù)可以重現(xiàn)
>>> _ = torch.manual_seed(2022)
>>> torch.randn(2, 3)
tensor([[ 0.1915, 0.3306, 0.2306],
[ 0.8936, -0.2044, -0.9081]])
>>> torch.normal(mean=1.0, std=0.1, size=[2, 3])
tensor([[0.7689, 1.1635, 1.2061],
[0.9746, 0.8488, 0.8720]])
# 不指定size, 由 mean 和 std 參數(shù)的形狀推斷出結(jié)果的維度
# 輸出的兩個(gè)隨機(jī)數(shù)分別服從均值為 1.0 和 2.0 標(biāo)準(zhǔn)差為 0.1 的正態(tài)分布
# 顯然, 兩個(gè)數(shù)分別在 1.0 和 2.0 的附近(標(biāo)準(zhǔn)差故意選的很小)
>>> torch.normal(mean=torch.Tensor([1.0, 2.0]), std=0.1)
tensor([1.0111, 2.0205])均勻分布
# [0, 1] 上的均勻分布 torch.rand(*size)
示例
# [2, 4] 上的均勻分布
>>> 2 * torch.rand(2, 2) + 2
tensor([[2.4388, 2.5786],
[3.3569, 2.9994]])隨機(jī)序列
# 0, 1, 2, ..., n-1 隨機(jī)排列 torch.randperm(n)
示例
>>> _ = torch.manual_seed(2022) >>> torch.randperm(6) tensor([5, 1, 3, 2, 0, 4])
隨機(jī)整數(shù)
# 隨機(jī)生成 low 到 high - 1 的整數(shù), 包括 low 和 high - 1 這兩個(gè)整數(shù) torch.randint(low=0, high, size)
示例
>>> torch.randint(5, [2, 3])
tensor([[1, 0, 3],
[1, 4, 2]])
>>> torch.randint(3, 6, [2, 2])
tensor([[5, 4],
[4, 3]])繼承張量類型
使用 Tensor.new_*() 的方式新建一個(gè)張量, 該張量與調(diào)用者具有相同的張量類型
例如:
# 未初始化 Tensor.new(*sizes) Tensor.new_empty(size) # 全 0 Tensor.new_zeros(size) # 全 1 Tensor.new_ones(size) # 指定初始值 Tensor.new_full(size, fill_value)
示例
>>> t = torch.cuda.IntTensor([2]) >>> t tensor([2], device='cuda:0', dtype=torch.int32) # 繼承了數(shù)據(jù)類型以及設(shè)備類型 >>> t.new_full([1, 2], 1) tensor([[1, 1]], device='cuda:0', dtype=torch.int32)
繼承維度以及張量類型
使用 torch.*_like(other) 的方式新建一個(gè)張量, 該張量與 other 張量具有相同的形狀和張量類型
例如:
# 未初始化 torch.empty_like(other) # 全 0 torch.zeros_like(other) # 全 1 torch.ones_like(other) # 指定初始值 torch.full_like(other, fill_value) # 均勻分布 torch.rand_like(other) # 標(biāo)準(zhǔn)正態(tài)分布 torch.randn_like(other) # 隨機(jī)整數(shù) torch.randint_like(other, low=0, high)
示例
>>> t = torch.tensor([[1, 2]], dtype=torch.int16, device='cuda') >>> t tensor([[1, 2]], device='cuda:0', dtype=torch.int16) >>> f = torch.zeros_like(t) # 繼承了 t 的形狀以及張量類型 >>> f tensor([[0, 0]], device='cuda:0', dtype=torch.int16)
到此這篇關(guān)于PyTorch Tensor創(chuàng)建實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)PyTorch Tensor創(chuàng)建內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python的a[:2]、a[:] 和a [::]的區(qū)別
本文主要介紹了python的a[:2]、a[:] 和a [::]的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2026-03-03
Python Pygame實(shí)現(xiàn)兔子獵人守護(hù)城堡游戲
這篇文章主要介紹了用python來(lái)制作的一個(gè)守護(hù)類小游戲兔子獵人守護(hù)城堡,文中的示例代碼介紹得很詳細(xì),感興趣的小伙伴快來(lái)跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
DJANGO-ALLAUTH社交用戶系統(tǒng)的安裝配置
django-allauth是集成了local用戶系統(tǒng)和social用戶系統(tǒng),其social用戶系統(tǒng)可以掛載多個(gè)賬戶。也是一個(gè)流行度非常高的Django user系統(tǒng),我們這里簡(jiǎn)單介紹下,分享下個(gè)人的使用經(jīng)驗(yàn)2014-11-11
PyTorch?中torch.clamp函數(shù)使用詳解和實(shí)戰(zhàn)示例(最新整理)
PyTorch中torch.clamp函數(shù)用于限制張量元素在[min,?max]范圍內(nèi),支持單向或雙向裁剪,可應(yīng)用于激活函數(shù)、數(shù)據(jù)預(yù)處理,避免梯度爆炸,操作為逐元素處理,可能產(chǎn)生計(jì)算開銷,建議合理設(shè)置參數(shù)優(yōu)化效率,對(duì)PyTorch?torch.clamp函數(shù)使用相關(guān)知識(shí)感興趣的朋友一起看看吧2025-06-06
CentOS 7如何實(shí)現(xiàn)定時(shí)執(zhí)行python腳本
這篇文章主要介紹了CentOS 7如何實(shí)現(xiàn)定時(shí)執(zhí)行python腳本,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
基于python對(duì)B站收藏夾按照視頻發(fā)布時(shí)間進(jìn)行排序的問(wèn)題
這篇文章主要介紹了基于python對(duì)B站收藏夾按照視頻發(fā)布時(shí)間進(jìn)行排序,在實(shí)現(xiàn)過(guò)程中中間程序可能因?yàn)楦鞣N原因掛掉,因此在中間加入了儲(chǔ)存中間狀態(tài)的功能,否則每次掛掉都要重新爬速度非常慢,本文給大家介紹具體使用方法,一起看看吧2021-05-05

