机器学习——梯度下降

1、简单的梯度下降算法

'''
简单的梯度下降算法
'''
import numpy as np
import matplotlib.pyplot as plt

#目标函数 y = x^2
def func(x):
    return np.square(x)
#目标函数的一阶导函数,也是偏导
def dfunc(x):
    return 2*x
#梯度下降算法

def GD(x_start,df,epochs,lr):
    '''
    梯度下降法:给定起始值和目标函数的一阶导函数,求epochs次迭代中x的更新值
    :param x_start: x的起始点
    :param df:目标函数的一阶导
    :param epochs:迭代周期
    :param lr:学习率
    :return:x在每次迭代后的位置(包含起始点),epochs长度+1
    '''
    xs = np.zeros(epochs + 1)
    x = x_start
    xs[0] = x
    for i in range(epochs):
        dx = df(x)
        #v表示x变化的幅度
        v = - dx * lr
        x += v
        xs[i+1] = x
    return xs
#展示梯度下降法
def demo_GD():
    line_x = np.linspace(-5,5,100)
    line_y = func(line_x)

    x_start = -5
    epochs = 5
    lr = 0.9
    '''
    当lr=0.1时,拟合效果最好,随着lr的增大,拟合越来也差
    '''

    x = GD(x_start,dfunc,epochs,lr=lr)

    color = 'r'
    plt.plot(line_x,line_y,color='blue')#画出目标函数
    plt.plot(x,func(x),color=color,label='lr={}'.format(lr))#梯度下降过程
    plt.scatter(x,func(x),color=color)#描点
    plt.legend()#用于显示图例
    plt.show()

demo_GD()

'''
给定数据集dataSet,每一行代表一组数据记录,每组数据记录中,第一个值为房屋面积(单位:平方英尺),
第二个值为房屋中的房间数,第三个值为房价(单位:千美元),
试用梯度下降法,构造损失函数,在函数gradientDescent中实现房价price关于房屋面积area和房间数rooms的线性回归,
返回值为线性方程price=θ0+θ1∗area+θ2∗rooms中系数θi(i=0,1,2)的列表


多变量的梯度下降问题
'''
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def gradientDescent(rooms, price, area):
    """
    梯度下降法。给定起始点与目标函数的一阶导数,求在epochs次迭代中theta0,theta1,theta2的更新值
    param theta0
    """
    theta = [1,1,1]  # 预设theta初值
    learn_rate = 0.0000000001  # 学习率
    predit_y = 0  # 预测值
    loss = []  # 损失数组
    epochs = 5000  # 迭代次数

    for j in range(epochs):
        theta0, theta1, theta2 = 0, 0, 0
        loss_t = 0  # 计算总体的方差
        for i in range(5):  # 一共五组数据
            predit_y = theta[0] + theta[1] * area[i] + theta[2] * rooms[i]
            theta0 = theta0 + (predit_y - price[i]) * 1
            theta1 = theta1 + (predit_y - price[i]) * area[i]
            theta2 = theta2 + (predit_y - price[i]) * rooms[i]
            loss_t = loss_t + ((predit_y - price[i]) ** 2) / 2
        loss.append(loss_t / 5)
        theta0 = theta0 / 5
        theta1 = theta1 / 5
        theta2 = theta2 / 5
        theta[0] = theta[0] - theta0 * learn_rate
        theta[1] = theta[1] - theta1 * learn_rate
        theta[2] = theta[2] - theta2 * learn_rate
    plt.plot(loss, c='b')
    plt.show()
    print(theta)
    return theta
def demo_GD():
    price = [400, 330, 369, 342, 540]
    rooms = [3, 3, 3, 2, 4]
    area = [2104, 1600, 2400, 1416, 3000]
    gradientDescent(rooms, price, area)
demo_GD()




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值