File size: 9,339 Bytes
688e887 086820c 237716a 086820c 527b2af ae884c3 086820c 527b2af 086820c 527b2af 086820c 527b2af 086820c 527b2af 086820c 527b2af 086820c 527b2af b668c7e 527b2af 086820c 527b2af 086820c 527b2af 086820c d404815 527b2af 086820c d404815 527b2af 086820c d404815 527b2af 086820c d404815 527b2af 086820c 688e887 086820c d404815 086820c d404815 086820c d404815 086820c 135b090 086820c 77ca615 9c9742b 77ca615 86d1c7a 9f5f543 86d1c7a 086820c 527b2af 086820c 3cf0e0f 086820c c6f97f0 086820c 28af0c6 086820c 688e887 8b71b4f 0df6dfd 50266c5 3cf0e0f 4bec5d9 6b4e6b7 086820c 527b2af 68affc8 086820c 527b2af 3cf0e0f 8b71b4f 527b2af c6f97f0 086820c 8b71b4f 0df6dfd c6f97f0 3c82907 db6d128 6bfda96 db6d128 420e766 646411c 086820c 838ce7d ae884c3 237716a f900a89 237716a 77ca615 86d1c7a 527b2af 237716a 86d1c7a 0df6dfd 56c8acc 527b2af 237716a 47df049 86d1c7a 086820c 952c48d 28af0c6 92e33c7 952c48d ea493d8 952c48d 527b2af 952c48d 0f7de41 e57a30b 86d1c7a 952c48d 086820c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
import gradio as gr
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
# import onnxruntime as ort
from PIL import Image
from scipy import special
import sys
from types import SimpleNamespace
from transformers import AutoModel
import torch
# sys.path.insert(1, "../")
# from utils import model_utils, train_utils, data_utils, run_utils
# from model_utils import jason_regnet_maker, jason_efficientnet_maker
model_path = 'chlab/'
# model_path = './models/'
# plotting a prameters
labels = 20
ticks = 14
legends = 14
text = 14
titles = 22
lw = 3
ps = 200
cmap = 'magma'
effnet_61_hparams = {
"num_classes": 2,
"gamma": 0.032606396652426956,
"lr": 0.008692971067922545,
"weight_decay": 0.00008348389688708425,
"batch_size": 23,
"num_channels": 61,
"stochastic_depth_prob": 0.003581930052432713,
"dropout": 0.027804120950575217,
"width_mult": 1.060782511229692,
"depth_mult": 0.7752918857163054,
}
effnet_61_config = SimpleNamespace(**effnet_61_hparams)
# which layers to look at
activation_indices = {'efficientnet': [0, 3]}
def normalize_array(x: list):
'''Makes array between 0 and 1'''
x = np.array(x)
return (x - np.min(x)) / np.max(x - np.min(x))
# def load_model(model: str, activation: bool=True):
# if activation:
# model += '_w_activation'
# # set options for onnx runtime
# options = ort.SessionOptions()
# options.intra_op_num_threads = 1
# options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
# provider = "CPUExecutionProvider"
# # start session
# ort_session = ort.InferenceSession(model_path + '%s.onnx' % (model), options, providers=[provider])
# # ort_session = ORTModel.load_model(model_path + '%s.onnx' % (model))
# return ort_session
def get_activations(model, image: list, model_name: str,
layer=None, vmax=2.5, sub_mean=True,
channel: int=0):
'''Gets activations for a given input image'''
# run model
# input_name = intermediate_model.get_inputs()[0].name
# outputs = intermediate_model.run(None, {input_name: image})
layer_outputs = {}
for i in range(len(model.model.features)):
image = model.model.features[i](image)
layer_outputs[i] = image
print(i, layer_outputs[i].shape)
output = model.model(image).detach().cpu().numpy()
output_1 = activation_indices[model_name].detach().cpu().numpy()
output_2 = activation_indices[model_name].detach().cpu().numpy()
# get activations
# output_1 = outputs[1]
# output_2 = outputs[2]
# get prediction
# output = outputs[0][0]
output = special.softmax(output)
# sum over velocity channels
if channel == 0:
in_image = np.sum(image[0, :, :, :], axis=0)
else:
image[0, int(channel-1), :, :]
in_image = normalize_array(in_image)
if layer is None:
# sum over all velocity channels
activation_1 = np.sum(output_1[0, :, :, :], axis=0)
activation_2 = np.sum(output_2[0, :, :, :], axis=0)
else:
# select a single channel
activation_1 = output_1[0, layer, :, :]
activation_2 = output_2[0, layer, :, :]
if sub_mean:
# y = |x - <x>|
activation_1 -= np.mean(activation_1)
activation_1 = np.abs(activation_1)
activation_2 -= np.mean(activation_2)
activation_2 = np.abs(activation_2)
return output, in_image, activation_1, activation_2
def plot_input(input_image: list, origin='lower'):
##### make the figure for the input image #####
plt.rcParams['xtick.labelsize'] = ticks
plt.rcParams['ytick.labelsize'] = ticks
input_fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(18, 8))
im0 = ax.imshow(input_image, cmap=cmap,
origin=origin)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
input_fig.colorbar(im0, cax=cax, orientation='vertical')
ax.set_title('Input', fontsize=titles)
return input_fig
def plot_activations(activation_1: list, activation_2: list, origin='lower'):
##### Make the activation figure ######
plt.rcParams['xtick.labelsize'] = ticks
plt.rcParams['ytick.labelsize'] = ticks
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(27, 12))
ax1, ax2 = axs[0], axs[1]
im1 = ax1.imshow(activation_1, cmap=cmap,
origin=origin)
im2 = ax2.imshow(activation_2, cmap=cmap,
origin=origin)
ims = [im1, im2]
for (i, ax) in enumerate(axs):
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(ims[i], cax=cax, orientation='vertical')
# ax0.set_title('Input', fontsize=titles)
ax1.set_title('Early Activation', fontsize=titles)
ax2.set_title('Late Activation', fontsize=titles)
return fig
def predict_and_analyze(model_name, num_channels, dim, input_channel, image):
'''
Loads a model with activations, passes through image and shows activations
The image must be a numpy array of shape (C, W, W) or (1, C, W, W)
'''
model_name = model_name.lower()
num_channels = int(num_channels)
W = int(dim)
print("Loading data")
print(image)
image = np.load(image.name, allow_pickle=True)
image = image.astype(np.float32)
if len(image.shape) != 4:
image = image[np.newaxis, :, :, :]
image = torch.from_numpy(image)
assert image.shape == (1, num_channels, W, W), "Data is the wrong shape"
# pipeline = pipeline(task="image-classification", model=model_path + "%s_%i_.pyt" % (model_name, num_channels))
# model_name += '_%i' % (num_channels)
model_loading_name = model_path + "%s_%i_planet_detection" % (model_name, num_channels)
print("Loading model")
# model = load_model(model_name, activation=True)
model = AutoModel.from_pretrained(model_loading_name)
print("Model loaded")
print("Looking at activations")
output, input_image, activation_1, activation_2 = get_activations(model, image, model_name,
channel=input_channel,
sub_mean=True)
print("Activations and predictions finished")
if output[0] < output[1]:
output = 'Planet predicted with %.3f percent confidence' % (100*output[1])
else:
output = 'No planet predicted with %.3f percent confidence' % (100*output[0])
input_image = normalize_array(input_image)
activation_1 = normalize_array(activation_1)
activation_2 = normalize_array(activation_2)
# convert input image to RGB (unused for now since not outputting actual image)
# input_pil_image = Image.fromarray(np.uint8(cm.magma(input_image)*255))
print("Plotting")
origin = 'upper'
# plot input image
input_fig = plot_input(input_image, origin=origin)
# plot mean subtracted activations
fig1 = plot_activations(activation_1, activation_2, model_name, origin=origin)
# plot raw activations
_, _, activation_1, activation_2 = get_activations(model, image, model_name,
channel=input_channel,
sub_mean=False)
activation_1 = normalize_array(activation_1)
activation_2 = normalize_array(activation_2)
fig2 = plot_activations(activation_1, activation_2, model_name, origin=origin)
print("Sending to Hugging Face")
return output, input_fig, fig1, fig2
if __name__ == "__main__":
demo = gr.Interface(
fn=predict_and_analyze,
inputs=[gr.Dropdown(["EfficientNet", "RegNet"],
value="EfficientNet",
label="Model Selection",
show_label=True),
gr.Dropdown(["47", "61", "75"],
value="61",
label="Number of Velocity Channels",
show_label=True),
gr.Dropdown(["600"],
value="600",
label="Image Dimensions",
show_label=True),
gr.Number(value=0.,
label="Input Channel to show (0 = sum over all)",
show_label=True),
gr.File(label="Input Data", show_label=True)],
outputs=[gr.Textbox(lines=1, label="Prediction", show_label=True),
# gr.Image(label="Input Image", show_label=True),
gr.Plot(label="Input Image", show_label=True),
gr.Plot(label="Mean-Subtracted Activations", show_label=True),
gr.Plot(label="Raw Activations", show_label=True)
],
title="Kinematic Planet Detector"
)
demo.launch()
|