09.编程理解无偏性与相合性
编程理解无偏性与相合性
无偏性
1 from statistics import mean 2 from statistics import variance 3 import random 4 import matplotlib.pyplot as plt 5 6 7 def variance_bias(data): 8 """方差""" 9 n = len(data) 10 if n <= 1: 11 return None 12 13 mean_value = mean(data) 14 return sum((e - mean_value) ** 2 for e in data) / n 15 16 17 def sample(num_of_samples, sample_sz, var): 18 data = [] 19 for _ in range(num_of_samples): 20 data.append(var([random.uniform(0.0, 1.0) for _ in range(sample_sz)])) 21 return data 22 23 24 if __name__ == "__main__": 25 26 data1 = sample(1000, 40, variance_bias) 27 plt.hist(data1, bins="auto", rwidth=0.8) 28 plt.axvline(x=mean(data1), c='black') 29 plt.axvline(x=1/12, c='red') 30 print("bias :", mean(data1), 1/12) 31 plt.show() 32 33 data2 = sample(1000, 40, variance) 34 plt.hist(data2, bins="auto", rwidth=0.8) 35 plt.axvline(x=mean(data2), c='black') 36 plt.axvline(x=1/12, c='red') 37 print("unbias :", mean(data2), 1/12) 38 plt.show()
相合性
import random from statistics import mean, variance import matplotlib.pyplot as plt if __name__ == "__main__": sample_means = [] sample_vars = [] indices = [] for sz in range(20, 10001, 50): indices.append(sz) sample = [random.gauss(0.0, 1.0) for _ in range(sz)] sample_means.append(mean(sample)) sample_vars.append(variance(sample)) plt.plot(indices, sample_means) plt.plot(indices, sample_vars) plt.show()