科学计算核心包(Scipy)
1.Scipy的安装
在cmd命令行中输入:
pip install scipy运行结果:
C:\Users\20361>pip install scipy
Collecting scipy
Downloading scipy-1.14.1-cp311-cp311-win_amd64.whl.metadata (60 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 60.8/60.8 kB 463.7 kB/s eta 0:00:00
Requirement already satisfied: numpy<2.3,>=1.23.5 in c:\users\20361\appdata\local\packages\pythonsoftwarefoundation.python.3.11_qbz5n2kfra8p0\localcache\local-packages\python311\site-packages (from scipy) (2.1.3)
Downloading scipy-1.14.1-cp311-cp311-win_amd64.whl (44.8 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 44.8/44.8 MB 10.5 MB/s eta 0:00:00
Installing collected packages: scipy
Successfully installed scipy-1.14.1
2.利用最小二乘法进行直线拟合
需要引入的库函数
import numpy as np
from scipy.optimize import leastsq
已知的训练数据
Xi=np.array([8.19,2.72,6.39,8.71,4.7,2.66,3.78])
Yi=np.array([7.01,2.78,6.47,6.71,4.1,4.23,4.05])
分别定义要拟合的函数形式和误差
def func(p,x):
k,b=p
return k*x+b
def error(p,x,y,s):
print(s)
return func(p,x)-y
随机给出初始值
p0=[100,2]
运用Scipy的leastsq函数估计参数
Para=leastsq(error,p0,args=(Xi,Yi,s))
k,b=Para[0]
print(“k=”,k,’\n’,”b=”,b)
估计结果如下
k = 0.613495346215
b = 1.79409255429
3.利用最小二乘法进行正弦函数的拟合
引入的库函数如下
import numpy as np
from scipy.optimize import leastsq
import pilab as pl
定义的函数和误差如下:
def func(x,p):
A,k,theta=p
return A * np.sin(2np.pi * kx+theta)def residuals(p,y,x):
return y-func(x,p)
训练数据生成如下:
x=np.linspace(0,-2np.pi,100)
A,k,theta=10,0.34,np.pi/6
y0=func(x,[A,k,theta])
y1=y0+2np.random.randn(len(s))
最终训练参数的过程如下:
Para=leastsq(error,p0,args=(Xi,Yi,s))
k,b=Para[0]
最终训练后的参数如下:
真实参数:[10,0.34,0.5235987755982988]
拟合参数:[-9.75643957 0.33910308 3.63048466]
4.非线性方程组求解
f1(u1,u2,u3)=0
f2(u1,u2,u3)=0
f3(u1,u2,u3)=0def func(x):
u1,u2,u3=x
return [f1(u1,u2,u3),f2(u1,u2,u3),f3(u1,u2,u3)]