优化问题无图表输出且gp_minimize报错的技术求助
牛顿法与高斯过程优化代码问题:图表生成失败及维度错误
我编写了一段集成**牛顿法(Newton's Method)和高斯过程优化(Gaussian Process)**的Python代码,运行后无法生成图表,多次修改仍会触发两类错误。以下是完整代码及错误信息:
import numpy as np from scipy.linalg import solve, cholesky from scipy.optimize import minimize from skopt import gp_minimize import matplotlib.pyplot as plt def gaussian_rbf(x, x_prime, beta): return np.exp(-beta * np.linalg.norm(x - x_prime)**2) def construct_interpolation_matrix(nodes, beta): N = len(nodes) K = np.zeros((N, N)) for i in range(N): for j in range(N): K[i, j] = gaussian_rbf(nodes[i], nodes[j], beta) return K def conditioning_analysis(N, m, beta): nodes = np.linspace(0, 1, N) K = construct_interpolation_matrix(nodes, beta) selected_indices = np.random.choice(N, m, replace=False) selected_nodes = nodes[selected_indices] condition_full = np.linalg.cond(K) condition_partial = np.linalg.cond(K[selected_indices][:, selected_indices]) return condition_full, condition_partial def objective_function(x): x_scalar = np.atleast_1d(x)[0] return -(x_scalar**2 + np.sin(5 * x_scalar)) def gradient_hessian(x): df_dx = 2 * x * np.exp(-(1 - x)**2) - 4 * x * (1 - x) * np.exp(-(1 - x)**2) d2f_dx2 = -2 * np.exp(-(1 - x)**2) + 4 * x * (1 - x) * np.exp(-(1 - x)**2) - 4 * (1 - x) * np.exp(-(1 - x)**2) return df_dx, d2f_dx2 def optimize_with_newton(initial_guess, max_iter=10): x_opt = initial_guess for _ in range(max_iter): df_dx, d2f_dx2 = gradient_hessian(x_opt) x_opt = x_opt - df_dx / d2f_dx2 return x_opt def gaussian_process_optimization(initial_points, objective_function, bounds, n_iter=10): def objective_function_gp(X): return np.array([objective_function(x) for x in X]) result = gp_minimize(objective_function_gp, bounds, acq_func="LCB", n_calls=n_iter + 1, random_state=42, x0=initial_points) return result.x[0] # Task 1: Analyze conditioning N = 10 m = 5 beta = 1.0 condition_full, condition_partial = conditioning_analysis(N, m, beta) print(f"Conditioning for full matrix: {condition_full}") print(f"Conditioning for partial matrix: {condition_partial}") # Optimize with Newton's method initial_guess_newton = 0.5 x_opt_newton = optimize_with_newton(initial_guess_newton) print(f"Optimal solution with Newton's method: {x_opt_newton}") # Gaussian process optimization initial_points_gp = np.random.rand(5) bounds_gp = [(0.0, 1.0)] x_opt_gp = gaussian_process_optimization(initial_points_gp, objective_function, bounds_gp, n_iter=10) print(f"Optimal solution with Gaussian process optimization: {x_opt_gp}") # Compare methods x_values = np.linspace(0, 1, 1000) y_true = objective_function(x_values) plt.plot(x_values, y_true, label="True Function") plt.scatter(x_opt_newton, objective_function(x_opt_newton), color="red", label="Newton's Method") plt.scatter(x_opt_gp, objective_function(x_opt_gp), color="green", label="Gaussian Process") plt.legend() plt.xlabel("x") plt.ylabel("f(x)") plt.title("Comparison of Optimization Methods") plt.show()
错误类型1(频繁出现)
result = gp_minimize(objective_function_gp, bounds, acq_func="LCB", n_calls=n_iter + 1, random_state=42, x0=initial_points) File ~\anaconda3\Lib\site-packages\skopt\optimizer\gp.py:259 in gp_minimize return base_minimize( File ~\anaconda3\Lib\site-packages\skopt\optimizer\base.py:266 in base_minimize raise RuntimeError("Optimization space (%s) and initial points in x0 " RuntimeError: Optimization space (Space([Real(low=0.0, high=1.0, prior='uniform', transform='normalize')])) and initial points in x0 use inconsistent dimensions.
错误类型2(调整后偶发)
File ~\anaconda3\Lib\site-packages\skopt\optimizer\gp.py:259 in gp_minimize return base_minimize( File ~\anaconda3\Lib\site-packages\skopt\optimizer\base.py:291 in base_minimize result = optimizer.tell(x0, y0) File ~\anaconda3\Lib\site-packages\skopt\optimizer\optimizer.py:482 in tell check_x_in_space(x, self.space) File ~\anaconda3\Lib\site-packages\skopt\utils.py:187 in check_x_in_space if not np.all([p in space for p in x]): File ~\anaconda3\Lib\site-packages\skopt\utils.py:187 in <listcomp> if not np.all([p in space for p in x]): File ~\anaconda3\Lib\site-packages\skopt\space\space.py:1035 in __contains__ if component not in dim: File ~\anaconda3\Lib\site-packages\skopt\space\space.py:364 in __contains__ return self.low <= point <= self.high ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
编辑补充
调整代码后成功生成图表,但仅能看到牛顿法的结果,高斯过程的结果未显示。调整后的图表代码如下:
x_values = np.linspace(0, 1, 1000) y_true = [objective_function(x) for x in x_values] plt.plot(x_values, y_true, label="True Function") plt.scatter(x_opt_newton, objective_function(x_opt_newton), color="red", label="Newton's Method") plt.scatter(x_opt_gp, objective_function(x_opt_gp), color="green", label="Gaussian Process") plt.legend() plt.xlabel("x") plt.ylabel("f(x)") plt.title("Comparison of Optimization Methods") plt.show()
内容的提问来源于stack exchange,提问作者Kurapika
相关产品推荐
相关产品推荐

