Scipy全局优化中Differential Evolution参数传递报错求助
Let's break down what's causing your error and how to fix it step by step:
1. Root Cause of the Error
Your callback function is calling objective(x) without passing the args parameter (the load value). When the callback runs, objective receives an empty *args, so np.append(x, args) just returns the original 2-element x array. Your ML model expects 3 input parameters, which leads to a shape mismatch when calling MLmodel.predict(x)—hence the broadcast together error.
Additionally, depending on your ML model's input requirements, the 1D array from np.append might need to be reshaped to a 2D array (since most scikit-learn-style models expect inputs in (n_samples, n_features) format).
2. Corrected Code
Here's the fixed version with explanations:
import numpy as np from scipy import optimize def objective(x, *args): # Combine optimized parameters with fixed argument, reshape to match ML model input full_params = np.append(x, args).reshape(1, -1) res = MLmodel.predict(full_params) return res[0] # Extract scalar (predict returns array even for single sample) fun_history = [] x_values = [] load = (50,) # Fixed third parameter (keep as tuple for Scipy's args) def callback(x, convergence): # Pass the fixed args to objective when tracking history fobj = objective(x, *load) x_values.append(x.copy()) # Copy to avoid overwriting by DE's internal array reuse fun_history.append(fobj) bounds = [(5.5,8.8),(29,40)] res = optimize.differential_evolution( objective, bounds, args=load, disp=True, callback=callback )
3. Key Modifications Explained
- Callback Argument Fix: We now pass
*loadtoobjectiveinside the callback, ensuring the fixed third parameter is included when calculating the objective value for history tracking. - Input Reshaping: Added
.reshape(1, -1)to convert the combined 1D parameter array into a 2D array, which aligns with the input format most ML models expect (single sample, 3 features). - Scalar Extraction: Used
return res[0]becausepredicttypically returns an array (even for a single sample), and Differential Evolution requires a scalar objective value to optimize. - Copying x Values: Added
x.copy()when appending tox_values—Differential Evolution reuses and modifies the same array internally, so without copying, your history will show the final x value repeated instead of each iteration's unique values.
4. Quick Additional Checks
If you still run into shape issues:
- Verify your
MLmodel's expected input shape (useMLmodel.n_features_in_if it's a scikit-learn model). - Double-check that
loadis a tuple (even for a single value, like(50,)instead of50—Scipy'sargsparameter requires a tuple input).
内容的提问来源于stack exchange,提问作者chink

