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
.
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.
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.
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.
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.
There is also the inbuilt function bitwise_xor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With