PyTorch框架詳解(1)

目錄

代碼會放在每條解釋的后面

一.概念:

2.張量的概念:

3.張量的創建

4.張量的數據類型及轉換

二.tensor和numpy互轉

三.張量的運算

四.索引的操作

五.張量形狀操作

維度交換:

六.張量拼接操作


代碼會放在每條解釋的后面

一.概念:

pytorch是基于python語言的深度學習框架,它將數據封裝成張量來進行處理

安裝:pip install torch

2.張量的概念:

張量(tensor)就是元素為同一種數據類型的多維矩陣。在pytorch中,張量以“類”的形式封裝起來。只有張量有GPU加速功能

3.張量的創建

Ⅰ張量的基本創建方式:?

① torch.tensor(data=,dtype=) :? ?只能指定數據,dtype指定類型
②torch.Tensor(data=, size=()):既能指定數據,又能指定形狀
③torch.IntTensor()/FloatTensor()...:Tensor直接指定類型創建

import numpy as np
import torch# TODO 1.tensor(data)創建張量
print(torch.tensor(10).ndim)
print(torch.tensor([10]).ndim)
print(torch.tensor([[10]]).ndim)
print(torch.tensor([[[10]]]).ndim)
# 通過列表創建張量
print(torch.tensor([[10, 20], [40, 50]]), torch.tensor([[10, 20], [40, 50]]).dtype)
# 通過numpy創建張量
print(torch.tensor(np.array([[10, 20], [40, 50]])))
print('----------------------------------------')
# dtype 指定類型創建張量
t1 = torch.tensor([[10, 20], [40, 50]], dtype=torch.float)
print(t1, t1.dtype)
# TODO 注意: 浮點數轉為整數會丟失精度,自動向下取整
t1 = torch.tensor([[10.9, 20.9], [40.9, 50.9]], dtype=torch.int)
print(t1)
print('===============================================')
# TODO 2.Tensor(data,size)創建張量
print(torch.Tensor(5))  # 指定形狀
print(torch.Tensor(2, 3))  # 指定形狀
print(torch.Tensor(size=(2, 3)))  # 指定形狀
print(torch.Tensor([10]).ndim)
print(torch.Tensor([[10]]).ndim)
print(torch.Tensor([[[10]]]).ndim)
# 通過列表創建張量
print(torch.Tensor([[10, 20], [40, 50]]), torch.tensor([[10, 20], [40, 50]]).dtype)
# 通過numpy創建張量
print(torch.Tensor(np.array([[10, 20], [40, 50]])))
print('----------------------------------------')
# TODO 3.IntTensor/FloatTensor創建張量
print(torch.ShortTensor([[10, 20]]))
print(torch.IntTensor([[10, 20]]))
print(torch.LongTensor([[10, 20]]), torch.LongTensor([[10, 20]]).dtype)
print(torch.HalfTensor([[10, 20]]))
print(torch.FloatTensor([[10, 20]]), torch.FloatTensor([[10, 20]]).dtype)
print(torch.DoubleTensor([[10, 20]]))

?結果:

0
1
2
3
tensor([[10, 20],[40, 50]]) torch.int64
tensor([[10, 20],[40, 50]], dtype=torch.int32)
----------------------------------------
tensor([[10., 20.],[40., 50.]]) torch.float32
tensor([[10, 20],[40, 50]], dtype=torch.int32)
===============================================
tensor([-2.1644e+09,  1.0608e-42,  0.0000e+00,  0.0000e+00,  0.0000e+00])
tensor([[-2.1644e+09,  1.0608e-42,  0.0000e+00],[ 0.0000e+00,  0.0000e+00,  0.0000e+00]])
tensor([[-2.1645e+09,  1.0608e-42,  0.0000e+00],[ 0.0000e+00,  0.0000e+00,  0.0000e+00]])
1
2
3
tensor([[10., 20.],[40., 50.]]) torch.int64
tensor([[10., 20.],[40., 50.]])
----------------------------------------
tensor([[10, 20]], dtype=torch.int16)
tensor([[10, 20]], dtype=torch.int32)
tensor([[10, 20]]) torch.int64
tensor([[10., 20.]], dtype=torch.float16)
tensor([[10., 20.]]) torch.float32
tensor([[10., 20.]], dtype=torch.float64)

線性和隨機張量

線性張量
? ?①? torch.arange(start=,end=,step=)

? ?②?torch.linspace(start=,end=,steps=)
?? ??? ?start: 開始位置
?? ??? ?end: 結束位置(含)
?? ??? ?steps: 個數

隨機張量
①torch.rand():

? ? ? ? 隨機生成0到1的浮點數
②torch.randn(size=()):
?? ??? ?隨機生成正態分布的浮點數
③torch.randint(low=,high=,size=()):
?? ??? ?隨機生成整數
④ 隨機種子:
?? ??? ?設置:manual_seed(常數)
?? ??? ?查看:initial_seed()

Ⅲ?0/1/指定值張量:
① torch.zeros/ones(size=):
? ? ? ? ? ? ? ? ? ?根據指定形狀直接生成全0/全1的張量
② torch.zeros_like/ones_like(input=tensor):
? ? ? ? ? ? ? ? ? 根據指定張量的形狀間接生成全0/全1的張量
③ torch.full(size=, fill_value=):
? ? ? ? ? ? ? ? ? 根據指定形狀和指定值生成張量
④ torch.full_like(input=tensor, fill_value=):
? ? ? ? ? ? ? ? ? 根據指定張量的形狀和指定值生成張量

