我必须使用以下变量获得等高线图,以获得最佳值的范围:
X axis = SiO2/Al2O3
Y axis = Precursor/Aggregate
Z axis = Compressive Strength我的代码如下
import numpy as np
import matplotlib as mlt
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_predict = regressor.predict(X_test)
feature_x = X_test[:, 1]
feature_y = X_test[:, 3]
[X, Y] = np.meshgrid(feature_x, feature_y)
Z = y_predict
ax.contourf(X, Y, Z)
ax.set_title('Filled Contour Plot')
ax.set_xlabel('SiO2/Al2O3')
ax.set_ylabel('Precursor/Aggregate')
plt.show()但是它给出了这个错误
TypeError: Input z must be 2D, not 1D我想我在Z轴输入中犯了一个错误。
这些数据可以在at this link上找到。
预期输出:

发布于 2021-11-06 15:03:51
你的代码将无法工作,你需要为你的预测值创建一个网格,首先我们读取你的数据并进行拟合:
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
regressor = LinearRegression()
regressor.fit(X_train, y_train)然后,您需要为您感兴趣的要素创建栅格:
feature_x = np.linspace(X_test[:, 1].min(),X_test[:, 1].max(),100)
feature_y = np.linspace(X_test[:, 3].min(),X_test[:, 3].max(),100)网格:
dim1, dim2 = np.meshgrid(feature_x, feature_y)现在,您的模型有6个其他预测值需要提供以进行拟合。一种方法是保持这些其他变量的平均值,然后我们在网格网格中开槽:
mesh_df = np.array([X_test.mean(axis=0) for i in range(dim1.size)])
mesh_df[:,1] = dim1.ravel()
mesh_df[:,2] = dim2.ravel()现在预测、重塑和绘制:
Z = regressor.predict(mesh_df).reshape(dim1.shape)
fig, ax = plt.subplots()
ax.contourf(dim1, dim2, Z)
ax.set_title('Filled Contour Plot')
ax.set_xlabel('SiO2/Al2O3')
ax.set_ylabel('Precursor/Aggregate')
plt.show()看起来像这样,因为您使用的是线性回归,这些值将随着您的变量线性增加或减少:

https://stackoverflow.com/questions/69861604
复制相似问题