學習目标:
分享一下在分類任務中,資料集均值和方差的計算方法,以及常用資料集(Cifa10、Cifa100)的均值和方差
計算方法:
精确值是通過分别計算R,G,B三個通道的資料算出來的, 比如你有2張圖檔,都是100100大小的,那麼兩圖檔的像素點共有2100*100 = 20 000 個; 那麼這兩張圖檔的
- 均值的求法: mean_R: 這20000個像素點的R值加起來,除以像素點的總數,這裡是20000;mean_G 和mean_B 兩個通道 的計算方法 一樣的。
- 标準差的求法:
代碼:
from itertools import repeat
import os
from multiprocessing.pool import ThreadPool
from pathlib import Path
from PIL import Image
import numpy as np
from tqdm import tqdm
NUM_THREADS = os.cpu_count()
def calc_channel_sum(img_path): # 計算均值的輔助函數,統計單張圖像顔色通道和,以及像素數量
img = np.array(Image.open(img_path).convert('RGB')) / 255.0 # 準換為RGB的array形式
h, w, _ = img.shape
pixel_num = h * w
channel_sum = img.sum(axis=(0, 1)) # 各顔色通道像素求和
return channel_sum, pixel_num
def calc_channel_var(img_path, mean): # 計算标準差的輔助函數
img = np.array(Image.open(img_path).convert('RGB')) / 255.0
channel_var = np.sum((img - mean) ** 2, axis=(0, 1))
return channel_var
def mean_and_var(data_path,data_format='*.png',decimal_places=4):
"""
計算均值方差
@param data_path: 資料集路徑
@param data_format: 圖檔格式(預設為png)
@param decimal_places: 均值和方差,保留的小數位數(預設為4)
@return:
"""
print("Data root is ",data_path)
train_path = Path(data_path)
img_f = list(train_path.rglob(data_format))
n = len(img_f)
print(f'Data Nums is : {n}')
print("Calculate the mean value")
result = ThreadPool(NUM_THREADS).imap(calc_channel_sum, img_f) # 多線程計算
channel_sum = np.zeros(3)
cnt = 0
pbar = tqdm(enumerate(result), total=n)
for i, x in pbar:
channel_sum += x[0]
cnt += x[1]
mean = channel_sum / cnt
mean=np.around(mean, decimal_places) # 使用around()函數保留小數位數
print('R_mean,G_mean,B_mean is ',mean)
print("Calculate the var value")
result = ThreadPool(NUM_THREADS).imap(lambda x: calc_channel_var(*x), zip(img_f, repeat(mean)))
channel_sum = np.zeros(3)
pbar = tqdm(enumerate(result), total=n)
for i, x in pbar:
channel_sum += x
var = np.sqrt(channel_sum / cnt)
var = np.around(var, decimal_places) # 使用around()函數保留小數位數
print('R_var,G_var,B_var is ', var)
if __name__ == '__main__':
mean_and_var('/home/yangzhanshan/disk/datasets/cifa10/val')
常用資料集均值和方差:
提示:這裡可以添加計劃學習的時間
cifa10 train
cifa10_mean=[0.4914, 0.4822, 0.4465]
cifa10_var=[0.4914, 0.4822, 0.4465]
cifa100-train
cifa100_mean=[0.5071, 0.4865, 0.4409]
cifa100_var=[0.2673, 0.2564, 0.2762]