KNN回归 波士顿房价load_boston R方、MSE评价 画图

自用,尽量简洁

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越好)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值