繁体   English   中英

使用 sklearn 中的 accuracy_score 时出错

[英]Error in using accuracy_score from sklearn

我正在使用逻辑回归进行平面数据分类。 导入准确度分数后出现错误。 为什么它不起作用? 这个答案建议使用准确度分数来估计准确度。代码的最后一行和倒数第三行必须给出相同的答案。 但最后第三行代码只给出了实际答案(即 47% 准确的 LR)。 我也应用了这个代码 score= accuracy_score(Y,LR_predictions) 但我得到了一个错误:索引太多

 import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
from sklearn.metrics import accuracy_score

X, Y = load_planar_dataset()

plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")

# Print accuracy
LR_predictions = clf.predict(X.T)
print(LR_predictions)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
       '% ' + "(percentage of correctly labelled datapoints)")
score= accuracy_score(Y,LR_predictions)
print(score)



ValueError                                Traceback (most recent call last)
<ipython-input-8-0f3a55d2e963> in <module>()
      8 print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
      9        '% ' + "(percentage of correctly labelled datapoints)")
---> 10 score= accuracy_score(Y,LR_predictions)
     11 print(score)

/opt/conda/lib/python3.6/site-packages/sklearn/metrics/classification.py in accuracy_score(y_true, y_pred, normalize, sample_weight)
    170 
    171     # Compute accuracy for each possible representation
--> 172     y_type, y_true, y_pred = _check_targets(y_true, y_pred)
    173     if y_type.startswith('multilabel'):
    174         differing_labels = count_nonzero(y_true - y_pred, axis=1)

/opt/conda/lib/python3.6/site-packages/sklearn/metrics/classification.py in _check_targets(y_true, y_pred)
     70     y_pred : array or indicator matrix
     71     """
---> 72     check_consistent_length(y_true, y_pred)
     73     type_true = type_of_target(y_true)
     74     type_pred = type_of_target(y_pred)

/opt/conda/lib/python3.6/site-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    179     if len(uniques) > 1:
    180         raise ValueError("Found input variables with inconsistent numbers of"
--> 181                          " samples: %r" % [int(l) for l in lengths])
    182 
    183 

ValueError: Found input variables with inconsistent numbers of samples: [1, 400]

将 Y 的形状更改为 accuracy_score 方法所需的 (n_samples,)。 只需尝试如下代码: Y = Y.reshape(1,-1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM