1、线性回归

1、介绍

1、定义:在这里插入图片描述
ε:误差
是独立分布的,服从均值为0,方差为θ^2的高斯分布在这里插入图片描述
两个式子结合就是最终所求:
在这里插入图片描述
求解θ的极值点,用似然函数
1、似然函数
在这里插入图片描述

2、转换成log形式(极值点木有变)
乘法转变成加法,更易求解
在这里插入图片描述

求其最大值,因为是负的,所以求代价函数的最小值
3、求阶得到代价函数
在这里插入图片描述
怎样求解得到极小值呢?两种方法

2、推导

1、正规方程(only)

在这里插入图片描述
对θ求偏导:
在这里插入图片描述
偏导为0,求极值点
在这里插入图片描述
具有特殊性,而且计算较难,所以此方法可以说是线性回归独有的

代码实现

1、准备数据:

import numpy as np
X = 2*np.random.rand(100,1)
y = 4+ 3*X +np.random.randn(100,1)

2、代入公式

X_b = np.c_[np.ones((100,1)),X]#1的是对应x的0次方
theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
#theta_best=array([[4.21509616],
#       [2.77011339]])

3、测试数据画图

X_new = np.array([[0],[2]])
# print(X_new)
X_new_b = np.c_[np.ones((2,1)),X_new]
# print(X_new_b)
y_predict = X_new_b.dot(theta_best)
#y_predict=array([[4.21509616],
#      [9.75532293]])
plt.plot(X_new,y_predict,'r--')
plt.plot(X,y,'b.')
plt.axis([0,2,0,15])
plt.show()

在这里插入图片描述

2、梯度下降(常用)

在这里插入图片描述

1、求解
对每一个θ求偏导
在这里插入图片描述
2、参数:
学习率(步长):每一步移动的大小

代码实现

注意拿到数据要做一次标准化:
在这里插入图片描述

eta = 0.1
n_iterations = 1000
m = 100
theta = np.random.randn(2,1)
for iteration in range(n_iterations):
    gradients = 1/m* X_b.T.dot(X_b.dot(theta)-y)
    theta = theta - eta*gradients

theta=array([[4.21509609],[2.77011344]])

X_new_b.dot(theta)

array([[4.21509616],[9.75532293]])
画图,查看不同学习率的结果

theta_path_bgd = []
def plot_gradient_descent(theta,eta,theta_path = None):
    m = len(X_b)
    plt.plot(X,y,'b.')
    n_iterations = 1000
    for iteration in range(n_iterations):
        y_predict = X_new_b.dot(theta)
        plt.plot(X_new,y_predict,'b-')
        gradients = 1/m* X_b.T.dot(X_b.dot(theta)-y)
        theta = theta - eta*gradients
        if theta_path is not None:
            theta_path.append(theta)
    plt.xlabel('X_1')
    plt.axis([0,2,0,15])
    plt.title('eta = {}'.format(eta))

theta = np.random.randn(2,1)

plt.figure(figsize=(10,4))
plt.subplot(131)
plot_gradient_descent(theta,eta = 0.02)
plt.subplot(132)
plot_gradient_descent(theta,eta = 0.1,theta_path=theta_path_bgd)
plt.subplot(133)
plot_gradient_descent(theta,eta = 0.5)
plt.show()

在这里插入图片描述
eta=0.02,趋近较慢,但不容易错过所求
eta=0.1,趋近速度较快
eta=0.5,两边跳跃,错过了所求
要正确选择学习率

种类

1、批量梯度下降bgd
容易得到最优解,但是每次考虑所有样本,速度较慢
2、随机梯度下降sgd:
每次找一个样本,迭代速度快,但是不一定每次朝着收敛方向
3、小批量梯度下降mgd
每次更新选择一小部分样本,最实用
画图对比:
在这里插入图片描述

库函数

from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X,y)
print (lin_reg.coef_)
print (lin_reg.intercept_)

[[2.77011339]]
[4.21509616]

多项式式回归:

次数越高,越易过拟合

m = 100
X = 6*np.random.rand(m,1) - 3
y = 0.5*X**2+X+np.random.randn(m,1)

