Machine Learning 简明教程

Machine Learning - K-Nearest Neighbors (KNN)

KNN 是一种有监督学习算法,可用于分类和回归问题。KNN 背后的主要思想是找到给定测试数据点的 k 个最近数据点,并使用这些最近邻域来进行预测。k 的值是一个需要调整的超参数,它表示要考虑的邻域数。

KNN is a supervised learning algorithm that can be used for both classification and regression problems. The main idea behind KNN is to find the k-nearest data points to a given test data point and use these nearest neighbors to make a prediction. The value of k is a hyperparameter that needs to be tuned, and it represents the number of neighbors to consider.

对于分类问题,KNN 算法会将测试数据点分配给在 k 个最近邻域中出现频率最高的类别。换句话说,邻域最多的类别就是预测类别。

For classification problems, the KNN algorithm assigns the test data point to the class that appears most frequently among the k-nearest neighbors. In other words, the class with the highest number of neighbors is the predicted class.

对于回归问题,KNN 算法会将测试数据点分配给 k 个最近邻域的值的平均值。

For regression problems, the KNN algorithm assigns the test data point the average of the k-nearest neighbors' values.

用于度量两个数据点之间相似性的距离指标是一个影响 KNN 算法性能的重要因素。最常用的距离指标是欧几里得距离、曼哈顿距离和闵可夫斯基距离。

The distance metric used to measure the similarity between two data points is an essential factor that affects the KNN algorithm’s performance. The most commonly used distance metrics are Euclidean distance, Manhattan distance, and Minkowski distance.

Working of KNN Algorithm

KNN 算法可以概括为以下步骤:

The KNN algorithm can be summarized in the following steps −

  1. Load the data − The first step is to load the dataset into memory. This can be done using various libraries such as pandas or numpy.

  2. Split the data − The next step is to split the data into training and test sets. The training set is used to train the KNN algorithm, while the test set is used to evaluate its performance.

  3. Normalize the data − Before training the KNN algorithm, it is essential to normalize the data to ensure that each feature contributes equally to the distance metric calculation.

  4. Calculate distances − Once the data is normalized, the KNN algorithm calculates the distances between the test data point and each data point in the training set.

  5. Select k-nearest neighbors − The KNN algorithm selects the k-nearest neighbors based on the distances calculated in the previous step.

  6. Make a prediction − For classification problems, the KNN algorithm assigns the test data point to the class that appears most frequently among the k-nearest neighbors. For regression problems, the KNN algorithm assigns the test data point the average of the k-nearest neighbors' values.

  7. Evaluate performance − Finally, the KNN algorithm’s performance is evaluated using various metrics such as accuracy, precision, recall, and F1-score.

Implementation in Python

现在我们已经讨论了 KNN 算法的理论,让我们使用 scikit-learn 在 Python 中实现它。Scikit-learn 是一个流行的 Python 机器学习库,它提供了用于分类和回归问题的各种算法。

Now that we have discussed the KNN algorithm’s theory, let’s implement it in Python using scikit-learn. Scikit-learn is a popular library for Machine Learning in Python and provides various algorithms for classification and regression problems.

我们将使用鸢尾花卉数据集,这是一个流行的机器学习数据集,其中包含有关三种不同鸢尾花卉物种的信息。该数据集有四个特征,包括萼片长度、萼片宽度、花瓣长度和花瓣宽度,以及一个目标变量,即花卉种类。

We will use the Iris dataset, which is a popular dataset in Machine Learning and contains information about three different species of Iris flowers. The dataset has four features, including the sepal length, sepal width, petal length, and petal width, and a target variable, which is the species of the flower.

要在 Python 中实现 KNN,我们需要遵循前面提到的步骤。以下是在鸢尾花卉数据集上实现 KNN 的 Python 代码:

To implement KNN in Python, we need to follow the steps mentioned earlier. Here’s the Python code for implementing KNN on the Iris dataset −

Example

# import libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# load the Iris dataset
iris = load_iris()

#split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target, test_size=0.35, random_state=42)

#normalize the data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

#initialize the KNN algorithm
knn = KNeighborsClassifier(n_neighbors=5)

#train the KNN algorithm
knn.fit(X_train, y_train)

#make predictions on the test set
y_pred = knn.predict(X_test)

#evaluate the performance of the KNN algorithm
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: {:.2f}%".format(accuracy*100))

执行此代码时,将生成以下输出 −

When you execute this code, it will produce the following output −

Accuracy: 98.11%