Lesson Introduction

In this lesson, we explore how to make predictions using a trained machine learning model and visualize the results. Understanding predictions and visualizations helps interpret model performance and make informed decisions.

Our goal is to build on the trained linear regression model from the last lesson, use it to predict, and visualize these predictions against actual data. This will provide a clear picture of your model's performance.

Making Predictions with a Trained Model: Understanding

First, let's recap. In the last lesson, we trained a linear regression model to understand the relationship between the area of a house and its price using synthetic data. We will use the same code snippet for generating the data as we used in the previous lesson:

import numpy as np
import pandas as pd

np.random.seed(42)
num_samples = 100
area = np.random.uniform(500, 3500, num_samples)  # House area in square feet

# Assume a linear relationship: price = base_price + (area * price_per_sqft)
base_price = 50000.00
price_per_sqft = 200.00
noise = np.random.normal(0, 25000, num_samples)  # Adding noise
price = base_price + (area * price_per_sqft) + noise

# Create DataFrame
df = pd.DataFrame({'Area': np.round(area, 2), 'Price': np.round(price, 2)})
X = df[['Area']]
y = df['Price']

Now, imagine you have new data, like areas of new houses, and want to predict their prices using your trained model. This is where the predict method from Scikit-Learn comes into play.

The predict method takes input data and generates the predicted output based on the model.

We'll start by importing essential libraries, including NumPy, Pandas, Matplotlib, and Scikit-Learn. We'll use the same data generation script as in the previous lesson.

Making Predictions with a Trained Model: Application

First, we initialize and train the model using our data.

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X, y)

Then, let's make predictions with our trained model. Suppose you want to predict prices for houses with areas of 200 and 3500 square feet.

X_new = np.array([[200.00], [3500.00]])
# Converting to a DataFrame to include feature name
X_new = pd.DataFrame(X_new, columns=['Area'])
y_predict = model.predict(X_new)
print("Predicted prices:", np.round(y_predict, 2))  # [ 96526.95 743883.09]

In real life, you might need to predict prices for several new houses, not just two.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal