# 分类准确度

## 以kNN算法为例

Posted by Waldo on March 10, 2018      • metric.py(度量准确率)
``````import numpy as np

def accuracy_score(y_true, y_predict):
'''计算y_true和y_predict之间的准确率'''
assert y_true.shape == y_predict.shape, \
"the size of y_true must be equal to the size of y_predict"

return sum(y_true == y_predict) / len(y_true)

``````
• kNN算法+score函数
``````import numpy as np
from math import sqrt
from collections import Counter
from .metrics import accuracy_score

class KNNClassifier:

def __init__(self, k):
"""初始化kNN分类器"""
assert k >= 1, "k must be valid"
self.k = k
self._X_train = None
self._y_train = None

def fit(self, X_train, y_train):
"""根据训练数据集X_train和y_train训练kNN分类器"""
assert X_train.shape == y_train.shape, \
"the size of X_train must be equal to the size of y_train"
assert self.k <= X_train.shape, \
"the size of X_train must be at least k."

self._X_train = X_train
self._y_train = y_train
return self

def predict(self, X_predict):
"""给定待预测数据集X_predict，返回表示X_predict的结果向量"""
assert self._X_train is not None and self._y_train is not None, \
"must fit before predict!"
assert X_predict.shape == self._X_train.shape, \
"the feature number of X_predict must be equal to X_train"

y_predict = [self._predict(x) for x in X_predict]
return np.array(y_predict)

def _predict(self, x):
"""给定单个待预测数据x，返回x的预测结果值"""
assert x.shape == self._X_train.shape, \
"the feature number of x must be equal to X_train"

distances = [sqrt(np.sum((x_train - x) ** 2))
for x_train in self._X_train]
nearest = np.argsort(distances)

topK_y = [self._y_train[i] for i in nearest[:self.k]]

• scikit-learn中的acuracy_score  