Nearest Neighbor and Cross-Validation (complemented by python)

本文介绍了k-最近邻算法,通过比较训练集之间的距离来预测标签,并详细阐述了算法过程。同时,探讨了交叉验证这一更复杂的超参数调整技术,特别是3折、5折和10折交叉验证的运用。
摘要由CSDN通过智能技术生成

k-Nearest Neighbor

Nearest Neighbor

Compare with the distance between the training set
Distance:

  •         L1 distance
    

在这里插入图片描述

  •         L2 distance
    

在这里插入图片描述

Algorithm:

class NearestNeighbour(Object):

    def __init__(self):
        pass
    
    def train(X_train, y_train, self):
        self.X_train = X_train
        self.y_train = y_train
        
    def predict(X_test, self):
        
        y_prd = []
        num_train = self.X_train.shape[0]
        num_test = X_test.shape[0]
        l2 = np.zeros[num_test, num_train]
        
        l2 += np.sum(self.X_train ** 2, axis=1).reshape(1, num_train)
        l2 += np.sum(X_test ** 2, axis=1).reshape(num_test, 1)
        l2 -= 2 * np.dot(X_test.T, self.X_train)
        l2 = np.sqrt(l2)
        
        y_prd = self.y_train[np.argmax(l2, axis=1)]
        
        return y_prd

k-Nearest Neighbour

To find the k closest label and vote the best label
Alogorithm:

'''same as above'''

class kNearestNeighbour(Object):

    def __init__(self):
        pass
        
    def train(X_train, y_train, self):
        self.X_train = X_train
        self.y_train = y_train
        
    def predict(X_test, k, self):
        
        y_prd = []
        num_train = self.X_train.shape[0]
        num_test = X_test.shape[0]
        l2 = np.zeros[num_test, num_train]
        
        l2 += np.sum(self.X_train ** 2, axis=1).reshape(1, num_train)
        l2 += np.sum(X_test ** 2, axis=1).reshape(num_test, 1)
        l2 -= 2 * np.dot(X_test, self.X_train.T)
        l2 = np.sqrt(l2)
        
        for i in range(num_test):
            y_closest
            l2_index = np.argsort(l2[i])[0:k]
            y_closest = self.y_train[dists_index]
            y_pred[i] = np.bincount(closest_y).argmax()
        
        return y_prd

Cross-Validation

A more sophisticated technique for hyperparameter tuning
Typical number of folds would be 3-fold, 5-fold or 10-fold cross-validation

在这里插入图片描述

Visiulization Algorithm:

# plot the raw observations
for k in k_choices:
    accuracies = k_to_accuracies[k]
    plt.scatter([k] * len(accuracies), accuracies)

# plot the trend line with error bars that correspond to standard deviation
accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])
accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])
plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)
plt.title('Cross-validation on k')
plt.xlabel('k')
plt.ylabel('Cross-validation accuracy')
plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值