Skip to content

梯度下降

🕒 Published at:

利用梯度下降法求函数最小值

import numpy as np

def numerical_gradient(f,x):
    h = 1e-4
    grad = np.zeros_like(x)

    for idx in range(x.size):
        tmp_val = x[idx]
        x[idx] = tmp_val + h
        fxh1 = f(x)

        x[idx] = tmp_val - h
        fxh2 = f(x)

        grad[idx] = (fxh1 - fxh2) / (2*h)
        x[idx] = tmp_val
    return grad

def gradient_descent(f,init_x,lr=0.01,step_num=100):
    x = init_x

    for i in range(step_num):
        grad = numerical_gradient(f,x)
        x -= lr*grad

    return x

def function_2(x):
    return x[0]**2 + x[1]**2

init_x = np.array([-3.0,4.0])
print(gradient_descent(function_2,init_x,lr=0.1,step_num=100))
神经网络的学习步骤

1.mini_batch 从训练数据中随机选出一部分数据 2.计算梯度,为了减小mini_batch损失函数的值,需要求出各个权重参数的梯度,梯度表示损失函数值减小最多的方向 3.更新参数,将权重参数沿梯度方向进行微小的更新 4.重复步骤1、2、3

随机梯度下降法(stochastic gradient descent)SGD