|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Created on Fri May 31 12:20:57 2019 |
| 5 | +Majorly revamped on Sun Jan 31 2021 |
| 6 | +
|
| 7 | +@author: kai |
| 8 | +""" |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +import pandas as pd |
| 12 | +#from sklearn import linear_model |
| 13 | +#from sklearn.metrics import mean_squared_error, r2_score |
| 14 | +import matplotlib |
| 15 | +#matplotlib.use('default') |
| 16 | +matplotlib.use('agg') |
| 17 | +import matplotlib.pyplot as plt |
| 18 | +#from scipy.optimize import curve_fit |
| 19 | +#from scipy import exp |
| 20 | +import pickle |
| 21 | +import os |
| 22 | +#from scipy.misc import imresize |
| 23 | +from skimage.transform import resize |
| 24 | + |
| 25 | +from rowwise_neuron_curves_controls import read_layer_reps, X_data |
| 26 | + |
| 27 | +# %% SETUP |
| 28 | +#PARS |
| 29 | +modelname = 'spatial_temporal_4_8-16-16-32_64-64-64-64_5272' |
| 30 | +datafolder = '../data/%s/' %modelname |
| 31 | + |
| 32 | +char_labels = ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'l', 'm', 'n', |
| 33 | + 'o', 'p', 'q', 'r', 's', 'u', 'v', 'w', 'y', 'z'] |
| 34 | +nchars = len(char_labels) |
| 35 | + |
| 36 | +topk = 5 |
| 37 | + |
| 38 | +# %% FUNCTIONS |
| 39 | +def get_max_act(actmap): |
| 40 | + return np.max(actmap.flatten()) |
| 41 | + |
| 42 | +def topk_actmaps(actmaps, labels): |
| 43 | + topkam = np.zeros(tuple([nchars, topk]) + actmaps[0].shape) |
| 44 | + idxs = np.zeros((nchars, topk)) |
| 45 | + for idx, am in enumerate(actmaps): |
| 46 | + char = labels[idx] |
| 47 | + maxact = get_max_act(am) |
| 48 | + #print(idx, maxact, ) |
| 49 | + if maxact > get_max_act(topkam[char, topk - 1]): |
| 50 | + topkam[char, topk - 1] = am |
| 51 | + maxacts = np.array([get_max_act(tam) for tam in topkam[char]]) |
| 52 | + order = np.argsort(- maxacts) |
| 53 | + #print(order) |
| 54 | + topkam[char] = topkam[char, order] |
| 55 | + |
| 56 | + idxs[char, topk - 1] = idx |
| 57 | + idxs[char] = idxs[char, order] |
| 58 | + return topkam, idxs |
| 59 | + |
| 60 | + |
| 61 | +# %% PLOT & ANALYZE RESULTS |
| 62 | +def above_threshold(am, threshold = 0.3): |
| 63 | + """Returns boolean map where activation is above 0.3 * maxact """ |
| 64 | + maxact = get_max_act(am) |
| 65 | + bat = np.where(am > maxact * threshold, True, False) |
| 66 | + return bat |
| 67 | + |
| 68 | +def get_t(fmapt, fmapnt, nt = 320, t_stride = 2): |
| 69 | + """Converts time dimension index from feature map to original time point""" |
| 70 | + centers = np.arange(nt) |
| 71 | + #if fmapntime != len(centers): |
| 72 | + for i in range(int(np.log2(len(centers)/ fmapnt))): |
| 73 | + centers = [centers[i*t_stride] for i in range(len(centers)//2)] |
| 74 | + |
| 75 | + assert len(centers) == fmapnt, "length of centers and fmapnt not equal!" |
| 76 | + |
| 77 | + return centers[fmapt] |
| 78 | + |
| 79 | +def get_s(fmaps, fmapns, ns = 25, s_stride = 2): |
| 80 | + """Converts time dimension index from feature map to original time point""" |
| 81 | + centers = np.arange(ns) |
| 82 | + #print("fmapns: %d" %fmapns) |
| 83 | + #if fmapntime != len(centers): |
| 84 | + while len(centers) > fmapns: |
| 85 | + centers = [centers[i*t_stride] for i in range((len(centers)+1)//2)] |
| 86 | + #print(centers) |
| 87 | + |
| 88 | + assert len(centers) == fmapns, "length of centers and fmapnt not equal!" |
| 89 | + |
| 90 | + return centers[fmaps] |
| 91 | + |
| 92 | +def get_ext(ext, fmapn, n = 320, stride = 2): |
| 93 | + cext = 0 |
| 94 | + centers = [] |
| 95 | + centers.append([i for i in range(n)]) |
| 96 | + while(len(centers[-1]) > fmapn): |
| 97 | + cs = centers[-1] |
| 98 | + centers.append([cs[i*stride] for i in range((len(cs)+1)//2)]) |
| 99 | + for i in np.arange(len(centers)-2, -1, -1): |
| 100 | + cs = centers[i] |
| 101 | + idx = cs.index(cext) |
| 102 | + #print(i, idx) |
| 103 | + cext = cs[np.min([idx + ext, len(cs) - 1])] |
| 104 | + return cext |
| 105 | + |
| 106 | +def translate(bat, osh = [25, 320]): |
| 107 | + """Returns boolean map in original space time""" |
| 108 | + bost = np.zeros(osh).astype(bool) |
| 109 | + for idx, b in np.ndenumerate(bat): |
| 110 | + if b: |
| 111 | + s, t = idx[0], idx[1] |
| 112 | + sext, text = skernelsize // 2, tkernelsize // 2 |
| 113 | + #print(s, t) |
| 114 | + if bat.shape[0] < osh[0]: |
| 115 | + s = get_s(idx[0], bat.shape[0], osh[0], s_stride) |
| 116 | + sext = get_ext(sext, bat.shape[0], nmuscles, s_stride) |
| 117 | + if bat.shape[1] < osh[1]: |
| 118 | + t = get_t(idx[1], bat.shape[1], osh[1], t_stride) |
| 119 | + text = get_ext(text, bat.shape[1], ntime, t_stride) |
| 120 | + smin = np.max([0, s - sext]) |
| 121 | + smax = np.min([osh[0], s + sext + 1]) |
| 122 | + tmin = np.max([0, t - text]) |
| 123 | + tmax = np.min([osh[1], t + text + 1]) |
| 124 | + for sidx in np.arange(smin, smax): |
| 125 | + for tidx in np.arange(tmin, tmax): |
| 126 | + bost[sidx, tidx] = True |
| 127 | + return bost |
| 128 | + |
| 129 | +def plot_hm_ctrs(mf, bost, ilayer, itf, char, k, th, ff, channel): |
| 130 | + plt.figure(dpi=275) |
| 131 | + plt.imshow(mf, aspect='auto') |
| 132 | + plt.contour(bost, colors='red', levels=[0.5]) |
| 133 | + plt.title('Network Dissection for %s Channel %d, L%d FM%d, k=%d' %(char, channel, ilayer, itf, k)) |
| 134 | + plt.xlabel('Time') |
| 135 | + plt.ylabel('Muscles (Muscle / Spindle Firing Rate)') |
| 136 | + plt.savefig('%s/l%d/tf%d/%s/nwdiss_%d_th%s_ch%d.png' %(ff, ilayer, itf, char, k, th, channel)) |
| 137 | + plt.savefig('%s/l%d/tf%d/%s/nwdiss_%d_th%s_ch%d.svg' %(ff, ilayer, itf, char, k, th, channel)) |
| 138 | + plt.close() |
| 139 | +''' |
| 140 | +am = actmaps[0][0][0,0] |
| 141 | +idx = idxs[0][0][0,0].astype(int) |
| 142 | +
|
| 143 | +mf = data[idx] |
| 144 | +
|
| 145 | +resized = resize(am, mf.shape) |
| 146 | +bat = above_threshold(resized, threshold=0.5) |
| 147 | +
|
| 148 | +#bost = translate(bat) |
| 149 | +
|
| 150 | +
|
| 151 | +plot_hm_ctrs(mf, bat, 0, 0 , 'a', 0) |
| 152 | +
|
| 153 | +''' |
| 154 | + |
| 155 | +# %% MAIN |
| 156 | + |
| 157 | +def main(model, runinfo): |
| 158 | + |
| 159 | + ff = runinfo.analysisfolder(model, 'network_dissection') |
| 160 | + os.makedirs(ff, exist_ok=True) |
| 161 | + |
| 162 | + datafolder = runinfo.datafolder(model) |
| 163 | + |
| 164 | + #IMPORT DATA |
| 165 | + #kinvars = pd.read_hdf(datafolder + 'kinvars_10pc.hdf5') |
| 166 | + #mc = np.swapaxes(kinvars['muscle_coords'].values, 0, 1) |
| 167 | + #labels = pickle.load(open(datafolder + 'labels_10pc.pkl', 'rb')) |
| 168 | + #data = pickle.load(open(datafolder + 'data_10pc.pkl', 'rb')) |
| 169 | + data, xyplmvt = X_data('mf', runinfo, datafolder, polar=False) |
| 170 | + labels, _ = X_data('labels', runinfo, datafolder, polar=False) |
| 171 | + |
| 172 | + layers = [] |
| 173 | + |
| 174 | + nlayers = model['nlayers'] |
| 175 | + for ilayer in np.arange(-1, nlayers): |
| 176 | + ''' |
| 177 | + if ilayer==-1: |
| 178 | + layer='data' |
| 179 | +
|
| 180 | + else: |
| 181 | + layer = 'l%d' %ilayer |
| 182 | + lo = pickle.load(open(datafolder + layer + '_10pc.pkl', 'rb')) |
| 183 | + ''' |
| 184 | + lo = read_layer_reps(ilayer, runinfo, model) |
| 185 | + layers.append(lo[xyplmvt]) |
| 186 | + |
| 187 | + # %% DISSECTION |
| 188 | + #Store highest activations for every layer |
| 189 | + actmaps = [] |
| 190 | + idxs = [] |
| 191 | + |
| 192 | + for ilayer, layer in enumerate(layers): |
| 193 | + actmaps.append([]) |
| 194 | + idxs.append([]) |
| 195 | + for itf in range(layer.shape[3]): |
| 196 | + ams, ids = topk_actmaps(layer[...,itf], labels) |
| 197 | + actmaps[ilayer].append(ams) |
| 198 | + idxs[ilayer].append(ids) |
| 199 | + |
| 200 | + for ilayer in range(nlayers + 1): |
| 201 | + print("Layer %d" %ilayer) |
| 202 | + for itf in range(len(actmaps[ilayer])): |
| 203 | + print("TF %d" %itf) |
| 204 | + for ichar, char in enumerate(char_labels): |
| 205 | + #print(char) |
| 206 | + try: |
| 207 | + os.makedirs('%s/l%d/tf%d/%s/'%(ff, ilayer, itf, char)) |
| 208 | + except: |
| 209 | + print('folder already exists') |
| 210 | + |
| 211 | + for k in range(topk): |
| 212 | + for channel in range(data.shape[-1]): |
| 213 | + #print(k) |
| 214 | + idx = idxs[ilayer][itf][ichar][k].astype(int) |
| 215 | + |
| 216 | + mf = data[idx, ..., channel] |
| 217 | + am = actmaps[ilayer][itf][ichar][k] |
| 218 | + resized = resize(am, mf.shape) |
| 219 | + bat = above_threshold(resized, threshold=0.5) |
| 220 | + #bost = translate(bat) |
| 221 | + |
| 222 | + plot_hm_ctrs(mf, bat, ilayer, itf, char, k, '05', ff, channel) |
| 223 | + bat = above_threshold(resized, threshold=0.3) |
| 224 | + plot_hm_ctrs(mf, bat, ilayer, itf, char, k, '03', ff, channel) |
| 225 | + plt.close('all') |
0 commit comments