我的SPSA(同步扰动随机逼近优化器)的实现有什么问题?

2024-03-28 16:44:25 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我为多项式x^4-x^2实现SPSA优化的尝试。我重新整理了我的代码只适用于1维,但它似乎根本不起作用。我还认识到,SPSA通常在你没有想要最小化的函数时使用;它来自包含噪声的测量,例如robot运动。可以吗也许我没有使用np.随机.二项式以正确的方式?我使用这个网站的伪代码https://www.jhuapl.edu/SPSA/PDF-SPSA/Matlab-SPSA_Alg.pdf来尝试实现它。对不起,我不习惯用这个代码。请随时提出我可以如何改进它的其他建议。谢谢你的时间。你知道吗

import numpy as np 

def SPSA(alpha,gamma,lowa,A,c,iterations,theta):

dimension=len(theta)

ppar = [1,0, -1, 0, 0]

p = np.poly1d(ppar)

# declare vector function quantities
gradient=np.zeros(dimension)
delta=np.zeros(dimension)
delta=np.random.binomial(3,.4, dimension)
if delta==0:
    print('error delta')
else:
    print('this is our delta')
    print(delta)
# simple for loop implementation as variables iterate
    i=0
    while i<=iterations:
        ak=lowa/np.power(i+1+A,alpha)
        ck=c/np.power(i+1,gamma)
        thetaplus=theta+ck*delta
        thetaminus=theta-ck*delta
        yplus=p(thetaplus)
        yminus=p(thetaminus)
        gradient=yplus-yminus/(2*ck*delta)
        theta=theta-ak*gradient
        print('graident, theta and F(theta)')
        return gradient,theta, p(theta)
        i+=1
        if gradient==0:
            print('gradient is zero')`

Tags: 代码alphaasnpplusckdeltaprint
1条回答
网友
1楼 · 发布于 2024-03-28 16:44:25

I recgonize my code only works for 1 dimension, but it seems to not be working at all.

原因一定是无条件的return gradient,theta, p(theta),它总是在第一次迭代中存在。也许你更想在这里写print(…),在函数末尾写return …。你知道吗

相关问题 更多 >