最近邻回归#

演示使用k-最近邻解决回归问题,并使用重心和常数权重对目标进行插值。

# 作者:scikit-learn 开发者
# SPDX-License-Identifier: BSD-3-Clause

生成示例数据#

import matplotlib.pyplot as plt
import numpy as np

from sklearn import neighbors

np.random.seed(0)
X = np.sort(5 * np.random.rand(40, 1), axis=0)
T = np.linspace(0, 5, 500)[:, np.newaxis]
y = np.sin(X).ravel()

# 添加噪声到目标
y[::5] += 1 * (0.5 - np.random.rand(8))

拟合回归模型#

n_neighbors = 5

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

    plt.subplot(2, 1, i + 1)
    plt.scatter(X, y, color="darkorange", label="data")
    plt.plot(T, 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')

Total running time of the script: (0 minutes 0.091 seconds)

Related examples

最近邻分类

最近邻分类

比较有无邻域成分分析的最近邻分类

比较有无邻域成分分析的最近邻分类

使用邻域成分分析进行降维

使用邻域成分分析进行降维

SVM:加权样本

SVM:加权样本

Gallery generated by Sphinx-Gallery