自用,尽量简洁
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.datasets import load_diabetes,load_boston
from sklearn.metrics import r2_score,mean_squared_error
boston = load_boston()
x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=10)
model1 = KNeighborsRegressor(n_neighbors=3)
model2 = KNeighborsRegressor(n_neighbors=7)
model1.fit(x_train, y_train)
model2.fit(x_train, y_train)
print("mse_score1:", mean_squared_error(y_test, model1.predict(x_test)))
print("mse_score2:", mean_squared_error(y_test, model2.predict(x_test)))
print("\n")
y_pred1 = model1.predict(x_test)
y_pred2 = model2.predict(x_test)
print("R方1:", r2_score(y_test, y_pred1))
print("R方2:", r2_score(y_test, y_pred2))
plt.plot(y_test, label='True')
plt.plot(y_pred1, 'r:', label='model1') # color="red" marker=":"
plt.plot(y_pred2, 'g:', label='model2') # color="green" marker=":"
plt.legend()
plt.show()
mse_score1: 55.290610021786485
mse_score2: 62.2832693077231
R方1: 0.4713117497116385
R方2: 0.4044480127898038
(mse越小越好,R方越接近1越好)