线性回归-----梯度下降法实现线性回归方程

一元线性回归:

在这里插入图片描述

代价函数:

在这里插入图片描述

梯度下降法:

要想拟合一个重合度高的函数,就必须使得其损失函数 J( θ \theta θ 0 _0 0, θ \theta θ 1 _1 1) 的值最小(如果是梯度下降法也可能是局部最小),要使得损失函数变小的速度最快,就得沿着对应参数最陡的方向下降(即对应的偏导方向),所以对 θ \theta θ 0 _0 0, θ \theta θ 1 _1 1的下一次迭代值要根据损失函数对自己的偏导来确定。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

下面是下降的过程图:
在这里插入图片描述
在这里插入图片描述
其中学习率α决定每一步下降的长度,如果太小下降到最低点需要很多步计算,会浪费很多计算资源,如果太大可能在最低点附近来回震荡,始终落入不到最低点去。
除此之外,初始点的选择也可能导致下降方向的不同,最终可能只得到一个局部最低点而不是全局最低点。但是对于凹函数(只有一个最低点)则初始点的不同选择,最终求得的最低点都会是一样的。

用python实现一元线性回归:

import numpy as np
import matplotlib.pyplot as plt
data=np.genfromtxt("D:\gzu_ml\资料\程序\回归\data.csv",delimiter=",")
x_data=data[:,0]
y_data=data[:,1]


# 学习率
lr=0.0001
# 截距
b=0
# 斜率
k=0
# 最大迭代次数
epochs=50

# 最小二乘法,求平均偏离程度
def compute_error(b,k,x_data,y_data):
    totalError=0
    for i in range(0,len(x_data)):
        totalError+=(y_data[i]-(k*x_data[i]+b))**2
    return totalError/float(len(x_data)) 

# 梯度下降
def gradient_descent_runner(x_data,y_data,b,k,lr,epochs):
    m=float(len(x_data))
    for i in range(epochs):
        # 存放求得的偏导
        b_grad=0
        k_grad=0
        for j in range(0,len(x_data)):
            b_grad+=(1/m)*((k*x_data[j])+b-y_data[j])
            k_grad+=(1/m)*x_data[j]*((k*x_data[j])+b-y_data[j])
            
        #每次学习得到一个对应的b和k
        b-=lr*b_grad
        k-=lr*k_grad
        #每迭代五次画一次图
        if(i%5==0):
            print("epochs",i)
            plt.plot(x_data,y_data,'b.')
            plt.plot(x_data,k*x_data+b,'r')
            plt.show()
    # 返回最后一次学习的b和k    
    return b,k

print("Starting b={0},k={1},error={2}".format(b,k,compute_error(b,k,x_data,y_data)))
print("Running...")
b,k=gradient_descent_runner(x_data,y_data,b,k,lr,epochs)
print("After {0},iterations b={1},k={2},error={3}".format(epochs,b,k,compute_error(b,k,x_data,y_data)))

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

…(经过一系列迭代)

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

多(二)元线性回归:

在这里插入图片描述

损失函数

在这里插入图片描述

用python实现二元线性回归

数据:
在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
from numpy import genfromtxt
import mpl_toolkits.mplot3d as Axes3D

data=np.genfromtxt("D:\gzu_ml\资料\程序\回归\Delivery.csv",delimiter=",")
# 切分数据
# 将前面两列作为x_data
x_data=data[:,:-1]
# 最后一列作为y_data
y_data=data[:,-1]

# 学习率
lr=0.0001
# 二元线性函数有三个参数
theta0=0
theta1=0
theta2=0
# 最大迭代次数
epochs=1000

# 最小二乘法,求平均偏离程度
def compute_error(theta0,theta1,theta2,x_data,y_data):
    totalError=0
    for i in range(0,len(x_data)):
        totalError+=(y_data[i]-(theta1*x_data[i,0]+theta2*x_data[i,1]+theta0))**2
    return totalError/float(len(x_data)) 


# 梯度下降
def gradient_descent_runner(x_data, y_data, theta0, theta1, theta2, lr, epochs):
    # 计算总数据量
    m = float(len(x_data))
    # 循环epochs次
    for i in range(epochs):
        theta0_grad = 0
        theta1_grad = 0
        theta2_grad = 0
        # 计算梯度的总和再求平均
        for j in range(0, len(x_data)):
            theta0_grad += (1/m) * ((theta1 * x_data[j,0] + theta2*x_data[j,1] + theta0)-y_data[j])
            theta1_grad += (1/m) * x_data[j,0] * ((theta1 * x_data[j,0] + theta2*x_data[j,1] + theta0)-y_data[j])
            theta2_grad += (1/m) * x_data[j,1] * ((theta1 * x_data[j,0] + theta2*x_data[j,1] + theta0)-y_data[j])
        # 更新参数
        theta0 = theta0 - (lr*theta0_grad)
        theta1 = theta1 - (lr*theta1_grad)
        theta2 = theta2 - (lr*theta2_grad)
    return theta0, theta1, theta2


print("Starting theta0 = {0}, theta1 = {1}, theta2 = {2}, error = {3}".format(theta0, theta1, theta2, compute_error(theta0, theta1, theta2, x_data, y_data)))
print("Running...")
theta0, theta1, theta2 = gradient_descent_runner(x_data, y_data, theta0, theta1, theta2, lr, epochs)
print("After {0} iterations theta0 = {1}, theta1 = {2}, theta2 = {3}, error = {4}".format(epochs, theta0, theta1, theta2, compute_error(theta0, theta1, theta2, x_data, y_data)))

ax = plt.figure().add_subplot(111, projection = '3d') 
ax.scatter(x_data[:,0], x_data[:,1], y_data, c = 'r', marker = 'o', s = 100) #绘制真实值  

x0 = x_data[:,0]
x1 = x_data[:,1]
# 生成网格矩阵
x0, x1 = np.meshgrid(x0, x1)
z = theta0 + x0*theta1 + x1*theta2
# 画3D图
ax.plot_surface(x0, x1, z)
#设置坐标轴  
ax.set_xlabel('Miles')  
ax.set_ylabel('Num of Deliveries')  
ax.set_zlabel('Time')  
  
#显示图像  
plt.show()  

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

附:基本概念

相关系数:

在这里插入图片描述
相关系数越接近1则越线性相关。

决定系数:在这里插入图片描述

其中 y i y_i yi 表示真实值, y ‾ \overline{y} y表示真实值的平均值, y ^ \widehat{y} y 表示预测值。
决定系数的适用范围更广,可以用于描述非线性或者有两个及两个以上自变量的相关关系。它可以用来评价模型的效果。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值