下载数据
https://www.kaggle.com/competitions/facebook-v-predicting-check-ins/data?select=train.csv.zip
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
# 获取数据集
# 数据基本处理 (数据清洗)
# 缩小数据集范围
# 选取有用的时间特征
# 将签到位置少于 n个用户的删除 去掉签到较少的地方
# 确定特征值和目标值
# 分割数据集
# 特征工程 - 标准化处理 特征预处理
# 模型评估 - k-近邻预测
# 读取数据 获取数据集
data = pd.read_csv("./train.csv")
# print(data)
# 显示前几行数据
print(data.head())
# 显示数据的统计描述
print(data.describe())
## count mean std min 25% 50% 75% max
# 查看行数 列数
print(data.shape)
# 缩小数据范围
query_data = data.query("x>2.0 & x < 2.5 & y>2.0 & y<2.5")
# 选择时间特征
time = pd.to_datetime(query_data["time"], unit="s")
datetime_index = pd.DatetimeIndex(time)
data["day"] = datetime_index.day
data["hour"] = datetime_index.hour
data["weekday"] = datetime_index.weekday
# 去除签到较少的地方
count = data.groupby("place_id").count()
count = count[count["row_id"] > 3]
data = data[data["place_id"].isin(count.index)]
# 确定特征值和目标值
x = data[["x", "y", "accuracy", "day", "hour", "weekday"]]
y = data["place_id"]
# 分割数据集
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)
# 特征工程 预处理
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.fit_transform(x_test)
# 机器学习 knn + cv
estimator = KNeighborsClassifier()
param_grid = {"n_neighbors": [1, 3, 5, 7, 9]}
estimator = GridSearchCV(estimator, param_grid=param_grid, cv=5)
# 训练模型
estimator.fit(x_train, y_train)
score = estimator.score(x_test, y_test)
print("最后预测的准确率为:\n", score)
y_predict = estimator.predict(x_test)
print("最后预测值为:\n", y_predict)
print("预测值和真实值的对比情况:\n", y_predict == y_test)
print("在交叉验证中验证的最好结果:\n", estimator.best_score_)
print("最好的参数模型:\n", estimator.best_estimator_)
print("每次交叉验证后的验证集准确率结果和训练集准确率结果:\n", estimator.cv_results_)