params_distribution.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: UTF-8 -*-
  2. """
  3. 此脚本用于展示模型参数估计值的分布
  4. """
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. import pandas as pd
  8. from sklearn import linear_model
  9. def generate_data():
  10. """
  11. 随机生成数据
  12. """
  13. # Python2和Python3的range并不兼容,所以使用list(range(xx, xx))
  14. x = np.array(list(range(0, 100)))
  15. error = np.round(np.random.randn(100), 2)
  16. y = x + error
  17. return pd.DataFrame({"x": x, "y": y})
  18. def train_model(x, y):
  19. """
  20. 利用训练数据,估计模型参数
  21. """
  22. # 创建一个线性回归模型
  23. model = linear_model.LinearRegression()
  24. # 训练模型,估计模型参数
  25. model.fit(x, y)
  26. return model
  27. def visualize_params(params):
  28. """
  29. 可视化模型参数估计值的分布
  30. """
  31. # 创建一个图形框
  32. fig = plt.figure(figsize=(6, 6), dpi=80)
  33. # 在图形框里只画一幅图
  34. ax = fig.add_subplot(111)
  35. n, bins, _ = ax.hist(params, bins=50, density=True, color="b",
  36. edgecolor='black', linewidth=1.2, alpha=0.5)
  37. # 用多项式拟合得到的直方图
  38. z1 = np.polyfit(bins[:-1], n, 10)
  39. p1 = np.poly1d(z1)
  40. ax.plot(bins[:-1], p1(bins[:-1]), "r-.")
  41. plt.show()
  42. def run():
  43. """
  44. 产生“结构”相似的随机数据,并它训练线性回归模型
  45. 以此展示模型参数估计值服从正态分布
  46. """
  47. features = ["x"]
  48. label = ["y"]
  49. coefs = []
  50. intercepts = []
  51. # 循环运行1000次
  52. for i in range(1000):
  53. data = generate_data()
  54. model = train_model(data[features], data[label])
  55. # 记录每一次参数a的估计值
  56. coefs.append(model.coef_[0][0])
  57. # 记录每一次参数b的估计值
  58. intercepts.append(model.intercept_[0])
  59. visualize_params(coefs)
  60. visualize_params(intercepts)
  61. if __name__ == "__main__":
  62. run()