比较两个 numpy 二维数组的相似性

comparing two numpy 2D arrays for similarity

我有 2D numpy array1,它只包含 0255

 ([[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]])

和一个 array2,其大小和形状与 array1 相同,并且也仅包含 0255

 ([[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]])

如何比较 array1array2 以确定相似度百分比?

由于您只有两个可能的值,我建议使用此算法进行相似性检查:

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))

统计相等元素,计算相等元素占元素总数的百分比