# SciPy优化optimize模块用法

• 全局优化例程(brute-force蛮力, anneal(), basinhopping())
• 最小二乘最小化算法(leastsq()和curve fit())
• 标量单变量函数最小化器(minimizer_scalar()和根查找器newton())

``````import numpy as np
import scipy
from scipy.optimize import minimize
#define function f(x)
def f(x):
return .2*(1 - x[0])**2

``````final_simplex: (array([[ 1.        , -1.27109375], [ 1.        , -1.27118835], [ 1.        , -1.27113762]]), array([0., 0., 0.]))
fun: 0.0
message: 'Optimization terminated successfully.'
nfev: 147
nit: 69
status: 0
success: True
x: array([ 1.        , -1.27109375])``````

### 最小二乘最小化

``````from scipy.optimize import least_squares
import numpy as np
input = np.array([2, 2])
def rosenbrock(x):
return np.array([10 * (x[1] - x[0]**3), (1 - x[0])])
res = least_squares(rosenbrock, input)
print(res)``````

``````active_mask: array([0., 0.])
cost: 0.0
fun: array([0., 0.])
jac: array([[-30.00000045, 10.        ], [ -1.        , 0.        ]])
message: '`gtol` termination condition is satisfied.'
nfev: 4
njev: 4
optimality: 0.0
status: 1
success: True
x: array([1., 1.])``````

### 寻根

• 标量函数

• 方程组

root()函数用于查找非线性方程的根。 MINPACK提供了多种方法, 例如hybr(默认)和Levenberg-Marquardt方法。

x2 + 3cos(x)= 0

``````import numpy as np
from scipy.optimize import root
def func(x):
return x*2 +  3* np.cos(x)
a = root(func, 0.3)
print(a)``````

``````fjac: array([[-1.]])
fun: array([2.22044605e-16])
message: 'The solution converged.'
nfev: 10
qtf: array([-1.19788401e-10])
r: array([-4.37742564])
status: 1
success: True
x: array([-0.91485648])``````

### 优化曲线拟合

``````import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
x = np.linspace(0, 10, num = 40)
# The coefficients are much bigger.
y = 10.35 * np.sin(5.330 * x) + np.random.normal(size = 40)
def test(x, a, b):
return a * np.sin(b * x)
param, param_cov = curve_fit(test, x, y)
print("Sine funcion coefficients:")
print(param)
print("Covariance of coefficients:")
print(param_cov)
ans = (param[0]*(np.sin(param[1]*x)))
plt.plot(x, y, 'o', color ='red', label ="data")
plt.plot(x, ans, '--', color ='blue', label ="optimized data")
plt.legend()
plt.show()``````

``````Sine funcion coefficients:
[-0.42111847  1.03945217]
Covariance of coefficients:
[[3.03920718 0.05918002]
[0.05918002 0.43566354]]``````

### SciPy幻想

scipy.optimize库提供了fsolve()函数, 该函数用于查找函数的根。给定初始估计值, 它将返回fun(x)= 0定义的方程式的根。

``````import numpy as np
from scipy.optimize import fsolve
sqrt = np.emath.sqrt
a = 132712000000
T = 365.35 * 86337 * 2 / 3
e = 580.2392124070273
def f(x):
return np.abs((T * a ** 2 / (2 * np.pi)) ** (1 / 3) * sqrt(1 - x ** 2)
- sqrt(.5 * a ** 2 / e * (1 - x ** 2)))
x = fsolve(f, 0.01)
x, f(x)``````

``(array([1.]), array([82.17252895]))``