1、前提知识:
- 回归:可以理解为拟合,就是根据训练数据的趋势,对输入数据进行预测。
- KNN回归:是一种有监督学习,因为需要提供目标数据(target)
2、案例:
- 用KNN回归拟合sin函数,首先通过sin函数上的点训练KNN模型,然后用随机生成的点拟合函数。
- 代码:
import math
import numpy as np
x_train = np.random.random(100)*10
y_train = np.sin(x_train)
x_train.shape, y_train.shape
x_train = x_train.reshape(100,-1)
x_train.shape
from sklearn.neighbors import KNeighborsRegressor
knn = KNeighborsRegressor()
knn.fit(x_train,y_train)
x_test = np.linspace(0,10,100).reshape(100,1)
x_test.shape
y_test = knn.predict(x_test)
import matplotlib.pyplot as plt
plt.scatter(x_train,y_train,c='blue')
plt.plot(x_test,y_test,c='red')