Konrad S
Konrad S

Reputation: 71

How to calculate a sum of mismatching elements in two NumPy arrays

So I'm currently trying to implement a perceptron, and I have two NumPy arrays, dimensions are 1x200. I would like to check each and every element in the two matrices against each other, and get back the sum of the elements which doesn't match each other. I tried doing something like this:

b = (x_A > 0).astype(int)
b[b == 0] = -1

Now I want to compare this matrix with the other, my question is therefore, is there a way to avoid for-loops and still get what I want (the sum of elements which doesn't match)?

Upvotes: 1

Views: 964

Answers (1)

nick
nick

Reputation: 1350

You should just be able to do this directly - assuming that your arrays are of the same dimensions. For numpy arrays a and b:

np.sum(a != b)

a != b gives an array of Booleans (True when they are not equal element-wise and False when they are). Sum will give you the count of all elements that are not equal.

Upvotes: 1

Related Questions