Kernel Regression

在prml這本書的第六章kernel methods提到了一種非參數迴歸的方法Kernel regression,這種模型是基於(特徵x之間)特徵越相似的則其所對應的y值也應該很相似,只不過他引進了kernel函數來衡量特徵之間的相似度。

下面是python代碼實現:

import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import  pdist,squareform,cdist
class KernelRegression:
    def __init__(self,bandwidth):
        self.bandwidth=bandwidth#帶寬這是主要的調節參數
    def fit(self,X,Y):
        self.X=X
        self.Y=Y
        return self
    def predict(self,data):
        size=self.X.shape[0]
        #計算測試數據和原始數據的距離
        distance=cdist(self.X,data)**2
        #將距離變換成kernel相似度
        kernel_dist=self.rbf_kernel(distance)
        sum=np.sum(kernel_dist,axis=1).reshape((size,1))
        weight=kernel_dist/sum
        #得到預測值,其實就是加權和,距離近的權重大,距離遠的權重小
        pred=weight.T.dot(self.Y)
        return pred
    def rbf_kernel(self,X):
        return np.exp(-X/(self.bandwidth**2))
#訓練數據
X=np.linspace(0,10,150).reshape((150,1))
#測試數據
data=np.linspace(0,10,150).reshape((150,1))
#真實值,可以試一下後面的sin函數
Y=np.cos(X)#Y=np.sin(X)
noise=np.random.normal(0,1,Y.shape)
#帶噪聲的數據,可以自己調節noise的大小
Y_noise=Y+0.4*noise
KG=KernelRegression(0.53)
KG.fit(X,Y_noise)
pred=KG.predict(data)
plt.scatter(X,Y_noise)
plt.plot(X,Y,label="True")
plt.plot(data,pred,label="Predict")
plt.legend()
plt.show()

如下圖中,散點爲帶有噪聲的數據 ,


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章