NearestNeighbor

import numpy as np

class NearestNeighbor:

  	def __init__(self):
		pass
	
	def train(self, X, y):
		self.Xtr = X
		self.ytr = y
	
	def predict(self, X):
		num_test = X.shape[0]
		Ypred = np.zeros(num_tset, dtype=self.ytr.dtype)
	
	for i in range(num_test):
		distance = np.sum(np.abs(self.Xtr - [i,:]), axis=1)
		min_index = np.argmin(distance)
		Ypred[i] = self.ytr[min_index]

	return Ypred

当有N个样本的时候训练速度与预测速度分别是:
train O(1)
predict O (N)

你可能感兴趣的:(NearestNeighbor)