Skip to content

Instantly share code, notes, and snippets.

View himanshurawlani's full-sized avatar

Himanshu Rawlani himanshurawlani

View GitHub Profile
@himanshurawlani
himanshurawlani / train_model.py
Last active March 21, 2019 20:54
Training a keras model using fit() method
def train_model(model):
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Creating Keras callbacks
tensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model_checkpoint_callback = keras.callbacks.ModelCheckpoint(
'training_checkpoints/weights.{epoch:02d}-{val_loss:.2f}.hdf5', period=5)
os.makedirs('training_checkpoints/', exist_ok=True)
@himanshurawlani
himanshurawlani / manually_train_model.py
Last active March 17, 2019 16:57
Using train_on_batch() method to customize training loop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True)
# Performing model training for the given number of epochs
for e in range(epochs):
print('Epoch', e)
@himanshurawlani
himanshurawlani / download_inceptionv3_model.py
Last active March 21, 2019 12:36
We can download Inception V3 base model pre-trained in Imagenet dataset using this script.
from tensorflow import keras
# Create the base model from the pre-trained model MobileNet V2
base_model = keras.applications.InceptionV3(input_shape=IMG_SHAPE,
# We cannot use the top classification layer of the pre-trained model as it contains 1000 classes.
# It also restricts our input dimensions to that which this model is trained on (default: 299x299)
include_top=False,
weights='imagenet')
@himanshurawlani
himanshurawlani / adding_classification_head.py
Created March 21, 2019 13:03
Using Keras's Sequential API to add classification head on top of InceptionV3 base model.
def build_model():
# Using Sequential API to stack up the layers
model = keras.Sequential([
base_model,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(metadata.features['label'].num_classes,
activation='softmax')
])
@himanshurawlani
himanshurawlani / finetune_inceptionv3.py
Last active March 21, 2019 15:23
Fine-tuning Inception V3 network by making base layers trainable and setting a lower learning rate.
# Un-freeze the top layers of the model
base_model.trainable = True
# Let's take a look to see how many layers are in the base model
print("Number of layers in the base model: ", len(base_model.layers))
# Fine tune from this layer onwards
fine_tune_at = 249
# Freeze all the layers before the `fine_tune_at` layer
for layer in base_model.layers[:fine_tune_at]:
@himanshurawlani
himanshurawlani / keras_export_savedmodel.py
Last active March 22, 2019 20:38
Exporting Keras models to SavedModel format in TensorFlow 2.0
from tensorflow import keras
# '/1' specifies the version of a model, or "servable" we want to export
path_to_saved_model = 'SavedModel/inceptionv3_128_tf_flowers/1'
# Saving the keras model in SavedModel format
keras.experimental.export_saved_model(inception_model, path_to_saved_model)
# Load the saved keras model back
restored_saved_model = keras.experimental.load_from_saved_model(path_to_saved_model)
@himanshurawlani
himanshurawlani / tensorflow_serving_request.py
Last active March 21, 2019 16:15
Making a TensorFlow Serving POST request to the REST client API
import json, requests
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import numpy as np
image_path = 'sunflower.jpg'
# Loading and pre-processing our input image
img = image.img_to_array(image.load_img(image_path, target_size=(128, 128))) / 255.
img = np.expand_dims(img, axis=0)
payload = {"instances": img.tolist()}
@himanshurawlani
himanshurawlani / augment_data.py
Created April 20, 2019 13:26
Performing data augmentation for data downloaded using TFDS
def augment_data(image, label):
print("Augment data called!")
image = tf.image.random_flip_left_right(image)
image = tf.image.random_contrast(image, lower=0.0, upper=1.0)
# Add more augmentation of your choice
return image, label
train = train.map(augment_data)
import tensorflow as tf
def FCN_model(len_classes=5, dropout_rate=0.2):
# Input layer
input = tf.keras.layers.Input(shape=(None, None, 3))
# A convolution block
x = tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=1)(input)
x = tf.keras.layers.Dropout(dropout_rate)(x)
# Uncomment the below line if you're using dense layers
# x = tf.keras.layers.GlobalMaxPooling2D()(x)
# Fully connected layer 1
# x = tf.keras.layers.Dropout(dropout_rate)(x)
# x = tf.keras.layers.BatchNormalization()(x)
# x = tf.keras.layers.Dense(units=64)(x)
# x = tf.keras.layers.Activation('relu')(x)
# Fully connected layer 1