Подсчет количества истинных положительных результатов по кривой точности-отзыва

Используя приведенный ниже график точности отзыва, где отзыв находится по оси x, а точность - по оси y, могу ли я использовать эту формулу для расчета количества прогнозов для заданной точности, порога отзыва?

введите описание изображения здесь

Эти расчеты основаны на оранжевой линии тренда.

Предположим, что эта модель была обучена на 100 экземплярах и является двоичным классификатором.

При значении отзыва 0,2 там (0,2 * 100) = 20 релевантных экземпляров. При значении отзыва 0,2 точность = 0,95, поэтому количество истинных положительных результатов (20 * 0,95) = 19. Является ли это правильным методом для расчета количества истинных положительных результатов из графика точности-отзыва?


person blue-sky    schedule 13.03.2019    source источник
comment
возможно, поможет матрица путаницы: en.wikipedia.org/wiki/Confusion_matrix   -  person Ray Tayek    schedule 19.03.2019


Ответы (5)


Я буду утверждать, что это невозможно сделать так. Для простоты вычислений я возьму отзыв 20%, точность 90% и 100 наблюдений.

Я могу сделать две матрицы результатов, которые будут давать эти числа. Здесь TP / TN обозначают положительный и отрицательный результат теста, CP / CN обозначают положительное / отрицательное состояние:

   CP CN
TP 9 1
TN 36 54

а также

   CP CN
TP 18 2
TN 72 8

Матрица 1 имеет TP 9, FP 1 и FN 36, что приводит к отзыву 9 / (36 + 9) = 20% и точности 9 / (1 + 9) = 90%.

Матрица 2 имеет TP 18, FP 2 и FN 72, что приводит к отзыву 18 / (72 + 18) = 20% и точности 18 / (2 + 18) = 90%.

Поскольку я могу создать две матрицы с разными TP и с одинаковым отзывом + точностью, график не дает достаточно информации для отслеживания TP.

person CIAndrews    schedule 19.03.2019
comment
Явно поясняется, что мы говорим о двоичном классификаторе. Я понимаю вашу точку зрения ... - person desertnaut; 21.03.2019
comment
Ты прав, не знаю, как я это пропустил. Обновил ответ. - person CIAndrews; 22.03.2019
comment
Что ж, теперь это действительно похоже на ответ;) - person desertnaut; 22.03.2019

Я не уверен, что именно вы имеете в виду, но я бы подумал об этом следующим образом:

Вспомните = TP / (TP + FN), что в вашем случае вы правильно поняли = 20 соответствующих экземпляров среди всех классифицированных экземпляров positive.

Точность = TP / (TP + FP), что в вашем случае, как вы говорите, составляет 0,95, означает, что 95 экземпляров из 100 были правильно классифицированы в этот момент.

Теперь давайте приравняем два для нашего случая:

0.2 = TP/ (TP + FN) и 0.95 = TP/ (TP + FP)

Следовательно,

0.75 TP = 0.2*FN - 0.95*FP

-> TP = (0.2*FN - 0.95*FP)/ 0.75

Я бы вычислил фактические истинные положительные результаты своих данных из приведенного выше уравнения.

Когда вы умножаете предсказанные релевантные выборки с точностью, вы просто вычисляете те экземпляры, которые были предсказаны TP и были релевантными. Я не уверен, что он учитывает все истинные положительные моменты в ваших данных.

Однако вы можете с хорошей уверенностью сказать (basically you are correct), что ваша модель предсказывала их как релевантные TP, если это то, что вы ищете.

Надеюсь это поможет!

person Shreyas Fadnavis    schedule 18.03.2019
comment
Вычисление TP из рассматриваемого уравнения, конечно, предполагает, что вы уже знаете FP и _3 _... - person desertnaut; 18.03.2019
comment
@desertnaut Тогда я думаю, что мой ответ кажется нормальным, не так ли? - person Shreyas Fadnavis; 18.03.2019
comment
Является ли? OP спрашивает, как рассчитать TP по кривой, поэтому, если вы не можете предоставить способ расчета FN и FP, это, безусловно, невозможно сделать из уравнения ... - person desertnaut; 18.03.2019

Нет,

Например: - Напоминание = 0,2, Точность = 0,95, 100 точек данных.

скажи, tp = True+ve, fp = False+ve , fn = False-ve, tn = True-ve

с вашим текущим методом.

tp = Precision * total number of data points

or

Precision = tp / (total number of data points)

Фактические состояния точности определения

Precision = tp / (tp+fp)

Чтобы ваш расчет работал, должно выполняться условие ниже.

 tp + fp = total number of data points

но

total number of data points = tp + fp + tn + fn
person sai    schedule 22.03.2019

Используйте python. Если вам нужны дополнительные изменения, задайте вопрос, посмотрите здесь. Собран из: https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html

