如何解决运行时警告:在对线性搜索进行建模时在 double_scalars 中遇到溢出
我的代码在这里。我想使用线性搜索获得结果,但我遇到了溢出问题。
import numpy as np
from matplotlib import pyplot as plt
def f(x):
return (x[0] - 1) ** 2 + 2 * (x[0] ** 2 - x[1]) ** 2
# gradient
def dot_f(x):
dx = np.array([8 * (x[0]) ** 3 + 2 * x[0] - 8 * x[0] * x[1] - 2,4 * x[1] - 4 * (x[0]) ** 2])
return dx
# hessian matrix
def ddot_f(x):
return np.array([24 * (x[0]) ** 2 + 2 - 8 * x[1],-8 * x[0]],[-8 * x[0],4])
def fs(x,y):
return (x - 1) ** 2 * 2 + 2 * (x ** 2 - y) ** 2
def exactlinearsearch(ax,epsilon,x0,lr):
xs = [x0]
x = x0
it_times = 0
while (np.linalg.norm(dot_f(x)) > epsilon):
it_times += 1
x = x - dot_f(x) * lr
xs.append(x)
xs = np.array(xs)
n = 1000
x = np.linspace(0,2,n)
y = np.linspace(0,n)
X,Y = np.meshgrid(x,y)
ax.contourf(X,Y,fs(X,Y))
ax.plot(xs[:,0],xs[:,1],color="white")
ax.scatter(xs[:,color="red")
ax.set_title("exact")
tt = "it_time: " + str(it_times)
ax.text(0,tt)
if __name__ == "__main__":
x0 = np.array([0,0])
fig = plt.figure()
ax1 = plt.subplot(1,1,1)
exactlinearsearch(ax1,1e-2,0.5)
plt.show()
当我运行这个程序时,我得到了这个:
RuntimeWarning: overflow encountered in double_scalars
dx = np.array([8* (x[0])**3+2*x[0]-8*x[0]*x[1]-2,4*x[1]-4*(x[0])**2])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。