import torch# TODO 1.創建線性張量
# arange() 包左不包右
print(torch.arange(10))
print(torch.arange(2, 10))
print(torch.arange(2, 10, 2))
print('-------------------------------------')
# linspace() 包左包右
print(torch.linspace(2, 10, 5))
print(torch.linspace(2, 10, 6))
print('==================================================')
# TODO 2.創建隨機張量
print(torch.rand(2, 3))  # rand隨機生成0-1的浮點數張量
print(torch.randn(2, 3))  # randn隨機生成正態分布的浮點數張量
print(torch.randint(10, (2, 3)))  # randint隨機生成整數張量
print(torch.randint(10, 20, (2, 3)))
print('--------------------------------------')
# TODO 隨機種子的設置和獲取
# manual_seed() : 設置隨機種子,保證隨機數生成一致
print(torch.manual_seed(666))
print(torch.rand(2, 3))
print(torch.randn(2, 3))
print(torch.randint(10, (2, 3)))
print(torch.randint(10, 20, (2, 3)))
# initial_seed(): 獲取當前隨機種子
print(torch.initial_seed())

tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([2, 3, 4, 5, 6, 7, 8, 9])
tensor([2, 4, 6, 8])
-------------------------------------
tensor([ 2.,  4.,  6.,  8., 10.])
tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])
==================================================
tensor([[0.1639, 0.6426, 0.6234],[0.8373, 0.1003, 0.0621]])
tensor([[-0.5436, -2.3693,  0.0441],[-0.1403, -1.1286,  0.7755]])
tensor([[3, 3, 4],[2, 6, 3]])
tensor([[15, 14, 17],[10, 10, 10]])
--------------------------------------
<torch._C.Generator object at 0x000001DFBD18F510>
tensor([[0.3119, 0.2701, 0.1118],[0.1012, 0.1877, 0.0181]])
tensor([[-0.7581, -1.0902,  0.2354],[ 0.0240,  1.4281, -0.2853]])
tensor([[1, 6, 2],[8, 9, 7]])
tensor([[10, 18, 15],[11, 15, 11]])
666

4.張量的數據類型及轉換

Ⅰ張量只能是數值類型
? ? ① 整數
?? ??? ?short->int16
?? ??? ?int -> int32
?? ??? ?long -> int64
? ? ② 浮點數
?? ??? ?half -> float16
?? ??? ?float -> float32
?? ??? ?double -> float64
? ? ③ 布爾
? ? ④ 復數

Ⅱ創建有類型的張量:
torch.tensor
torch.int位數/torch.float位數
torch.Tensor

Ⅲ張量.類型函數()
?? ?half()/float()/double()/int()/long()

import torch# 創建一個張量,然后數據類型轉換
data = torch.randint(0, 10, [2, 5])
print(data.dtype)
# TODO 張量.類型函數()
print(data.short())
print(data.int())
print(data.long())
print(data.half())
print(data.float())
print(data.double())
print('==========================================')
# TODO 張量.type(指定類型)
# 類型轉換方式1  torch.小寫類型名
print(data.type(torch.short))
print(data.type(torch.int))
print(data.type(torch.long), data.type(torch.long).dtype)
print(data.type(torch.half))
print(data.type(torch.float), data.type(torch.float).dtype)
print(data.type(torch.double))
print('--------------------------')
# 類型轉換方式2 torch.int位數/torch.float位數
print(data.type(torch.int16))
print(data.type(torch.int32))
print(data.type(torch.int64))
print(data.type(torch.float16))
print(data.type(torch.float32))
print(data.type(torch.float64))
print('--------------------------')
# 類型轉換方式3 torch.大寫類型Tensor  有警告
print(data.type(torch.ShortTensor))
print(data.type(torch.IntTensor))
print(data.type(torch.LongTensor))
print(data.type(torch.HalfTensor))
print(data.type(torch.FloatTensor))
print(data.type(torch.DoubleTensor))

tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int16)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int32)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]])
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float16)
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]])
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float64)
==========================================
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int16)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int32)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]]) torch.int64
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float16)
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]]) torch.float32
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float64)
--------------------------
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int16)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int32)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]])
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float16)
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]])
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float64)
--------------------------
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int16)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]], dtype=torch.int32)
tensor([[9, 0, 3, 2, 0],[5, 6, 1, 3, 7]])
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float16)
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]])
tensor([[9., 0., 3., 2., 0.],[5., 6., 1., 3., 7.]], dtype=torch.float64)

二.tensor和numpy互轉

1.張量轉換成numpy數組
? ?① tensor.numpy():共享內存
? ?②tensor.numpy().copy():不共享內存

import numpy as np
import torch#  TODO 1.numpy數組轉換為張量
# todo from_numpy()將numpy數組轉換為張量,但是共享內存
# 創建numpy數組
n1 = np.array([1, 2, 3])
t1 = torch.from_numpy(n1)
print(n1, type(n1))
print(t1, type(t1))
# 演示from_numpy()結果共享內存
n1[0] = 100
print(n1, id(n1))
print(t1, id(t1))
print('------------------------------')
# todo torch.tensor(ndarray)將numpy數組轉換為張量,不會共享內存
# 創建numpy數組
n2 = np.array([1, 2, 3])
t2 = torch.tensor(n2)
print(n2, type(n2))
print(t2, type(t2))
# 演示tensor(ndarray)結果不共享內存
n2[0] = 200
print(n2, id(n2))
print(t2, id(t2))
print('========================================================')
#  TODO 2.張量轉換為numpy數組
# todo numpy()將張量轉換為numpy數組
# 創建張量
t3 = torch.tensor([1, 2, 3])
# 轉換
n3 = t3.numpy()
print(t3, type(t3))
print(n3, type(n3))
# 演示numpy()結果共享內存
t3[0] = 300
print(t3, id(t3))
print(n3, id(n3))
print('------------------------------')
# todo numpy().copy()將張量轉換為numpy數組
# 創建張量
t4 = torch.tensor([1, 2, 3])
# 轉換
n4 = t4.numpy().copy()
print(t4, type(t4))
print(n4, type(n4))
# 演示numpy().copy()結果不共享內存
t4[0] = 300
print(t4, id(t4))
print(n4, id(n4))

