python实现梯度下降法

# coding:utf-8
import numpy as np 
import matplotlib.pyplot as plt
x = np.arange(-5/2,5/2,0.01)
y = -x**3+x**2+np.e+x**4

dy = lambda x:-3*x**2+2*x+4*x**3
dyy = lambda x:-6*x+2+12*x**2

a = 0.001
def sgd_func(n):
    x0=-10
    ady = []
    for i in range(n):
        # x0 = x0 -a*dy(x0)
        x0 = x0 - dy(x0)/dyy(x0)
        ady.append(x0)
    return x0,ady

x0,ady = sgd_func(10)

y0 = x0**2+x0+np.e
plt.subplot(1,2,1)
plt.plot(ady)
plt.subplot(1,2,2)
plt.plot(x,y)
plt.text(x0,y0,'* min_value')
plt.show()

原文地址:https://www.cnblogs.com/wuzaipei/p/10085626.html