python最小二乘法拟合曲面
时间: 2023-08-28 08:06:21 浏览: 276
Python中可以通过scipy库中的optimize函数来实现最小二乘法拟合曲面。具体步骤如下:
1. 导入必要的库
```
import numpy as np
from scipy.optimize import curve_fit
```
2. 定义拟合函数,这里以二次函数为例
```
def func(x, y, a, b, c):
return a * x**2 + b * y**2 + c
```
3. 生成样本数据
```
# 生成10个点的x、y、z数据
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
z = np.array([2.1, 4.3, 6.7, 8.5, 10.3, 12.1, 14.5, 16.7, 18.1, 20.5])
```
4. 调用curve_fit函数进行拟合
```
# 调用curve_fit函数进行拟合
popt, pcov = curve_fit(func, (x, y), z)
# 输出拟合参数
print(popt)
```
5. 绘制拟合曲面
```
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
# 生成网格点
X, Y = np.meshgrid(x, y)
# 计算拟合曲面上的z值
Z = func(X, Y, *popt)
# 绘制拟合曲面
ax.plot_surface(X, Y, Z)
plt.show()
```
完整代码如下:
```
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 定义拟合函数
def func(x, y, a, b, c):
return a * x**2 + b * y**2 + c
# 生成样本数据
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
z = np.array([2.1, 4.3, 6.7, 8.5, 10.3, 12.1, 14.5, 16.7, 18.1, 20.5])
# 调用curve_fit函数进行拟合
popt, pcov = curve_fit(func, (x, y), z)
# 输出拟合参数
print(popt)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
# 生成网格点
X, Y = np.meshgrid(x, y)
# 计算拟合曲面上的z值
Z = func(X, Y, *popt)
# 绘制拟合曲面
ax.plot_surface(X, Y, Z)
plt.show()
```
阅读全文