2.3、梯度下降法

一、什么是梯度下降算法

梯度下降就是求一个函数的最小值,对应的梯度上升就是求函数最大值,梯度下降法不是机器学习算法,不能用来解决分类或回归问题,而是一种基于搜索的最优化方法,作用是优化目标函数,如求损失函数的最小值。那么为什么我们常常提到“梯度下降”而不是梯度上升“呢?主要原因是在大多数模型中,我们往往需要求函数的最小值。我们得出损失函数,当然是希望损失函数越小越好,这个时候肯定是需要梯度下降算法的。梯度下降算法作为很多算法的一个关键环节,其重要意义是不言而喻的。

二、算法原理

先任取点(x0,f(x0)),求f(x)在该点x0的导数f'(x0),在用x0减去导数值f'(x0),计算所得就是新的点x1。然后再用x1减去f'(x1)得x2…以此类推,循环多次,慢慢x值就无限接近极小值点。

 其中g(x)表示梯度,表示步长。

 小步长:小步长表现为计算量大,耗时长,但比较精准。

 大步长:表现为震荡,容易错过最低点,计算量相对较小

 梯度下降代码实现

import numpy as np
import matplotlib.pyplot as plt


# 定义目标函数 f(x)=x**2+1
def f(x):
    return np.array(x)**2 + 1

# 对目标函数求导 d(x)=x*2
def d1(x):
    return x * 2

def Gradient_Descent_d1(current_x = 0.1,learn_rate = 0.01,e = 0.001,count = 50000):
    # current_x initial x value
    # learn_rate 学习率
    # e error
    # count number of iterations
    for i in range(count):
        grad = d1(current_x) # 求当前梯度
        if abs(grad) < e: # 梯度收敛到控制误差内
            break # 跳出循环
        current_x = current_x - grad * learn_rate # 一维梯度的迭代公式
        print("第{}次迭代逼近值为{}".format(i+1,current_x))

    print("最小值为:",current_x)
    print("最小值保存小数点后6位:%.6f"%(current_x))
    return current_x

# 显示目标函数曲线及梯度下降最小值毕竟情况
def ShowLine(min_X,max_Y):
    x = [x for x in range(10)] + [x * (-1) for x in range(1,10)]
    x.sort()
    print(x)
    plt.plot(x,f(x))
    plt.plot(min_X,max_Y,'ro')
    plt.show()

minValue = Gradient_Descent_d1(current_x = 0.1,learn_rate = 0.01,e = 0.001,count = 50000)
minY = f(minValue)
print('目标函数最小值约为:',minY)
ShowLine(minValue,minY)

 

 四、梯度下降算法简单应用——线性回归

# -*- coding:UTF-8 -*-
'''
@Author:yzh
@Date:2022/10/31 17:54
'''
import numpy as np
import matplotlib.pyplot as plt


def costFunctionJ(x, y, theta):
    '''代价函数'''
    m = np.size(x, axis=0)
    predictions = x * theta
    sqrErrors = np.multiply((predictions - y), (predictions - y))
    j = 1 / (2 * m) * np.sum(sqrErrors)
    return j


def gradientDescent(x, y, theta, alpha, num_iters):
    '''
    alpha为学习率
    num_iters为迭代次数
    '''
    m = len(y)
    n = len(theta)
    temp = np.mat(np.zeros([n, num_iters]))  # 用来暂存每次迭代更新的theta值,是一个矩阵形式
    j_history = np.mat(np.zeros([num_iters, 1]))  # #记录每次迭代计算的代价值
    for i in range(num_iters):  # 遍历迭代次数
        h = x * theta
        # temp[0,i] = theta[0,0] - (alpha/m)*np.dot(x[:,1].T,(h-y)).sum()
        # temp[1,i] = theta[1,0] - (alpha/m)*np.dot(x[:,1].T,(h-y)).sum()
        temp[:, i] = theta - (alpha / m) * np.dot(x[:, 1].T, (h - y)).sum()
        theta = temp[:, i]
        j_history[i] = costFunctionJ(x, y, theta)
    return theta, j_history, temp


x = np.mat([1, 3, 1, 4, 1, 6, 1, 5, 1, 1, 1, 4, 1, 3, 1, 4, 1, 3.5, 1, 4.5, 1, 2, 1, 5]).reshape(12, 2)
theta = np.mat([0, 2]).reshape(2, 1)
y = np.mat([1, 2, 3, 2.5, 1, 2, 2.2, 3, 1.5, 3, 1, 3]).reshape(12, 1)

# 求代价函数值
j = costFunctionJ(x, y, theta)
# print('代价值:',j)

plt.figure(figsize=(15, 5))
plt.subplot(1, 2, 1)
plt.scatter(np.array(x[:, 1])[:, 0], np.array(y[:, 0])[:, 0], c='r', label='real data')  # 画梯度下降前的图像
plt.plot(np.array(x[:, 1])[:, 0], x * theta, label='test data')
plt.legend(loc='best')
plt.title('before')

theta, j_history, temp = gradientDescent(x, y, theta, 0.01, 100)
print('最终j_history值:\n', j_history[-1])
print('最终theta值:\n', theta)
print('每次迭代的代价值:\n', j_history)
print('theta值更新历史:\n', temp)

plt.subplot(1, 2, 2)
plt.scatter(np.array(x[:, 1])[:, 0], np.array(y[:, 0])[:, 0], c='r', label='real data')  # 画梯度下降后的图像
plt.plot(np.array(x[:, 1])[:, 0], x * theta, label='predict data')
plt.legend(loc='best')
plt.title('after')
plt.show()

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值