00001 import os, sys
00002 from numpy import *
00003 import matplotlib.pyplot as plt
00004 from pylab import *
00005
00006 conf_array_array = []
00007
00008 def buildConfusionMatrix(path,nr):
00009 for i in range(1, int(nr)):
00010 input = open(path)
00011
00012 k = l = 0
00013 nr_lines = 0
00014 conf_array = []
00015 for el in range(1, int((nr))):
00016 conf_array.append(0)
00017 for line in input.xreadlines():
00018
00019
00020 j = [int(line.split()[0]), int(line.split()[1])]
00021 if i == int(j[1]):
00022 conf_array[int(j[0]) - 1] = conf_array[int(j[0]) - 1] + 1
00023
00024 nr_lines = nr_lines + 1
00025 print "nr lines", nr_lines
00026
00027 conf_array_array.append(conf_array)
00028 input.close()
00029 print 'rows are ground truth, columns the classification: ', conf_array_array
00030 compute_false_pos_statistics(conf_array_array)
00031 plot_confusion_matrix(conf_array_array, int(nr)-1)
00032
00033 def plot_confusion_matrix(conf_arr, nr):
00034 norm_conf = []
00035 for i in conf_arr:
00036 a = 0
00037 tmp_arr = []
00038 a = sum(i,0)
00039 for j in i:
00040 if j == 0 and a == 0:
00041 tmp_arr.append(0)
00042 else:
00043 tmp_arr.append(float(j)/float(a))
00044
00045 norm_conf.append(tmp_arr)
00046
00047 plt.clf()
00048 fig = plt.figure()
00049
00050
00051 plt.xticks( arange(nr), ('bowl', 'box_medium', 'box_small', 'cylinder_big', 'cylinder_short', 'cylinder_small', 'flat_big', 'flat_small', 'pan', 'plate', 'tetrapak'), rotation=90)
00052 plt.yticks( arange(nr), ('bowl', 'box_medium', 'box_small', 'cylinder_big', 'cylinder_short', 'cylinder_small', 'flat_big', 'flat_small', 'pan', 'plate', 'tetrapak') )
00053
00054 plt.title('GRSD Confusion Matrix for Training Objects')
00055 ax = fig.add_subplot(111)
00056 res = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest', aspect='auto')
00057 cb = fig.colorbar(res)
00058 savefig("confmat.png", format="png", bbox_inches='tight')
00059
00060 def compute_false_pos_statistics(conf_arr):
00061 tp = 0
00062 all = 0
00063 array_len = conf_arr.__len__()
00064 for i in range(array_len):
00065 tp = tp + conf_arr[i][i]
00066 all = all + sum(conf_arr[i])
00067 print 'all: ', all, 'true positives: ', tp, 'percentage: ', double(tp)/double(all)
00068
00069
00070 if __name__ == "__main__":
00071 if sys.argv.__len__() < 3:
00072 print "Usage: build_confusion_matrix.py \t test.conf \t number_of_classes+1 \n\nAlso, adopt lines plt.xticks plt.yticks with actual category names"
00073 sys.exit()
00074 path = sys.argv[1]
00075 nr = sys.argv[2]
00076 buildConfusionMatrix(path, nr)