jpterry commited on
Commit
527b2af
·
1 Parent(s): ea493d8

trying to use pyt

Browse files
Files changed (2) hide show
  1. app.py +80 -30
  2. requirements.txt +2 -2
app.py CHANGED
@@ -3,12 +3,20 @@ from matplotlib import cm
3
  import matplotlib.pyplot as plt
4
  from mpl_toolkits.axes_grid1 import make_axes_locatable
5
  import numpy as np
6
- import onnxruntime as ort
7
  from PIL import Image
8
  from scipy import special
 
 
 
 
9
 
10
- # model_path = 'chlab/planet_detection_models/'
11
- model_path = './models/'
 
 
 
 
12
 
13
  # plotting a prameters
14
  labels = 20
@@ -20,6 +28,24 @@ lw = 3
20
  ps = 200
21
  cmap = 'magma'
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def normalize_array(x: list):
24
 
25
  '''Makes array between 0 and 1'''
@@ -28,42 +54,56 @@ def normalize_array(x: list):
28
 
29
  return (x - np.min(x)) / np.max(x - np.min(x))
30
 
31
- def load_model(model: str, activation: bool=True):
32
 
33
- if activation:
34
- model += '_w_activation'
35
 
36
- # set options for onnx runtime
37
- options = ort.SessionOptions()
38
- options.intra_op_num_threads = 1
39
- options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
40
- provider = "CPUExecutionProvider"
41
 
42
- # start session
43
- ort_session = ort.InferenceSession(model_path + '%s.onnx' % (model), options, providers=[provider])
44
- # ort_session = ORTModel.load_model(model_path + '%s.onnx' % (model))
45
 
46
- return ort_session
47
 
48
- def get_activations(intermediate_model, image: list,
49
- layer=None, vmax=2.5, sub_mean=True):
 
50
 
51
  '''Gets activations for a given input image'''
52
 
53
  # run model
54
- input_name = intermediate_model.get_inputs()[0].name
55
- outputs = intermediate_model.run(None, {input_name: image})
 
 
 
 
 
 
 
 
 
 
56
 
57
  # get activations
58
- output_1 = outputs[1]
59
- output_2 = outputs[2]
60
 
61
  # get prediction
62
- output = outputs[0][0]
63
  output = special.softmax(output)
64
 
65
  # sum over velocity channels
66
- in_image = np.sum(image[0, :, :, :], axis=0)
 
 
 
67
  in_image = normalize_array(in_image)
68
 
69
  if layer is None:
@@ -134,7 +174,7 @@ def plot_activations(activation_1: list, activation_2: list, origin='lower'):
134
  return fig
135
 
136
 
137
- def predict_and_analyze(model_name, num_channels, dim, image):
138
 
