4 4 分類準確度

2021-09-26 07:58:05 字數 2469 閱讀 9854

分類準確度的計算方式:

分類正確的樣本數 / 總樣本數

(新加了score(x_test, y_test)函式,不關心predict的具體值是多少(predict函式在score中呼叫),只關心模型的準確度)

# from sklearn.neighbors import kneighborsclassifier

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分類器"""

print(x_train.shape[0])

print(y_train.shape[0])

assert x_train.shape[0] == y_train.shape[0]#, \ "the size of x_train must be equal to y_train"

assert self.k <= x_train.shape[0]#, \ "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[1] == self._x_train.shape[1]#, \ "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的**結果值"""

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]]

votes = counter(topk_y)

return votes.most_common(1)[0][0]

def score(self, x_test, y_test):

"""根據測試集x_test和y_test確定當前模型的準確度"""

y_predit = self.predict(x_test)

return accuracy_score(y_test, y_predit)

from sklearn.model_selection import train_test_split

from sklearn import datasets

# 資料集載入

digits = datasets.load_digits()

x = digits.data

y = digits.target

print(x.shape)

print(y.shape)

x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=666)

# knn

from sklearn.neighbors import kneighborsclassifier

knn_classifier = kneighborsclassifier(n_neighbors=3)

knn_classifier.fit(x_train, y_train)

# knn中自帶的準確度計算函式

print(knn_classifier.score(x_test, y_test))

03 分類準確度

在本文中,我們首先會再使用這樣的思路用我們的 knn 演算法在另外乙個更大一些的資料集上進行測試。與此同時,我們進一步來封裝 accuracy,同時也學習 sklearn 中分類的準確度相應的呼叫方式。最後,我們真正使用我們的測試資料集測試出的模型的結果來看,所謂的模型選擇是怎麼回事?在這個過程中,...

3 邏輯回歸 分類準確度

準確的有 0,0 1,1 其餘的都是 錯誤的點 from sklearn.metrics import confusion matrix 引入混淆矩陣 confusion matrix y test,y predict from sklearn.metrics import precision sc...

筆記 KNN之分類準確度

分類準確度 以sklearn中的手寫數字datasets.load digits為例,其是8 8的圖形,具有64個特徵值,類別由0到9 我們挑選出666這個圖形,將其視覺化 x digits.data some digit x 666 some digit image some digit.resh...