k近邻算法(KNN)

定义:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
import pandas as pd
 
 
def knncls():
    """
    K-近邻预测用户签到位置
    :return:None
    """
    # 读取数据
    data = pd.read_csv("./data/FBlocation/train.csv")
 
    # print(data.head(10))
 
    # 处理数据
    # 1、缩小数据,查询数据晒讯
    data = data.query("x > 1.0 &  x < 1.25 & y > 2.5 & y < 2.75")
 
    # 处理时间的数据
    time_value = pd.to_datetime(data['time'], unit='s')
 
    print(time_value)
 
    # 把日期格式转换成 字典格式
    time_value = pd.DatetimeIndex(time_value)
 
    # 构造一些特征
    data['day'] = time_value.day
    data['hour'] = time_value.hour
    data['weekday'] = time_value.weekday
 
    # 把时间戳特征删除
    data = data.drop(['time'], axis=1)
 
    print(data)
 
    # 把签到数量少于n个目标位置删除
    place_count = data.groupby('place_id').count()
 
    tf = place_count[place_count.row_id > 3].reset_index()
 
    data = data[data['place_id'].isin(tf.place_id)]
 
    # 取出数据当中的特征值和目标值
    y = data['place_id']
 
    x = data.drop(['place_id'], axis=1)
 
    # 进行数据的分割训练集合测试集
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
 
    # 特征工程(标准化)
    std = StandardScaler()
 
    # 对测试集和训练集的特征值进行标准化
    x_train = std.fit_transform(x_train)
 
    x_test = std.transform(x_test)
 
    # 进行算法流程 # 超参数
    knn = KNeighborsClassifier()
 
    # # fit, predict,score
    # knn.fit(x_train, y_train)
    #
    # # 得出预测结果
    # y_predict = knn.predict(x_test)
    #
    # print("预测的目标签到位置为:", y_predict)
    #
    # # 得出准确率
    # print("预测的准确率:", knn.score(x_test, y_test))
 
    # 构造一些参数的值进行搜索
    param = {"n_neighbors": [3, 5, 10]}
 
    # 进行网格搜索
    gc = GridSearchCV(knn, param_grid=param, cv=2)
 
    gc.fit(x_train, y_train)
 
    # 预测准确率
    print("在测试集上准确率:", gc.score(x_test, y_test))
 
    print("在交叉验证当中最好的结果:", gc.best_score_)
 
    print("选择最好的模型是:", gc.best_estimator_)
 
    print("每个超参数每次交叉验证的结果:", gc.cv_results_)
 
    return None
 
 
if __name__ == "__main__":
    knncls()