首页 > 解决方案 > 为什么我在 python 上实现梯度下降产生输出这么慢?

问题描述

为什么每次连续迭代时代码的输出都会变慢?

我想编写一个工作代码,在同一函数上实现梯度下降法和牛顿法,我想比较这两种方法的速度和迭代以得出近似解。

此代码片段仅适用于梯度下降,并且每次迭代的输出似乎都会变慢。所以我得到前 10 个输出相对较快,之后每个输出至少需要 5-6 秒或更长时间。

#A python program to approximate a root of a polynomial
#using the newton-raphson method
import math
#f(x) - the function of the polynomial
h = 0.000001

def f(x):
    function = (x*x*x) - (2*x) - 1
    return function

def derivative(h,x): #function to find the derivative of the polynomial
    derivative = (f(x + h) - f(x)) / h
    return derivative

def GD(h,x):
    return (x - h*derivative(h,x))

# p - the initial point i.e. a value closer to the root

# n - number of iterations 

def iterate(p, n): #
    x = 0
    for i in range(n):
        if i == 0: #calculate first approximation
            x = GD(h,p)
        else:
            x = GD(h,iterate(x, n)) #iterate the first and subsequent approximations
        n=n-1
    return x

for i in range(100):
    print (iterate(1, i)) #print the root of the polynomial x^3 - 2x - 1 using 3 iterations and taking initial point as 1

我不知道它是由于代码还是梯度下降而发生的。

标签: pythongradient-descent

解决方案


推荐阅读