目錄
代碼會放在每條解釋的后面
一.概念:
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]]])