How to Build AI Applications with Python and Machine Learning
Building a small AI application is a good way to understand how machine learning works. With Python and a laptop, we can train a model to recognize spam and give people a way to try it.
We’ll build a spam message detector, starting with the data and ending with a small web API. If you know Python variables, loops, and functions, you have enough to get started.
What is an AI application?
An AI application uses a model to make predictions or produce an output. Familiar examples include email spam filters, shopping recommendations, speech transcription apps, and tools that identify objects in photos.
For this project, we’ll use a machine learning model that learns patterns from labeled messages. Once we’ve trained it, the model can use those patterns to classify messages it hasn’t seen before.
Why use Python?
Python’s readable syntax makes it a practical choice for a first machine learning project. Libraries such as NumPy, pandas, scikit-learn, TensorFlow, and PyTorch provide tools that would take a lot of work to write yourself.
There are also plenty of tutorials and community discussions to turn to when you get stuck. For this project, we’ll use pandas to work with the data and scikit-learn to train the model.
Pick a small problem
Choose a task with a clear output. You might classify a movie review as positive or negative, estimate a house price, or decide whether a message is spam.
We’ll build the spam detector. It keeps the scope small enough to work through the full process, including testing the model and making it available through an API.
Set up your Python environment
Install Python from python.org, then create a folder for your project. Open a terminal in that folder and create a virtual environment to keep the project’s libraries separate from your other Python work.
python -m venv ai-env
On macOS or Linux, activate it with:
source ai-env/bin/activate
On Windows, using Command Prompt:
ai-env\Scripts\activate
Then install the libraries:
pip install pandas scikit-learn joblib fastapi uvicorn
You can write the training code in a Python file or use Jupyter Notebook to run it a piece at a time. VS Code is another option if you prefer working in an editor.
Collect your data
The model needs examples of messages with the correct label attached. We’ll use spam for unwanted messages and ham for ordinary messages.
You can look for a labeled message dataset on Kaggle or the UCI Machine Learning Repository. Save the data as messages.csv in your project folder, with two columns named text and label. You may need to rename columns in the dataset you download.
Pay attention to the examples themselves. More data can help, but it needs to be relevant and labeled correctly for the model to learn useful patterns.
Clean and prepare the data
Check for missing messages and duplicate rows before training. Run this code first:
import pandas as pd
data = pd.read_csv("messages.csv")
data = data.dropna(subset=["text", "label"])
data = data.drop_duplicates()
print(data.head())
Read a few rows to check that the messages and labels look right. You’ll also need to convert the text into numbers before the model can use it. We’ll handle that with scikit-learn when we build the training pipeline.
Split the data into training and test sets
Set aside some messages before you train the model. Testing it on messages it has already learned from won’t tell you how well it handles new ones.
We’ll use 80% of the data for training and keep 20% for testing:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
data["text"],
data["label"],
test_size=0.2,
random_state=42,
)
X_train and X_test contain the messages. The corresponding y variables contain their labels.
Choose and train a model
We’ll use logistic regression to classify the messages. Despite its name, logistic regression can handle classification tasks like deciding whether a message is spam.
First, TF-IDF converts the text into numerical features based on how often terms appear in a message and across the training messages. A pipeline connects that conversion step to the classifier:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
model = make_pipeline(
TfidfVectorizer(),
LogisticRegression(),
)
model.fit(X_train, y_train)
The fit() call trains the pipeline using your training messages and labels.
Check the model’s predictions
Use the test set to see how often the model gets a message right:
from sklearn.metrics import accuracy_score
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
An accuracy of 0.95 means the model classified 95% of the test messages correctly. That’s an example of how to read the score, not a result you should expect from this code.
Accuracy can be misleading if most messages belong to one class. A model might get many ordinary messages right while missing spam. Precision and recall help you examine those mistakes: precision measures how often a spam prediction is correct, while recall measures how much of the actual spam the model catches.
Improve the model
If the results aren’t good enough, read the messages the model gets wrong. You might need more examples of those messages, or you might find labels that need correcting.
You can also try another classifier, such as Naive Bayes or Random Forest, or change the model’s settings. These settings are called hyperparameters.
Change one thing at a time so you can tell what helped. If you repeatedly compare changes, use a separate validation set or cross-validation and keep the test set for a final check.
Save the trained model
Save the pipeline so your app can load it without training again for every prediction:
import joblib
joblib.dump(model, "spam_model.joblib")
This saves both the text conversion step and the classifier in one file.
Build an API for the model
An API gives other software a way to send a message to your model and receive a prediction. We’ll use FastAPI for this part.
Create a file called main.py in the same folder as spam_model.joblib:
from fastapi import FastAPI
import joblib
app = FastAPI()
model = joblib.load("spam_model.joblib")
@app.post("/predict")
def predict(text: str):
result = model.predict([text])[0]
return {"prediction": str(result)}
Start the development server from that folder:
uvicorn main:app --reload
Open http://127.0.0.1:8000/docs in your browser. Expand the /predict endpoint, click “Try it out,” enter a message in the text field, and click “Execute.” The response will contain the model’s prediction.
If you’d rather build a page with a text box and a button, Streamlit or Gradio are other options for creating a small interface in Python.
Put your app online
Deployment makes your app available to people beyond your computer. Our spam detector can become a hosted API, or you can give it a web interface first.
Hugging Face Spaces, Render, Railway, and Streamlit Community Cloud are hosting options to investigate. Choose one that supports the kind of app you’ve built, and check its current pricing and setup instructions before deploying. The steps depend on the platform; uploading your code alone may not be enough to get it running.
Using pretrained models and AI APIs
Training a small classifier helps you understand the process, but you can also build applications with models that someone else has already trained.
Hugging Face Transformers provides tools for working with pretrained models for text, images, and audio. AI APIs let your app send a request to a hosted model and use its response, without running the model on your own computer.
These approaches can be useful for chatbots, summarizers, and image tools. You can try them after the spam detector, or use them when they suit the application you want to build.
Common beginner mistakes
Keep your first project small enough to finish. A working spam detector gives you something you can test and improve before you add more features.
Keep training and test data separate, and spend time reading your data before choosing a more complicated model. Missing messages, incorrect labels, and repeated examples can affect your results regardless of the algorithm you use.
What to try next
Once the detector runs, try new messages and inspect its mistakes. Then choose another small project, such as estimating house prices, classifying images, or building a chatbot, and work through the same process with that task’s data and model.