自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一個(gè)超強(qiáng) Pytorch 操作?。?!

開(kāi)發(fā) 深度學(xué)習(xí)
Pytorch 同樣提供了許多用于數(shù)據(jù)處理和轉(zhuǎn)換的函數(shù)。今兒來(lái)看下,最重要的幾個(gè)必會(huì)函數(shù)。

哈嘍,我是小壯!

這幾天關(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é)果易于可視化。

責(zé)任編輯:趙寧寧 來(lái)源: DOWHAT小壯
相關(guān)推薦

2024-01-31 08:16:38

IPythonPython解釋器

2018-04-27 16:00:15

Windows上帝模式

2021-06-09 11:26:37

BokehPython可視化

2019-03-28 14:10:53

CPU單核

2020-06-04 12:55:44

PyTorch分類器神經(jīng)網(wǎng)絡(luò)

2011-03-28 09:56:03

存儲(chǔ)增刪操作

2022-12-05 08:55:39

MavenGradle項(xiàng)目

2020-12-08 10:33:56

DDoS攻擊開(kāi)源安全安全工具

2023-05-26 15:38:40

2021-03-17 08:11:29

SpringBoot項(xiàng)目數(shù)據(jù)庫(kù)

2021-08-30 09:25:25

Bert模型PyTorch語(yǔ)言

2013-03-08 10:19:03

Oberon操作系統(tǒng)

2009-12-16 12:30:25

openSUSE操作系

2009-08-31 14:19:20

C#打開(kāi)一個(gè)文件

2010-04-20 14:43:01

Unix操作系統(tǒng)

2012-05-07 13:02:46

Linux服務(wù)器集群

2018-10-26 09:30:47

Boxes操作系統(tǒng)Linux

2009-08-25 15:23:16

C#子線程

2016-03-01 14:37:47

華為

2020-05-14 14:45:33

深度學(xué)習(xí) PyTorch人工智能
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)