1. 程式人生 > 其它 >python機器學習-KNN演算法

python機器學習-KNN演算法

K-近鄰演算法API

  • sklearn.neighbors.KNeighborsClassifier(n_neighbors=5,algorithm='auto')
    • n_neighbors:int,可選(預設= 5),k_neighbors查詢預設使用的鄰居數
    • algorithm:{‘auto’,‘ball_tree’,‘kd_tree’,‘brute’},可選用於計算最近鄰居的演算法:‘ball_tree’將會使用 BallTree,‘kd_tree’將使用 KDTree。‘auto’將嘗試根據傳遞給fit方法的值來決定最合適的演算法。 (不同實現方式影響效率)
#KNN演算法
def
knn_iris(): #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.模型評估 y_predict=estimator.predict(x_test) print(y_predict) print(y_test==y_predict) print(estimator.score(x_test,y_test)) pass #KNN演算法網格搜尋與交叉驗證 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_grid={"n_neighbors":[1,3,5,7,9,11]} estimator=GridSearchCV(estimator,param_grid=param_grid,cv=10) estimator.fit(x_train,y_train) #5.模型評估 y_predict=estimator.predict(x_test) print(y_predict) print(y_test==y_predict) print(estimator.score(x_test,y_test)) print("最佳引數:",estimator.best_params_) print("最佳結果:",estimator.best_score_) print("最佳估計器:",estimator.best_estimator_) print("交叉驗證結果:",estimator.cv_results_) pass