一個(gè)超強(qiáng) Pytorch 操作?。?!
哈嘍,我是小壯!
這幾天關(guān)于深度學(xué)習(xí)的內(nèi)容,已經(jīng)分享了一些。
另外,類似于numpy、pandas常用數(shù)據(jù)處理函數(shù),在Pytorch中也是同樣的重要,同樣的有趣??!
Pytorch同樣提供了許多用于數(shù)據(jù)處理和轉(zhuǎn)換的函數(shù)。
今兒來(lái)看下,最重要的幾個(gè)必會(huì)函數(shù)。
torch.Tensor
torch.Tensor 是PyTorch中最基本的數(shù)據(jù)結(jié)構(gòu),用于表示張量(tensor)。張量是多維數(shù)組,可以包含數(shù)字、布爾值等。你可以使用torch.Tensor的構(gòu)造函數(shù)創(chuàng)建張量,也可以通過(guò)其他函數(shù)創(chuàng)建。
import torch
# 創(chuàng)建一個(gè)空的張量
empty_tensor = torch.Tensor()
# 從列表創(chuàng)建張量
data = [1, 2, 3, 4]
tensor_from_list = torch.Tensor(data)
torch.from_numpy
用于將NumPy數(shù)組轉(zhuǎn)換為PyTorch張量。
import numpy as np
numpy_array = np.array([1, 2, 3, 4])
torch_tensor = torch.from_numpy(numpy_array)
torch.Tensor.item
用于從只包含一個(gè)元素的張量中提取Python數(shù)值。適用于標(biāo)量張量。
scalar_tensor = torch.tensor(5)
scalar_value = scalar_tensor.item()
torch.Tensor.view
用于改變張量的形狀。
original_tensor = torch.randn(2, 3) # 2x3的隨機(jī)張量
reshaped_tensor = original_tensor.view(3, 2) # 將形狀改變?yōu)?x2
torch.Tensor.to
用于將張量轉(zhuǎn)換到指定的設(shè)備(如CPU或GPU)。
cpu_tensor = torch.randn(3)
gpu_tensor = cpu_tensor.to("cuda") # 將張量移動(dòng)到GPU
torch.Tensor.numpy
將張量轉(zhuǎn)換為NumPy數(shù)組。
pytorch_tensor = torch.tensor([1, 2, 3])
numpy_array = pytorch_tensor.numpy()
torch.nn.functional.one_hot
用于對(duì)整數(shù)張量進(jìn)行獨(dú)熱編碼。
import torch.nn.functional as F
integer_tensor = torch.tensor([0, 2, 1])
one_hot_encoded = F.one_hot(integer_tensor)
torch.utils.data.Dataset和torch.utils.data.DataLoader
用于加載和處理數(shù)據(jù)集。這兩個(gè)類通常與自定義的數(shù)據(jù)集類一起使用。
from torch.utils.data import Dataset, DataLoader
class CustomDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
dataset = CustomDataset([1, 2, 3, 4, 5])
dataloader = DataLoader(dataset, batch_size=2, shuffle=True)
以上這些是PyTorch中一些重要的數(shù)據(jù)轉(zhuǎn)換函數(shù),進(jìn)行了簡(jiǎn)單的使用。
它們對(duì)于處理和準(zhǔn)備深度學(xué)習(xí)任務(wù)中的數(shù)據(jù)非常非常有幫助。
一個(gè)案例
接下來(lái),我們制作一個(gè)圖像分割的案例。
在這個(gè)案例中,我們將使用PyTorch和torchvision庫(kù)進(jìn)行圖像分割,使用預(yù)訓(xùn)練的DeepLabV3模型和PASCAL VOC數(shù)據(jù)集。
在整個(gè)的代碼中,涉及到上面所學(xué)到的內(nèi)容,調(diào)整大小、裁剪、標(biāo)準(zhǔn)化等。
import torch
import torchvision.transforms as transforms
from torchvision import models
from PIL import Image
import matplotlib.pyplot as plt
# 下載示例圖像
!wget -O example_image.jpg https://pytorch.org/assets/deeplab/deeplab1.jpg
# 定義圖像轉(zhuǎn)換
transform = transforms.Compose([
transforms.Resize((256, 256)), # 調(diào)整大小
transforms.ToTensor(), # 轉(zhuǎn)換為張量
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 標(biāo)準(zhǔn)化
])
# 加載并轉(zhuǎn)換圖像
image_path = 'example_image.jpg'
image = Image.open(image_path).convert("RGB")
input_tensor = transform(image).unsqueeze(0) # 添加批次維度
# 加載預(yù)訓(xùn)練的DeepLabV3模型
model = models.segmentation.deeplabv3_resnet101(pretrained=True)
model.eval()
# 進(jìn)行圖像分割
with torch.no_grad():
output = model(input_tensor)['out'][0]
output_predictions = output.argmax(0)
# 將預(yù)測(cè)結(jié)果轉(zhuǎn)換為彩色圖像
def decode_segmap(image, nc=21):
label_colors = np.array([(0, 0, 0), # 0: 背景
(128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), # 1-5: 物體
(0, 128, 128), (128, 128, 128), (64, 0, 0), (192, 0, 0), # 6-9: 道路
(64, 128, 0), (192, 128, 0), (64, 0, 128), (192, 0, 128), # 10-13: 面部
(64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), # 14-17: 植物
(0, 192, 0), (128, 192, 0), (0, 64, 128)]) # 18-20: 建筑
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
for l in range(0, nc):
idx = image == l
r[idx] = label_colors[l, 0]
g[idx] = label_colors[l, 1]
b[idx] = label_colors[l, 2]
rgb = np.stack([r, g, b], axis=2)
return rgb
# 將預(yù)測(cè)結(jié)果轉(zhuǎn)換為彩色圖像
output_rgb = decode_segmap(output_predictions.numpy())
# 可視化原始圖像和分割結(jié)果
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image)
plt.title('Original Image')
plt.subplot(1, 2, 2)
plt.imshow(output_rgb)
plt.title('Segmentation Result')
plt.show()
在這個(gè)案例中,我們首先定義了一系列圖像轉(zhuǎn)換函數(shù),包括調(diào)整大小、轉(zhuǎn)換為張量和標(biāo)準(zhǔn)化。這些轉(zhuǎn)換確保輸入圖像滿足模型的需求。
然后,加載了一個(gè)示例圖像并應(yīng)用了這些轉(zhuǎn)換。
接下來(lái),我們使用了torchvision中預(yù)訓(xùn)練的DeepLabV3模型來(lái)進(jìn)行圖像分割。對(duì)于輸出,我們提取了預(yù)測(cè)結(jié)果的最大值索引,以獲得每個(gè)像素的預(yù)測(cè)類別。
最后,我們將預(yù)測(cè)結(jié)果轉(zhuǎn)換為彩色圖像,并可視化原始圖像和分割結(jié)果。
這個(gè)案例強(qiáng)調(diào)了圖像轉(zhuǎn)換函數(shù)在圖像分割任務(wù)中的重要作用,確保輸入圖像符合模型的輸入要求,并且輸出結(jié)果易于可視化。