1 簡要說明
背景:各個(gè)酒店的住房記錄,數(shù)據(jù)中含有row_id,x,y(x,y給出酒店位置),accurary(酒店定位準(zhǔn)確性),time(簽到時(shí)間),place_id,用k-近鄰算法預(yù)測(cè)進(jìn)行地點(diǎn)預(yù)測(cè)
ps:沒找到數(shù)據(jù)T-T
首先寫出幾點(diǎn)步驟:
1截亦、需要標(biāo)準(zhǔn)化處理
2、由于數(shù)據(jù)量大柬讨,節(jié)省時(shí)間崩瓤,x,y要縮小
3、時(shí)間戳轉(zhuǎn)為(年踩官,月却桶,日,周蔗牡,時(shí)分秒)颖系,當(dāng)做新的特征
4、幾千-幾萬辩越,少于指定簽到人數(shù)的位置刪除
2 導(dǎo)入模塊
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
3 編寫函數(shù)
def knn():
#讀取數(shù)據(jù)
data = pd.read_csv('train.csv')
#處理數(shù)據(jù)
#1嘁扼、縮小數(shù)據(jù)
data.query('x>1.0 & x<1.25 & y>2.5 & y<2.75')
#處理時(shí)間
time_value = pd.to_datetime(data['time'],unit='s')#最小單位為秒
#把日期格式轉(zhuǎn)為元組,好取里面的‘year’,‘month’,‘day’,‘hour’,‘second’,‘weekday’黔攒。趁啸。。
time_value = pd.DatetimeIndex(time_value)
#3亏钩、構(gòu)造一些特征
data['day']=time_value.day
data['hour']=time_value.hour
data['weekday']=time_value.weekday
#把時(shí)間戳特征time刪除
data=data.drop(['time'],axis=1)
#把簽到數(shù)量少于n個(gè)目標(biāo)位置刪除
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)]
#取出特征值和目標(biāo)值
y = data['place_id']
x = data.drop(['place_id'],axis=1)
#數(shù)據(jù)分割
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.25)
#特征工程(標(biāo)準(zhǔn)化)
std=StandardScaler()
#對(duì)測(cè)試集和訓(xùn)練集的特征值標(biāo)準(zhǔn)化
x_train = std.fit_transform(x_train)
x_test = std.transform(x_test)
#進(jìn)行算法流程
knn=KNeighborsClassifier(n_neighbors=5)
knn.fit(x_train,y_train)
#得出預(yù)測(cè)結(jié)果
y_predict = knn.predict(x_test)
print('預(yù)測(cè)的目標(biāo)簽到位置為:',y_predict)
#得出測(cè)試集上的準(zhǔn)確率
print('預(yù)測(cè)的準(zhǔn)確率',knn.score(x_test,y_test))
if __name__=='__main__':
knncls()
4 簡單的作業(yè)
對(duì)iris數(shù)據(jù)集進(jìn)行分析
首先導(dǎo)入數(shù)據(jù)
from sklearn.datasets import load_iris
iris = load_iris()
x = iris.data
y = iris.target
數(shù)據(jù)劃分
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25)
knn算法
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
def knncls():
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(x_train,y_train)
y_predict=knn.predict(x_test)
print('預(yù)測(cè)結(jié)果:',y_predict)
score = knn.score(x_test,y_test)
print('準(zhǔn)確性:',score)
if __name__=='__main__':
knncls()
輸出:
預(yù)測(cè)結(jié)果: [2 2 0 0 2 0 2 1 2 0 2 1 1 2 2 1 0 2 0 0 0 1 0 0 1 2 1 1 1 2 2 1 1 2 2 2 0
0]
準(zhǔn)確性: 0.9210526315789473