comparing two numpy 2D arrays for similarity

白昼怎懂夜的黑 提交于 2021-01-29 08:48:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!