Nearest Neighbors regression#

演示如何使用 k-Nearest Neighbor 解决回归问题,以及如何使用重心(barycenter)和常量权重对目标进行插值。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

生成样本数据#

我们在这里生成一些数据点来训练模型。我们还在训练数据的整个范围内生成数据,以可视化模型在该整个区域的反应。

import matplotlib.pyplot as plt
import numpy as np

from sklearn import neighbors

rng = np.random.RandomState(0)
X_train = np.sort(5 * rng.rand(40, 1), axis=0)
X_test = np.linspace(0, 5, 500)[:, np.newaxis]
y = np.sin(X_train).ravel()

# Add noise to targets
y[::5] += 1 * (0.5 - np.random.rand(8))

拟合回归模型#

在这里,我们训练一个模型并可视化预测中的 uniformdistance 权重如何影响预测值。

n_neighbors = 5

for i, weights in enumerate(["uniform", "distance"]):
    knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)
    y_ = knn.fit(X_train, y).predict(X_test)

    plt.subplot(2, 1, i + 1)
    plt.scatter(X_train, y, color="darkorange", label="data")
    plt.plot(X_test, y_, color="navy", label="prediction")
    plt.axis("tight")
    plt.legend()
    plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, weights))

plt.tight_layout()
plt.show()
KNeighborsRegressor (k = 5, weights = 'uniform'), KNeighborsRegressor (k = 5, weights = 'distance')

脚本总运行时间: (0 minutes 0.173 seconds)

相关示例

最近邻分类

最近邻分类

比较带和不带邻域成分分析的最近邻

比较带和不带邻域成分分析的最近邻

SVM:加权样本

SVM:加权样本

缓存最近邻

缓存最近邻

由 Sphinx-Gallery 生成的图库