Use Case: Deploying a Keras Image Classification Model Using Google Cloud Platform
- Objective: Build an image classification model using Keras and deploy it on Google Cloud Platform (GCP) to handle requests at scale.
Prepare the Environment
- Create a Google Cloud account and initiate a new project.
- Enable APIs such as Cloud Storage, AI Platform, and Compute Engine for your project.
- Install Google Cloud SDK for managing GCP resources, and configure it to access your project.
- Set up a virtual environment and install necessary libraries:
python3 -m venv myenv
source myenv/bin/activate
pip install tensorflow keras google-cloud-storage
Build the Keras Model
- Create an image classification model using Keras. Here's an example using a convolutional neural network:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
- Preprocess and organize your image dataset into train and test directories.
Utilize Google Cloud Storage
- Upload your image data to a Google Cloud Storage bucket for accessibility during training and inference.
- Transfer files using the gsutil command:
gsutil cp -r /local/path/to/images gs://your-bucket-name/images
Train the Model on AI Platform
- Train your model on AI Platform to take advantage of GCP’s powerful infrastructure.
- Convert your training script into a Python module, and create a setup.py file to define dependencies.
- Submit the training job:
gcloud ai-platform jobs submit training job_name \
--scale-tier BASIC_TPU \
--package-path /path/to/your/code \
--module-name your_code.module_name \
--region us-central1 \
-- \
--data-dir gs://your-bucket-name/images \
--num-epochs 20
Model Deployment on AI Platform
- Deploy your trained model to Google Cloud AI Platform for scalable serving.
- Export the model using the SavedModel format and upload it to your Cloud Storage bucket:
model.save('save_dir/model.h5')
gsutil cp save_dir/model.h5 gs://your-bucket-name/models/model.h5
- Register the model and create a version to serve it through a managed endpoint:
gcloud ai-platform models create image_classifier --regions us-central1
gcloud ai-platform versions create v1 \
--model image_classifier \
--origin gs://your-bucket-name/models/model.h5 \
--runtime-version 2.5 \
--framework "KERAS" \
--python-version 3.8
Conclusion
- By integrating Keras with Google Cloud Platform, you can efficiently build, train, and deploy image classification models. GCP provides resources that enable model scalability and accessibility for users worldwide through its robust infrastructure.