当前位置:   article > 正文

递推最小二乘法——python程序_rls-fun

rls-fun

算法引用的数据为python自带的波士顿房价数据。代码如下:

  1. # data 第一列为标记值
  2. # data 后几列为特征向量
  3. # initialTheta 为需要求得的theta
  4. import numpy as np
  5. import sklearn.datasets
  6. from sklearn.model_selection import train_test_split
  7. from sklearn.metrics import mean_squared_error
  8. import matplotlib as mpl
  9. import matplotlib.pyplot as plt
  10. import warnings
  11. ###################
  12. ## data 第一列为真值,后面所有列为特征
  13. ## initialTheta 估算的权值初值
  14. ## featureNum 特征的个数
  15. def RLS_Fun(data, initialTheta, featureNum):
  16. Theta = initialTheta
  17. P = 10 ** 6 * np.eye(featureNum)
  18. lamda = 1
  19. for i in range(len(data)):
  20. featureMatrix = data[i][1:]
  21. featureMatrix = featureMatrix.reshape(featureMatrix.shape[0], 1)
  22. y_real = data[i][0]
  23. K = np.dot(P, featureMatrix) / (lamda + np.dot(np.dot(featureMatrix.T, P), featureMatrix))
  24. Theta = Theta + np.dot(K, (y_real - np.dot(featureMatrix.T, Theta)))
  25. P = np.dot((np.eye(featureNum) - np.dot(K, featureMatrix.T)), P)
  26. return Theta
  27. if __name__ == '__main__':
  28. warnings.filterwarnings(action='ignore')
  29. dataInitial = sklearn.datasets.load_boston()
  30. x = np.array(dataInitial.data)
  31. y = np.array(dataInitial.target)
  32. y = y.reshape((y.shape[0], 1))
  33. x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, random_state=0)
  34. data = np.concatenate((y_train, x_train), axis=1)
  35. featureNum = np.shape(x)[1] # 有几个特征
  36. initialTheta = 0.5 * np.ones((featureNum, 1))
  37. Theta = RLS_Fun(data, initialTheta, featureNum)
  38. y_pred = np.dot(x_test, Theta)
  39. mse = mean_squared_error(y_test, y_pred)
  40. print('均方误差:', mse)
  41. t = np.arange(len(y_pred))
  42. mpl.rcParams['font.sans-serif'] = ['simHei']
  43. mpl.rcParams['axes.unicode_minus'] = False
  44. plt.figure(facecolor='w')
  45. plt.plot(t, y_test, 'r-', lw=2, label='真实值')
  46. plt.plot(t, y_pred, 'g-', lw=2, label='估计值')
  47. plt.legend(loc='best')
  48. plt.title('波士顿房价预测', fontsize=18)
  49. plt.xlabel('样本编号', fontsize=15)
  50. plt.ylabel('房屋价格', fontsize=15)
  51. plt.grid()
  52. plt.show()

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/131502
推荐阅读
相关标签
  

闽ICP备14008679号