[Pytorch] torchvision.transforms.ToTensor

PyTorch框架中有一个非常重要且好用的包:torchvision,该包主要由3个子包组成,分别是:torchvision.datasets、torchvision.models、torchvision.transforms

[Pytorch] torchvision.transforms.ToTensor_第1张图片
代码:

import numpy as np
from torchvision import transforms

data = np.random.randint(0, 255, size=300)
img = data.reshape(10,10,3)
print(img.shape)
img_tensor = transforms.ToTensor()(img) # 转换成tensor
print(img_tensor)

输出:

(10, 10, 3)
tensor([[[155, 217,  27, 149,  72, 251,  90,   6,  44,  60],
         [ 92,  15, 217,  93,  44, 223,  14, 140,  66, 244],
         [221,  92,  10, 172, 113,  72,  66, 184,  65,  64],
         [168,   7, 171,  77,  43, 123, 137,  46,  21, 206],
         [126,  85,  74, 134,  54,  22,  34, 164, 126, 151],
         [ 85, 128,  11,  87,   0, 146, 214, 126, 124, 134],
         [223,  45, 182, 232,  34, 148,  60,   7, 193, 206],
         [152, 194,  47, 182, 253,  30,  21, 108, 187, 196],
         [146, 110, 242,  13, 250,  69, 208,  95, 167,  87],
         [180,  51, 169,   0, 107,   2, 122, 221, 239, 160]],

        [[147, 100, 124, 241, 170, 220,  19, 168, 119, 108],
         [ 87,  87, 145, 158, 181,  13, 166,  50,  14,  37],
         [191,  81, 133, 108,   4,  58, 114, 126,  53, 167],
         [101, 151,  86, 166, 145, 241,  79,  74, 146, 202],
         [231,  40, 236,  58,  49, 172, 211, 143, 250,  27],
         [ 40, 216, 100,  13, 161,  51, 207, 129, 115,  13],
         [124, 134, 175, 207, 237, 170,  82,  32, 189, 188],
         [148, 197,  54, 159, 117, 234, 103, 253,  80, 197],
         [ 95,  50, 156, 206, 191,  14, 120, 214, 128, 189],
         [225,  63, 205,  98, 145, 213, 188, 157, 250,  71]],

        [[123, 249, 133, 250, 177, 103,  78, 213, 129, 215],
         [172, 169,  83, 122, 231, 253, 146, 132, 132, 200],
         [188,  13, 142,  12,  29, 240,  39, 249, 153,  76],
         [146,   8,   2,   5, 185,  25,  58, 143, 231, 117],
         [225,  82, 195,  75,   1,  76, 177, 208, 104,  50],
         [177,  37, 153, 221, 178,  42, 167, 190,  85,  77],
         [130, 168, 226, 218,  17, 178, 139, 165, 242, 226],
         [ 37, 127,  89, 105, 182,  77, 160, 122, 214, 143],
         [227,  68,  77,  16, 216, 211,  84,  63, 167,  10],
         [186, 102, 136, 116, 185,  14,  61, 242, 107, 126]]],
       dtype=torch.int32)

transform=transforms.Compose([
])
Ctrl+点击Compose可以查看transforms.py源码。

参考:
[1] PyTorch中文文档:https://pytorch-cn.readthedocs.io/zh/latest/torchvision/torchvision-transform/
[2] pytorch源码解读之torchvision.transforms:https://www.jianshu.com/p/1ae863c1e66d

你可能感兴趣的:(model-pytorch,pytorch,深度学习,机器学习)