PyTorch中tensor[..., 2:4]的實現(xiàn)示例
1. 動機
在看YOLO v3-SPP源碼時,看到tensor[..., a: b]的切片方式比較新奇,接下來進行分析:
p = p.view(bs, self.na, self.no, self.ny, self.nx).permute(0, 1, 3, 4, 2).contiguous() # prediction
if self.training:
return p
p = p.view(m, self.no)
p[:, :2] = (torch.sigmoid(p[:, 0:2]) + grid) * ng # x, y
p[:, 2:4] = torch.exp(p[:, 2:4]) * anchor_wh # width, height
p[:, 4:] = torch.sigmoid(p[:, 4:])
p[:, 5:] = p[:, 5:self.no] * p[:, 4:5]
return p
2. 分析問題
2.1list數組使用[..., a:b]方式切片
list_simple = [1, 2, 3, 4, 5]
list_complex = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
# 對list數組進行切片
try: # ① list_simple
print(f"...: {list_simple[..., 2:4]}")
except Exception as e:
print(f"a_list_simple切片報錯,錯誤為: {e}")
try: # ② list_complex
print(f"...: {list_complex[..., 2:4]}")
except Exception as e:
print(f"a_list_complex切片報錯,錯誤為: {e}")
"""
a_list_simple切片報錯,錯誤為: list indices must be integers or slices, not tuple
a_list_complex切片報錯,錯誤為: list indices must be integers or slices, not tuple
"""
很明顯,Python的基礎數據類型list并不支持這樣的切片方式。
2.2 numpyarray使用[..., a:b]方式切片
import numpy as np
numpy_simple = np.array([1, 2, 3, 4, 5])
numpy_complex = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(f"numpy_simple: \n{numpy_simple}")
print(f"numpy_complex: \n{numpy_complex}")
print("\n-------------------------\n")
# 對numpy array進行切片
try: # ① list_simple
print(f"...切片沒有報錯,結果為: {numpy_simple[..., 2:4]}")
except Exception as e:
print(f"numpy_simple切片報錯,錯誤為: {e}")
try: # ② list_complex
print(f"...切片沒有報錯,結果為: {numpy_complex[..., 2:4]}")
except Exception as e:
print(f"numpy_complex切片報錯,錯誤為: {e}")
"""
numpy_simple:
[1 2 3 4 5]
numpy_complex:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
-------------------------
...切片沒有報錯,結果為: [3 4]
...切片沒有報錯,結果為: [[ 3]
[ 6]
[ 9]
[12]]
"""
說明使用[..., a:b]方式是可以對numpy array進行切片的。
2.3 PyTorchtensor使用[..., a:b]方式切片
我們直接創(chuàng)建一個tensor進行分析:
import torch
a = torch.rand([3, 112, 112])
print(f"...: {a[..., :2].shape}") # ...: torch.Size([3, 112, 2])
可以看到[...,a:b]中的...表示前n-1個維度,a:b表示直接對最后一個維度進行切片
3. 總結
[..., a:b]是array/tensor特有的切片方式,表示直接對最后一個維度進行切片。
到此這篇關于PyTorch中tensor[..., 2:4]的實現(xiàn)示例的文章就介紹到這了,更多相關PyTorch tensor[..., 2:4]內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- 使用PyTorch/TensorFlow搭建簡單全連接神經網絡
- PyTorch使用教程之Tensor包詳解
- 最新tensorflow與pytorch環(huán)境搭建的實現(xiàn)步驟
- pytorch?tensor合并與分割方式
- Pytorch實現(xiàn)tensor序列化和并行化的示例詳解
- PyTorch?TensorFlow機器學習框架選擇實戰(zhàn)
- pytorch中tensorboard安裝及安裝過程中出現(xiàn)的常見錯誤問題
- Pytorch之tensorboard無法啟動和顯示問題及解決
- Pytorch Dataset,TensorDataset,Dataloader,Sampler關系解讀
相關文章
Python的Flask框架中集成CKeditor富文本編輯器的教程
在用Flask搭建網站時的后臺文章編輯器可以使用CKeditor,CKeditor所支持的文本樣式較多且開源,這里我們就來看一下Python的Flask框架中集成CKeditor富文本編輯器的教程2016-06-06

