---
# System prepended metadata

title: Pytorch 常用
tags: [PyTorch, ' Python']

---

---
tags: PyTorch, Python
---

# Pytorch 常用

### 1. 转换形态
```python!
torch.tensor([[1, 1, 1], [-1, -1, -1]], dtype=torch.int8)
temp = torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
print(temp[0][0].item())

torch.zeros([1, 3], dtype=torch.int32)
cuda = torch.device('cuda:0')
torch.ones([2, 2], dtype=torch.float32, device=cuda)


temp = torch.tensor([[1, 1, 1], [-1, -1, -1]], dtype=torch.float32, requires_grad=True)
print(temp)

t = temp.pow(3).sum()
print(t)
t.backward()
print(temp.grad)
```

### 2. 复制到 c 的 Tensor
```python!
a = torch.arange(1, 21)
print(a.view(-1, 5))
b = a.reshape(2, 10)
c = torch.empty(2, 10)
torch.add(b, torch.ones(2, 10), out=c)
```

### 3. 切换 device
```python!
device = torch.device('cuda:0')
a = torch.tensor([1, 2, 3, 4])
a.to(device)
```

### 4. 合併多個圖片並且顯示
```python!
imgs = torch.Tensor(train_data.data[:3]).int().permute(0, 3, 1, 2)
imgs = torchvision.utils.make_grid(imgs).permute(1, 2, 0)
plt.imshow(imgs)
```
:::info
* 輸入到`torchvision.utils.make_grid(imgs)`時，要是`NCHW`型態
* 輸入到`plt.show(imgs)`時，要是`HWC`型態
:::

### 5. 轉換維度順序
```python!
arr = torch.zeros(3, 4, 5).permute(2, 0, 1)
'''
創建時   shape=(3, 4, 5)
後來改為 shape=(5, 3, 4)
'''
```

### 6. 轉換為 long 型態
```python!
torch.Tensor(arr).type(torch.LongTensor)
```