KNN算法学习实践
1.理论学习
原文链接
ShowMeAI知识社区
2.案例实践
假如一套房子打算出租,但不知道市场价格,可以根据房子的规格(面积、房间数量、厕所数量、容纳人数等),在已有数据集中查找相似(K近邻)规格的房子价格,看别人的相同或相似户型租了多少钱。
我们本次用到的数据集是 rent_price,见附件或第一章链接网盘地址下载。
2.1分类过程
已知的数据集中,每个已出租住房都有房间数量、厕所数量、容纳人数等字段,并有对应出租价格。将预计出租房子数据与数据集中每条记录比较计算欧式距离,取出距离最小的5条记录,将其价格取平均值,可以将其看做预计出租房子的市场平均价格。
先引入需要的包
import pandas as pd
import numpy as np
from scipy.spatial import distance#用于计算欧式距离
from sklearn.preprocessing import StandardScaler#用于对数据进行标准化操作
from sklearn.neighbors import KNeighborsRegressor#KNN算法
from sklearn.metrics import mean_squared_error#用于计算均方根误差
导入数据并提取目标字段,我们看一下dc_listings数据集。
#导入数据并提取目标字段
path = r'rent_price.csv'
file = open(path, encoding = 'gb18030', errors = 'ignore')
dc_listings = pd.read_csv(file)
features = ['accommodates','bedrooms','bathrooms','beds','price','minimum_nights','maximum_nights','number_of_reviews']
dc_listings = dc_listings[features]
2.2进行初步数据清洗
1.数据集中非数值类型的字段需要转换,替换掉美元$符号和千分位符号逗号。
#数据初步清洗
our_acc_value = 3
dc_listings['distance'] = np.abs(dc_listings.accommodates - our_acc_value)
dc_listings = dc_listings.sample(frac=1, random_state=0)
dc_listings = dc_listings.sort_values('distance')
dc_listings['price'] = dc_listings.price.str.replace("\$|,", "").astype(float)
dc_listings = dc_listings.dropna()
2.理想情况下,数据集中每个字段取值范围都相同,但实际上这是几乎不可能的,如果计算时直接用原数据计算,则会造成较大训练误差,所以需要对各列数据进行标准化或归一化操作,尽量减少不必要的训练误差。
#数据标准化
dc_listings[features] = StandardScaler().fit_transform(dc_listings[features])
normalized_listings = dc_listings
3.最好不要将所有数据全部拿来测试,需要分出训练集和测试集具体划分比例按数据集确定。
#取得训练集和测试集
norm_train_df = normalized_listings[:2792]
norm_test_df = normalized_listings[2792:]
2.3计算欧氏距离并预测房屋价格
#scipy包distance模块计算欧式距离
first_listings = normalized_listings.iloc[0][['accommodates', 'bathrooms']]
fifth_listings = normalized_listings.iloc[20][['accommodates', 'bathrooms']]
#用python方法做多变量KNN模型
def predict_price_multivariate(new_listing_value, feature_columns):
temp_df = norm_train_df
#distance.cdist计算两个集合的距离
temp_df['distance'] = distance.cdist(temp_df[feature_columns], [new_listing_value[feature_columns]])
temp_df = temp_df.sort_values('distance')#temp_df按distance排序
knn_5 = temp_df.price.iloc[:5]
predicted_price = knn_5.mean()
return predicted_price
cols = ['accommodates', 'bathrooms']
norm_test_df['predicted_price'] = norm_test_df[cols].apply(predict_price_multivariate, feature_columns=cols, axis=1)
norm_test_df['squared_error'] = (norm_test_df['predicted_price'] - norm_test_df['price']) ** 2
mse = norm_test_df['squared_error'].mean()
rmse = mse ** (1/2)
print(rmse)
#利用sklearn完成KNN
col = ['accommodates', 'bedrooms']
knn = KNeighborsRegressor()
#将自变量和因变量放入模型训练,并用测试数据测试
knn.fit(norm_train_df[cols], norm_train_df['price'])
two_features_predictions = knn.predict(norm_test_df[cols])
#计算预测值与实际值的均方根误差
two_features_mse = mean_squared_error(norm_test_df['price'], two_features_predictions)
two_features_rmse = two_features_mse ** (1/2)
print(two_features_rmse)
输出为:
1.4667825805653032
1.5356457412450537
2.3全部代码
import math
import pandas as pd
import numpy as np
from scipy.spatial import distance # 用于计算欧氏距离
from sklearn.preprocessing import StandardScaler # 用于对数据进行标准化操作
from sklearn.neighbors import KNeighborsRegressor # KNN算法
from sklearn.metrics import mean_squared_error # 用于计算均方根误差
#导入数据并提取目标字段
path = r'E:\DeepLearn\KNN\rent_price.csv'
file = open(path, encoding='gb18030', errors='ignore')
dc_listings = pd.read_csv(file)
features = ['accommodates','bedrooms','bathrooms','beds','price','minimum_nights','maximum_nights','number_of_reviews']
dc_listings = dc_listings[features]
#数据初步清洗
# 数据集中非数值类型的字段需要转换,替换掉美元$符号和千分位逗号。
our_acc_value = 3
dc_listings['distance'] = np.abs(dc_listings.accommodates - our_acc_value)
dc_listings = dc_listings.sample(frac = 1, random_state = 0)
dc_listings = dc_listings.sort_values('distance')
dc_listings['price'] = dc_listings.price.str.replace('\$|,','').astype(float)
dc_listings = dc_listings.dropna()
# 数据标准化
dc_listings[features] = StandardScaler().fit_transform(dc_listings[features])
normalized_listings = dc_listings
# 取得训练集和测试集
norm_train_df = normalized_listings[: 2792]
norm_test_df = normalized_listings[2792:]
# 计算欧氏距离并预测房屋价格
# scipy包distance模块计算欧氏距离
first_listings = normalized_listings.iloc[0][['accommodates', 'bathrooms']]
fifth_listings = normalized_listings.iloc[20][['accommodates', 'bathrooms']]
# 用python方法做多变量KNN模型
def predict_price_multivariate(new_listings_value, feature_columns):
temp_df = norm_train_df
# distance.cdist计算两个集合的距离
temp_df['distance'] = distance.cdist(temp_df[feature_columns], [new_listings_value[feature_columns]])
# temp_df 按distance排序
temp_df = temp_df.sort_values('distance')
knn_5 = temp_df.price.iloc[:5]
predicted_price = knn_5.mean()
return predicted_price
cols = ['accommodates', 'bathrooms']
norm_test_df['predicted_price'] = norm_test_df[cols].apply(predict_price_multivariate, feature_columns = cols, axis = 1)
norm_test_df['squared_error'] = (norm_test_df['predicted_price'] - norm_test_df['price']) ** 2
mse = norm_test_df['squared_error'].mean()
rmse = mse ** 0.5
print(rmse)
# 利用sklearn完成KNN
col = ['accommodates', 'bedrooms']
knn = KNeighborsRegressor()
# 将自变量和因变量放入模型训练,并用测试数据测试
knn.fit(norm_train_df[cols],norm_train_df["price"])
two_features_predictions = knn.predict(norm_test_df[cols])
# 计算预测值与实际值的均方根误差
two_features_mse = mean_squared_error(norm_test_df['price'], two_features_predictions)
two_features_rmse = math.sqrt(two_features_mse)
print(two_features_rmse)