基于SciPy库的非线性优化实例

import scipy.optimize as sp
import numpy as np

#设置自变量的约束
bounds = [[-10.0, 5], [-3.0, 4.0]]
#设置初值
x_0 = [1.0, 1.0]


#定义目标函数
def objective_function(x):
    return x[0] ** 2 + 4 * x[0] * x[1]

#定义目标函数的导数,如果是矩阵的话,就是对应的雅克比矩阵
def objective_jacobian(x):
    return np.array([2 * x[0] + 4 * x[1], 4 * x[0]])

#求解
result = sp.minimize(objective_function, x_0, method='L-BFGS-B', jac=objective_jacobian, bounds=bounds,
                     options={'disp': True})

print(result.x)

你可能感兴趣的:(基于SciPy库的非线性优化实例)