Python Data Science and Machine Learning: 6 Steps to Start
ZMedia Purwodadi

Python Data Science and Machine Learning: 6 Steps to Start

Table of Contents

Most beginners think machine learning is a wall of maths they will never climb. It is not. At its core, a machine learning model is just code that studies past data and uses the pattern to make a prediction. If you can write a few lines of Python, you can build one today. This guide shows you how Python, data science, and machine learning fit together, in 6 clear steps, by building a real model that predicts apartment rent in Lagos.

We will use one running example the whole way, a small table of Lagos apartments with their size, number of bedrooms, and rent in Naira. By the end you will have trained a model and used it to predict the rent of a flat it has never seen. No heavy theory. Just the exact steps.

If you are new to the wider field, our beginner's guide to data science with Python is a good companion to read alongside this one.

1. What you need for Python data science and machine learning

You need two free libraries. A library is code someone already wrote that you import and use. For Python for data science and machine learning you will lean on pandas for handling data and scikit-learn for the machine learning itself. Both come ready in Anaconda, or you can install them once with pip.

# Run this once in your terminal if the libraries are missing
# pip install pandas scikit-learn

# Then import what we need at the top of your notebook
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

print("Libraries ready")

That is the entire toolkit for this project. To see the other libraries analysts use day to day, read our roundup of 10 Python libraries every data analyst should know.

2. Load your dataset with pandas

Every machine learning project starts with data. Here we build a small table by hand so you can see every value. This is the foundation of doing data science and machine learning using Python. In a real project you would load a file instead, which we cover in how to read a CSV file in Python.

# Twelve Lagos apartments: size in square metres, bedrooms, and monthly rent in Naira
data = {
    "area_sqm":   [35, 45, 60, 40, 75, 55, 90, 50, 65, 80, 30, 70],
    "bedrooms":   [1, 1, 2, 1, 3, 2, 3, 2, 2, 3, 1, 3],
    "rent_naira": [600000, 750000, 1100000, 700000, 1600000, 950000,
                   2000000, 900000, 1200000, 1750000, 550000, 1500000]
}

# Turn it into a DataFrame, which is a table
df = pd.DataFrame(data)

# Show the first five rows
df.head()

Running this prints a clean table of the first five apartments. This table is our whole world for the rest of the project.

3. Explore the data before you model it

Never model data you have not looked at. A quick summary tells you the range of your numbers and, more importantly, which features move together. Exploring first is the heart of Python data science and machine learning done well.

# A fast statistical summary of every column
print(df.describe())

# How strongly does each column move with rent?
print(df.corr(numeric_only=True)["rent_naira"])

The correlation between area and rent comes out at about 0.99, which is very strong and close to a perfect 1. In plain words, bigger apartments almost always cost more, so area will be a powerful clue for our model. For a fuller routine on this stage, see our guide to 5 steps to perform exploratory data analysis in Python.

Enjoying this and want the full path? Our Python for Data Analysts course takes you from these first models to portfolio ready analysis, using real Nigerian datasets and lessons that build on each other.

4. Split into training and test sets

Here is the one idea that separates real machine learning from guesswork. You never test a model on the same data it learned from. You hold some rows back, train on the rest, then check the model on the rows it never saw. This step is what makes machine learning in data science using Python trustworthy.

# X is the input features the model learns from
X = df[["area_sqm", "bedrooms"]]

# y is the answer we want it to predict
y = df["rent_naira"]

# Keep 25 percent of the rows aside for testing
# random_state fixes the shuffle so your result matches this post
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42
)

print("Training rows:", len(X_train))
print("Testing rows:", len(X_test))

You will see 9 training rows and 3 testing rows. The model will study the 9, then be graded on the 3 it has not met. That honest test is the whole point.

5. Train your machine learning model

Now the part that sounds hard and is actually two lines. We use linear regression, a model that draws the best straight line relationship between the features and the rent. This is the moment Python machine learning data science work pays off.

# Create the model
model = LinearRegression()

# Train it on the training data. This is the learning step.
model.fit(X_train, y_train)

print("Model trained and ready")

That is it. The call to fit is where the model studies the training apartments and works out how much each extra square metre and each extra bedroom adds to the rent. The pattern is now stored inside model.

6. Evaluate the model, then make a prediction

A trained model is only useful if it is accurate and if you can ask it new questions. So we do both, which completes the full loop of Python for machine learning and data science.

# First, grade the model on the 3 test apartments
predictions = model.predict(X_test)
error = mean_absolute_error(y_test, predictions)
print("Average error:", round(error), "Naira")

# Now ask it about a brand new flat: 58 square metres, 2 bedrooms
new_flat = pd.DataFrame({"area_sqm": [58], "bedrooms": [2]})
predicted_rent = model.predict(new_flat)[0]
print("Predicted rent:", round(predicted_rent), "Naira")

The average error lands around 120,000 Naira, meaning the model is typically off by about that much on rents that run into millions, which is close for a first model on twelve rows. And for the new 58 square metre, 2 bedroom flat, it predicts a rent of about 1.1 million Naira. You just built a working machine learning model and used it to price an apartment it had never seen.

Summary of the 6 steps

StepWhat you didKey tool
1Set up your librariespandas, scikit-learn
2Loaded the datasetDataFrame
3Explored the datadescribe, corr
4Split training and test datatrain_test_split
5Trained the modelLinearRegression, fit
6Evaluated and predictedpredict, mean_absolute_error

What to do next

Change the new flat to a size and bedroom count you know a real price for, then see how close the model gets. After that, swap in your own data. The same six steps work for predicting POS sales, transport demand, or crop yields. The dataset changes, but the workflow you just learned does not.

If you want structured projects to practise this on, grab our free guide, 5 Real World Data Projects You Can Do With Python and SQL as a Beginner. It gives you full briefs to build after this post, so the skill actually sticks. And if you are still setting up your tools, our guide to learning Python in Jupyter Notebook is the perfect place to run all of this code.

References

For deeper reference on the tools used here, see the official documentation:

Post a Comment