機器學習(9)--構建一個KNN迴歸器
阿新 • • 發佈:2018-12-29
構建一個KNN迴歸器
程式碼如下:
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors
''' KNN 迴歸器'''
# 生成樣本資料
amplitude = 10
num_points = 100
x = amplitude * np.random.rand(num_points, 1)-0.5*amplitude
# 計算目標並新增噪聲 sinc 辛格函式 稱為取樣函式 抽樣函式 基本正弦函式
# sinc(x)=sin(x)/x(x!=0)=1(x=0)
y = np.sinc(x).ravel()
y += 0.2*(0.5-np.random.rand(y.size))
# 畫出圖形
plt.figure()
plt.scatter(x,y,s=40,c='k',facecolor='none')
plt.title('Input data')
# 定義更加密集的網格 輸入資料的10倍數定義網格
x_values=np.linspace(-0.5*amplitude,0.5*amplitude,10*num_points)[:,np.newaxis]
# 定義最近鄰網格
num_neighbors=8
# 定義並訓練迴歸器
knn_regressor=neighbors.KNeighborsRegressor(num_neighbors,weights='distance' )
y_values=knn_regressor.fit(x,y).predict(x_values)
plt.figure()
plt.scatter(x,y,s=40,c='k',facecolors='none',label='input_data')
plt.plot(x_values,y_values,c='k',linestyle='--',label='Predicted values')
plt.xlim(x.min()-1,x.max()+1)
plt.ylim(y.min()-0.2,y.max()+0.2)
# 用於顯示圖例
plt.legend()
plt.title('K nearest Neignbors Regressor' )
plt.show()
輸入資料分佈圖如下所示:
KNN迴歸器 預測值如下所示: