Build and Deploy a Simple Image Classifier on macOS with Anaconda and Docker

This guide walks you through setting up Anaconda, preparing UI component images, training a SimpleVGGNet model on macOS, and deploying the model as a Docker‑based service that can be queried via an HTTP API.

Taobao Frontend Technology
Taobao Frontend Technology
Taobao Frontend Technology
Build and Deploy a Simple Image Classifier on macOS with Anaconda and Docker

Many beginners feel lost when starting with machine learning because they have to set up environments, train models, and deploy them. This tutorial provides a step‑by‑step, ready‑to‑run example that lets you experience the full machine‑learning workflow on a Mac.

Environment Preparation

Install Anaconda

Download Anaconda from the official site, install it, and refresh the shell: $ source ~/.bashrc Verify the installation: $ cat ~/.bashrc List installed packages: $ conda list If installation fails, reinstall and choose a custom install location.

Install additional dependencies

$ pip install keras
$ pip install tensorflow
$ pip install opencv-python

Sample Preparation (NO.2)

Four UI component categories are used: button , keyboard , searchbar , and switch , each with about 200 images.

sample images
sample images

Model Training (NO.3)

Create a project train-project with the following structure:

.
├── CNN_net.py
├── dataset
├── nn_train.py
└── utils_paths.py

The main training script nn_train.py loads images, builds a SimpleVGGNet model, applies data augmentation, and trains for a small number of epochs (5) for quick demonstration:

# nn_train.py
from CNN_net import SimpleVGGNet
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
import utils_paths, matplotlib.pyplot as plt, cv2, numpy as np, argparse, random, pickle, os

print("------开始读取数据------")
# ... (data loading code omitted for brevity) ...
model = SimpleVGGNet.build(width=256, height=256, depth=3, classes=len(lb.classes_))
INIT_LR = 0.01
EPOCHS = 5
BS = 32
opt = SGD(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])
H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS), validation_data=(testX, testY), steps_per_epoch=len(trainX)//BS, epochs=EPOCHS)
# Save model
model.save('./cnn.model.h5')

Run the training: $ python nn_train.py Training logs and generated files ( cnn.model.h5 and output/cnn_plot.png) are shown in the article.

Model Evaluation (NO.4)

Use predict.py to load the saved model and predict the class of a test image:

# predict.py
import tensorflow as tf, cv2, numpy as np, json
model = tf.keras.models.load_model('./train/cnn.model.h5')
Label = ["button", "keyboard", "searchbar", "switch"]
image = cv2.imread('./test/button.png')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (256,256))
pred = model.predict(np.expand_dims(image, axis=0))
print('Predicted:', Label[np.argmax(pred)])

Model Service Development (NO.5)

Create a service script app.py that receives image URLs via JSON, decodes them, runs inference, and returns the top‑k predictions with confidence thresholds.

# app.py (simplified)
import allspark, json, cv2, numpy as np, tensorflow as tf
model = tf.keras.models.load_model('./cnn.model.h5')
# Functions to download images, preprocess, predict, and format response

Deploying the Service

Package the service in a Docker container. First install Docker (e.g., via Homebrew) and run the pre‑built image:

$ brew install --cask docker
$ sudo docker run -ti -v /path/to/deploy-project:/home -p 8080:8080 registry.cn-shanghai.aliyuncs.com/eas/eas-python-base-image:py3.6-allspark-0.8

Inside the container, start the service:

$ cd /home
$ ./ENV/bin/python app.py

After successful startup, the API is reachable at http://localhost:8080/predict. Test it with curl:

curl -X POST 'localhost:8080/predict' \
-H 'Content-Type: application/json' \
-d '{"images": ["https://img.alicdn.com/tfs/TB1W8K2MeH2gK0jSZJnXXaT1FXa-638-430.png"], "threshold": 0.5}'

The response looks like:

{"content": [{"isConfident": true, "label": "keyboard"}]}

Full Code and Repository

The complete source code is available at https://github.com/imgcook/ml-mac-classify . Follow the README to clone the repo, train the model, copy the model file to the deployment project, and run the Docker‑based service.

Summary

By using SimpleVGGNet for image classification, preparing a small UI component dataset, training on macOS, and wrapping the model in a Docker‑deployed HTTP service, you can quickly prototype and test deep‑learning solutions without needing large compute resources.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Image ClassificationDockermachine learningPythonAnaconda
Taobao Frontend Technology
Written by

Taobao Frontend Technology

The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.