原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12673231.html
准备数据
import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import make_regression from sklearn.neighbors import KNeighborsRegressor X, y = make_regression(n_samples=200, n_features=1, n_informative=1, noise=20, random_state=1) # (200, 1) X.shape # (200,) y.shape plt.figure(figsize=(12, 8)) plt.scatter(X, y, c='r')
建模训练
# KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski', # metric_params=None, n_jobs=None, n_neighbors=5, p=2, # weights='uniform') knn = KNeighborsRegressor(n_neighbors=5) knn.fit(X, y)
评价模型
# 0.9544385303760471 knn.score(X, y) X_test = np.linspace(-2, 2, 500).reshape(-1, 1) y_test = knn.predict(X_test) # (500, 1) X_test.shape # (500,) y_test.shape plt.figure(figsize=(12, 8)) plt.scatter(X, y, c='r', s=100, label='samples') plt.plot(X_test, y_test, c='g', linewidth=3, label='prediction') plt.legend()
Reference
https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html
https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsRegressor.html