2022年 11月 9日

Python——计算方差、标准差、均方差、均方根值、均方误差、均方根误差

  1. # -*- coding: utf-8 -*-
  2. import math
  3. def get_average(records):
  4. """
  5. 平均值
  6. """
  7. return sum(records) / len(records)
  8. def get_variance(records):
  9. """
  10. 方差 反映一个数据集的离散程度
  11. """
  12. average = get_average(records)
  13. return sum([(x - average) ** 2 for x in records]) / len(records)
  14. def get_standard_deviation(records):
  15. """
  16. 标准差 == 均方差 反映一个数据集的离散程度
  17. """
  18. variance = get_variance(records)
  19. return math.sqrt(variance)
  20. def get_rms(records):
  21. """
  22. 均方根值 反映的是有效值而不是平均值
  23. """
  24. return math.sqrt(sum([x ** 2 for x in records]) / len(records))
  25. def get_mse(records_real, records_predict):
  26. """
  27. 均方误差 估计值与真值 偏差
  28. """
  29. if len(records_real) == len(records_predict):
  30. return sum([(x - y) ** 2 for x, y in zip(records_real, records_predict)]) / len(records_real)
  31. else:
  32. return None
  33. def get_rmse(records_real, records_predict):
  34. """
  35. 均方根误差:是均方误差的算术平方根
  36. """
  37. mse = get_mse(records_real, records_predict)
  38. if mse:
  39. return math.sqrt(mse)
  40. else:
  41. return None
  42. def get_mae(records_real, records_predict):
  43. """
  44. 平均绝对误差
  45. """
  46. if len(records_real) == len(records_predict):
  47. return sum([abs(x - y) for x, y in zip(records_real, records_predict)]) / len(records_real)
  48. else:
  49. return None
  50. if __name__ == '__main__':
  51. records1 = [3, 4, 5]
  52. records2 = [2, 4, 6]
  53. # 平均值
  54. average1 = get_average(records1) # 4.0
  55. average2 = get_average(records2) # 4.0
  56. # 方差
  57. variance1 = get_variance(records1) # 0.66
  58. variance2 = get_variance(records2) # 2.66
  59. # 标准差
  60. std_deviation1 = get_standard_deviation(records1) # 0.81
  61. std_deviation2 = get_standard_deviation(records2) # 1.63
  62. # 均方根
  63. rms1 = get_rms(records1) # 4.08
  64. rms2 = get_rms(records2) # 4.32
  65. # 均方误差
  66. mse = get_mse(records1, records2) # 0.66
  67. # 均方根误差
  68. rmse = get_rmse(records1, records2) # 0.81
  69. # 平均绝对误差
  70. mae = get_mae(records1, records2) # 0.66
  71. print(mae)

注意事项

1、X** 2 表示 X的平方;

2、别忘了包含  import math