def predict(self, x, k=1, model='regression'):
"""
Note: currenly only works on single vector and not matrices
Args:
x (np.ndarray): Training data of shape[1, n_features]
k (int): number of nearest neighbor to consider
model: {'regression', 'classification'}
K nearest neighbor classification or regression.
Choice most likely depends on the type of data the
model was fit with.
Returns:
float: Returns predicted value
Raises:
ValueError if model has not been fit
"""
if not self.learned:
raise NameError('Fit model first')
distances = np.array([])
for row in range(np.shape(self.samples)[0]):
# Add distance from x to sample row to distances vector
distances = np.append(distances,
np.linalg.norm(x - self.samples[row, :]))
nearestneighbors = distances.argsort()[:k]
if model == 'regression':
prediction = self.values[nearestneighbors].mean()
if model == 'classification':
prediction = stats.mode(self.values[nearestneighbors]).mode
return prediction
评论列表
文章目录