拟合曲面与根据相同数据生成的热图不同

问题描述 投票:0回答:1

我有一些 z 值跨越 x 和 z 值的网格。 z 值可以描述为 x-y 平面上的热图(左子图)。现在我想将表面拟合到热图中显示的相同数据。然而,拟合曲面(右侧子图)看起来根本不像热图。我在这里做错了什么?

这是代码:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

x_values = np.linspace(0.001, 0.38024, 10)
y_values = np.linspace(1, 10, 10)
z_values = [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
            [0.0046, 0.0003, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
            [0.0128, 0.0029, 0.0009, 0.0006, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
            [0.0049, 0.0157, 0.0067, 0.0003, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
            [0.0203, 0.0096, 0.0055, 0.0096, 0.0012, 0.0023, 0.0000, 0.0000, 0.0000, 0.0000],
            [0.0229, 0.0191, 0.0020, 0.0073, 0.0055, 0.0026, 0.0022, 0.0000, 0.0000, 0.0000],
            [0.0218, 0.0357, 0.0035, 0.0133, 0.0073, 0.0145, 0.0000, 0.0029, 0.0000, 0.0000],
            [0.0261, 0.0232, 0.0365, 0.0200, 0.0212, 0.0107, 0.0036, 0.0007, 0.0022, 0.0007],
            [0.0305, 0.0244, 0.0284, 0.0786, 0.0226, 0.0160, 0.0000, 0.0196, 0.0007, 0.0007],
            [0.0171, 0.0189, 0.0598, 0.0215, 0.0218, 0.0464, 0.0399, 0.0051, 0.0000, 0.0000]]
z_values = np.array(z_values)

x_grid, y_grid = np.meshgrid(x_values, y_values)

fig = plt.figure(figsize=(12, 5))

ax1 = fig.add_subplot(121)
contour1 = ax1.contourf(x_grid, y_grid, np.log(z_values.T + 1))
fig.colorbar(contour1, ax=ax1)
ax1.set_xlabel('x values')
ax1.set_ylabel('y values')

x_flat = x_grid.flatten()
y_flat = y_grid.flatten()
z_flat = z_values.flatten()

degree = 4
poly_features = PolynomialFeatures(degree=degree)
X_poly = poly_features.fit_transform(np.column_stack((x_flat, y_flat)))

model = LinearRegression()
model.fit(X_poly, z_flat)

z_pred = model.predict(X_poly)
z_pred_grid = z_pred.reshape(x_grid.shape)

ax2 = fig.add_subplot(122, projection='3d')
ax2.plot_surface(x_grid, y_grid, z_pred_grid, cmap='viridis')
ax2.set_xlabel('x values')
ax2.set_ylabel('y values')
ax2.set_zlabel('z values')

plt.show()

这是图:

python matplotlib linear-regression heatmap surface
1个回答
0
投票

好的,我想已经解决了。

应用“mesh_grid”命令后,

z_values
的布局对应于以下内容(如果您想查看,请打印
x_grid
y_grid
z_values
):

    x ------->
 y
 |   [        ]
 |   [z_values]
\|/  [        ]

您的多边形拟合图形与此相对应,但您的热图则不然。我认为这是因为你在热图中调换了 z 。

只需更改(删除

.T

contour1 = ax1.contourf(x_grid, y_grid, np.log(z_values.T + 1))

contour1 = ax1.contourf(x_grid, y_grid, np.log(z_values + 1))

那么至少你会收到信件:

© www.soinside.com 2019 - 2024. All rights reserved.