TorchVision官方文档翻译为中文-示例库Tensor转换与JIT-002

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

此示例演示了张量图像上的图像变换现在支持的各种功能。特别是,我们展示了如何在GPU上执行图像转换,以及如何使用JIT编译编写它们的脚本。

在v0.8.0之前,torchvision中的转换传统上是以PIL为中心的,因此存在多个限制。现在,从v0.8.0开始,转换实现与Tensor和PIL兼容,我们可以实现以下新功能:

变换多波段torch张量图像(具有3-4个以上通道)
torchscript与用于部署的模型一起进行转换
支持GPU加速
批处理转换,如视频
直接以torchscript支持的torch张量读取和解码数据(用于PNG和JPEG图像格式)
(注意:这些特征仅适用于张量图像)

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

import torch
import torchvision.transforms as T
from torchvision.io import read_image

plt.rcParams["savefig.bbox"] = 'tight'
torch.manual_seed(1)

def show(imgs):
    fix, axs = plt.subplots(ncols=len(imgs), squeeze=False)
    for i, img in enumerate(imgs):
        img = T.ToPILImage()(img.to('cpu'))
        axs[0, i].imshow(np.asarray(img))
        axs[0, i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])

read_image()函数的作用是:读取图像并将其作为张量直接加载

dog1 = read_image(str(Path('assets') / 'dog1.jpg'))
dog2 = read_image(str(Path('assets') / 'dog2.jpg'))
show([dog1, dog2])

在这里插入图片描述

在GPU上转换图像
大多数变换支持PIL图像顶部的张量(要可视化变换的效果,请参阅此链接)。使用张量图像,如果cuda可用,我们可以在GPU上运行变换!

import torch.nn as nn

transforms = torch.nn.Sequential(
    T.RandomCrop(224),
    T.RandomHorizontalFlip(p=0.3),
)

device = 'cuda' if torch.cuda.is_available() else 'cpu'
dog1 = dog1.to(device)
dog2 = dog2.to(device)

transformed_dog1 = transforms(dog1)
transformed_dog2 = transforms(dog2)
show([transformed_dog1, transformed_dog2])

在这里插入图片描述
可编写脚本的转换,便于通过torchscript进行部署
现在,我们将展示如何结合图像转换和模型正向传递,同时使用torch.jit.script获得单个脚本化模块。
让我们定义一个预测模块,该模块转换输入张量,然后对其应用ImageNet模型。

from torchvision.models import resnet18


class Predictor(nn.Module):

    def __init__(self):
        super().__init__()
        self.resnet18 = resnet18(pretrained=True, progress=False).eval()
        self.transforms = nn.Sequential(
            T.Resize([256, ]),  #由于torchscript类型的限制,我们在列表中使用单个int值
            T.CenterCrop(224),
            T.ConvertImageDtype(torch.float),
            T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        with torch.no_grad():
            x = self.transforms(x)
            y_pred = self.resnet18(x)
            return y_pred.argmax(dim=1)

现在,让我们定义预测器的脚本和非脚本实例,并将其应用于相同大小的多个张量图像。

predictor = Predictor().to(device)
scripted_predictor = torch.jit.script(predictor).to(device)

batch = torch.stack([dog1, dog2]).to(device)

res = predictor(batch)
res_scripted = scripted_predictor(batch)

输出

Downloading: “https://download.pytorch.org/models/resnet18-f37072fd.pth” to /home/matti/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth
/home/matti/miniconda3/envs/pytorch-test/lib/python3.8/site-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at /opt/conda/conda-bld/pytorch_1623448216815/work/c10/core/TensorImpl.h:1156.)
return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)

我们可以验证脚本模型和非脚本模型的预测是相同的:

import json

with open(Path('assets') / 'imagenet_class_index.json', 'r') as labels_file:
    labels = json.load(labels_file)

for i, (pred, pred_scripted) in enumerate(zip(res, res_scripted)):
    assert pred == pred_scripted
    print(f"Prediction for Dog {i + 1}: {labels[str(pred.item())]}")

输出

Prediction for Dog 1: ['n02113023', 'Pembroke']
Prediction for Dog 2: ['n02106662', 'German_shepherd']

