Download a model and use it offline

This is an example to show how to download a model and use it offline. We use VGG16 which is a convolutional neural network model that’s used for image recognition.

Step 1: Save the Model Weights and Architecture

You can save the model using TensorFlow’s built-in functions. The model can be saved in two parts:

  1. Model Architecture (JSON): Save the model’s architecture as a JSON file.
  2. Model Weights (HDF5): Save the model’s weights in an HDF5 file.

Here’s the modified code to save the model:

from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
import tensorflow as tf

# Load the VGG16 model
base_model = VGG16(input_shape=(224, 224, 3), include_top=False, weights='imagenet')

# Freeze the layers
for layer in base_model.layers:
    layer.trainable = False

# Add custom layers
x = Flatten()(base_model.output)
x = Dense(1024, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(3, activation='softmax')(x)

# Create the final model
model = Model(base_model.input, x)

# Compile the model
model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=["accuracy"])

# Save the model architecture to a JSON file
model_json = model.to_json()
with open("vgg16_model.json", "w") as json_file:
    json_file.write(model_json)

# Save the model weights to an HDF5 file
model.save_weights("vgg16_weights.h5")

print("Model and weights saved successfully!")

Step 2: Load the Model Offline

To use the model offline, you can load the saved architecture and weights:

from tensorflow.keras.models import model_from_json

# Load the model architecture from the JSON file
with open("vgg16_model.json", "r") as json_file:
    loaded_model_json = json_file.read()

loaded_model = model_from_json(loaded_model_json)

# Load the weights into the model
loaded_model.load_weights("vgg16_weights.h5")

# Compile the model (necessary before using it)
loaded_model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=["accuracy"])

print("Model loaded successfully!")
loaded_model.summary()

Step 3: Use the Model Offline

Now you can use the loaded_model for predictions or further training without needing an internet connection.

Notes:

  • The weights='imagenet' argument in VGG16 downloads the pre-trained weights from the internet. Once saved locally, you won’t need to download them again.
  • Ensure you have the required dependencies (e.g., TensorFlow) installed on the offline machine.
  • If you want to save the entire model (architecture + weights + optimizer state) in a single file, you can use model.save("vgg16_full_model.h5") and load it using tf.keras.models.load_model("vgg16_full_model.h5"). This is simpler but less modular.