DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Java vs. Python Comparison: The Battle of Best Programming Language in 2021
  • Java for AI
  • Oracle NoSQL Database: A Comprehensive Guide for Developers
  • Explainable AI (XAI): How Developers Build Trust and Transparency in AI Systems

Trending

  • Enforcing Architecture With ArchUnit in Java
  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • How to Create a Successful API Ecosystem
  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. How to Build Custom Image Classifiers in Java With Minimal ML Experience

How to Build Custom Image Classifiers in Java With Minimal ML Experience

Look at how to create a training project, add classification tags, upload images, train the project, obtain the endpoint URL, and use the endpoint to test an image.

By 
Ruth Yakubu user avatar
Ruth Yakubu
·
Updated Aug. 21, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

Using Machine Learning to train your own custom Deep Learning models can be challenging without understanding the algorithms, having a good dataset, having a high-performance test environment, or knowing the correct optimization settings. Although there a lot of image recognization API solutions available for developers to leverage, many times businesses or developers have unique cases or outliers out there that these solutions are unable to accurately identify the image.

As a solution to this problem, Microsoft released the Azure Custom Vision service last year at Build 2017. The Azure Custom Vision service enables developers with minimum to expertise Machine Learning knowledge to build robust custom image classifiers. It makes it easy and fast to build, deploy, and improve an image classifier. As an output, the Custom Vision service provides a REST API and a web interface to upload your images and train the classifier.

The Custom Vision service is a great solution in identifying medical defects that would be difficult to diagnose with the human eye in Healthcare, identifying design trends and logos in Retail, or identifying plants or wildlife species in the Biological field.

Tutorial

This Java Tutorial shows how to create a training project, add classification tags, upload your images, train the project, obtain the project's default prediction endpoint URL, and use the endpoint to programmatically test an image.

Prerequisites

  • Login or register for a FREE account on http://customvision.ai
  • Copy the account Training Key and Prediction Key values by clicking on the gear icon in the upper right corner of the customvision portal page
  • Retrieve the Custom Vision Prediction SDK and Custom Vision Training SDK. Include this in your maven pom.xml file.
    • https://mvnrepository.com/artifact/com.microsoft.azure.cognitiveservices

Training Your Model

For this tutorial, we'll be classifying dog breeds

  • Authenticate Custom Vision Train API your Training Key
  TrainingApi client = CustomVisionTrainingManager.authenticate(trainingKey); 
  • Create a new project

The FREE tier of Custom Vision service allows developers to create up to 2 projects and upload up to 50,000 images per project.

Trainings trainings = client.trainings();
Project project = trainings.createProject().withName("Dog Breeds").execute();
  • Create Tags

A tag is a label assigned for each classification group. The Custom Vision service requires at least 2 tags in a project and up to 250 tags for the FREE tier.

Tag chihuahuaTag = trainings.createTag().withProjectId(project.id())
    .withName("Chihuahua").execute();
Tag beagleTag = trainings.createTag().withProjectId(project.id())
    .withName("Beagle").execute();
Tag germanShepherdTag = trainings.createTag().withProjectId(project.id())
    .withName("German Shepherd").execute(); 
  • Upload images to each Tag

Ideally, 50 images per tag are enough for training. In this tutorial, you can see the 10 images yield a highly accurate trained model.

The Custom Vision SDK provides developers the ability to upload images to the tags one at a time or in a batch. This tutorial reads images from a file array list one at a time.

for(File image : chihuahuaImages)
{
    List chihuahuaTagIds = new ArrayList();
    chihuahuaTagIds.add(chihuahuaTag.id().toString());
    try {
        byte[] fileContent = Files.readAllBytes(image.toPath());
        trainings.createImagesFromData()
            .withProjectId(project.id())
            .withImageData(fileContent)
            .withTagIds(chihuahuaTagIds )
            .execute();
     } catch (Exception e) {
         System.out.println("Exception occurred: " + e );
     }
}  

Image title

  • Train the project

While training the model, the returned iteration will be in progress, so the iteration status has to be queried periodically to see when it has completed. Once complete, the developer can choose which iteration to set as default to be used as a prediction model endpoint.

while (iteration.status().equals("Training") )
{
    try {

            Thread.sleep(1000);

           // Re-query the iteration to get it's updated status
           iteration = trainings.getIteration(project.id(), iteration.id());

        } catch (InterruptedException e) {

            e.printStackTrace();
        }


}

iteration.withIsDefault(true);

Image title

Make a Prediction

The Custom Vision Service provides a Prediction REST API for developers to call the trained model or export it to be run offline. The images are saved in the project for developers to improve the classifier overtime.

  • Authenticate and Create prediction endpoint using your Prediction Key
Now there is a trained endpoint, it can be used to make a prediction
PredictionEndpoint endpoint = CustomVisionPredictionManager.authenticate(predictionKey);
  • Use test image to make a prediction trained model
Provide a test image file to make a prediction against the training model
ImagePrediction result = endpoint.predictions().predictImage()
    .withProjectId(project.id())
    .withImageData(testImage)
    .withIterationId(iteration.id())
    .execute();

for(com.microsoft.azure.cognitiveservices.vision.customvision.prediction.models.Prediction c : result.predictions()) 
{ 
    System.out.println("Tag: " + c.tagName() + ", Probability: " + c.probability()); 
} 

Image title

Let's see the results...

Making a prediction...
Tag: Chihuahua, Probability: 0.9569713
Tag: Beagle, Probability: 2.607554E-4
Tag: German Shepherd, Probability: 8.893044E-5

As you can see, the model accurately predicted that the test image of a chihuahua in the cup can be classified as a Chihuahua dog with a 0.95 passing score!

References

To download the complete code and try it out, check out: https://github.com/ruyakubu/azure-customvision-sample.

Machine learning Build (game engine) Java (programming language) dev

Opinions expressed by DZone contributors are their own.

Related

  • Java vs. Python Comparison: The Battle of Best Programming Language in 2021
  • Java for AI
  • Oracle NoSQL Database: A Comprehensive Guide for Developers
  • Explainable AI (XAI): How Developers Build Trust and Transparency in AI Systems

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!