我们经常不知道数据是根据什么类型的函数进行分布, 此时就需要非参数密度估计的方法。 本文对同一组数据进行了三种不同的非参数密度估计, 即直方图,核密度估计,K近邻。
使用数据集:
https://download.csdn.net/download/weixin_42388833/19418489?spm=1001.2014.3001.5501
1. 直方图
计算并画出数据分布的直方图(size of bin = 0.02, 0.5, 2.0)
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import logsumexp
def plot_histogram(data_set, bin_size):
"""
compute and plot the histogram with given size of bin
:param data_set: given data_set
:param bin_size: given size of bin
"""
# compute the number of bins
bins = ((int(np.max(data_set))+1) - int(np.min(data_set))) // bin_size+1
#plot
plt.figure()
plt.hist(data_set,bins = int(bins))
plt.title(f'bin_size={bin_size}')
plt.ylabel('times')
plt.xlabel('data')
plt.grid()
plt.show()
if __name__ == '__main__':
# load dataset
train_data = np.loadtxt('nonParamTrain.txt')
test_data = np.loadtxt('nonParamTest.txt')
#3a histogram
size_list=[0.02,0.5,