knn回归预测波士顿房价代码实现
时间: 2024-10-12 07:02:52 浏览: 32
KNN (K-Nearest Neighbors) 回归是一种基于实例的学习方法,常用于预测连续数值,如波士顿房价预测。在Python中,我们可以使用scikit-learn库中的`KNeighborsRegressor`类来实现。下面是一个简单的例子:
```python
# 导入所需库
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsRegressor
import pandas as pd
# 加载波士顿房价数据集
boston = load_boston()
X = boston.data
y = boston.target
# 数据预处理:标准化数值特征
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 创建KNN回归模型
knn = KNeighborsRegressor(n_neighbors=5) # 设定邻居数
# 训练模型
knn.fit(X_train, y_train)
# 进行预测
predictions = knn.predict(X_test)
# 打印预测结果
print("Predicted prices:", predictions)
#
阅读全文