阅读背景:

函数的随机梯度下降(固定函数与自定义函数随机梯度下降)

来源:互联网 

1. 基于python实现随机梯度下降

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    """构造函数"""
    #print("calculating f(x) {}".format(x))
    return 0.19 * x*x*x - 1.2 * (x*x) - 6 * x + 2.76
    
def g(x):
    """导数"""
    return 0.57 * x * x - 2.4 * x - 6
    
def autoGD(init_x, lr, thresh, epoch):
    x = init_x
    draw_x,draw_y = [],[]
    for i in range(epoch):
        grad = g(x)
        x = x - lr * grad
        print("Epoch {}: x={:.5f} grad={} y={}".format(i,x,grad,f(x)))
        if i % 200 == 0:
            draw_x.append(x)
            draw_y.append(f(x))
        if abs(grad) < thresh:
            break
    return draw_x,draw_yimport matplotlib.pyplot 



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: