我有一些从高斯分布生成的样本,我想转换它们,使它们具有均匀分布。我按照以下步骤操作:
1-标准化高斯分布,使其平均值为0,标准值为1。
2-使用此标准化高斯分布的CDF来获得均匀分布。
我使用here解释的方法来估算CDF。但最终结果并不统一。它看起来像中间的均匀,但在边缘(接近0和1)有错误。
这是我的代码:
import numpy as np
import matplotlib.pyplot as plt
# ================= Parameers ===================
mu = 5.0
sig = 2.0
data_cnt = 10**6
bin_cnt = 10**3
# ================ Functions ===================
# Estimates gaussian distribution parameters from data using ML
def gaussian_estimation(vector):
mu = np.mean(vector)
sig = np.std(vector)
return (mu,sig)
# Adjusts the data so it forms a gaussian with mean of 0 and std of 1
def gaussian_normalization(vector, char = None):
if char is None:
mu , sig = gaussian_estimation(vector)
else:
mu = char[2]
sig = char[3]
normalized = (vector-mu)/np.sqrt(sig)
return normalized
# Taken from https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function
def CDF(x, max_i = 100):
sum = x
value = x
for i in np.arange(max_i)+1:
value = value*x*x/(2.0*i+1)
sum = sum + value
return 0.5 + (sum/np.sqrt(2*np.pi))*np.exp(-1*(x*x)/2)
def gaussian_to_uniform(vector, if_normal = False):
if (if_normal == False):
vector = gaussian_normalization(vector)
uni = np.apply_along_axis(CDF, 0, vector)
return uni
# ========== Step1: Data Generation ============
data = np.random.normal(mu, sig, data_cnt)
plt.hist(data,bin_cnt)
# ========= Step2: Data Normalization ==========
data2 = gaussian_normalization(data)
plt.hist(data2,bin_cnt)
# ======== Step3: Data Uniformization ==========
data3 = gaussian_to_uniform(data2, if_normal = True)
plt.hist(data3,bin_cnt)
所以有人可以帮我解决这个问题吗?也许近似方法不那么准确?