python - RuntimeWarning:在建模线性搜索时在 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, 2, 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[:, 0], xs[:, 1], color="red")
ax.set_title("exact")
tt = "it_time: " + str(it_times)
ax.text(0, 0, tt)
if __name__ == "__main__":
x0 = np.array([0, 0])
fig = plt.figure()
ax1 = plt.subplot(1, 1, 1)
exactlinearsearch(ax1, 1e-2, x0, 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])
解决方案
推荐阅读
- apache - Apache ProxyPass 用于从 blog 开始的所有 url
- android - 为什么当我尝试存储状态时对象不需要添加@Parcelize?
- javascript - 在 vue-chartJS 中更改图例的位置
- php - odbc_exec():SQL 错误:[Microsoft][ODBC Microsoft Access Driver] 查询表达式中的语法错误(缺少运算符)
- azure - 使用 Azure AD 验证签名
- excel - VBA 导入变量库数据集 ILLUSTRATOR
- java - “org.eclipse.jdt.launching.IVMInstall.getLibraryLocations()”问题
- javascript - 如何在 React 组件中添加版权符号?
- html - 为什么提交按钮的宽度小于其他输入字段的宽度?
- python - 在 M1 上有 x86_64 和 ARM python 版本