训练数据集、测试数据集
sklearn中的数据集划分
In [282]: from sklearn.model_selection import train_test_split
In [285]: X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=666)
In [286]: X_test.shape
Out[286]: (30, 4)
In [287]: X_train.shape
Out[287]: (120, 4)
分类准确度
import numpy as np
def accuracy_score(y_test,y_predict):
'''计算y_test和y_predict之间的准确率'''
assert y_test.shape[0]==y_predict.shape[0],\
"the size of y_true must be equal to the size of y_predict"
return sum(y_test == y_predict)/len(y_test)
可以直接在(一)中的knn.py后面添加函数,直接计算分类的准确度
def score(self,X_test,y_test):
'''根据测试数据集X_test和y_test确定当前模型的准确度'''
y_predict = self.predict(X_test)
return accuracy_score(y_test)
sklearn中的accuracy_score
下面是调用sklearn中的knn算法的完整过程
#划分数据集
In [330]: from sklearn.model_selection import train_test_split
In [331]: X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=666)
#knn
In [332]: from sklearn.neighbors import KNeighborsClassifier
In [334]: knn_clf = KNeighborsClassifier(n_neighbors=3)
In [337]: knn_clf.fit(X_train,y_train)
In [338]: y_predict = knn_clf.predict(X_test)
#knn直接调用内部函数输出正确度
In [344]: knn_clf.score(X_test,y_test)
Out[344]: 0.9888888888888889
#sklearn中的accuracy_score
In [341]: from sklearn.metrics import accuracy_score
In [342]: accuracy_score(y_test,y_predict)
Out[342]: 0.9888888888888889