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

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

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

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Automatic 1111: Custom Sketch-to-Image API
  • AI Advancement for API and Microservices
  • LLM: Trust, but Verify
  • Cloud-Native Integration Platforms To Accelerate Business Transformation

Trending

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • Infrastructure as Code (IaC) Beyond the Basics
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Creating and Serving Your First Machine Learning Model

Creating and Serving Your First Machine Learning Model

Welcome to the world of machine learning. In this tutorial, you'll learn how to create, train, and serve your first machine-learning model.

By 
Helber Belmiro user avatar
Helber Belmiro
DZone Core CORE ·
Nov. 23, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
2.3K Views

Join the DZone community and get the full member experience.

Join For Free

Welcome to the world of machine learning, where computers learn from data and make predictions without explicit programming. At the heart of this technology lies the concept of a “model.”

What Is a Model?

In traditional programming, we create functions/methods that receive inputs/parameters and return a result based on a formula. For example, imagine a Java method that applies the formula y = 3x + 1.

Java
 
public int formula(int x) {
    return 3 * x + 1;
}


The above code would return the following data for x and y:

x -1 0 1 2 3 4
y -2 1 4 7 10 13

Now, imagine that rather than the formula, you have lots of x and y values. You can create a machine learning model to discover the formula and predict new values.

As a real-life example, we can use the facial recognition that happens in the gallery of our phones. We have several inputs (photos) and outputs (people’s names), and the machine learning model is the formula that knows how to recognize people. As you give names to people in the photos, you’re feeding the model with data that is constantly retrained to better recognize those people.

Python: The Language of Machine Learning

Python has become the de facto language for machine learning. Its vast ecosystem of libraries, including TensorFlow and Keras, makes it a powerhouse for building and training models. If you’re curious about stepping into the world of machine learning, Python is your trusty companion on this journey.

Our Model

For simplicity, we’ll use the x and y data above to train a model that will know how to predict a y value based on x.

Python
 
import tensorflow as tf
import numpy as np
from tensorflow import keras
import os


def build_model():
    # Create a model that receives 1 input value and returns 1 output value
    model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

    # Define the algorithms for learning. You don't need to worry about this for now
    model.compile(optimizer='sgd', loss='mean_squared_error')
    return model


def train_model(model, xs, ys, epochs=500):
    # Train the model. Here we're saying the algorithm to try 500 random formulas to find the one that best matches
    # the input and output data.
    model.fit(xs, ys, epochs=epochs)


def predict_with_model(model, input_data):
    # Predict using the trained model
    return model.predict([input_data])


def save_model(model, export_path):
    # Save the model
    tf.keras.models.save_model(
        model,
        export_path,
        overwrite=True,
        include_optimizer=True,
        save_format=None,
        signatures=None,
        options=None
    )


def main():
    # Input data
    xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
    ys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float)

    # Build the model
    model = build_model()

    # Train the model
    train_model(model, xs, ys)

    # Predict the value for x = 10. It will print a number very close to 31, like 30.9994 or something
    prediction = predict_with_model(model, 10.0)
    print(prediction)

    # Save the model
    model_dir = "./model"
    version = 1
    export_path = os.path.join(model_dir, str(version))
    print('export_path = {}\n'.format(export_path))
    save_model(model, export_path)
    print('\nSaved model: ' + export_path)


if __name__ == "__main__":
    main()


Run the above Python code to create, train, and test the model. It will create the model under the ./model directory.

Serving the Model

Once you have created the model and have it under the ./model directory, you can serve it as a REST API. To do so, you can use the tensorflow/serving container image:

Shell
 
podman run -p 8501:8501 \
    --name=tf_serving \
    --mount type=bind,source=./model,target=/models/model -e MODEL_NAME=model \
    -t tensorflow/serving


Consuming the Model

Once your container is up and running, you can send a request to make an inference. Run the following command to infer the y value for x = 10:

Shell
 
curl -d '{"instances": [[10.0]]}' \                                                                                 
    -H "Content-Type: application/json" \
    -X POST http://localhost:8501/v1/models/model:predict


You should see a result similar to the following:

Shell
 
{
    "predictions": [[30.9971237]
    ]
}


That’s all, Folks!

You’ve just created, trained, served, and consumed your first machine-learning model. You can find the source code used in this post on GitHub. Feel free to ask any questions in the comments, and stay tuned for more.

API Machine learning

Published at DZone with permission of Helber Belmiro. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Automatic 1111: Custom Sketch-to-Image API
  • AI Advancement for API and Microservices
  • LLM: Trust, but Verify
  • Cloud-Native Integration Platforms To Accelerate Business Transformation

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!