这是我的数据:
[[1.0183786345931547, 1.0299586760768078, 1.038641346963767, 1.0450398412805133, 1.194598528164483], [1.0498980141678536, 1.0740481275807727, 1.101990429736493, 1.1528998376687427, 1.4439775675193383], [1.072406763443829, 1.150808521648661, 1.2306731013044911, 1.3516512408949992, 1.8936625169205694]]
这是情节代码:
J4 = [0.3,0.4,0.5,0.6,0.7]
d = [0.25,0.333333,0.5]
Data = np.array(data).transpose()
x, y = np.meshgrid(d,J4)
fig = plt.figure(figsize=(6,10))
ax = Axes3D(fig)
ax.scatter(x, y, Data, s=40, alpha=1)
ax.set_proj_type('ortho')
plt.tight_layout()
我想拟合一个指数曲面,这样我既可以沿着散点图绘制它,也可以得到曲面的方程。
提供数据集:
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
from sklearn.metrics import r2_score
x = np.array([0.25, 0.333333, 0.5])
y = np.array([0.3, 0.4, 0.5, 0.6, 0.7])
X, Y = np.meshgrid(x, y)
Z = np.array([
[1.0183786345931547, 1.0299586760768078, 1.038641346963767, 1.0450398412805133, 1.194598528164483],
[1.0498980141678536, 1.0740481275807727, 1.101990429736493, 1.1528998376687427, 1.4439775675193383],
[1.072406763443829, 1.150808521648661, 1.2306731013044911, 1.3516512408949992, 1.8936625169205694]
]).T
我们可以假设以下模型:
def model(x, a, b, c):
return a + b * x[0] ** 2 * np.exp(c * x[1])
我们执行回归:
r = np.vstack([
X.ravel(),
Y.ravel()
])
z = Z.ravel()
popt, pcov = optimize.curve_fit(model, r, z)
分数约为:
zhat = model(r, *popt)
score = r2_score(z, zhat) # 0.9746146254532012
对于未知型号来说这还不错。
视觉上,拟合效果如下:
xlin = np.linspace(x.min(), x.max(), 50)
ylin = np.linspace(y.min(), y.max(), 50)
Xlin, Ylin = np.meshgrid(xlin, ylin)
rlin = np.vstack([
Xlin.ravel(),
Ylin.ravel()
])
zlin = model(rlin, *popt)
Zlin = zlin.reshape(Xlin.shape)
fig, axe = plt.subplots(subplot_kw={"projection": "3d"})
axe.scatter(X, Y, Z)
axe.plot_surface(Xlin, Ylin, Zlin, alpha=0.3, cmap="jet")
axe.contour(Xlin, Ylin, Zlin, 10, cmap="jet")