Detong Chen
Detong Chen

Reputation: 11

Python: how to compare two array in easiest way

I am doing machine learning stuffs. I meet a problem these day, hope someone can help me.

I have two arrays [Array(Prediction) and Array(Labels)) with both same dimension [Shape: (128, 5)]. The first dimension is the index of each predict and label. The second dimension is the results associated with each predict and label

I want to output the accuracy Here is my code.

right_count = 0
for i in range(Prediction.shape[0])  # Foreach each predict/label
    if(np.array_equal(Prediction[i], Labels[i])):  # Compare each result
        right_count += 1

accuracy = float(right_count) / Prediction.shape[0]'

I just wonder whether there is a better way to simply the following code.

Thank you

Upvotes: 1

Views: 922

Answers (1)

1''
1''

Reputation: 27105

That code can be simplified, for instance:

accuracy = (Prediction == Labels).all(axis=1).mean()

This will also run faster than the original version because more of the operations are done inside Numpy instead of in Python code.

Upvotes: 4

Related Questions