139
  '''
140
  Loads a model with activations, passes through image and shows activations
@@ -153,16 +193,23 @@ def predict_and_analyze(model_name, num_channels, dim, image):
153
  if len(image.shape) != 4:
154
  image = image[np.newaxis, :, :, :]
155
 
 
 
156
  assert image.shape == (1, num_channels, W, W), "Data is the wrong shape"
157
 
158
- model_name += '_%i' % (num_channels)
 
 
 
 
159
 
160
  print("Loading model")
161
- model = load_model(model_name, activation=True)
 
162
  print("Model loaded")
163
 
164
  print("Looking at activations")
165
- output, input_image, activation_1, activation_2 = get_activations(model, image, sub_mean=True)
166
  print("Activations and predictions finished")
167
 
168
  if output[0] < output[1]:
@@ -185,13 +232,13 @@ def predict_and_analyze(model_name, num_channels, dim, image):
185
  input_fig = plot_input(input_image, origin=origin)
186
 
187
  # plot mean subtracted activations
188
- fig1 = plot_activations(activation_1, activation_2, origin=origin)
189
 
190
  # plot raw activations
191
- _, _, activation_1, activation_2 = get_activations(model, image, sub_mean=False)
192
  activation_1 = normalize_array(activation_1)
193
  activation_2 = normalize_array(activation_2)
194
- fig2 = plot_activations(activation_1, activation_2, origin=origin)
195
 
196
  print("Sending to Hugging Face")
197
 
@@ -214,6 +261,9 @@ if __name__ == "__main__":
214
  value="600",
215
  label="Image Dimensions",
216
  show_label=True),
 
 
 
217
  gr.File(label="Input Data", show_label=True)],
218
  outputs=[gr.Textbox(lines=1, label="Prediction", show_label=True),
219
  # gr.Image(label="Input Image", show_label=True),
 
3
  import matplotlib.pyplot as plt
4
  from mpl_toolkits.axes_grid1 import make_axes_locatable
5
  import numpy as np
6
+ # import onnxruntime as ort
7
  from PIL import Image
8
  from scipy import special
9
+ import sys
10
+ from types import SimpleNamespace
11
+ from transformers import AutoModel
12
+ import torch
13
 
14
+ # sys.path.insert(1, "../")
15
+ # from utils import model_utils, train_utils, data_utils, run_utils
16
+ # from model_utils import jason_regnet_maker, jason_efficientnet_maker
17
+
18
+ model_path = 'chlab/'
19
+ # model_path = './models/'
20
 
21
  # plotting a prameters
22
  labels = 20
 
28
  ps = 200
29
  cmap = 'magma'
30
 
31
+ effnet_61_hparams = {
32
+ "num_classes": 2,
33
+ "gamma": 0.032606396652426956,
34
+ "lr": 0.008692971067922545,
35
+ "weight_decay": 0.00008348389688708425,
36
+ "batch_size": 23,
37
+ "num_channels": 61,
38
+ "stochastic_depth_prob": 0.003581930052432713,
39
+ "dropout": 0.027804120950575217,
40
+ "width_mult": 1.060782511229692,
41
+ "depth_mult": 0.7752918857163054,
42
+ }
43
+ effnet_61_config = SimpleNamespace(**effnet_61_hparams)
44
+
45
+ # which layers to look at
46
+ activation_indices = {'efficientnet': [0, 3]}
47
+
48
+
49
  def normalize_array(x: list):
50
 
51
  '''Makes array between 0 and 1'''
 
54
 
55
  return (x - np.min(x)) / np.max(x - np.min(x))
56
 
57
+ # def load_model(model: str, activation: bool=True):
58
 
59
+ # if activation:
60
+ # model += '_w_activation'
61
 
62
+ # # set options for onnx runtime
63
+ # options = ort.SessionOptions()
64
+ # options.intra_op_num_threads = 1
65
+ # options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
66
+ # provider = "CPUExecutionProvider"
67
 
68
+ # # start session
69
+ # ort_session = ort.InferenceSession(model_path + '%s.onnx' % (model), options, providers=[provider])
70
+ # # ort_session = ORTModel.load_model(model_path + '%s.onnx' % (model))
71
 
72
+ # return ort_session
73
 
74
+ def get_activations(model, image: list, model_name: str,
75
+ layer=None, vmax=2.5, sub_mean=True,
76
+ channel: int=0):
77
 
78
  '''Gets activations for a given input image'''
79
 
80
  # run model
81
+ # input_name = intermediate_model.get_inputs()[0].name
82
+ # outputs = intermediate_model.run(None, {input_name: image})
83
+
84
+
85
+ layer_outputs = {}
86
+ for i in range(len(model.model.features)):
87
+ image = model.model.features[i](image)
88
+ layer_outputs[i] = image
89
+ print(i, layer_outputs[i].shape)
90
+ output = model.model(image).detach().cpu().numpy()
91
+ output_1 = activation_indices[model_name].detach().cpu().numpy()
92
+ output_2 = activation_indices[model_name].detach().cpu().numpy()
93
 
94
  # get activations
95
+ # output_1 = outputs[1]
96
+ # output_2 = outputs[2]
97
 
98
  # get prediction
99
+ # output = outputs[0][0]
100
  output = special.softmax(output)
101
 
102
  # sum over velocity channels
103
+ if channel == 0:
104
+ in_image = np.sum(image[0, :, :, :], axis=0)
105
+ else:
106
+ image[0, int(channel-1), :, :]
107
  in_image = normalize_array(in_image)
108
 
109
  if layer is None:
 
174
  return fig
175
 
176
 
177
+ def predict_and_analyze(model_name, num_channels, dim, input_channel, image):
178
 
179
  '''
180
  Loads a model with activations, passes through image and shows activations
 
193
  if len(image.shape) != 4:
194
  image = image[np.newaxis, :, :, :]
195
 
196
+ image = torch.from_numpy(image)
197
+
198
  assert image.shape == (1, num_channels, W, W), "Data is the wrong shape"
199
 
200
+ # pipeline = pipeline(task="image-classification", model=model_path + "%s_%i_.pyt" % (model_name, num_channels))
201
+
202
+ # model_name += '_%i' % (num_channels)
203
+
204
+ model_loading_name = model_path + "%s_%i_planet_detection" % (model_name, num_channels)
205
 
206
  print("Loading model")
207
+ # model = load_model(model_name, activation=True)
208
+ model = AutoModel.from_pretrained(model_loading_name)
209
  print("Model loaded")
210
 
211
  print("Looking at activations")
212
+ output, input_image, activation_1, activation_2 = get_activations(model, image, model_name, sub_mean=True)
213
  print("Activations and predictions finished")
214
 
215
  if output[0] < output[1]:
 
232
  input_fig = plot_input(input_image, origin=origin)
233
 
234
  # plot mean subtracted activations
235
+ fig1 = plot_activations(activation_1, activation_2, model_name, origin=origin)
236
 
237
  # plot raw activations
238
+ _, _, activation_1, activation_2 = get_activations(model, image, model_name, sub_mean=False)
239
  activation_1 = normalize_array(activation_1)
240
  activation_2 = normalize_array(activation_2)
241
+ fig2 = plot_activations(activation_1, activation_2, model_name, origin=origin)
242
 
243
  print("Sending to Hugging Face")
244
 
 
261
  value="600",
262
  label="Image Dimensions",
263
  show_label=True),
264
+ gr.Number(value=0.,
265
+ label="Input Channel to show (0 = sum over all)",
266
+ show_label=True),
267
  gr.File(label="Input Data", show_label=True)],
268
  outputs=[gr.Textbox(lines=1, label="Prediction", show_label=True),
269
  # gr.Image(label="Input Image", show_label=True),
requirements.txt CHANGED
@@ -2,5 +2,5 @@ torch
2
  numpy
3
  matplotlib
4
  scipy
5
- onnxruntime
6
- Pillow
 
2
  numpy
3
  matplotlib
4
  scipy
5
+ Pillow
6
+ transformers