📜  Python中的k最近邻算法

📅  最后修改于: 2022-05-13 01:54:29.411000             🧑  作者: Mango

Python中的k最近邻算法

监督学习:
这是我们想要预测的值或结果在训练数据(标记数据)中的学习,而我们想要研究的数据中的值被称为目标或因变量或响应变量

数据集中的所有其他列都称为特征或预测变量或自变量。

监督学习分为两类:

  1. 分类:这里我们的目标变量由类别组成。
  2. 回归:这里我们的目标变量是连续的,我们通常会尝试找出曲线的线。

正如我们所了解的,要进行监督学习,我们需要标记数据。我们如何获得标记数据?有多种方法可以获取标记数据:

  1. 历史标记数据
  2. 实验以获取数据:我们可以执行实验以生成标记数据,例如 A/B 测试。
  3. 众包

现在是时候了解可用于解决有监督机器学习问题的算法了。在这篇文章中,我们将使用流行的 scikit-learn包。

k-最近邻算法:

该算法用于解决分类模型问题。 K-最近邻或 K-NN 算法基本上创建了一个假想的边界来对数据进行分类。当新的数据点进来时,算法将尝试预测到最近的边界线。

因此,较大的 k 值意味着更平滑的分离曲线,从而导致模型不太复杂。而较小的 k 值往往会过度拟合数据并导致模型复杂化。

注意:在分析数据集时,具有正确的 k 值非常重要,以避免数据集的过拟合和欠拟合。

使用 k 近邻算法,我们拟合历史数据(或训练模型)并预测未来。

k-最近邻算法示例

Python3
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
 
# Loading data
irisData = load_iris()
 
# Create feature and target arrays
X = irisData.data
y = irisData.target
 
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(
             X, y, test_size = 0.2, random_state=42)
 
knn = KNeighborsClassifier(n_neighbors=7)
 
knn.fit(X_train, y_train)
 
# Predict on dataset which model has not seen before
print(knn.predict(X_test))


Python3
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
 
# Loading data
irisData = load_iris()
 
# Create feature and target arrays
X = irisData.data
y = irisData.target
 
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(
             X, y, test_size = 0.2, random_state=42)
 
knn = KNeighborsClassifier(n_neighbors=7)
 
knn.fit(X_train, y_train)
 
# Calculate the accuracy of the model
print(knn.score(X_test, y_test))


Python3
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
 
irisData = load_iris()
 
# Create feature and target arrays
X = irisData.data
y = irisData.target
 
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(
             X, y, test_size = 0.2, random_state=42)
 
neighbors = np.arange(1, 9)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
 
# Loop over K values
for i, k in enumerate(neighbors):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
     
    # Compute training and test data accuracy
    train_accuracy[i] = knn.score(X_train, y_train)
    test_accuracy[i] = knn.score(X_test, y_test)
 
# Generate plot
plt.plot(neighbors, test_accuracy, label = 'Testing dataset Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training dataset Accuracy')
 
plt.legend()
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.show()


在上面显示的示例中,执行以下步骤:

  1. k-最近邻算法是从 scikit-learn 包中导入的。
  2. 创建特征和目标变量。
  3. 将数据拆分为训练和测试数据。
  4. 使用邻居值生成 k-NN 模型。
  5. 将数据训练或拟合到模型中。
  6. 预测未来。

我们已经看到了如何使用 K-NN 算法来解决有监督的机器学习问题。但是如何衡量模型的准确性呢?

考虑下面显示的示例,我们在该示例中预测了上述模型的性能:

Python3

# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
 
# Loading data
irisData = load_iris()
 
# Create feature and target arrays
X = irisData.data
y = irisData.target
 
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(
             X, y, test_size = 0.2, random_state=42)
 
knn = KNeighborsClassifier(n_neighbors=7)
 
knn.fit(X_train, y_train)
 
# Calculate the accuracy of the model
print(knn.score(X_test, y_test))


模型精度:
到现在为止还挺好。但是如何为数据集确定正确的 k 值呢?显然,我们需要熟悉数据才能获得预期 k 值的范围,但要获得准确的 k 值,我们需要针对每个预期 k 值测试模型。请参考下图示例。

Python3

# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
 
irisData = load_iris()
 
# Create feature and target arrays
X = irisData.data
y = irisData.target
 
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(
             X, y, test_size = 0.2, random_state=42)
 
neighbors = np.arange(1, 9)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
 
# Loop over K values
for i, k in enumerate(neighbors):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
     
    # Compute training and test data accuracy
    train_accuracy[i] = knn.score(X_train, y_train)
    test_accuracy[i] = knn.score(X_test, y_test)
 
# Generate plot
plt.plot(neighbors, test_accuracy, label = 'Testing dataset Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training dataset Accuracy')
 
plt.legend()
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.show()

输出:

在上面显示的示例中,我们正在创建一个图来查看我们具有高精度的 k 值。

注意:这是一种在行业范围内未用于选择正确 n_neighbors 值的技术。相反,我们进行超参数调整以选择能够提供最佳性能的值。我们将在以后的帖子中介绍这一点。

概括 -
在这篇文章中,我们了解了监督学习是什么以及它的类别是什么。在对监督学习有了基本的了解之后,我们探索了用于解决监督机器学习问题的 k 近邻算法。我们还探索了测量模型的准确性。