Skip to content

Practical Exam: Customer Purchase Prediction

RetailTech Solutions is a fast-growing international e-commerce platform operating in over 20 countries across Europe, North America, and Asia. They specialize in fashion, electronics, and home goods, with a unique business model that combines traditional retail with a marketplace for independent sellers.

The company has seen rapid growth. A key part of their success has been their data-driven approach to personalization. However, as they plan their expansion into new markets, they need to improve their ability to predict customer behavior.

Their marketing team wants to predict which customers are most likely to make a purchase based on their browsing behavior.

As an AI Engineer, you will help build this prediction system. Your work will directly impact RetailTech's growth strategy and their goal of increasing revenue.

Data Description

Column NameCriteria
customer_idInteger. Unique identifier for each customer. No missing values.
time_spentFloat. Minutes spent on website per session. Missing values should be replaced with median.
pages_viewedInteger. Number of pages viewed in session. Missing values should be replaced with mean.
basket_valueFloat. Value of items in basket. Missing values should be replaced with 0.
device_typeString. One of: Mobile, Desktop, Tablet. Missing values should be replaced with "Unknown".
customer_typeString. One of: New, Returning. Missing values should be replaced with "New".
purchaseBinary. Whether customer made a purchase (1) or not (0). Target variable.

Task 1

The marketing team has collected customer session data in raw_customer_data.csv, but it contains missing values and inconsistencies that need to be addressed. Create a cleaned version of the dataframe:

  • Start with the data in the file raw_customer_data.csv
  • Your output should be a DataFrame named clean_data
  • All column names and values should match the table below.
Column NameCriteria
customer_idInteger. Unique identifier for each customer. No missing values.
time_spentFloat. Minutes spent on website per session. Missing values should be replaced with median.
pages_viewedInteger. Number of pages viewed in session. Missing values should be replaced with mean.
basket_valueFloat. Value of items in basket. Missing values should be replaced with 0.
device_typeString. One of: Mobile, Desktop, Tablet. Missing values should be replaced with "Unknown".
customer_typeString. One of: New, Returning. Missing values should be replaced with "New".
purchaseBinary. Whether customer made a purchase (1) or not (0). Target variable.
# Write your answer to Task 1 here
import pandas as pd
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv('raw_customer_data.csv')

df['time_spent'] = df['time_spent'].astype(float)
df['basket_value'] = df['basket_value'].astype(float)

df['time_spent'].fillna(df['time_spent'].median(), inplace=True)
df['pages_viewed'].fillna(df['pages_viewed'].mean(), inplace=True)
df['pages_viewed'] = df['pages_viewed'].astype(int)  
df['basket_value'].fillna(0, inplace=True)
df['device_type'].fillna('Unknown', inplace=True)
df['customer_type'].fillna('New', inplace=True)

clean_data = df.copy()

print(clean_data.head())

Task 2

The pre-cleaned dataset model_data.csv needs to be prepared for our neural network. Create the model features:

  • Start with the data in the file model_data.csv
  • Scale numerical features (time_spent, pages_viewed, basket_value) to 0-1 range
  • Apply one-hot encoding to the categorical features (device_type, customer_type)
    • The column names should have the following format: variable_name_category_name (e.g., device_type_Desktop)
  • Your output should be a DataFrame named model_feature_set, with all column names from model_data.csv except for the columns where one-hot encoding was applied.
# Write your answer to Task 2 here
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder

model_data = pd.read_csv('model_data.csv')

model_feature_set = model_data.copy()

numerical_features = ['time_spent', 'pages_viewed', 'basket_value']
scaler = MinMaxScaler()
model_feature_set[numerical_features] = scaler.fit_transform(model_feature_set[numerical_features])

categorical_features = ['device_type', 'customer_type']
encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)  
encoded_data = encoder.fit_transform(model_feature_set[categorical_features])
encoded_df = pd.DataFrame(encoded_data, columns=encoder.get_feature_names_out(categorical_features))

model_feature_set = pd.concat([model_feature_set, encoded_df], axis=1)
model_feature_set.drop(categorical_features, axis=1, inplace=True)

print(model_feature_set.columns)

print(model_feature_set.head())

Task 3

Now that all preparatory work has been done, create and train a neural network that would allow the company to predict purchases.

  • Using PyTorch, create a network with:
    • At least one hidden layer with 8 units
    • ReLU activation for hidden layer
    • Sigmoid activation for the output layer
  • Using the prepared features in input_model_features.csv, train the model to predict purchases.
  • Use the validation dataset validation_features.csv to predict new values based on the trained model.
  • Your model should be named purchase_model and your output should be a DataFrame named validation_predictions with columns customer_id and purchase. The purchase column must be your predicted values.
# Write your answer to Task 3 here
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, TensorDataset

input_data = pd.read_csv("input_model_features.csv")
validation_data = pd.read_csv("validation_features.csv")

X = input_data.drop(columns=["customer_id", "purchase"])
y = input_data["purchase"]

X_tensor = torch.tensor(X.values, dtype=torch.float32)
y_tensor = torch.tensor(y.values, dtype=torch.float32).view(-1, 1)

X_train, X_val, y_train, y_val = train_test_split(X_tensor, y_tensor, test_size=0.2, random_state=42)

train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True)
val_loader = DataLoader(TensorDataset(X_val, y_val), batch_size=32)

class PurchasePredictor(nn.Module):
    def __init__(self, input_dim):
        super(PurchasePredictor, self).__init__()
        self.fc1 = nn.Linear(input_dim, 8)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(8, 1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.sigmoid(self.fc2(x))
        return x

input_dim = X.shape[1]
purchase_model = PurchasePredictor(input_dim)

criterion = nn.BCELoss()
optimizer = optim.Adam(purchase_model.parameters(), lr=0.01)

epochs = 50
for epoch in range(epochs):
    for X_batch, y_batch in train_loader:
        optimizer.zero_grad()
        y_pred = purchase_model(X_batch)
        loss = criterion(y_pred, y_batch)
        loss.backward()
        optimizer.step()

purchase_model.eval()
X_validation = torch.tensor(validation_data.drop(columns=["customer_id"]).values, dtype=torch.float32)
predictions = purchase_model(X_validation).detach().numpy().flatten()
predictions = (predictions > 0.5).astype(int)  

validation_predictions = pd.DataFrame({
    "customer_id": validation_data["customer_id"],
    "purchase": predictions
})

validation_predictions.head()