Issue
can some tell me what does closest_zero, closest_zero_p and closest_zero_r mean?
from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(y_test, y_scores_lr)
closest_zero = np.argmin(np.abs(thresholds))
closest_zero_p = precision[closest_zero]
closest_zero_r = recall[closest_zero]
plt.figure()
plt.xlim([0.0, 1.01])
plt.ylim([0.0, 1.01])
plt.plot(precision, recall, label='Precision-Recall Curve')
plt.plot(closest_zero_p, closest_zero_r, 'o', markersize = 12, fillstyle = 'none', c='r', mew=3)
plt.xlabel('Precision', fontsize=16)
plt.ylabel('Recall', fontsize=16)
plt.axes().set_aspect('equal')
plt.show()
Solution
First we have y_test which is the ground-truth and supposed to be of a binary type - two classes (0 and 1 usually). Also, we have y_scores_lr which is the prediction values that are continuous.
precision_recall_curve is a function calculating the values to draw a recall-precision curve and its output is:
precision - the values of the x-axis.
recall - the values of the y-axis.
thresholds - the threshold used to achieve the corresponding precision and recall values. To elaborate a little bit about these values' meaning, each threshold is used to make a different classification results, where all predictions from y_scores_lr below this value are assigned to one class, and all other values (above the threshold) are considered as the other class. After classifying the predicted values by the specific threshold, precision and recall can be calculated according to the resulted classification.
It is important to say now that one can use the precision-recall curve to find the best threshold to perform future classifications, or at least understand better the behavior of the model.
The code looks for a specific threshold value, the one closest to zero (no matter if it is positive or negative) and takes the corresponding precision and recall values to this threshold in order to plot it as a point on the plotted curve.
So, closest_zero is the index of the highest negative threshold, or the lowest positive one, depends which is closer to zero. (np.argmin returns the index for which the value is the lowest, and abs makes sure to consider only the difference from zero, regardless of the sign)
Accordingly, closest_zero_p and closest_zero_r are the precision and recall at the same index of the threshold that is closest to zero.
Answered By - ronpi Answer Checked By - David Goodson (Python.Easybugfix Volunteer)
Post a Comment
Post a Comment