计算pytorch标准化(Normalize)所需要数据集的均值和方差实例

yipeiwu_com5年前Python基础

pytorch做标准化利用transforms.Normalize(mean_vals, std_vals),其中常用数据集的均值方差有:

if 'coco' in args.dataset:
  mean_vals = [0.471, 0.448, 0.408]
  std_vals = [0.234, 0.239, 0.242]
elif 'imagenet' in args.dataset:
  mean_vals = [0.485, 0.456, 0.406]
  std_vals = [0.229, 0.224, 0.225]

计算自己数据集图像像素的均值方差:

import numpy as np
import cv2
import random
 
# calculate means and std
train_txt_path = './train_val_list.txt'
 
CNum = 10000   # 挑选多少图片进行计算
 
img_h, img_w = 32, 32
imgs = np.zeros([img_w, img_h, 3, 1])
means, stdevs = [], []
 
with open(train_txt_path, 'r') as f:
  lines = f.readlines()
  random.shuffle(lines)  # shuffle , 随机挑选图片
 
  for i in tqdm_notebook(range(CNum)):
    img_path = os.path.join('./train', lines[i].rstrip().split()[0])
 
    img = cv2.imread(img_path)
    img = cv2.resize(img, (img_h, img_w))
    img = img[:, :, :, np.newaxis]
    
    imgs = np.concatenate((imgs, img), axis=3)
#     print(i)
 
imgs = imgs.astype(np.float32)/255.
 
 
for i in tqdm_notebook(range(3)):
  pixels = imgs[:,:,i,:].ravel() # 拉成一行
  means.append(np.mean(pixels))
  stdevs.append(np.std(pixels))
 
# cv2 读取的图像格式为BGR,PIL/Skimage读取到的都是RGB不用转
means.reverse() # BGR --> RGB
stdevs.reverse()
 
print("normMean = {}".format(means))
print("normStd = {}".format(stdevs))
print('transforms.Normalize(normMean = {}, normStd = {})'.format(means, stdevs))

以上这篇计算pytorch标准化(Normalize)所需要数据集的均值和方差实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python找出微信上删除你好友的人脚本写法

相信大家在微信上一定被上面的这段话刷过屏,群发消息应该算是微信上流传最广的找到删除好友的方法了。但群发消息不仅仅会把通讯录里面所有的好友骚扰一遍,而且你还得挨个删除好几百个聊天记录,回复...

python修改list中所有元素类型的三种方法

修改list中所有元素类型: 方法一: new = list() a = ['1', '2', '3'] for x in a: new.append(int(x)) print(...

Python利用matplotlib做图中图及次坐标轴的实例

Python利用matplotlib做图中图及次坐标轴的实例

图中图 准备数据 import matplotlib.pyplot as plt fig = plt.figure() x = [1, 2, 3, 4, 5, 6, 7] y =...

Python 限定函数参数的类型及默认值方式

python作为一门动态语言,在使用变量之前是不需要进行定义,而是通过动态绑定的方法将变量绑定为某种类型。这样做为我们使用变量时提供了方便,但有时也给我们使用变量时造成了一定的困扰,例如...

Python中的二维数组实例(list与numpy.array)

关于python中的二维数组,主要有list和numpy.array两种。 好吧,其实还有matrices,但它必须是2维的,而numpy arrays (ndarrays) 可以是多维...