KNN 分类器 Python

KNN Classifier Python

我目前正在使用 scikit 学习模块来帮助解决犯罪预测问题。我在使用 knn.predict 方法对整个 Dataframe 进行批量编码时遇到问题。

如何使用 knn.predict() 方法对 Dataframe 的整个两列进行批处理,以便将输出存储在另一个 Dataframe 中?

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

knn_df = pd.read_csv("/Users/helenapunset/Desktop/knn_dataframe.csv")

# x is the set of features 
x = knn_df[['latitude', 'longitude']]

# y is the target variable 
y = knn_df['Class']

# train and test data 
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=0)

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 5)

# training the data 
knn.fit(x_train,y_train)

# test score was approximately 69% 
knn.score(x_test,y_test)

# this is predicted to be a safe zone 
crime_prediction = knn.predict([[25.787882, -80.358427]])
print(crime_prediction)

在代码的最后一行,我能够添加我正在使用的两个特征,它们是来自标记为 knn_df 的 Dataframe 的纬度和经度。但是,这是我一直在搜索有关简化整个 Dataframe 的 knn 预测过程的文档的一个要点,但似乎无法找到执行此操作的方法。是否有可能为此使用 for 循环?

设要预测的新集合为'knn_df_predict'。假设列名相同,请尝试以下代码行:

x_new = knn_df_predict[['latitude', 'longitude']] #formating features
crime_prediction = knn.predict(x_new) #predicting for the new set
knn_df_predict['prediction'] = crime_prediction #Adding the prediction to dataframe