machine learning : 最小二乘法之线性函数 --- python实现

来源:互联网 发布:手机上怎么用淘宝神笔 编辑:程序博客网 时间:2024/05/27 20:20

最小二乘法 之 线性函数模型

原理可见https://zh.wikipedia.org/wiki/%E6%9C%80%E5%B0%8F%E4%BA%8C%E4%B9%98%E6%B3%95

链接需要科学上网(2015.10),

实现阶段有多种方法,本文采用维基百科最后介绍的广义逆矩阵的方法计算。

即输入矩阵的广义逆矩阵{点乘}输出矩阵 ,运算结果既为求解的 参数矩阵。


需要用到的函数为 pinv ,matlab中pinv(X) , python中numpy库中有此函数,即 : np.linalg.pinv


code:

#Global Varsglobal params#train functiondef train(train_x , train_y):global paramspinv = np.linalg.pinv(train_x)  # cacul the pseudo-inverse matrixparams = np.dot( pinv , train_y ) # figure out the paramsprint('The params:')print(params)

np.linalg.pinv求得train_x的广义逆矩阵 pinv , pinv 点乘 train_y 即得参数矩阵 params

以上即为训练过程。


随后可以进行回归:  即将测试数据的x矩阵点乘参数矩阵 ,可得模型得到的输出。


code

#test functiondef test(test_x , test_y , result_path):global paramsrs = open(result_path , 'w')regressValue = np.dot(test_x,params)print('The regress value of test data:')print(regressValue)print('-------------------------------------------------------')print('The errors:')err = regressValue - test_yprint(err)print('The RMSE(root mean squared error) is:')MRSE  =  math.sqrt(np.sum(np.square(err)) / regressValue.size)print(MRSE)print('-------------------------------------------------------')

回归完成以后,可以通过MRSE(root mean squared error)观察回归效果。


源代码传送门(python):http://download.csdn.net/detail/zzukun/9210049


1 0
原创粉丝点击