Python 中残差与预测值的残差图

ni7*_*ni7 8 python machine-learning scikit-learn data-science

我运行了一个 KNN 模型。现在我想绘制残差与预测值图。来自不同网站的每个示例都表明我必须首先运行线性回归模型。但我不明白该怎么做。有人可以帮忙吗?提前致谢。这是我的模型-

train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))])
x_train = train.iloc[:,[2,5]].values
y_train = train.iloc[:,4].values
x_validate = validate.iloc[:,[2,5]].values
y_validate = validate.iloc[:,4].values
x_test = test.iloc[:,[2,5]].values
y_test = test.iloc[:,4].values
clf=neighbors.KNeighborsRegressor(n_neighbors = 6)
clf.fit(x_train, y_train)
y_pred = clf.predict(x_validate)
Run Code Online (Sandbox Code Playgroud)

小智 6

残差只不过是预测值与实际值的差异程度。因此,它的计算方式为实际值-预测值。在你的情况下,它是残差= y_test-y_pred。现在对于情节,只需使用这个;

import matplotlib.pyplot as plt

plt.scatter(residuals,y_pred)

plt.show()
Run Code Online (Sandbox Code Playgroud)