PyTorch教程(四):维度变换
生活随笔
收集整理的這篇文章主要介紹了
PyTorch教程(四):维度变换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
view和reshape
在PyTorch0.3版本中使用view,在PyTorch0.4以后增加了reshape,作用是將一個shape轉變為另一個shape。
shape變化的前提是保證numel()一致
a = torch.rand(4,1,28,28) # 4張圖片,灰度,28長,28寬 # torch.Size([4, 1, 28, 28]) a.view(4, 1*28*28) a.view(4, 1*28*28).shape # torch.Size([4, 784]) # 這里丟失了原始的數據存儲順序unsqueeze和Squeeze
添加維度unsqueeze
a = torch.rand(4,1,28,28) a.unsqueeze(0).shape # 在最前面添加了一個維度,例如數據組 # torch.Size([1, 4, 1, 28, 28]) a.unsqueeze(-1).shape # 在最后面添加了一個維度,例如方差 # torch.Size([4, 1, 28, 28, 1])unsqueeze不會更改數據本身,只是插入一個維度。
舉例f+bf+bf+b求偏置項
刪減維度
b.shape # torch.Size([1, 32, 1, 1]) b.squeeze().shape # torch.Size([32]) 把所有的1維度數據刪除 b.squeeze(0).shape # torch.Size([32, 1, 1]) 刪除了第一個維度 b.squeeze(-1).shape # torch.Size([1, 32, 1]) 刪除了最后一個維度 b.squeeze(1).shape # torch.Size([1, 32, 1, 1]) 刪除了第一個維度,但是這個維度中包含了數據,所以不變化 b.squeeze(-4).shape # torch.Size([32, 1, 1]) 從右往左刪除第四個維度維度擴展expand和repeat
b.shape # torch.Size([1, 32, 1, 1]) b.expand(4,32,14,14).shape # torch.Size([4, 32, 14, 14]) 將原先維度是1的進行擴展 b.expand(-1,32,14,14).shape # torch.Size([1, 32, 14, 14]) 如果不想改變某個維度,只需要寫為-1就可以# 對于repeat表示在某個維度上的重復倍數 b.repeat(4,32,1,1).shape # torch.Size([4, 1024, 1, 1]) 對應維度分別擴展4倍、32倍、不擴展、不擴展 b.repeat(4,1,1,1).shape # torch.Size([4, 32, 1, 1]) 對應維度分別擴展4倍、不擴展、不擴展、不擴展轉置
a = torch.randn(3,4) a.t() #tensor([[ 0.3362, 0.3310, -0.9111], # [-0.9452, -0.3859, -0.2837], # [-2.0296, 0.7222, -1.2428], # [-1.0731, 1.2659, 1.5356]])轉置只能適用于矩陣,也就是dim=2
總結
以上是生活随笔為你收集整理的PyTorch教程(四):维度变换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国队世界杯(国足历次冲击世界杯战果)
- 下一篇: 「原创」吃莲雾有什么好处