tensor([1, 2, 3], dtype=torch.int32) <class 'torch.Tensor'>
[100   2   3] 2510262623120
tensor([100,   2,   3], dtype=torch.int32) 2510261756992
------------------------------
[1 2 3] <class 'numpy.ndarray'>
tensor([1, 2, 3], dtype=torch.int32) <class 'torch.Tensor'>
[200   2   3] 2508302536304
tensor([1, 2, 3], dtype=torch.int32) 2510316399552
========================================================
tensor([1, 2, 3]) <class 'torch.Tensor'>
[1 2 3] <class 'numpy.ndarray'>
tensor([300,   2,   3]) 2510317607008
[300   2   3] 2508296293040
------------------------------
tensor([1, 2, 3]) <class 'torch.Tensor'>
[1 2 3] <class 'numpy.ndarray'>
tensor([300,   2,   3]) 2508302991680
[1 2 3] 2508295928208

2.numpy數組轉換成張量
?? ?torch.from_numpy(data=ndarray)
?? ??? ?共享內存
?? ?torch.tensor(data=ndarray)
?? ??? ?不共享內存

3.僅有一個元素的張量和標量互轉
?? ?torch.tensor(標量)
?? ?tensor.item()

import torch# TODO 標量轉張量
a1 = 10
t1 = torch.tensor(a1)
print(a1, type(a1))
print(t1, type(t1))
print('------------------')
# TODO 張量轉標量
a2 = t1.item()
print(t1, type(t1))
print(a2, type(a2))
10 <class 'int'>
tensor(10) <class 'torch.Tensor'>
------------------
tensor(10) <class 'torch.Tensor'>
10 <class 'int'>

三.張量的運算

1.基本運算

? ? 可以直接進行運算的符號:+ - * /?
?? ?add()/sub()/mul()/div()/neg()
?? ?add_()/sub_()/mul_()/div_()/neg_():修改原數據

import torch# TODO 張量的加減乘除負號基本運算
t1 = torch.tensor([[1, 2], [3, 4]])
print(t1 + 2)
print(t1 - 2)
print(t1 * 2)
print(t1 / 2)
print('----------------------')
print(torch.add(t1, 2))
print(torch.sub(t1, 2))
print(torch.mul(t1, 2))
print(torch.div(t1, 2))
print(torch.neg(t1))
print('----------------------')
# TODO add_,  sub_, mul_, div_, neg_直接修改原有張量,但是類型不能變更
print(t1)
t1.add_(2)
print(t1)
t1.sub_(2)
print(t1)
t1.mul_(2)
print(t1)
# t1.div_(2) # 注意:除以2后結果是浮點類型,原來數據是整數類型,此行報錯! 因為不能直接變更原有張量元素類型
t1.neg_()
print(t1)
[5, 6]])
tensor([[-1,  0],[ 1,  2]])
tensor([[2, 4],[6, 8]])
tensor([[0.5000, 1.0000],[1.5000, 2.0000]])
----------------------
tensor([[3, 4],[5, 6]])
tensor([[-1,  0],[ 1,  2]])
tensor([[2, 4],[6, 8]])
tensor([[0.5000, 1.0000],[1.5000, 2.0000]])
tensor([[-1, -2],[-3, -4]])
----------------------
tensor([[1, 2],[3, 4]])
tensor([[3, 4],[5, 6]])
tensor([[1, 2],[3, 4]])
tensor([[2, 4],[6, 8]])
tensor([[-2, -4],[-6, -8]])
?2.點乘運算

