generated from XpressAI/xai-component-library-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtf_keras.py
804 lines (688 loc) · 30.9 KB
/
tf_keras.py
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
from tensorflow.keras import applications
from tensorflow.keras.preprocessing import image
import numpy as np
from xai_components.base import InArg, InCompArg, OutArg, Component, xai_component
@xai_component
class LoadKerasModel(Component):
"""Loads a Keras application model instance.
## Reference:
- [Keras Model Applications](https://keras.io/api/applications/)
##### inPorts:
- model_name: A Keras model instance.
- include_top: whether to include the fully-connected
layer at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
- args: additional arguments that may configure the Keras model
instance behaviour, but not included as inPorts. Click link
in Reference for more details.
##### outPorts:
- model: A Keras model instance.
"""
model_name: InCompArg[str]
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
args: InArg[int]
model: OutArg[any]
def execute(self,ctx) -> None:
args = self.args.value if self.args.value else {}
try:
import tensorflow
model = getattr(tensorflow.keras.applications, self.model_name.value)(weights='imagenet', **args)
self.model.value = model
except Exception as e:
if self.model_name.value:
print(f"model_name:{e} not found!\nPlease refer to the official keras list of supported models: https://keras.io/api/applications/")
@xai_component
class KerasPredict(Component):
"""Performs prediction given a Keras application model instance.
### Reference:
- [Keras Model Applications](https://keras.io/api/applications/)
##### inPorts:
- model: A Keras model instance.
- img_string: an image path.
- class_list: list of classes if not using IMAGENET.
- target_shape: optional shape tuple, only to be
specified if using a input custom shape.
Expected two values (height and width).
"""
model:InCompArg[any]
img_string: InCompArg[str]
class_list: InArg[any]
target_shape: InArg[tuple]
def execute(self, ctx) -> None:
model = self.model.value
img_path = self.img_string.value
class_list = self.class_list.value if self.class_list.value else []
class keras_model_config:
preprocess_input: any
decode_predictions: any
target_size:any
def __init__(self):
self.preprocess_input = None
self.decode_predictions = None
self.target_size = (224, 224)
model_config = keras_model_config()
# Note: currently searches whether model name starts with the common terms.
# Using str.split("_")[0] does not work as inception_v3 and mobilenetv2 will return different values.
# Note2: each Keras Application expects a specific kind of input preprocessing.
# IE: For DenseNet, call tf.keras.applications.densenet.preprocess_input on your inputs before passing them to the model.
if model.name.startswith('xception'):
model_config.preprocess_input = applications.xception.preprocess_input
model_config.decode_predictions = applications.xception.decode_predictions
model_config.target_size = (299, 299)
if model.name.startswith('vgg16'):
model_config.preprocess_input = applications.vgg16.preprocess_input
model_config.decode_predictions = applications.vgg16.decode_predictions
if model.name.startswith('vgg19'):
model_config.preprocess_input = applications.vgg19.preprocess_input
model_config.decode_predictions = applications.vgg19.decode_predictions
if model.name.startswith('resnet50'):
model_config.preprocess_input = applications.resnet50.preprocess_input
model_config.decode_predictions = applications.resnet50.decode_predictions
if model.name.startswith('resnet101'):
model_config.preprocess_input = applications.resnet.preprocess_input
model_config.decode_predictions = applications.resnet.decode_predictions
if model.name.startswith('resnet152'):
model_config.preprocess_input = applications.resnet.preprocess_input
model_config.decode_predictions = applications.resnet.decode_predictions
if model.name.startswith('inception_v3'):
model_config.preprocess_input = applications.inception_v3.preprocess_input
model_config.decode_predictions = applications.inception_v3.decode_predictions
model_config.target_size = (299, 299)
if model.name.startswith('mobilenetv2'):
model_config.preprocess_input = applications.mobilenet_v2.preprocess_input
model_config.decode_predictions = applications.mobilenet_v2.decode_predictions
if model.name.startswith('mobilenet'):
model_config.preprocess_input = applications.mobilenet.preprocess_input
model_config.decode_predictions = applications.mobilenet.decode_predictions
#handler for densenet121, 169, 201
if model.name.startswith('densenet'):
model_config.preprocess_input = applications.densenet.preprocess_input
model_config.decode_predictions = applications.densenet.decode_predictions
if model_config.preprocess_input:
img = image.load_img(img_path, target_size=model_config.target_size)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = model_config.preprocess_input(x)
preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print(model.name, ' predictions:', model_config.decode_predictions(preds, top=3)[0])
else:
print(f"Keras model {model.name} config not found!\n")
print(f"Auto adjusting according to model input.\n")
# expected input_shape => (None, 256, 256, 3)
if isinstance(self.target_shape.value, tuple):
if len(self.target_shape.value) != 2:
raise AssertionError(f"Expected two values (height and width) as target shape, got {len(self.target_shape.value)}")
target_shape = self.target_shape.value if self.target_shape.value else model.input_shape[1:3]
img = image.load_img(img_path, target_size=target_shape)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
preds = model.predict(x)
print(preds)
class resnet_model_config:
include_top: bool #true
weights:str #"imagenet",
input_tensor: any
input_shape: any
pooling: any
classes: int
def __init__(self):
self.include_top = True
self.weights = "imagenet"
self.input_tensor = None
self.pooling = None
self.classes = 1000
@xai_component
class ResNet50(Component):
"""Instantiates the ResNet50 model.
### Reference:
- [Keras Application ResNet50](
https://keras.io/api/applications/resnet/#resnet50-function)
- [Deep Residual Learning for Image Recognition](
https://arxiv.org/abs/1512.03385) (CVPR 2015)
##### inPorts:
- include_top: whether to include the fully-connected
layer at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
- kwargs: additional arguments that may configure the Keras model
instance behaviour, but not included as inPorts. Click link
in Reference for more details.
##### outPorts:
- model: A Keras model instance.
"""
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
kwargs: InArg[int]
model: OutArg[any]
def execute(self, ctx) -> None:
model_config = resnet_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.ResNet50(model_config)
self.model.value = model
@xai_component
class ResNet101(Component):
"""Instantiates the ResNet101 model.
### Reference:
- [Keras Application ResNet50](
https://keras.io/api/applications/resnet/#resnet101-function)
- [Deep Residual Learning for Image Recognition](
https://arxiv.org/abs/1512.03385) (CVPR 2015)
##### inPorts:
- include_top: whether to include the fully-connected
layer at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
- kwargs: additional arguments that may configure the Keras model
instance behaviour, but not included as inPorts. Click link
in Reference for more details.
##### outPorts:
- model: A Keras model instance.
"""
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
kwargs: InArg[int]
model: OutArg[any]
def execute(self, ctx) -> None:
model_config = resnet_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.ResNet101(model_config)
self.model.value = model
@xai_component
class ResNet152(Component):
"""Instantiates the ResNet152 model.
### Reference:
- [Keras Application ResNet152](
https://keras.io/api/applications/resnet/#resnet152-function)
- [Deep Residual Learning for Image Recognition](
https://arxiv.org/abs/1512.03385) (CVPR 2015)
##### inPorts:
- include_top: whether to include the fully-connected
layer at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
- kwargs: additional arguments that may configure the Keras model
instance behaviour, but not included as inPorts. Click link
in Reference for more details.
##### outPorts:
- model: A Keras model instance.
"""
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
kwargs: InArg[int]
model: OutArg[any]
def execute(self, ctx) -> None:
model_config = resnet_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.ResNet152(model_config)
self.model.value = model
class vgg_model_config:
include_top: bool #true
weights:str #"imagenet",
input_tensor: any
input_shape: any
pooling: any
classes: int
classifier_activation: str
def __init__(self):
self.include_top = True
self.weights = "imagenet"
self.input_tensor = None
self.pooling = None
self.classes = 1000
self.classifier_activation = "softmax"
@xai_component
class VGG16(Component):
"""Instantiates the VGG16 model.
### Reference:
- [Keras Application VGG16](
https://keras.io/api/applications/vgg/#vgg16-function)
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](
https://arxiv.org/abs/1409.1556) (ICLR 2015)
##### inPorts:
- include_top: whether to include the 3 fully-connected
layers at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)`
(with `channels_last` data format)
or `(3, 224, 224)` (with `channels_first` data format).
It should have exactly 3 input channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
- classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
When loading pretrained weights, `classifier_activation` can only
be `None` or `"softmax"`.
- kwargs: additional arguments that may configure the Keras model
instance behaviour, but not included as inPorts. Click link
in Reference for more details.
##### outPorts:
- model: A Keras model instance.
"""
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
classifier_activation: InArg[int]
model: OutArg[any]
def execute(self, ctx) -> None:
model_config = vgg_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.VGG16(model_config)
self.model.value = model
@xai_component
class VGG19(Component):
"""Instantiates the VGG19 architecture.
### Reference:
- [Keras Application VGG19](
https://keras.io/api/applications/vgg/#vgg19-function)
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](
https://arxiv.org/abs/1409.1556) (ICLR 2015)
##### inPorts:
- include_top: whether to include the 3 fully-connected
layers at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)`
(with `channels_last` data format)
or `(3, 224, 224)` (with `channels_first` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
- classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
When loading pretrained weights, `classifier_activation` can only
be `None` or `"softmax"`.
##### outPorts:
- model: A Keras model instance.
"""
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
classifier_activation: InArg[int]
model: OutArg[any]
def execute(self, ctx) -> None:
model_config = vgg_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.VGG19(model_config)
self.model.value = model
@xai_component
class Xception(Component):
"""Instantiates the Xception architecture.
### Reference:
- [Keras Application Xception](
https://keras.io/api/applications/xception/)
- [Xception: Deep Learning with Depthwise Separable Convolutions](
https://arxiv.org/abs/1610.02357) (CVPR 2017)
##### inPorts:
- include_top: whether to include the fully-connected
layer at the top of the network.
- weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
- input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
- input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(299, 299, 3)`.
It should have exactly 3 inputs channels,
and width and height should be no smaller than 71.
E.g. `(150, 150, 3)` would be one valid value.
- pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
- classes: optional number of classes to classify images
into, only to be specified if `include_top` is True,
and if no `weights` argument is specified.
- classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
When loading pretrained weights, `classifier_activation` can only
be `None` or `"softmax"`.
##### outPorts:
- model: A Keras model instance.
"""
include_top: InArg[bool]
weights:InArg[str]
input_tensor: InArg[any]
input_shape: InArg[any]
pooling: InArg[any]
classes: InArg[int]
classifier_activation: InArg[int]
model: OutArg[any]
def execute(self, ctx) -> None:
#Xception and vgg share model configs
model_config = vgg_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.Xception(model_config)
self.model.value = model
class mobile_model_config:
input_shape: any
alpha:any
depth_multiplier:int
dropout:float
include_top: bool
weights: str
input_tensor: any
pooling: any
classes: int
classifier_activation: str
def __init__(self):
self.input_shape=None
self.alpha=1.0
self.depth_multiplier=1
self.dropout=0.001
self.include_top=True
self.weights="imagenet"
self.input_tensor=None
self.pooling=None
self.classes=1000
self.classifier_activation="softmax"
@xai_component
class MobileNet(Component):
"""Instantiates the Keras MobileNet model for image classification,
optionally loaded with weights pre-trained on ImageNet.
### Reference:
- [Keras Application MobileNet](
https://keras.io/api/applications/mobilenet/)
- [MobileNets: Efficient Convolutional Neural Networks
for Mobile Vision Applications](
https://arxiv.org/abs/1704.04861)
##### inPorts:
- input_shape: Optional shape tuple, only to be specified if `include_top`
is False (otherwise the input shape has to be `(224, 224, 3)` (with
`channels_last` data format) or (3, 224, 224) (with `channels_first`
data format). It should have exactly 3 inputs channels, and width and
height should be no smaller than 32. E.g. `(200, 200, 3)` would be one
valid value. Default to `None`.
`input_shape` will be ignored if the `input_tensor` is provided.
- alpha: Controls the width of the network. This is known as the width
multiplier in the MobileNet paper. - If `alpha` < 1.0, proportionally
decreases the number of filters in each layer. - If `alpha` > 1.0,
proportionally increases the number of filters in each layer. - If
`alpha` = 1, default number of filters from the paper are used at each
layer. Default to 1.0.
- depth_multiplier: Depth multiplier for depthwise convolution. This is
called the resolution multiplier in the MobileNet paper. Default to 1.0.
- dropout: Dropout rate. Default to 0.001.
- include_top: Boolean, whether to include the fully-connected layer at the
top of the network. Default to `True`.
- weights: One of `None` (random initialization), 'imagenet' (pre-training
on ImageNet), or the path to the weights file to be loaded. Default to
`imagenet`.
- input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`) to
use as image input for the model. `input_tensor` is useful for sharing
inputs between multiple different networks. Default to None.
- pooling: Optional pooling mode for feature extraction when `include_top`
is `False`.
- `None` (default) means that the output of the model will be
the 4D tensor output of the last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will be applied.
- classes: Optional number of classes to classify images into, only to be
specified if `include_top` is True, and if no `weights` argument is
specified. Defaults to 1000.
- classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
When loading pretrained weights, `classifier_activation` can only
be `None` or `"softmax"`.
- **kwargs: For backwards compatibility only.
##### outPorts:
- model: A Keras model instance.
"""
input_shape: InArg[any]
alpha: InArg[any]
depth_multiplier: InArg[int]
dropout: InArg[float]
include_top: InArg[bool]
weights: InArg[str]
input_tensor: InArg[any]
pooling: InArg[any]
classes: InArg[int]
classifier_activation: InArg[str]
kwargs: InArg[any]
model: OutArg[any]
def execute(self, ctx) -> None:
model_config = mobile_model_config()
#dynamically sync model config with node inputs
for port in self.__dict__.keys():
try:
portValue = getattr(self, port).value
if portValue != None:
for config in model_config.__dict__.keys():
if config == port:
setattr(model_config, config, portValue)
except Exception as e:
pass
model = applications.MobileNet(model_config)
self.model.value = model