Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using numpy to test for false positives and false negatives

I am trying to figure out how to calculate false positives and false negatives using numpy.

I am able to calculate accuracy and inaccuracy with the following:

In the following examples y_prediction is a 2d array of the predictions made on the dataset, a 2d array of 1s and 0s. Truth_labels is the 1d array of class labels associated with the feature vector, 2d array.

accurate_prediction_rate = np.count_nonzero(y_prediction == truth_labels)/truth_labels.shape[0]
inaccurate_prediction_rate = np.count_nonzero(y_prediction != truth_labels)/truth_labels.shape[0]

I then tried to calculate false positives (positives in my dataset are indicated by a 1) like so...

false_positives = np.count_nonzero((y_prediction != truth_labels)/truth_labels.shape[0] & predictions == 1)

but that returns an TypeError. I am new to using numpy and so unfamiliar with all available methods. Is there a numpy method better suited for what I am trying to do?

like image 998
Zuckerbrenner Avatar asked Feb 01 '26 03:02

Zuckerbrenner


2 Answers

You can achieve this using np.logical_and() and np.sum() and I also included how to calculate the true positives and true negatives.

negative = 0.0
positive = 1.0

tp = np.sum(np.logical_and(y_prediction == positive, truth_labels == positive))
tn = np.sum(np.logical_and(y_prediction == negative, truth_labels == negative))
fp = np.sum(np.logical_and(y_prediction == positive, truth_labels == negative))
fn = np.sum(np.logical_and(y_prediction == negative, truth_labels == positive))
like image 98
yudhiesh Avatar answered Feb 03 '26 16:02

yudhiesh


Base on your question I tried to produce a minimal example.

y_pred = np.array([[0, 1], [1, 0], [0, 1]]) #predictions
y_class = np.array([1, 0, 0]) #actual class

y_pred_class = np.argmax(y_pred, axis=1) #extracting class from predictions
false_positive = np.sum((y_pred_class == 1) & (y_class == 0))
like image 36
dufrmbgr Avatar answered Feb 03 '26 18:02

dufrmbgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!