K-近邻算法(K Nearest Neighbor)
KNN算法的核心思想:你的“邻居”来推测你的类别
K的取值:
K值取得过小,容易受到异常点的影响
K值取得过大,受样本不均衡的影响
KNN的API
sklearn.neighbors.KNeighborsClassifier(n_neighbors = 5, algoriyhm = “auto”)
- n_neighbors:默认值为5,即“邻居”数。
- algorithm:默认为auto,可选用计算近邻居的算法。
算法对鸢尾花进行分类的步骤
- 获取数据
- 数据集划分
- 特征工程
- KNN算法预估器
- 模型评估
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
#KNN算法对鸢尾花进行分类
#1、获取数据
iris = load_iris()
#2、数据集划分
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,random_state = 22)
#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:\n",y_predict)
print("对真实值和预测值:\n",y_test == y_predict)
#方法二:计算准确率
score = estimator.score(x_test,y_test)
print("准确值为:\n",score)