机器学习之线性回归

第一大类.广义线性模型

1. 普通最小二乘法
LinearRegression类的拟合系数为w = (w1,w2,w3,…,wn),以此来最小化样本集中观测点和线性近似的预测点之间的残差平方和,数学本质就是:

在这里插入图片描述

其fit()函数以数组x,y为输入,将拟合后的系数存储在变量coef_中,截距储存在变量intercept_中
predict(xtest)函数,传入一个参数xtest,输出预测得到的y值。
normalize()函数,传入需要进行归一化的数据集
score(xtest,ytest)函数,传入测试数据集,输出得到的拟合程度或者说x,y之间的线性关系是否足够强
构建误差函数 error = np.mean((regr.predict(xtest)-ytest)**2) 来度量预测值与真实值之间的差距
(后续用到再补充)
该方法通过对X进行 singular value decomposition ( 奇异值分解 ) 来计算最小二乘法的解。如果 X 是大小为(n, p) 的矩阵,则该方法的复杂度为在这里插入图片描述

,假设在这里插入图片描述

代码示例

from sklearn import linear_model
import numpy as np 
import matplotlib.pyplot as plt 

x = np.array([1.08,1.12,1.19,1.28,1.36,1.48,1.59,1.68,1.80,1.87,1.98,2.07]).reshape(-1,1)
y = np.array([2.25,2.37,2.40,2.55,2.64,2.75,2.92,3.03,3.14,3.26,3.36,3.50]).reshape(-1,1)
regr = linear_model.LinearRegression()
regr.fit(x, y)
# print('The coef is :%f'%regr.coef_)
# print('The intercept is :%f'%regr.intercept_)
a = regr.coef_
b = regr.intercept_
Y = a * x + b
#plt.figure('LinearRegression')
#plt.plot(x,y,'.')
plt.scatter(x, y)
#plt.figure('Predict')
plt.plot(x,Y)
#plt.figure('LinearRegression & Predict')
plt.show() 

拟合后的图像在这里插入图片描述
2.岭回归(Ridge Regression)
由于最小二乘法在使用过程中存在一些难以忽略的问题,比如对于高度病态的数据的处理就变得比较困难,因此在此基础上,添加一个对系数大小的惩罚项来增加对共线性的鲁棒性,公式解释如下(其中alpha为非负数,是控制缩减量的复杂度参数:其值越大,缩减量越大,对应的鲁棒性也就越强)

在这里插入图片描述
岭回归的复杂度与普通最小二乘法的复杂度相同
其成员函数与最小二乘法基本相同,通过一段代码来了解。

import numpy as np 
import matplotlib.pyplot as plt 
from sklearn import linear_model

#create data
x = 1. / (np.arange(1, 11) + np.arange(0, 10)[:,np.newaxis])
y = np.ones(10)

n_alphas = 200
alphas = np.logspace(-10, -2,n_alphas)

coefs = []
for a in alphas:
    ridge = linear_model.Ridge(alpha=a,fit_intercept=False)
    ridge.fit(x, y)
    coefs.append(ridge.coef_)
ax = plt.gca()
ax.plot(alphas,coefs)
ax.set_xscale('log')
ax.set_xlim(ax.get_xlim()[::-1])
plt.xlabel('alpha')
plt.ylabel('weights')
plt.title('Ridge coefficients as a function of the regularization')
plt.axis('tight')
plt.show()

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值