我想为一个包含多个特征的预测创建一个等高线图。剩余的值应该被固定,以便绘制两个感兴趣的值。不幸的是,结果矩阵在所有位置上的值都相同,而不是预期的值。
我认为我的矩阵有问题,但我找不到错误。
[...]f_learn = [x_1,x_2,x_3,x_4]r_lear = [r_1]clf = svm.MLPRegressor(...)clf.fit(f_learn,r_learn)[...]x_1 = np.linspace(1, 100, 100)x_2 = np.linspace(1, 100, 100)X_1, X_2 = np.meshgrid(x_1, x_2)x_3 = np.full( (100,100), 5).ravel()x_4 = np.full( (100,100), 15).ravel()predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3,x_4])prediction = clf.predict(predict_matrix.T)prediction_plot = prediction.reshape(X_1.shape)plt.figure() cp = plt.contourf(X_1, X_2, prediction_plot, 10) plt.colorbar(cp) plt.show()
如果我手动逐行测试矩阵,我会得到正确的结果。然而,如果我这样将它们组合起来,就不起作用了。
编辑:代码复制时出错
带有数据的示例。所有答案都是7.5,而不是不同的值;(
import matplotlib.pyplot as pltimport numpy as npfrom sklearn import linear_modelf_learn = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])r_learn = np.array([6,7,8,9])reg = linear_model.LinearRegression()reg.fit (f_learn, r_learn)x_1 = np.linspace(0, 20, 10)x_2 = np.linspace(0, 20, 10)X_1, X_2 = np.meshgrid(x_1, x_2)x_3 = np.full( (10,10), 5).ravel()x_4 = np.full( (10,10), 2).ravel()predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3, x_4])prediction = reg.predict(predict_matrix.T)prediction_plot = prediction.reshape(X_1.shape)plt.figure()cp = plt.contourf(X_1, X_2, prediction_plot, 10)plt.colorbar(cp)plt.show()
回答:
在你的示例数据中,有4个例子具有相同特征值但不同的标签。LinearRegression无法从中学到任何东西。你可以通过以下方式检查它:
>>> reg.coef_[0. 0. 0. 0.]
也许在你的真实数据中也是如此,即特征x_1, x_2并不重要。检查reg.coef_
,看是否有x_1, x_2特征的数值过小的情况。
我更改了示例数据,图表现在可以正常工作了。
import matplotlib.pyplot as pltimport numpy as npfrom sklearn import linear_model# f_learn = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])# r_learn = np.array([6,7,8,9])f_learn = np.arange(20.).reshape(5, 4)f_learn += np.random.randn(5, 4)r_learn = f_learn[:, 0] + 2 * f_learn[:, 1] + 3 * f_learn[:, 2] + 4 * f_learn[:, 3]reg = linear_model.LinearRegression()reg.fit(f_learn, r_learn)print(reg.coef_)x_1 = np.linspace(0, 20, 10)x_2 = np.linspace(0, 20, 10)X_1, X_2 = np.meshgrid(x_1, x_2)x_3 = np.full( (10,10), 5).ravel()x_4 = np.full( (10,10), 2).ravel()predict_matrix = np.vstack([X_1.ravel(), X_2.ravel(), x_3, x_4])prediction = reg.predict(predict_matrix.T)prediction_plot = prediction.reshape(X_1.shape)plt.figure()cp = plt.contourf(X_1, X_2, prediction_plot, 10)plt.colorbar(cp)plt.show()