比较两个numpy 2D数组的相似性

时间:2018-11-28 14:18:45

标签: arrays numpy python-2.x

我有一个仅包含array10值的2D numpy 255

 ([[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以确定相似度百分比?

1 个答案:

答案 0 :(得分:2)

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

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

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