X_new = np.linspace(-3,3,100).reshape(100,1)
X_new_poly = poly_features.transform(X_new)
y_new = lin_reg.predict(X_new_poly)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
plt.figure(figsize=(12,6))
for style,width,degree in (('g-',1,100),('b--',1,2),('r-+',1,1)):
#数据预处理,将数据处理成degree次数的模型
    poly_features = PolynomialFeatures(degree = degree,include_bias = False)
#进行标准化模型
    std = StandardScaler()
#线性回归模型
    lin_reg = LinearRegression()
# 用管道,将所需的依次进行
    polynomial_reg = Pipeline([('poly_features',poly_features),
             ('StandardScaler',std),
             ('lin_reg',lin_reg)])
 #进行训练
    polynomial_reg.fit(X,y)
 #数据预测
    y_new_2 = polynomial_reg.predict(X_new)
    #画图展示
    plt.plot(X_new,y_new_2,style,label = 'degree   '+str(degree),linewidth = width)
plt.plot(X,y,'b.')
plt.axis([-3,3,-5,10])
plt.legend()
plt.show()

在这里插入图片描述

过拟合的影响

from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

def plot_learning_curves(model,X,y):
    X_train, X_val, y_train, y_val = train_test_split(X,y,test_size = 0.2,random_state=100)
    train_errors,val_errors = [],[]
    for m in range(1,len(X_train)):
        model.fit(X_train[:m],y_train[:m])
        y_train_predict = model.predict(X_train[:m])
        y_val_predict = model.predict(X_val)
        train_errors.append(mean_squared_error(y_train[:m],y_train_predict[:m]))
        val_errors.append(mean_squared_error(y_val,y_val_predict))
    plt.plot(np.sqrt(train_errors),'r-+',linewidth = 2,label = 'train_error')
    plt.plot(np.sqrt(val_errors),'b-',linewidth = 3,label = 'val_error')
    plt.xlabel('Trainsing set size')
    plt.ylabel('RMSE')
    plt.legend()

polynomial_reg = Pipeline([('poly_features',PolynomialFeatures(degree = 25,include_bias = False)),
             ('lin_reg',LinearRegression())])
plot_learning_curves(polynomial_reg,X,y)
plt.axis([0,80,0,5])
plt.show()

在这里插入图片描述

正则化

解决过拟合的问题
对权重进行惩罚,让权重参数尽可能平滑一些
1、Ridge
在这里插入图片描述

from sklearn.linear_model import Ridge
np.random.seed(42)
m = 20
X = 3*np.random.rand(m,1)
y = 0.5 * X +np.random.randn(m,1)/1.5 +1
X_new = np.linspace(0,3,100).reshape(100,1)

def plot_model(model_calss,polynomial,alphas,**model_kargs):
    for alpha,style in zip(alphas,('b-','g--','r:')):
        model = model_calss(alpha,**model_kargs)
        if polynomial:
            model = Pipeline([('poly_features',PolynomialFeatures(degree =10,include_bias = False)),
             ('StandardScaler',StandardScaler()),
             ('lin_reg',model)])
        model.fit(X,y)
        y_new_regul = model.predict(X_new)
        lw = 2 if alpha > 0 else 1
        plt.plot(X_new,y_new_regul,style,linewidth = lw,label = 'alpha = {}'.format(alpha))
    plt.plot(X,y,'b.',linewidth =3)
    plt.legend()

plt.figure(figsize=(14,6))
plt.subplot(121)
plot_model(Ridge,polynomial=False,alphas = (0,10,100))
plt.subplot(122)
plot_model(Ridge,polynomial=True,alphas = (0,10**-5,1))
plt.show()

在这里插入图片描述
alpha越大,决策方程越平缓

2、Lasso
在这里插入图片描述

from sklearn.linear_model import Lasso

plt.figure(figsize=(14,6))
plt.subplot(121)
plot_model(Lasso,polynomial=False,alphas = (0,0.1,1))
plt.subplot(122)
plot_model(Lasso,polynomial=True,alphas = (0,10**-1,1))
plt.show()

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值