引子 :
如图:在各种机器学习算法中我们经常会遇见metrics.accuracy_score()这个函数,它到底有什么作用呢?为此我专门搜集了一些相关资料。
sklearn 中accuracy_score函数计算了准确率。
一:函数作用
在二分类或者多分类中,预测得到的label,跟真实label比较,计算准确率。即:通过prediction预测结果和test_y测试集结果 计算得到模型的准确率
print("The acc of the SVM is ;",metrics.accuracy_score(prediction,test_y))
print('The accuracy of the Logistic Regression is',metrics.accuracy_score(prediction,test_y))
二:函数介绍和使用
分类准确率分数:是指所有分类正确的百分比
sklearn.metrics.accuracy_score(
y_true,
y_pred,
*,
normalize=True,
sample_weight=None)
y_true:真是标签。二分类和多分类情况下是一列,多标签情况下是标签的索引。
y_pred:预测标签。二分类和多分类情况下是一列,多标签情况下是标签的索引。
normalize:bool, optional (default=True),如果是false,正确分类的样本的数目(int);如果为true,返回正确分类的样本的比例,必须严格匹配真实数据集中的label,才为1,否则为0。
sample_weight:array-like of shape (n_samples,), default=None。Sample weights.
补充:如果normalize == True,返回正确分类的样本的比例,否则返回正确分类的样本的数目(int)
实例:
#基于鸢尾花数据的一个例子
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import metricsiris =pd.read_csv('iris.csv')
petal=iris[['PetalLengthCm','PetalWidthCm','Species']]
sepal=iris[['SepalLengthCm','SepalWidthCm','Species']]train_p,test_p=train_test_split(petal,test_size=0.3,random_state=0) #petals
train_x_p=train_p[['PetalWidthCm','PetalLengthCm']]
train_y_p=train_p.Species
test_x_p=test_p[['PetalWidthCm','PetalLengthCm']]
test_y_p=test_p.Speciesmodel=svm.SVC()
model.fit(train_x_p,train_y_p)
prediction=model.predict(test_x_p)
print('The accuracy of the SVM using Petals is:',metrics.accuracy_score(prediction,test_y_p))