案例:对鸢尾花种类进行预测
流程:1)获取数据;2)数据集划分;3)特征工程:标准化;4)Knn预估器流程;5)模型评估
from sklearn.datasets import load_iris #获取数据集
from sklearn.model_selection import train_test_split #划分数据集
from sklearn.preprocessing import StandardScaler #标准化
from sklearn.neighbors import KNeighborsClassifier #knn算法分类
def knn_iris():
"""
用knn算法对鸢尾花进行分类
:return:
"""
#1、获取数据
iris = load_iris()
#2、划分数据集
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target, random_state=6)
#3、特征工程:标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train) #训练集标准化
x_test = transfer.transform(x_test) #测试集标准化
#4、knn算法预估器
estimator = KNeighborsClassifier(n_neighbors=3)
estimator.fit(x_train,y_train)
#5、模型评估
#方法1:直接对比真实值和预测值
y_predit = estimator.predict(x_test)
print("y_predict:\n",y_predit)
print("直接必读真实值和预测值:\n",y_test==y_predit)
#方法2:计算准确率
score = estimator.score(x_test,y_test) #测试集的特征值,测试集的目标值
print("准确率:\n",score)
return None
if __name__ == "__main__":
knn_iris()
模型选择与调优
交叉验证:为了让被评估的模型更加准确可信
超参数搜索-----网格搜索
超参数:是指参数需要手动指定的
但是手动过程繁杂,所以需要对模型预设几种超参数组合,每组超参数都需采用交叉验证来进行评估,最后选出最优参数组合建立模型。
from sklearn.datasets import load_iris #获取数据集
from sklearn.model_selection import train_test_split #划分数据集
from sklearn.preprocessing import StandardScaler #标准化
from sklearn.neighbors import KNeighborsClassifier #knn算法分类
from sklearn.model_selection import GridSearchCV
def knn_iris():
"""
用knn算法对鸢尾花进行分类
:return:
"""
#1、获取数据
iris = load_iris()
#2、划分数据集
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target, random_state=6)
#3、特征工程:标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train) #训练集标准化
x_test = transfer.transform(x_test) #测试集标准化
#4、knn算法预估器
estimator = KNeighborsClassifier(n_neighbors=3)
estimator.fit(x_train,y_train)
#5、模型评估
#方法1:直接对比真实值和预测值
y_predit = estimator.predict(x_test)
print("y_predict:\n",y_predit)
print("直接必读真实值和预测值:\n",y_test==y_predit)
#方法2:计算准确率
score = estimator.score(x_test,y_test) #测试集的特征值,测试集的目标值
print("准确率:\n",score)
return None
def knn_iris_gscv():
# 1、获取数据
iris = load_iris()
# 2、划分数据集
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=6)
# 3、特征工程:标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train) # 训练集标准化
x_test = transfer.transform(x_test) # 测试集标准化
# 4、knn算法预估器
estimator = KNeighborsClassifier()
#加入网格搜索与交叉验证
param_dict = {"n_neighbors":[1,3,5,7,9,11]}
estimator = GridSearchCV(estimator,param_grid=param_dict,cv=10)
estimator.fit(x_train, y_train)
# 5、模型评估
# 方法1:直接对比真实值和预测值
y_predit = estimator.predict(x_test)
print("y_predict:\n", y_predit)
print("直接必读真实值和预测值:\n", y_test == y_predit)
# 方法2:计算准确率
score = estimator.score(x_test, y_test) # 测试集的特征值,测试集的目标值
print("准确率:\n", score)
#查看最佳参数:best_params_
print("查看最佳参数:",estimator.best_params_)
#最佳结果:best_score_
print("最佳结果:",estimator.best_score_)
#最佳估计器:best_estimator_
print("最佳估计器:",estimator.best_estimator_)
#交叉验证结果:cv_results_
print("交叉验证结果:",estimator.cv_results_)
return None
if __name__ == "__main__":
#knn_iris()
knn_iris_gscv()
综合案例编写:预测facebook签到位置
本次比赛的目的是预测一个人将要签到的地方。 为了本次比赛,Facebook创建了一个虚拟世界,其中包括10公里*10公里共100平方公里的约10万个地方。 对于给定的坐标集,您的任务将根据用户的位置,准确性和时间戳等预测用户下一次的签到位置。 数据被制作成类似于来自移动设备的位置数据。 请注意:您只能使用提供的数据进行预测。
数据集来源:
kaggle网址:https://www.kaggle.com/navoshta/grid-knn/data
代码:
import pandas as pd
# 1、获取数据
data = pd.read_csv("./FBlocation/train.csv") #29118021 rows × 6 columns
# 2、基本的数据处理
# 1)缩小数据范围
data = data.query("x<2.5 & x>2 & y<1.5 & y>1.0") #83197 rows × 6 columns
# 2)处理时间特征
time_value = pd.to_datetime(data["time"], unit="s") #Name: time, Length: 83197
date = pd.DatetimeIndex(time_value)
data["day"] = date.day
data["weekday"] = date.weekday
data["hour"] = date.hour
data.head() #83197 rows × 9 columns
# 3)过滤签到次数少的地点
place_count = data.groupby("place_id").count()["row_id"] #2514 rows × 8 columns
place_count[place_count > 3].head()
data_final = data[data["place_id"].isin(place_count[place_count>3].index.values)]
data_final.head() #80910 rows × 9 columns
# 筛选特征值和目标值
x = data_final[["x", "y", "accuracy", "day", "weekday", "hour"]]
y = data_final["place_id"]
# 数据集划分
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y)
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
# 3、特征工程:标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train) # 训练集标准化
x_test = transfer.transform(x_test) # 测试集标准化
# 4、KNN算法预估器
estimator = KNeighborsClassifier()
# 加入网格搜索与交叉验证
# 参数准备
param_dict = {"n_neighbors": [3,5,7,9]}
estimator = GridSearchCV(estimator, param_grid=param_dict, cv=5) # 10折,数据量不大,可以多折
estimator.fit(x_train, y_train)
# 5、模型评估
# 方法1:直接比对真实值和预测值
y_predict = estimator.predict(x_test)
print("y_predict:\n", y_predict)
print("直接必读真实值和预测值:\n", y_test == y_predict) # 直接比对
# 方法2:计算准确率
score = estimator.score(x_test, y_test) # 测试集的特征值,测试集的目标值
print("准确率:", score)
# 查看最佳参数:best_params_
print("最佳参数:", estimator.best_params_)
# 最佳结果:best_score_
print("最佳结果:", estimator.best_score_)
# 最佳估计器:best_estimator_
print("最佳估计器:", estimator.best_estimator_)
# 交叉验证结果:cv_results_
print("交叉验证结果:", estimator.cv_results_)