? ? 元素級乘法, 對應位置的元素進行相乘,相乘的兩個張量形狀必須相同
?? ?mul()/*

3.矩陣乘法運算

? ?方法: 行*列, 行每個數據和列每個數據相乘求和
?? 規則: (n, m) * (m, p) =(n, p)
?? ?@/torch.matmul()

import numpy as np
import torch# 矩陣的乘法運算 已知A(n,m)和B(m,p)
# 如果A列=B行, 則A和B可以相乘. 結果是C(n,p)
# 創建張量
A = torch.tensor([[1, 2], [3, 4], [5, 6]])
B = torch.tensor([[5, 6], [7, 8]])
#  TODO 張量(矩陣)乘法運算 @和matmul
# 方式1: @
print(A @ B)
print('-----------------------')
# 方式2: torch.matmul
print(torch.matmul(A, B))
print('-----------------------')
# TODO 張量中有dot()函數,但是只能用于一維張量!!!
# C3 = torch.dot(A, B) # todo 報錯,因為torch中dot只支持1維!!!
print(torch.dot(A[0], B[0]))
print('=================================================')
# TODO 回顧numpy的矩陣乘法運算
AA = np.array([[1, 2], [3, 4], [5, 6]])
BB = np.array([[5, 6], [7, 8]])
print(AA @ BB)
print('-----------------------')
print(np.matmul(AA, BB))
print('-----------------------')
print(np.dot(AA, BB))  # todo numpy中dot可以用于2維!!!
print('-----------------------')
print(np.dot(AA[0], BB[0]))  # numpy中dot可以用于1維!!!
tensor([[19, 22],[43, 50],[67, 78]])
-----------------------
tensor([[19, 22],[43, 50],[67, 78]])
-----------------------
tensor(17)
=================================================
[[19 22][43 50][67 78]]
-----------------------
[[19 22][43 50][67 78]]
-----------------------
[[19 22][43 50][67 78]]
-----------------------
17

4.張量運算函數

① min/max/mean/sum(dim=)
?? ??? ?不設置dim參數, 對所有元素進行計算
?? ??? ?設置dim參數, 對應維度元素進行計算
②? sqrt():平方根, 開根號
③? log()/log2()/log10()/log1p():對數
④ pow(exponent=):冪次方 x^n
⑤? exp():指數 ?e^x

# 張量的其他運算函數
import torch# 設置隨機種子(方便使用統一數據)
torch.manual_seed(666)
# 創建張量
t = torch.randint(1, 10, (2, 3), dtype=torch.float64)
print(t)
print('----------------------------------------------')
# TODO 演示sum()/mean()/max()/min()/pow()/sqrt()/log()/log2()/log10()/exp()
print(t.sum())
print(t.sum(dim=0))  # dim=0,按列求和
print(t.sum(dim=1))  # dim=1 按行求和
print('----------------------------------------------')
print(t.mean())
print(t.mean(dim=0))  # dim=0 按列求均值
print(t.mean(dim=1))  # dim=1 按行求均值
print('----------------------------------------------')
print(t.max())  # 打印t的最大值
print('----------------------------------------------')
print(t.min())  # 打印t的最小值
print('----------------------------------------------')
print(t.pow(2))  # 打印t的平方
print(t.pow(3))  # 打印t的立方
print('----------------------------------------------')
print(t.sqrt())  # 打印t的平方根
print('----------------------------------------------')
print(t.log())  # 打印t的自然對數
print(t.log2())  # 打印t的以2為底的對數
print(t.log10())  # 打印t的以10為底的對數
print('----------------------------------------------')
print(t.exp())  # 打印t的指數函數結果:以e為底,tensor中每個元素的指數函數結果
print('----------------------------------------------')
# 回顧math
import mathprint(math.e)
[7., 4., 7.]], dtype=torch.float64)
----------------------------------------------
tensor(36., dtype=torch.float64)
tensor([13.,  8., 15.], dtype=torch.float64)
tensor([18., 18.], dtype=torch.float64)
----------------------------------------------
tensor(6., dtype=torch.float64)
tensor([6.5000, 4.0000, 7.5000], dtype=torch.float64)
tensor([6., 6.], dtype=torch.float64)
----------------------------------------------
tensor(8., dtype=torch.float64)
----------------------------------------------
tensor(4., dtype=torch.float64)
----------------------------------------------
tensor([[36., 16., 64.],[49., 16., 49.]], dtype=torch.float64)
tensor([[216.,  64., 512.],[343.,  64., 343.]], dtype=torch.float64)
----------------------------------------------
tensor([[2.4495, 2.0000, 2.8284],[2.6458, 2.0000, 2.6458]], dtype=torch.float64)
----------------------------------------------
tensor([[1.7918, 1.3863, 2.0794],[1.9459, 1.3863, 1.9459]], dtype=torch.float64)
tensor([[2.5850, 2.0000, 3.0000],[2.8074, 2.0000, 2.8074]], dtype=torch.float64)
tensor([[0.7782, 0.6021, 0.9031],[0.8451, 0.6021, 0.8451]], dtype=torch.float64)
----------------------------------------------
tensor([[ 403.4288,   54.5982, 2980.9580],[1096.6332,   54.5982, 1096.6332]], dtype=torch.float64)
----------------------------------------------
2.718281828459045

四.索引的操作

作用:根據索引獲取對應位置的數據
?1.? tensor[0軸下標, 1軸下標, ...]
?? ??? ?從左到右從0開始, 0->第一個數據
?? ??? ?從右到左從-1開始, -1->最后一個數據
2. 下標取值
?? ??? ?tensor[0]->0軸第一個數據
?? ??? ?tensor[:, 0] ->1軸第一個數據
3. 列表取值
?? ??? ?tensor[[0,1], [2,4]]->0軸第1個1軸第3個值, 0軸第2個1軸第5個值
4.范圍取值(切片)
?? ??? ?tensor[起始索引:結束索引:步長,...]
5. 布爾取值
?? ??? ?tensor[:, 0]>10:判斷1軸第1組數據大于10->返回T/F
?? ??? ?tensor[tensor[:, 0]>10]:獲取True對應的0軸數據

import torch# 提前設置隨機數種子,保證數據統一
torch.manual_seed(666)
# 創建張量
data = torch.randint(0, 10, (4, 5))
print(data)
print('======================================')
# TODO 演示索引獲取數據格式為: 張量[行,列]
# TODO 注意: 行列表現形式:單個 列表  切片  布爾索引
# TODO 1.演示單個索引獲取數據
# 需求: 獲取張量中第2行數據
print(data[1, :])
print(data[1,])
print(data[1])
print('-------------------------------')
# 需求: 獲取張量中第2列數據
print(data[:, 1])
print('======================================')
# TODO 2.演示列表指定多個索引獲取數據
# 需求: 獲取張量中第1行和第3行數據
print(data[[0, 2], :])
print('-------------------------------')
# 需求: 獲取張量中第1列和第3列數據
print(data[:, [0, 2]])
print('-------------------------------')
# 需求: 獲取張量中第1行和第3行數據中第1列和第3列數據
# TODO 注意: 如果用以下方式的話:它是自動把找的(0,0)(2,2)兩個位置的數據
print(data[[0, 2], [0, 2]])
# TODO 如果要真正拿到符合當前需求的數據,需要用列表嵌套的方式
print(data[[[0], [2]], [0, 2]])
print('======================================')
# TODO 3.演示切片獲取數據
# 需求: 獲取張量中第1行到第3行數據
print(data[0:3, :])
print(data[:3, :])
print('-------------------------------')
# 需求: 獲取張量中第1列到第3列數據
print(data[:, 0:3])
print(data[:, :3])
print('======================================')
# TODO 4.演示布爾索引
# 需求: 獲取張量中數據大于5的數據
print(data[data > 5])
print('-------------------------------')
# 需求: 判斷第1行數據是否大于5
print(data[0] > 5)  # tensor([False, False,  True,  True, False])
# 需求: 先判斷第1行是否大于5,根據布爾索引獲取數據
print(data[:, torch.tensor([False, False, True, True, False])])
print(data[:, data[0] > 5])
print('-------------------------------')
# 需求: 判斷第1列數據是否大于3
print(data[:, 0] > 3)  # tensor([False, False,  True, False])
# 需求: 先判斷第1列是否大于3,根據布爾索引獲取數據
print(data[torch.tensor([False, False, True, False]), :])
print(data[data[:, 0] > 3, :])
[2, 7, 0, 4, 7],[5, 4, 1, 8, 5],[0, 2, 9, 1, 6]])
======================================
tensor([2, 7, 0, 4, 7])
tensor([2, 7, 0, 4, 7])
tensor([2, 7, 0, 4, 7])
-------------------------------
tensor([4, 7, 4, 2])
======================================
tensor([[0, 4, 9, 8, 4],[5, 4, 1, 8, 5]])
-------------------------------
tensor([[0, 9],[2, 0],[5, 1],[0, 9]])
-------------------------------
tensor([0, 1])
tensor([[0, 9],[5, 1]])
======================================
tensor([[0, 4, 9, 8, 4],[2, 7, 0, 4, 7],[5, 4, 1, 8, 5]])
tensor([[0, 4, 9, 8, 4],[2, 7, 0, 4, 7],[5, 4, 1, 8, 5]])
-------------------------------
tensor([[0, 4, 9],[2, 7, 0],[5, 4, 1],[0, 2, 9]])
tensor([[0, 4, 9],[2, 7, 0],[5, 4, 1],[0, 2, 9]])
======================================
tensor([9, 8, 7, 7, 8, 9, 6])
-------------------------------
tensor([False, False,  True,  True, False])
tensor([[9, 8],[0, 4],[1, 8],[9, 1]])
tensor([[9, 8],[0, 4],[1, 8],[9, 1]])
-------------------------------
tensor([False, False,  True, False])
tensor([[5, 4, 1, 8, 5]])
tensor([[5, 4, 1, 8, 5]])
?多維索引
import torch
# 提前設置種子
torch.manual_seed(666)
# 創建三位張量
data = torch.randint(1, 10, (3, 4, 5))
print(data)
print(data[:, :, :])
# 格式: data[0軸索引,1軸索引,2軸索引]
print('----------------------------------')
# 獲取0軸上的第一個數據
print(data[0, :, :])
print(data[0])
print('----------------------------------')
# 獲取1軸上的第一個數據
print(data[:, 0, :])
print('----------------------------------')
# 獲取2軸上的第一個數據
print(data[:, :, 0])

[7, 1, 4, 7, 4],[9, 7, 1, 2, 1],[4, 9, 4, 9, 2]],[[9, 7, 9, 8, 1],[1, 9, 3, 8, 8],[6, 5, 9, 1, 6],[2, 8, 2, 5, 4]],[[8, 3, 4, 1, 3],[7, 8, 4, 7, 9],[5, 3, 1, 9, 2],[6, 6, 1, 4, 2]]])
tensor([[[6, 4, 8, 7, 4],[7, 1, 4, 7, 4],[9, 7, 1, 2, 1],[4, 9, 4, 9, 2]],[[9, 7, 9, 8, 1],[1, 9, 3, 8, 8],[6, 5, 9, 1, 6],[2, 8, 2, 5, 4]],[[8, 3, 4, 1, 3],[7, 8, 4, 7, 9],[5, 3, 1, 9, 2],[6, 6, 1, 4, 2]]])
----------------------------------
tensor([[6, 4, 8, 7, 4],[7, 1, 4, 7, 4],[9, 7, 1, 2, 1],[4, 9, 4, 9, 2]])
tensor([[6, 4, 8, 7, 4],[7, 1, 4, 7, 4],[9, 7, 1, 2, 1],[4, 9, 4, 9, 2]])
----------------------------------
tensor([[6, 4, 8, 7, 4],[9, 7, 9, 8, 1],[8, 3, 4, 1, 3]])
----------------------------------
tensor([[6, 7, 9, 4],[9, 1, 6, 2],[8, 7, 5, 6]])

五.張量形狀操作

1.tensor.reshape(shape=)
?? ??? ?在保證數據不變的前提下, 修改連續和非連續張量形狀
?? ??? ?修改前后的張量元素個數一致
?? ??? ?-1:自動計算
2. tensor.squeeze(dim=)
?? ??? ?刪除維度值為1的維度, 可以通過dim指定刪除維度
3
.tensor.unsqueeze(dim=):
?? ??? ?在指定維度上增加維度值1
4.tensor.transpose(dim0=, dim1=):
?? ??? ?交換指定兩個維度的數據
?? ??? ?參數值是維度下標值
5. tensor.permute(dims=()):
?? ??? ?交換任意維度的數據
?? ??? ?參數值是維度下標值
6. tensor.view(shape=) : 修改連續張量的形狀, 操作等同于reshape
? ? ? ? tensor.contiguous() : 轉換成連續張量
????????tensor.is_contiguous() : 判斷張量是否連續

獲取形狀
import torch# 創建張量
t = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(t)
print('===================================')
# TODO shape獲取形狀
print(t.shape, t.shape[0], t.shape[1], t.shape[-1])
print(t.size(), t.size()[0], t.size()[1], t.size()[-1])
print('===================================')
# TODO reshape修改形狀(元素個數不會變化)
print(t.reshape(3, 2))
print('--------------------')
print(t.reshape(1, 6))
print('--------------------')
print(t.reshape(6, 1))
print('--------------------')
# print(t.reshape(2, 2))  # 個數不匹配就報錯!!!

[4, 5, 6]])
===================================
torch.Size([2, 3]) 2 3 3
torch.Size([2, 3]) 2 3 3
===================================
tensor([[1, 2],[3, 4],[5, 6]])
--------------------
tensor([[1, 2, 3, 4, 5, 6]])
--------------------
tensor([[1],[2],[3],[4],[5],[6]])
--------------------
?張量的升維和降維
import torch# 創建張量
t = torch.tensor([1, 2, 3, 4, 5, 6])
print(t, t.shape, t.ndim)
print('==============================================')
# TODO 先使用reshape()變向完成升維操作,可以操作連續喝非連續的張量
t2 = t.reshape(2, 3)
print(t2, t2.shape, t2.ndim)
t3 = t.reshape(1, 2, 3)
print(t3, t3.shape, t3.ndim)
print('----------------------------')
# TODO 再使用專業的升維操作: unsqueeze()
t4 = t.unsqueeze(dim=0)  # (1,6)
print(t4, t4.shape, t4.ndim)
t5 = t.unsqueeze(dim=1)  # (6,1)
print(t5, t5.shape, t5.ndim)
# tt = t.unsqueeze(dim=2) # 報錯: 維度超出范圍(預期應在[-2, 1]范圍內,但得到的是 2)
tt = t.unsqueeze(dim=-1)
print(tt, tt.shape, tt.ndim)
tt = t.unsqueeze(dim=-2)
print(tt, tt.shape, tt.ndim)
print('==============================================')
# TODO 使用專業的降維操作: squeeze()
t6 = t4.squeeze()
print(t6, t6.shape, t6.ndim)
t7 = t5.squeeze()
print(t7, t7.shape, t7.ndim)


==============================================
tensor([[1, 2, 3],[4, 5, 6]]) torch.Size([2, 3]) 2
tensor([[[1, 2, 3],[4, 5, 6]]]) torch.Size([1, 2, 3]) 3
----------------------------
tensor([[1, 2, 3, 4, 5, 6]]) torch.Size([1, 6]) 2
tensor([[1],[2],[3],[4],[5],[6]]) torch.Size([6, 1]) 2
tensor([[1],[2],[3],[4],[5],[6]]) torch.Size([6, 1]) 2
tensor([[1, 2, 3, 4, 5, 6]]) torch.Size([1, 6]) 2
==============================================
tensor([1, 2, 3, 4, 5, 6]) torch.Size([6]) 1
tensor([1, 2, 3, 4, 5, 6]) torch.Size([6]) 1

維度交換:

import torch# 提前設置一個種子
torch.manual_seed(666)
# 創建三維張量
t = torch.randint(1, 5, (3, 4, 5))
print(t, t.shape)
# TODO 需求: 把張量形狀(3,4,5)轉變為(4,5,3)
print('=====================================================')
# TODO transpose方式: 交換多次
t2 = t.transpose(1, 0)  # (3,4,5)->(4,3,5)
print(t2, t2.shape)
print('------------------------------------------------')
t3 = t2.transpose(2, 1)  # (4,3,5)->(4,5,3)
print(t3, t3.shape)
print('=====================================================')
# TODO permute方式: 一次指定多個維度
t4 = t.permute(dims=(1, 2, 0))  # (3,4,5)->(4,5,3)
print(t4, t4.shape)
# 注意: 還可以直接使用torch調用transpose()和permute()
[3, 2, 3, 1, 2],[4, 3, 4, 1, 4],[1, 3, 2, 4, 1]],[[3, 1, 4, 2, 3],[1, 4, 2, 2, 2],[1, 4, 1, 1, 1],[1, 1, 1, 3, 3]],[[3, 4, 1, 2, 1],[3, 2, 3, 4, 2],[2, 1, 3, 1, 4],[3, 3, 3, 3, 1]]]) torch.Size([3, 4, 5])
=====================================================
tensor([[[1, 3, 2, 3, 3],[3, 1, 4, 2, 3],[3, 4, 1, 2, 1]],[[3, 2, 3, 1, 2],[1, 4, 2, 2, 2],[3, 2, 3, 4, 2]],[[4, 3, 4, 1, 4],[1, 4, 1, 1, 1],[2, 1, 3, 1, 4]],[[1, 3, 2, 4, 1],[1, 1, 1, 3, 3],[3, 3, 3, 3, 1]]]) torch.Size([4, 3, 5])
------------------------------------------------
tensor([[[1, 3, 3],[3, 1, 4],[2, 4, 1],[3, 2, 2],[3, 3, 1]],[[3, 1, 3],[2, 4, 2],[3, 2, 3],[1, 2, 4],[2, 2, 2]],[[4, 1, 2],[3, 4, 1],[4, 1, 3],[1, 1, 1],[4, 1, 4]],[[1, 1, 3],[3, 1, 3],[2, 1, 3],[4, 3, 3],[1, 3, 1]]]) torch.Size([4, 5, 3])
=====================================================
tensor([[[1, 3, 3],[3, 1, 4],[2, 4, 1],[3, 2, 2],[3, 3, 1]],[[3, 1, 3],[2, 4, 2],[3, 2, 3],[1, 2, 4],[2, 2, 2]],[[4, 1, 2],[3, 4, 1],[4, 1, 3],[1, 1, 1],[4, 1, 4]],[[1, 1, 3],[3, 1, 3],[2, 1, 3],[4, 3, 3],[1, 3, 1]]]) torch.Size([4, 5, 3])

六.張量拼接操作


1. torch.cat([t1, t2, ...], dim=)
?? ??? ?在指定維度上對張量進行拼接
?? ??? ?其他維度值相同, 不改變新張量的維度
?? ??? ?指定維度的維度值相加
2.?torch.stack([t1, t2, ...], dim=)
?? ??? ?在指定維度上對張量進行堆疊
?? ??? ?其他維度值相同, 新張量在指定維度新增維度
?? ??? ?指定維度的維度值就是張量個數

import torch# 提前設置一個隨機種子
torch.manual_seed(666)
# TODO cat()拼接三維案例:對應維度上的維數相加
# 創建張量
t1 = torch.randint(1, 5, (1, 2, 3))
t2 = torch.randint(1, 5, (1, 2, 3))
print('----------------------------')
# 拼接
print(torch.cat([t1, t2], dim=0))  # (2, 2, 3)
print('----------------------------')
# 拼接
print(torch.cat([t1, t2], dim=1))  # (1, 4, 3)
print('----------------------------')
# 拼接
print(torch.cat([t1, t2], dim=2))  # (1, 2, 6)
print('=========================================================')
#  TODO cat()拼接的是除拼接維度外,其他所有張量的形狀必須完全相同。
t1 = torch.randint(1, 5, (2, 3))
t2 = torch.randint(1, 5, (1, 3))
# 拼接0軸上
print(torch.cat([t1, t2], dim=0))  # (3, 3)print('=========================================================')
# TODO stack()拼接的是所有張量的形狀必須完全相同(所有維度一致)。
t1 = torch.randint(1, 5, (2, 3))
t2 = torch.randint(1, 5, (2, 3))
print(t1)
print(t2)
print(torch.stack([t1, t2], dim=0))  # (2,2,3)
print(torch.stack([t1, t2], dim=1))  # (2,2,3)
print(torch.stack([t1, t2], dim=2))  # (2,3,2)

tensor([[[1, 3, 2],[3, 3, 3]],[[2, 3, 1],[2, 4, 3]]])
----------------------------
tensor([[[1, 3, 2],[3, 3, 3],[2, 3, 1],[2, 4, 3]]])
----------------------------
tensor([[[1, 3, 2, 2, 3, 1],[3, 3, 3, 2, 4, 3]]])
=========================================================
tensor([[4, 1, 4],[1, 3, 2],[4, 1, 3]])
=========================================================
tensor([[[1, 4, 2],[3, 1, 4]],[[2, 2, 2],[1, 4, 1]]])
tensor([[[1, 4, 2],[2, 2, 2]],[[3, 1, 4],[1, 4, 1]]])
tensor([[[1, 2],[4, 2],[2, 2]],[[3, 1],[1, 4],[4, 1]]])

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/86899.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/86899.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/86899.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring Boot 與 Kafka 的深度集成實踐(一)

引言 ** 在當今的軟件開發領域&#xff0c;構建高效、可靠的分布式系統是眾多開發者追求的目標。Spring Boot 作為 Java 生態系統中極具影響力的框架&#xff0c;極大地簡化了企業級應用的開發流程&#xff0c;提升了開發效率和應用的可維護性。它基于 Spring 框架構建&#…

PIN to PIN兼容設計:MT8370與MT8390核心板開發對比與優化建議

X8390 是基于聯發科 MT8390 CPU 的一款開發板&#xff0c; MT8390 與 MT8370 是 PIN to PIN 的封裝&#xff0c;可以共用一個核心 板。 MT8390 (Genio 700) 是一款高性能的邊緣 AI 物聯網平臺&#xff0c;廣泛應用于智能家居、交 互式零售、工業和商業等領域。它采用…

【論文解讀】START:自學習的工具使用者模型

1st author: ?Chengpeng Li? - ?Google 學術搜索? paper: [2503.04625] START: Self-taught Reasoner with Tools code: 暫未公布 5. 總結 (結果先行) 大型語言推理模型&#xff08;Large Reasoning Models, LRMs&#xff09;在模擬人類復雜推理方面取得了顯著進展&…

【GitOps】Kubernetes安裝ArgoCD,使用阿里云MSE云原生網關暴露服務

?? ArgoCD是什么? ArgoCD是一款開源的持續交付(CD)工具,專門為Kubernetes環境設計。它采用GitOps理念,將Git倉庫作為應用部署的唯一真實來源(SSOT),實現了聲明式的應用部署和管理。 簡單來說,ArgoCD就像是一位不知疲倦的"倉庫管理員",時刻盯著你的Git倉庫,…

三維重建 —— 1. 攝像機幾何

文章目錄 1. 針孔相機1.1. 針孔成像1.2. 光圈對成像的影響 2. 透視投影相機2.1. 透鏡成像2.2. 失焦2.3. 徑向畸變2.4. 透視投影的性質 3. 世界坐標系到像素坐標系的變換4. 其它相機模型4.1. 弱透視投影攝像機4.2. 正交投影攝像機4.3. 各種攝像機模型的應用場合 課程視頻鏈接&am…

Linux基本指令(包含vim,用戶,文件等方面)超詳細

文章目錄 Linux 基本指令前序Vim編輯器分為兩種設計理念模式轉化指令解釋 Normal模式移動光標&#xff08;motion 核心&#xff09;常用指令 動作(action)常用指令將動作與移動進行組合 查找&#xff08;正則表達式&#xff09;替換&#xff08;substitude&#xff09;文本對象…

如何徹底刪除Neo4j中的所有數據:完整指南

如何徹底刪除Neo4j中的所有數據&#xff1a;完整指南 Neo4j作為領先的圖數據庫&#xff0c;在某些場景下我們需要完全清空數據庫中的所有數據。本文將介紹多種刪除Neo4j數據的有效方法&#xff0c;涵蓋不同版本和部署方式的操作步驟。 一、Neo4j數據刪除的常見需求場景 開發…

Keil無法下載程序到STM32 Error: Flash Download failed - Target DLL has been cancelled

背景 Keil通過st-link v2連接STM32&#xff0c;下載報錯 Error: Flash Download failed - Target DLL has been cancelled 我有多臺STM32需要下載程序&#xff0c;會出現這個問題 原因 應該是Keil保存了設備的相關信息&#xff0c;當換了設備之后下載就會出錯 解決辦法 斷…

CIM和建筑風貌管控平臺

2025年的雄安新區&#xff0c;中央綠谷的碧波倒映著現代建筑群&#xff0c;中國星網總部大廈的曲面幕墻與古風飛檐相映成趣。這座“未來之城”的每一處建筑肌理&#xff0c;都離不開一項關鍵技術——城市信息模型&#xff08;CIM&#xff09;與建筑風貌管控平臺的支撐。從雄安到…

REBT 分類任務中,`loss`(損失值)和 `logits`(原始預測分數)是什么

REBT 分類任務中,loss(損失值)和 logits(原始預測分數)是什么 在分類任務中,loss(損失值)和 logits(原始預測分數)的含義及計算邏輯可以通過具體示例清晰解釋。以下結合你提供的數值(loss=0.7478,logits=[-0.1955, -0.3021])進行說明 一、logits 的本質:未歸一化…

6月13日day52打卡

神經網絡調參指南 知識點回顧&#xff1a; 隨機種子內參的初始化神經網絡調參指南 參數的分類調參的順序各部分參數的調整心得 作業&#xff1a;對于day41的簡單cnn&#xff0c;看看是否可以借助調參指南進一步提高精度。 用“燒水調溫”的日常場景來打比方&#xff1a; 每個…

穿越時空的刀劍之旅:走進VR刀劍博物館?

VR 刀劍博物館不僅僅是一個展示刀劍的場所&#xff0c;更是文化傳承與教育的重要基地&#xff0c;在弘揚刀劍文化、增強民族文化認同感以及開展教育活動等方面發揮著不可替代的重要作用。? 從文化傳承的角度來看&#xff0c;刀劍文化源遠流長&#xff0c;它承載著不同國家、不…

基于GA遺傳優化的PID控制器最優控制參數整定matlab仿真

PID&#xff08;比例-積分-微分&#xff09;控制器是工業控制領域中最常用的控制器之一。通過調節PID控制器的三個參數&#xff1a;比例&#xff08;Kp&#xff09;、積分&#xff08;Ki&#xff09;和微分&#xff08;Kd&#xff09;&#xff0c;可以實現系統的穩定控制。然而…

華為OD最新機試真題-上班之路-OD統一考試(B卷)

題目描述 Jungle 生活在美麗的藍鯨城,大馬路都是方方正正,但是每天馬路的封閉情況都不一樣。地圖由以下元素組成: .—空地,可以達到 *—路障,不可達到; S—Jungle的家。 T—公司;

大模型驅動數據分析革新:美林數據智能問數解決方案破局傳統 BI 痛點

在數字化向智能化躍遷的時代浪潮中&#xff0c;大模型技術正驅動企業數據分析模式迎來顛覆性變革。傳統自助式BI工具主導的數據分析模式&#xff0c;雖在降低分析門檻、提升報表開發效率層面發揮了一定作用&#xff0c;但隨著數據應用場景的深化&#xff0c;其指標固化、響應滯…

(Note)基于Pytorch手搓RNN參考

Coding a Recurrent Neural Network (RNN) from scratch using PytorchPyTorch RNN from Scratch - Jake Taelearning pytorch 3: coding an RNN, GRU, LSTM | Kaggle

《網絡安全與防護》知識點復習

? 一、網絡安全基礎&#xff08;CIA / AAA / 安全服務&#xff09; 概念快速記憶CIA 三元組機密性&#xff08;Confidentiality&#xff09;、完整性&#xff08;Integrity&#xff09;、可用性&#xff08;Availability&#xff09;安全服務&#xff08;OSI&#xff09;鑒別…

編譯,多面體庫

1&#xff09; barvinok是一個用于計算整數點數的庫 在參數和非參數多面體以及投影中 這樣的集合。 對于參數多面體&#xff0c;計數由以下任一表示 顯式函數或生成函數。 第一種是分段階躍多項式的形式。 這是Ehrhart擬多項式的推廣 以及向量分割函數。 第二個是Ehrhart級數的…

Kotlin基礎語法一

語言聲明變量與內置數據類型 var&#xff1a;數據可變 val: 數據不可變 內置數據類型 String 字符串 Char 單字符 Boolean true/false Int 整形 Double 小數 List 集合 Set 無重復的元素集合 Map 鍵值對的集合 Kotlin語言的類型推斷 val info : String "Hello KT&quo…

無人機避障——感知篇(在Ubuntu20.04的Orin nx上基于ZED2實現Vins Fusion)

設備&#xff1a;Jetson Orin nx 系統&#xff1a;Ubuntu 20.04 雙目視覺&#xff1a;zed 2 結果展示&#xff1a; 官網中的rosdep install --from-paths src --ignore-src -r -y如果連不上&#xff0c;可以用小魚rosdepc進行替換&#xff1a; 安裝標定工具&#xff1a; 1、…