我必須獲得等高線圖才能使用以下變數獲得一系列最佳值:
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 軸輸入中犯了一個錯誤。
資料可
uj5u.com熱心網友回復:
您的代碼將不起作用,您需要為您的預測值創建一個網格,首先我們讀入您的資料并進行擬合:
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://www.uj5u.com/shujuku/352388.html
標籤:Python 熊猫 matplotlib scikit 学习 回归
