def knn_iris(): # 获取数据 iris = load_iris() # 划分数据集 x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=22) # 特征工程:标准化 transfer = StandardScaler() x_train = transfer.fit_transform(x_train) x_test = transfer.fit_transform(x_test) # KNN算法预估器 estimator = KNeighborsClassifier(n_neighbors=3) estimator.fit(x_train, y_train) # 模型评估 # 方法1:直接比对真实值和预测值 y_predict = estimator.predict(x_test) print("y_predict:\n", y_predict) print("直接比对真实值和预测值:\n", y_test == y_predict) # 方法2:计算准确率 score = estimator.score(x_test, y_test) print("准确率为:\n", score) def knn_iris_gscv(): # 添加网格搜索和交叉验证 # 获取数据 iris = load_iris() # 划分数据集 x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=22) # 特征工程:标准化 transfer = StandardScaler() x_train = transfer.fit_transform(x_train) x_test = transfer.fit_transform(x_test) # KNN算法预估器 estimator = KNeighborsClassifier() # 不用添加k值了 # 网格搜索与交叉验证 # 数据准备 param_data = {"n_neighbors": [1, 3, 5, 7, 9, 11]} estimator = GridSearchCV(estimator, param_grid=param_data, cv=10) estimator.fit(x_train, y_train) # 模型评估 # 方法1:直接比对真实值和预测值 y_predict = estimator.predict(x_test) print("y_predict:\n", y_predict) print("直接比对真实值和预测值:\n", y_test == y_predict) # 方法2:计算准确率 score = estimator.score(x_test, y_test) print("准确率为:\n", score) # 最佳参数 print("最佳参数:\n", estimator.best_params_) # 最佳结果 print("最佳结果:\n", estimator.best_score_) # 最佳估计器 print("最佳估计器:\n", estimator.best_estimator_) # 交叉验证结果 print("交叉验证结果:\n", estimator.cv_results_)