由于模型是脚本化的,因此可以很容易地转储到磁盘上并重新使用

import tempfile

with tempfile.NamedTemporaryFile() as f:
    scripted_predictor.save(f.name)

    dumped_scripted_predictor = torch.jit.load(f.name)
    res_scripted_dumped = dumped_scripted_predictor(batch)
assert (res_scripted_dumped == res_scripted).all()

更多计算机视觉与图形学相关资料,请关注微信公众号:计算机视觉与图形学实战
在这里插入图片描述

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

### Planar-to-Tensor 处理的概念实现方式 Planar-to-Tensor 处理是一种在计算机视觉和数据转换技术中常见的方法,用于将平面数据(例如二维图像或网格)转换为张量形式的数据结构。这种转换通常是为了更好地适应深度学习框架中的操作需求,因为许多现代深度学习模型(如卷积神经网络,CNNs)以张量作为输入和输出[^1]。 #### 平面数据的定义 平面数据通常指二维数据结构,例如图像、点云投影或网格数据。这些数据可以表示为一个矩阵,其中每个元素对应于某个特定位置上的值。例如,在图像处理中,平面数据可能是一个灰度图像或RGB图像,其维度为 \(W \times H\) 或 \(W \times H \times C\),分别表示宽度、高度和通道数(如颜色通道)[^2]。 #### 张量的定义 张量是多维数组的泛化形式,可以看作是标量(0阶张量)、向量(1阶张量)和矩阵(2阶张量)的扩展。在深度学习中,张量通常用于表示更高维度的数据结构,例如三维体积数据或时间序列图像数据。张量的维度可以表示为 \(N \times C \times H \times W\),其中 \(N\) 是批量大小,\(C\) 是通道数,\(H\) 和 \(W\) 分别是高度和宽度[^1]。 #### Planar-to-Tensor 转换的基本步骤 Planar-to-Tensor 转换的核心思想是将平面数据重新组织为适合深度学习模型输入的张量形式。以下是该过程的关键步骤: 1. **数据预处理**: 在将平面数据转换为张量之前,通常需要对其进行标准化或归一化处理。例如,将图像像素值从 [0, 255] 范围映射到 [0, 1] 或 [-1, 1] 范围。这一步骤有助于提高模型训练的收敛速度和稳定性。 2. **通道扩展**: 如果平面数据仅包含单个通道(如灰度图像),则需要将其扩展为多通道张量。例如,可以通过复制单通道数据来创建三通道张量,或者通过特征提取算法生成额外的通道信息[^1]。 3. **维度调整**: 根据目标模型的要求,调整张量的维度顺序。例如,在 PyTorch 中,张量的维度顺序通常为 \(N \times C \times H \times W\),而在 TensorFlow 中可能为 \(N \times H \times W \times C\)。这一步骤可以通过转置操作实现。 4. **批量处理**: 如果需要同时处理多个平面数据样本,则需要将它们堆叠为一个批量张量。例如,对于 \(M\) 个图像样本,最终的张量形状可能为 \(M \times C \times H \times W\)。 #### 示例代码 以下是一个使用 PythonPyTorch 实现 Planar-to-Tensor 转换的示例代码: ```python import torch import numpy as np # 假设我们有一个 2D 平面数据 (H x W) plane_data = np.random.rand(100, 100) # 随机生成一个 100x100 的平面数据 # 将平面数据转换为张量 tensor_data = torch.tensor(plane_data, dtype=torch.float32) # 扩展通道维度 (C) tensor_data = tensor_data.unsqueeze(0) # 形状变为 (1 x H x W) # 添加批量维度 (N) tensor_data = tensor_data.unsqueeze(0) # 形状变为 (1 x 1 x H x W) print("Tensor Shape:", tensor_data.shape) ``` #### 应用场景 Planar-to-Tensor 转换广泛应用于以下领域: - **图像分类分割**:将二维图像转换为张量后输入 CNN 模型进行分类或分割任务。 - **三维重建**:将二维投影图像转换为张量并结合深度信息进行三维模型重建。 - **视频处理**:将时间序列图像帧转换为四维张量以捕捉时空特征[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值