机器学习:线性回归

线性回归

线性回归,简单地讲就是要找到一条直线或者平面,在最大程度上去拟合样本数据点。

1、梯度下降实现线性回归

(1)梯度下降算法的直观理解:
比如我们在一座大山上的某处位置,由于我们不知道怎么下山,于是决定走一步算一步,也就是在每走到一个位置的时候,求解当前位置的梯度,沿着梯度的负方向,也就是当前最陡峭的位置向下走一步,然后继续求解当前位置梯度,向这一步所在位置沿着最陡峭最易下山的位置走一步。这样一步步的走下去,一直走到觉得我们已经到了山脚。当然这样走下去,有可能我们不能走到山脚,而是到了某一个局部的山峰低处。
从上面的解释可以看出,梯度下降不一定能够找到全局的最优解,有可能是一个局部最优解。当然,如果损失函数是凸函数,梯度下降法得到的解就一定是全局最优解。
在这里插入图片描述
(2)梯度下降公式
线性回归方程:
在这里插入图片描述
损失函数:
在这里插入图片描述
更新Θ:
在这里插入图片描述
对损失函数求偏导:
在这里插入图片描述
在这里插入图片描述
代码:

# 梯度下降法实现线性回归
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2, 2, 100).reshape(-1, 1)
y = 2*x + 2*np.random.random((100,1))

x = np.hstack((np.ones((100,1)), x))

def loss_function(x, y, w, m):
    return ((y - np.matmul(x, w))**2).sum()/2/m

def gradient_Descent(x, y):
    epoch = 1000
    learning_rate = 0.01
    m, n = x.shape
    w = np.zeros((n, 1))
    loss = []
    for i in range(epoch):
        w_grad = np.matmul(x.T, (np.matmul(x, w)) - y) / m
        w = w - learning_rate*w_grad
        loss.append(loss_function(x, y, w, m))
    return w, loss

w, loss = gradient_Descent(x, y)

plt.scatter(x[:, 1], y)
plt.plot(x[:, 1], x[:, 1]*w[1]+w[0], c='r')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

plt.plot(range(1000), loss)
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()

在这里插入图片描述
在这里插入图片描述

2、 sklearn实现线性回归

数据下载地址: http://archive.ics.uci.edu/ml/machine-learning-databases/00294/
代码:

# 线性回归
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split, cross_val_predict
from sklearn.metrics import mean_squared_error

# 读取数据
data = pd.read_excel('Folds5x2_pp.xlsx')

# 样本特征
x = data.iloc[:, :4]

# 样本标签
y = data.iloc[:, 4]

# 训练集和测试集划分
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=1)

# 模型
lr = LinearRegression()

# 训练模型
lr.fit(x_train, y_train)

# 预测
y_pred = lr.predict(x_test)

# 模型评估、均方误差
print('mse: ', mean_squared_error(y_test, y_pred))

# 交叉验证
y_pred_cross = cross_val_predict(lr, x, y, cv=5)

# 均方误差
print('cross_val_predict_mse: ', mean_squared_error(y, y_pred_cross))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值