简体   繁体   English

Python中的梯度下降方法

[英]Method of Gradient Descent in Python

So I'm running a simple algorithm for gradient descent in python, trying to find the minimums of functions. 因此,我在python中运行一个用于梯度下降的简单算法,试图找到函数的最小值。

My code is reasonably straightforward, I feel it is intuitive. 我的代码相当简单明了,我觉得它很直观。 I've tried with the simple example of a second order polynomial. 我尝试了一个二阶多项式的简单示例。

def s(x):
    return x**2

def t(x):
    return 2*x

def steepd(a, alpha, epsilon):
    b = a - alpha*t(a)
    while abs(t(a)) > epsilon:
        if t(b) ==0:
            return b
        else: 
            a = b
            b = a - alpha*t(a)

         return b

   print(steepd(2,0.1,0.001))


x = np.arange(-10,10,0.01)
plt.plot(x,s(x))
plt.show()

I'm not getting anywhere near close to the minimum however, even by varying both alpha and epsilon significantly. 但是,即使通过显着改变alpha和ε,我也无法接近最小值。

Can someone point out what the issue is? 有人可以指出问题所在吗?

Cheers. 干杯。

Your code terminates only if t(a) is within epsilon of zero, so there's no way it would produce a value that violates this constraint unless your indentation is broken (as it is in your question body) and your code really looks like this: 仅当t(a)epsilon零以内时,您的代码才会终止,因此除非您的缩进被破坏(因为它在您的问题正文中)并且您的代码看起来像这样,否则它不会产生违反此约束的值:

def steepd(a, alpha, epsilon):
    b = a - alpha*t(a)
    while abs(t(a)) > epsilon:
        if t(b) ==0:
            return b
        else: 
            a = b
            b = a - alpha*t(a)

        return b

Indentation in Python is important. Python中的缩进很重要。 Here, your while loop never runs more than once because of that return statement at the end and steepd is more or less just a - alpha*t(a) . 在这里,由于结尾处的return语句, while循环永远不会运行超过一次,并且steepd或多或少只是a - alpha*t(a) You'll need to properly indent the return statement for your code to function the way you want. 您需要正确缩进return语句,以使代码以所需的方式运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM