davidaf3 commited on
Commit
65e71e9
1 Parent(s): 1078ded

Added pipeline

Browse files
Files changed (2) hide show
  1. fcnutr.py +38 -0
  2. pipeline.py +32 -0
fcnutr.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tensorflow import keras
2
+
3
+ class FCNutr(keras.Model):
4
+ def __init__(self, nutr_names, crop_size, hidden_dim, num_shared_hidden, use_dropout):
5
+ super().__init__()
6
+
7
+ self.cnn = keras.applications.InceptionV3(
8
+ include_top=False,
9
+ weights="imagenet",
10
+ input_shape=crop_size + (3,),
11
+ pooling='avg'
12
+ )
13
+
14
+ shared_layers = []
15
+ for i in range(num_shared_hidden):
16
+ if use_dropout:
17
+ shared_layers.append(keras.layers.Dropout(0.2 if i == 0 else 0.5))
18
+ shared_layers.append(keras.layers.Dense(hidden_dim, activation="relu"))
19
+
20
+ self.shared = keras.Sequential(shared_layers, name='shared')
21
+
22
+ self.multitask_heads = []
23
+ for name in nutr_names:
24
+ head_layers = [
25
+ keras.layers.Dense(hidden_dim, activation="relu"),
26
+ keras.layers.Dense(1, activation="relu")
27
+ ]
28
+
29
+ if use_dropout:
30
+ head_layers.insert(0, keras.layers.Dropout(0.5))
31
+ head_layers.insert(2, keras.layers.Dropout(0.5))
32
+
33
+ self.multitask_heads.append(keras.Sequential(head_layers, name=name))
34
+
35
+ def call(self, inputs, training=False):
36
+ x = self.cnn(inputs, training=training)
37
+ x = self.shared(x, training=training)
38
+ return {head.name: head(x, training=training) for head in self.multitask_heads}
pipeline.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from PIL import Image
3
+ from fcnutr import FCNutr
4
+
5
+ import os
6
+ import json
7
+ import numpy as np
8
+ import tensorflow as tf
9
+
10
+
11
+ class PreTrainedPipeline():
12
+ def __init__(self, path=""):
13
+ crop_size = (224, 224)
14
+ self.nutr_names = ('energy', 'fat', 'protein', 'carbs')
15
+ self.model = FCNutr(self.nutr_names, crop_size, 4096, 3, False)
16
+ self.model.compile()
17
+ self.model(tf.zeros((1, crop_size[0], crop_size[1], 3)))
18
+ self.model.load_weights(os.path.join(path, "fcnutr.h5"))
19
+
20
+ def __call__(self, inputs: "Image.Image") -> List[Dict[str, Any]]:
21
+ image = tf.keras.preprocessing.image.img_to_array(inputs)
22
+ height = tf.shape(image)[0]
23
+ width = tf.shape(image)[1]
24
+ if width > height:
25
+ image = tf.image.resize(image, (self.img_size, int(float(self.img_size * width) / float(height))))
26
+ else:
27
+ image = tf.image.resize(image, (int(float(self.img_size * height) / float(width)), self.img_size))
28
+
29
+ image = tf.keras.applications.inception_v3.preprocess_input(image)
30
+ image = tf.keras.layers.CenterCrop(*self.crop_size)(image)
31
+ prediction = self.model(image[tf.newaxis, :])
32
+ return {name: float(prediction[name].numpy()[0, 0]) for name in self.nutr_names}