Machine Learning Using Python: A Practical Introduction
Machine learning is a way of teaching computers to identify patterns in data and use them to make predictions or decisions. It is used in applications ranging from email filtering and product recommendations to medical research and fraud detection.
Python is one of the most popular languages for machine learning. Its clear syntax and extensive collection of libraries make it suitable for beginners and experienced developers alike. This article introduces the basic workflow and shows how to build a simple machine-learning model.
What is machine learning?
In traditional programming, a developer writes explicit instructions for a computer to follow. In machine learning, a model is instead trained using examples. It learns patterns from those examples and applies what it has learnt to new data.
There are three broad types of machine learning:
- Supervised learning: the model learns from examples that include the correct answers. It can be used to predict a category, such as whether an email is spam, or a numerical value, such as a house price.
- Unsupervised learning: the model looks for patterns in data without being given labelled answers. One example is grouping customers with similar behaviours.
- Reinforcement learning: the model learns by taking actions and receiving rewards or penalties, often in a simulated environment.
Why use Python?
Python’s machine-learning ecosystem offers tools for different stages of a project. pandas helps with working with tables of data, while NumPy supports numerical calculations. Matplotlib and seaborn are commonly used to visualise data. For machine learning itself, scikit-learn provides a consistent set of tools for preparing data, training models and assessing their performance.
A simple machine-learning workflow
- Define the problem. Decide what you want the model to predict or discover.
- Collect and inspect data. Check its size, format, quality and relevance.
- Prepare the data. Handle missing values, convert categories into usable formats and choose relevant features.
- Split the data. Keep some examples aside so you can test how well the model performs on data it has not seen before.
- Train a model. Use the training data to let the algorithm learn patterns.
- Evaluate the results. Choose measures that suit the task and examine whether the model is useful.
- Improve and monitor it. Test alternatives and check performance when the model is used with new data.
Building a basic model with scikit-learn
The example below uses the Iris dataset, which contains measurements of iris flowers and their species. The task is to predict a flower’s species from its measurements. The dataset is included with scikit-learn, so no separate download is needed.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# Load the data
iris = load_iris()
X = iris.data
y = iris.target
# Set aside data for testing
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Create and train the model
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
# Make predictions and measure accuracy
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
print(f"Accuracy: {accuracy:.2f}")
Here, X contains the flower measurements, while y contains the species labels. The model learns from the training portion of the data. Its predictions are then compared with the known labels in the test portion. The random_state setting makes the split repeatable, while stratify=y helps preserve the balance of species in both sets.
Choosing the right evaluation measure
Accuracy is the proportion of predictions that are correct. It is useful for some problems, but it can be misleading when one category is much more common than another. For example, a model that labels every transaction as legitimate could appear highly accurate if fraudulent transactions are rare.
For classification tasks, other useful measures include precision, recall and the F1 score. For prediction of numerical values, measures such as mean absolute error or root mean squared error may be more appropriate. The best measure depends on the problem and the consequences of different kinds of mistakes.
Common challenges
- Poor-quality data: missing, inconsistent or incorrectly labelled records can undermine results.
- Overfitting: a model may learn the training examples too closely and perform poorly on new data.
- Data leakage: information that would not be available at prediction time may accidentally influence training or evaluation, making results appear better than they really are.
- Bias: data can reflect historical inequalities or gaps in representation. A model may reproduce or amplify them.
- Unclear objectives: a technically accurate model is not necessarily useful if it does not address the real-world need.
Good practices for beginners
Start with a clear question and a simple baseline model. Keep test data separate from the training process, and use a validation approach such as cross-validation when comparing models. Document the data sources and decisions made during preparation. Consider privacy, fairness and the potential impact of automated decisions from the beginning, rather than treating them as an afterthought.
It is also important to remember that machine learning does not remove the need for human judgement. Predictions can be uncertain, and their limitations should be understood before they are used in important decisions.
Conclusion
Python makes it straightforward to explore machine learning, from inspecting a dataset to training and evaluating a model. Libraries such as scikit-learn provide accessible tools, but successful projects depend just as much on asking the right question, preparing reliable data and evaluating results carefully. A small, well-understood model is often the best place to begin.
