python最小二乘函数leastsq拟合数据以及root求解方程组
1. leastsq
需求将下面这些点分布拟合,找到相似的函数,使用sigmoid变换来拟合1 - a / (1 + np.exp(b*x + c))
2. root求解方程组
import numpy as np
from scipy.optimize import leastsq
X = np.array([0, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1])
Y = np.array([1, 0.9, 0.7, 0.5, 0.3, 0.2, 0.1, 0.07, 0.05, 0.03, 0.01, 0.009,0.007, 0.005,0.003, 0.001, 0.0009, 0.0007, 0.0005, 0])
def func(p, x):
a, b, c = p
return 1 - a / (1 + np.exp(b*x + c))
def error(p, x, y):
return func(p, x) - y # x、y都是列表,故返回值也是个列表
p = [1, 2, 1]
Para = leastsq(error, p, args=(X, Y)) # 把error函数中除了p以外的参数打包到args中
a, b, c = Para[0]
print("a=", a, b, c)
plt.figure(figsize=(8, 6))
plt.scatter(X, Y, color="red", label="Sample Point", linewidth=3) # 画样本点
x = np.linspace(0, 1, 100)
y = 1 - a / (1 + np.exp(b*x + c))
plt.plot(x, y, color="orange", label="Fitting Curve", linewidth=2) # 画拟合曲线
plt.legend()
plt.show()
from scipy.optimize import root
## 1、求解f(x)=2*sin(x)-x+1
def fun(x):
return 2 * np.sin(x) - x + 1
res = root(fun, 1)
print(res.x) # [2.38006127]
## 3、求解非线性方程组
def f3(p):
x, y, z = p
return np.array([2 * x ** 2 + 3 * y - 3 * z ** 3 - 7,
x + 4 * y ** 2 + 8 * z - 10,
x - 2 * y ** 3 - 2 * z ** 2 + 1])
sol3_root = root(f3, [0, 0, 0])
print(sol3_root)
print(sol3_root.x) # [1.52964909 0.973546 0.58489796]