"""
================
Precision-Recall
================

Example of Precision-Recall metric to evaluate classifier output quality.

Precision-Recall is a useful measure of success of prediction when the
classes are very imbalanced. In information retrieval, precision is a
measure of result relevancy, while recall is a measure of how many truly
relevant results are returned.

The precision-recall curve shows the tradeoff between precision and
recall for different threshold. A high area under the curve represents
both high recall and high precision, where high precision relates to a
low false positive rate, and high recall relates to a low false negative
rate. High scores for both show that the classifier is returning accurate
results (high precision), as well as returning a majority of all positive
results (high recall).

A system with high recall but low precision returns many results, but most of
its predicted labels are incorrect when compared to the training labels. A
system with high precision but low recall is just the opposite, returning very
few results, but most of its predicted labels are correct when compared to the
training labels. An ideal system with high precision and high recall will
return many results, with all results labeled correctly.

Precision (:math:`P`) is defined as the number of true positives (:math:`T_p`)
over the number of true positives plus the number of false positives
(:math:`F_p`).

:math:`P = \\frac{T_p}{T_p+F_p}`

Recall (:math:`R`) is defined as the number of true positives (:math:`T_p`)
over the number of true positives plus the number of false negatives
(:math:`F_n`).

:math:`R = \\frac{T_p}{T_p + F_n}`

These quantities are also related to the (:math:`F_1`) score, which is defined
as the harmonic mean of precision and recall.

:math:`F1 = 2\\frac{P \\times R}{P+R}`

Note that the precision may not decrease with recall. The
definition of precision (:math:`\\frac{T_p}{T_p + F_p}`) shows that lowering
the threshold of a classifier may increase the denominator, by increasing the
number of results returned. If the threshold was previously set too high, the
new results may all be true positives, which will increase precision. If the
previous threshold was about right or too low, further lowering the threshold
will introduce false positives, decreasing precision.

Recall is defined as :math:`\\frac{T_p}{T_p+F_n}`, where :math:`T_p+F_n` does
not depend on the classifier threshold. This means that lowering the classifier
threshold may increase recall, by increasing the number of true positive
results. It is also possible that lowering the threshold may leave recall
unchanged, while the precision fluctuates.

The relationship between recall and precision can be observed in the
stairstep area of the plot - at the edges of these steps a small change
in the threshold considerably reduces precision, with only a minor gain in
recall.

**Average precision** (AP) summarizes such a plot as the weighted mean of
precisions achieved at each threshold, with the increase in recall from the
previous threshold used as the weight:

:math:`\\text{AP} = \\sum_n (R_n - R_{n-1}) P_n`

where :math:`P_n` and :math:`R_n` are the precision and recall at the
nth threshold. A pair :math:`(R_k, P_k)` is referred to as an
*operating point*.

AP and the trapezoidal area under the operating points
(:func:`sklearn.metrics.auc`) are common ways to summarize a precision-recall
curve that lead to different results. Read more in the
:ref:`User Guide <precision_recall_f_measure_metrics>`.

Precision-recall curves are typically used in binary classification to study
the output of a classifier. In order to extend the precision-recall curve and
average precision to multi-class or multi-label classification, it is necessary
to binarize the output. One curve can be drawn per label, but one can also draw
a precision-recall curve by considering each element of the label indicator
matrix as a binary prediction (micro-averaging).

.. note::

    See also :func:`sklearn.metrics.average_precision_score`,
             :func:`sklearn.metrics.recall_score`,
             :func:`sklearn.metrics.precision_score`,
             :func:`sklearn.metrics.f1_score`
"""
from __future__ import print_function

###############################################################################
# In binary classification settings
# --------------------------------------------------------
#
# Create simple data
# ..................
#
# Try to differentiate the two first classes of the iris data
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
import numpy as np

iris = datasets.load_iris()
X = iris.data
y = iris.target

# Add noisy features
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# Limit to the two first classes, and split into training and test
X_train, X_test, y_train, y_test = train_test_split(X[y < 2], y[y < 2],
                                                    test_size=.5,
                                                    random_state=random_state)

# Create a simple classifier
classifier = svm.LinearSVC(random_state=random_state)
classifier.fit(X_train, y_train)
y_score = classifier.decision_function(X_test)

###############################################################################
# Compute the average precision score
# ...................................
from sklearn.metrics import average_precision_score
average_precision = average_precision_score(y_test, y_score)

print('Average precision-recall score: {0:0.2f}'.format(
      average_precision))

###############################################################################
# Plot the Precision-Recall curve
# ................................
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt
from sklearn.utils.fixes import signature

precision, recall, _ = precision_recall_curve(y_test, y_score)

# In matplotlib < 1.5, plt.fill_between does not have a 'step' argument
step_kwargs = ({'step': 'post'}
               if 'step' in signature(plt.fill_between).parameters
               else {})
