# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 11:02:33 2018
@author: Administrator
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x=np.sort( 5*np.random.rand(40,1),axis=0)
y=np.sin(x).ravel()
y[::5]=0.5-np.random.rand(8)
t=np.linspace(0,5,500)[:,np.newaxis]
from sklearn.neighbors import KNeighborsRegressor
n=5
for i,weights in enumerate( ['uniform','distance']):
knn = KNeighborsRegressor(n_neighbors=n,weights=weights)
pre=knn.fit(x,y).predict(t)
plt.figure(figsize=(8,8))
plt.subplot(2,1,i+1)
plt.scatter(x,y,c='k',label='data')
plt.plot(t,pre,c='g',label='predict')
plt.title('KNeighborsRegressor(k=%d,weights=%s)'%(n,weights))
plt.legend()
plt.show()
KNN算法练习
最新推荐文章于 2022-02-16 10:41:26 发布