一维梯度下降算法

2019-08-20  本文已影响0人  光头披风侠

一维梯度下降算法

import sympy as sy
import matplotlib.pyplot as plt
import numpy as np

def Gradient_descent(x0):
    w = 1e-8
    delta = 0.01
    x = sy.symbols('x')
    f = x**4 + 13 * x**3 + 35 * x**2 - 85 * x
y_index = np.arange(-8, 3, 0.01)
y = []
for i in y_index:
    y.append(f.subs(x, i))
plt.plot(y_index, y)
plt.show()
delta_f = sy.diff(f, x, 1)
f_start = f.subs(x, x0)
t = x0
while True:
    f_end = f_start
    t += -delta * delta_f.subs(x, t)
    f_start = f.subs(x, t)
    if(abs(f_end - f_start) < w):
        break
print(f_start, f_end, t)
if __name__ == '__main__':
    Gradient_descent(-6)
上一篇下一篇

猜你喜欢

热点阅读