plt.step(recall, precision, color='b', alpha=0.2,
         where='post')
plt.fill_between(recall, precision, alpha=0.2, color='b', **step_kwargs)

plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('2-class Precision-Recall curve: AP={0:0.2f}'.format(
          average_precision))

###############################################################################
# In multi-label settings
# ------------------------
#
# Create multi-label data, fit, and predict
# ...........................................
#
# We create a multi-label dataset, to illustrate the precision-recall in
# multi-label settings

from sklearn.preprocessing import label_binarize

# Use label_binarize to be multi-label like settings
Y = label_binarize(y, classes=[0, 1, 2])
n_classes = Y.shape[1]

# Split into training and test
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5,
                                                    random_state=random_state)

# We use OneVsRestClassifier for multi-label prediction
from sklearn.multiclass import OneVsRestClassifier

# Run classifier
classifier = OneVsRestClassifier(svm.LinearSVC(random_state=random_state))
classifier.fit(X_train, Y_train)
y_score = classifier.decision_function(X_test)


###############################################################################
# The average precision score in multi-label settings
# ....................................................
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score

# For each class
precision = dict()
recall = dict()
average_precision = dict()
for i in range(n_classes):
    precision[i], recall[i], _ = precision_recall_curve(Y_test[:, i],
                                                        y_score[:, i])
    average_precision[i] = average_precision_score(Y_test[:, i], y_score[:, i])

# A "micro-average": quantifying score on all classes jointly
precision["micro"], recall["micro"], _ = precision_recall_curve(Y_test.ravel(),
    y_score.ravel())
average_precision["micro"] = average_precision_score(Y_test, y_score,
                                                     average="micro")
print('Average precision score, micro-averaged over all classes: {0:0.2f}'
      .format(average_precision["micro"]))

###############################################################################
# Plot the micro-averaged Precision-Recall curve
# ...............................................
#

plt.figure()
plt.step(recall['micro'], precision['micro'], color='b', alpha=0.2,
         where='post')
plt.fill_between(recall["micro"], precision["micro"], alpha=0.2, color='b',
                 **step_kwargs)

plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title(
    'Average precision score, micro-averaged over all classes: AP={0:0.2f}'
    .format(average_precision["micro"]))

###############################################################################
# Plot Precision-Recall curve for each class and iso-f1 curves
# .............................................................
#
from itertools import cycle
# setup plot details
colors = cycle(['navy', 'turquoise', 'darkorange', 'cornflowerblue', 'teal'])

plt.figure(figsize=(7, 8))
f_scores = np.linspace(0.2, 0.8, num=4)
lines = []
labels = []
for f_score in f_scores:
    x = np.linspace(0.01, 1)
    y = f_score * x / (2 * x - f_score)
    l, = plt.plot(x[y >= 0], y[y >= 0], color='gray', alpha=0.2)
    plt.annotate('f1={0:0.1f}'.format(f_score), xy=(0.9, y[45] + 0.02))

lines.append(l)
labels.append('iso-f1 curves')
l, = plt.plot(recall["micro"], precision["micro"], color='gold', lw=2)
lines.append(l)
labels.append('micro-average Precision-recall (area = {0:0.2f})'
              ''.format(average_precision["micro"]))

for i, color in zip(range(n_classes), colors):
    l, = plt.plot(recall[i], precision[i], color=color, lw=2)
    lines.append(l)
    labels.append('Precision-recall for class {0} (area = {1:0.2f})'
                  ''.format(i, average_precision[i]))

fig = plt.gcf()
fig.subplots_adjust(bottom=0.25)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Extension of Precision-Recall curve to multi-class')
plt.legend(lines, labels, loc=(0, -.38), prop=dict(size=14))


plt.show()
person NinjaStar    schedule 25.03.2019

Поскольку вы можете построить кривую точности-отзыва, я предполагаю, что у вас есть значения точности и отзыва в некоторой переменной.

Предположим, что точность = 0,75.

0,75 можно записать как 3/4

fraction=(0.75).as_integer_ratio()

выход:

(3, 4)

Если у вас есть 100 предметов,

числитель = 3 * 100 / (3 + 4)

nr=(fraction[0]*100)/sum(fraction)

знаменатель = 4 * 100 / (3 + 4)

dr=(fraction[1]*100)/sum(fraction)

Формула точности: TP / (TP + FP).

поэтому TP = числитель и FP = знаменатель-TP

tp=nr
fp=dr-tp

Точно так же мы можем вычислить FN из отзыва

Результатом может быть десятичное значение, и поскольку TP, TN, FP, FN не могут быть дробью, мы можем округлить значение до ближайшего 1.

Надеюсь, это поможет!

person Sridhar Murali    schedule 19.03.2019