下面是我为多项式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')`
原因一定是无条件的
return gradient,theta, p(theta)
,它总是在第一次迭代中存在。也许你更想在这里写print(…)
,在函数末尾写return …
。你知道吗相关问题 更多 >
编程相关推荐