问题
I have 2D numpy array1
that contains only 0
and 255
values
([[255, 0, 255, 0, 0],
[ 0, 255, 0, 0, 0],
[ 0, 0, 255, 0, 255],
[ 0, 255, 255, 255, 255],
[255, 0, 255, 0, 255]])
and an array2
that is identical in size and shape as array1
and also contains only 0
and 255
values
([[255, 0, 255, 0, 255],
[ 0, 255, 0, 0, 0],
[255, 0, 0, 0, 255],
[ 0, 0, 255, 255, 255],
[255, 0, 255, 0, 0]])
How can I compare array1
to array2
to determine a similarity percentage?
回答1:
As you only have two possible values, I would propose this algorithm for similarity-checking:
import numpy as np
A = np.array([[255, 0, 255, 0, 0],
[ 0, 255, 0, 0, 0],
[ 0, 0, 255, 0, 255],
[ 0, 255, 255, 255, 255],
[255, 0, 255, 0, 255]])
B = np.array([[255, 0, 255, 0, 255],
[ 0, 255, 0, 0, 0],
[255, 0, 0, 0, 255],
[ 0, 0, 255, 255, 255],
[255, 0, 255, 0, 0]])
number_of_equal_elements = np.sum(A==B)
total_elements = np.multiply(*A.shape)
percentage = number_of_equal_elements/total_elements
print('total number of elements: \t\t{}'.format(total_elements))
print('number of identical elements: \t\t{}'.format(number_of_equal_elements))
print('number of different elements: \t\t{}'.format(total_elements-number_of_equal_elements))
print('percentage of identical elements: \t{:.2f}%'.format(percentage*100))
It counts equal elements and calculates the percentage of the equal elements to the total number of elements
来源:https://stackoverflow.com/questions/53521531/comparing-two-numpy-2d-arrays-for-similarity