SNABSuite  0.x
Spiking Neural Architecture Benchmark Suite
show_csv.py
Go to the documentation of this file.
1 import matplotlib
2 matplotlib.use('AGG')
3 import numpy as np
4 import pandas as pd
5 import argparse
6 import re
7 import os
8 import sys
9 import matplotlib.pyplot as plt
10 import matplotlib.colors as mpc
11 from operator import mul
12 
13 parser = argparse.ArgumentParser()
14 parser.add_argument('-p', '--path', help='File path', required=True)
15 parser.add_argument('-n', '--num', help='number of accuracies', type=int, default=3)
16 parser.add_argument('-g', '--group', help='Group accuracies', type=bool, default=False)
17 parser.add_argument('-o', '--out', help='Output folder for plotting', type=str, default='plots')
18 args = parser.parse_args()
19 
20 if not args.path:
21  print('Please give the path to the csv file!')
22  print('Usage: show_csv.py -p FILEPATH [-n NUMBER OF accuracies/groups] '
23  '[-g if accuracies should be grouped in e.g 0.7-0.79]')
24  sys.exit(1)
25 path = args.out
26 figsize = (7, 8)
27 # figsize = (4, 5)
28 
29 cols = list(pd.read_csv(args.path, nrows=1))
30 
31 filter_in = [re.compile('[\w]*_weight'), re.compile('accuracy'), re.compile('pool_delay')]
32 csv_data = pd.read_csv(args.path, usecols=[i for i in cols if any(re.match(fil, i) for fil in filter_in)])
33 
34 cols = []
35 data = []
36 for row, dat in csv_data.items():
37  cols.append(row.replace('#', ''))
38  data.append(dat)
39 data = np.array(data)
40 data = data[:, data[-1].argsort()[::-1]]
41 cols = cols[:-1]
42 uni_accuracies = np.unique(data[-1])
43 
44 
46  if args.group:
47  best_accuracy = uni_accuracies[-1]
48  upper_thresh = np.floor(best_accuracy*10)/10
49  lower_thresh = upper_thresh - 0.1 * (args.num - 1) - 0.0001
50  i = lower_thresh
51  best_accs = []
52  while i < upper_thresh:
53  j = i
54  # avoid floating point error like 0.70001, which doesn't include 0.7 anymore
55  i += 0.099998
56  best_accs.append([acc for acc in uni_accuracies if j <= acc < i])
57  else:
58  best_accs = [[acc] for acc in uni_accuracies[-args.num:]]
59  indent = max(8, 4+2*args.num)
60 
61  word = 'accuracy groups' if args.group else 'accuracies'
62 
63  print(f'Count of best {args.num} {word} in the tables below from right to left:')
64  if not args.group:
65  print([x[0] for x in best_accs])
66  else:
67  print([(x[0], x[-1]) for x in best_accs])
68  if not args.group:
69  print(f'0+1+2 means 0 occurrences of {best_accs[0]}, 1 occurrence of {best_accs[1]} and 2 occurrences of '
70  f'{best_accs[2]} for this specific parameters')
71  else:
72  print(f'0+1+2 means 0 occurrences of {best_accs[0][0]}-{best_accs[0][-1]}, ', end='')
73  if len(best_accs) > 1:
74  print(f'1 occurrence of {best_accs[1][0]}-{best_accs[1][-1]} ', end='')
75  if len(best_accs) > 2:
76  print(f'and 2 occurrences of {best_accs[2][0]}-{best_accs[2][-1]} ', end='')
77  print(f'for this specific parameters')
78  print('')
79  for idx in range(len(cols)):
80  for idx2 in range(idx + 1, len(cols)):
81  print(f'↓ {cols[idx]} → {cols[idx2]}')
82  unique1 = np.unique(data[idx])
83  unique2 = np.unique(data[idx2])
84  print(f"{'':>{8}}", end='')
85  for uni2 in unique2:
86  print(f'{uni2.round(5):>{indent}}', end='')
87  print('')
88  for uni1 in unique1:
89  print(f'{uni1.round(5):>8}', end='')
90  for uni2 in unique2:
91  acc = [d[-1] for d in data.transpose() if d[idx] == uni1 and d[idx2] == uni2]
92  counts = []
93  for best_acc in best_accs:
94  counts.append(sum([x in best_acc for x in acc]))
95  count_str = ''
96  for count in counts:
97  count_str += str(count) + '+'
98  print(f'{count_str[:-1]:>{indent}}', end='')
99  print('')
100  print('')
101 
102 
104  for idx in range(len(cols)):
105  for idx2 in range(idx + 1, len(cols)):
106  unique1 = np.unique(data[idx])
107  unique2 = np.unique(data[idx2])
108  if len(unique2) < len(unique1):
109  tmp = idx
110  idx = idx2
111  idx2 = tmp
112  tmp = unique1
113  unique1 = unique2
114  unique2 = tmp
115  fig, axs = plt.subplots(nrows=len(unique2), ncols=len(unique1), sharex='all', sharey='all', figsize=figsize)
116  fig.suptitle(f'↓ {cols[idx2]} → {cols[idx]}')
117  for uni1_idx, uni1 in enumerate(unique1):
118  for uni2_idx, uni2 in enumerate(unique2):
119  acc_sum = list(np.zeros(uni_accuracies.shape))
120  for ind, acc in enumerate(uni_accuracies):
121  count_acc = [True for dat in data.transpose()
122  if dat[idx] == uni1 and dat[idx2] == uni2 and dat[-1] == acc]
123  acc_sum[ind] = len(count_acc)
124  avg_acc = uni_accuracies - uni_accuracies[0]
125  avg_acc = avg_acc/uni_accuracies[-1]
126  avg_acc = list(map(mul, acc_sum, avg_acc))
127  avg_acc = sum(avg_acc)/sum(acc_sum)
128  acc_sum = np.cumsum(acc_sum)
129  hue = (-(1/3)+avg_acc/3)+1
130  hsv_colors = (hue, 1, 1)
131  ax = axs[uni2_idx][uni1_idx]
132  ax.plot(uni_accuracies, acc_sum, c=mpc.hsv_to_rgb(hsv_colors))
133  ax.grid()
134  if uni2_idx == 0:
135  ax.set_title(f'{uni1:.4f}')
136  if uni1_idx == 0:
137  ax.set_ylabel(f'{uni2:.4f}')
138  os.makedirs(path, exist_ok=True)
139  plt.savefig(f'{path}/{cols[idx2]}_{cols[idx]}.png', bbox_inches='tight')
140 
141  if idx2 < idx:
142  tmp = idx
143  idx = idx2
144  idx2 = tmp
145 
146 
148 plot_tabular()
def plot_tabular()
Definition: show_csv.py:103
def print_tabular()
Definition: show_csv.py:45