事先声明,本文章仅仅是我个人简单整理,很多内容不全,还望谅解。
多元线性回归顾名思义,就是假设多个自变量同时对一个因变量产生影响。其特殊情况就是一一映射,即一个自变量对应一个因变量。
首先我们先了解一些指标。这些指标在机器学习中很常见。我偷懒,
- MSE
- RMSE
- MAE
- R-Square
def r_square_score(y_predict,y_test):
r = 1 - mse_score( y_predict,y_test )/mse_score( np.array([np.mean(y_test)]*len(y_test)) , y_test )
return r
下面是线性回归的代码简单实现:
def lr(train_feature,train_label,test_feature):
'''
input:
train_feature(ndarray):训练样本特征
train_label(ndarray):训练样本标签
test_feature(ndarray):测试样本特征
output:
predict(ndarray):测试样本预测标签
'''
#将x0=1加入训练数据
new_train = np.concatenate( (np.ones(len(train_feature)).reshape(-1,1) , train_feature) , axis=1)
#使用正规方程解求得参数
theta = np.linalg.inv( new_train.T @ new_train ) @ new_train.T @ train_label
#将x0=1加入测试数据
new_test = np.concatenate( (np.ones(len(test_feature)).reshape(-1,1),test_feature),axis=1 )
#求得测试集预测标签
predict = new_test @ theta
return predict
注意,使用最小二乘法求的数值解时,需要特别注意矩阵是否可逆,若不可逆,则可考虑添加正则化项。