pytorch使用(一)torchvision.ToTensor、torchvision.Normalize(转张量,归一化)

import numpy as np
import torch
import torchvision.transforms
from torch.utils.tensorboard import SummaryWriter
from torchvision.transforms import transforms


# arrary数据
data = np.array([
                [[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
                [[2,2,2],[2,2,2],[2,2,2],[2,2,2],[2,2,2]],
                [[3,3,3],[3,3,3],[3,3,3],[3,3,3],[3,3,3]],
                [[4,4,4],[4,4,4],[4,4,4],[4,4,4],[4,4,4]],
                [[5,5,5],[5,5,5],[5,5,5],[5,5,5],[5,5,5]]
        ],dtype='uint8')
print(data.shape)
print(data)
# 转tensor
arrayToTensor = torchvision.transforms.ToTensor()
data_tensor = arrayToTensor(data)
print(data_tensor.shape)
print(data_tensor)

# 归一化
# 这里的第一个参数(0.5,0.5,0.5)表示每个通道的均值都是0.5
#第二个参数(0.5,0.5,0.5)表示每个通道的方差都为0.5。
#【因为图像一般是三个通道,所以这里的向量都是1x3的🍵🍵🍵】
# normalize = transforms.Normalize(mean=(0.5,0.5,0.5), std=(0.5,0.5,0.5))
# 下面这样写也行,怎么解释可能是python的问题,期待大佬的回复
normalize = transforms.Normalize(mean=[0.5], std=[0.5])

data_normalized = normalize(data_tensor)
print(data_normalized.shape)
print(data_normalized)

参考:
代码讲解:
https://developer.aliyun.com/article/928968
原理讲解:
https://www.bilibili.com/video/BV1Pa411X76s/?p=26&spm_id_from=pageDriver&vd_source=168ed2a82d904bea741505ff76857c55

posted @ 2023-07-04 17:29  DuJunlong  阅读(88)  评论(0编辑  收藏  举报