Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use xor on numpy matrices?

I have 2 numpy matrix like this.

matrix1

arr1 =
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  1.,  0.]])

matrix2

arr2 =
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  0.]])

I want to find similarity of these matrices. I think xor can be used on matrices. Xor operation should show where values are different and then I can count value 1 to calculate a percentage of similarity. I don't know how to use xor in python.

This code doesn't work: a = arr1 xor arr2 .

like image 452
user572575 Avatar asked Mar 01 '17 18:03

user572575


People also ask

Is NumPy matrix deprecated?

tl; dr: the numpy. matrix class is getting deprecated. There are some high-profile libraries that depend on the class as a dependency (the largest one being scipy.

What is the difference between NumPy array and NumPy matrix?

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

Does NumPy allow mixed data types?

Introduction to Data Types Having a data type (dtype) is one of the key features that distinguishes NumPy arrays from lists. In lists, the types of elements can be mixed. One index of a list can contain an integer, another can contain a string.


2 Answers

You can simply use arr1 != arr2 which results in:

>>> arr1 != arr2
array([[False, False, False],
       [False, False,  True],
       [False,  True, False]], dtype=bool)

and then use .sum() since int(False) is 0 and int(True) is 1:

>>> (arr1 != arr2).sum()
2

So there are two indices for which arr1[i,j] is not equal to arr2[i,j].

If you want to calculate the similarity (here defined as the number of elements that are the same) you can use:

>>> (arr1 == arr2).sum()/arr1.size
0.77777777777777779

so 77.77% of the elements are the same.

like image 195
Willem Van Onsem Avatar answered Oct 20 '22 19:10

Willem Van Onsem


There is also the inbuilt function bitwise_xor

like image 27
john ktejik Avatar answered Oct 20 '22 19:10

john ktejik