1、前提知识: 回归:可以理解为拟合,就是根据训练数据的趋势,对输入数据进行预测。KNN回归:是一种有监督学习,因为需要提供目标数据(target) 2、案例: 用KNN回归拟合sin函数,首先通过sin函数上的点训练KNN模型,然后用随机生成的点拟合函数。代码: # 首先随机生成100个数用于sin函数生产成训练数据 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为二维,y为一维 x_train = x_train.reshape(100,-1) # -1本身代替1,目的是简化参数输入的计算 x_train.shape # 进行KNN回归 from sklearn.neighbors import KNeighborsRegressor knn = KNeighborsRegressor() knn.fit(x_train,y_train) # 进行KNN预测 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')