Menu

Creating the Prediction Interface

Lesson 2: Creating the Prediction Interface

In this lesson, we create a function that connects user input to the trained Logistic Regression model. This function acts as the core bridge between the interface and the model, allowing users to input customer details and get a churn probability instantly.

Code:

import gradio as gr

import pandas as pd

def predict_churn(gender, senior, partner, dependents, tenure, phone, paperless,

monthly, total, contract, payment):

# Build input dictionary

input_dict = {

'gender': gender,

'SeniorCitizen': senior,

'Partner': partner,

'Dependents': dependents,

'tenure': tenure,

'PhoneService': phone,

'PaperlessBilling': paperless,

'MonthlyCharges': monthly,

'TotalCharges': total,

'Contract': contract,

'PaymentMethod': payment

}

# Convert to DataFrame

input_df = pd.DataFrame([input_dict])

# ----- Apply Same Preprocessing As Training -----

input_df['TotalCharges'] = pd.to_numeric(input_df['TotalCharges'], errors='coerce')

input_df['TenureGroup'] = input_df['tenure'].apply(

lambda x: '0-12' if x <= 12 else

'12-24' if x <= 24 else

'24-48' if x <= 48 else

'48+'

)

input_df['AvgMonthlySpend'] = input_df['TotalCharges'] / (input_df['tenure'].replace(0, 1))

input_df['PaymentStability'] = input_df['PaymentMethod'].apply(

lambda x: 'Automatic' if 'automatic' in x.lower() else 'Manual'

)

# Binary Encoding

for col in ['gender','Partner','Dependents','PhoneService',

'PaperlessBilling','PaymentStability']:

input_df[col] = 1 if input_df[col].iloc[0] in ['Yes', 'Female', 'Automatic'] else 0

# One-Hot Encode Multi-Class Columns

input_df = pd.get_dummies(

input_df,

columns=['Contract','PaymentMethod','TenureGroup'],

drop_first=True

)

# Align columns with training data

input_df = input_df.reindex(columns=X.columns, fill_value=0)

# Predict Probability

prob = log_reg.predict_proba(input_df)[0][1]

return f"Churn Probability: {prob:.2f}"

# Define Inputs

inputs = [

gr.Dropdown(choices=["Male","Female"], label="Gender"),

gr.Dropdown(choices=[0,1], label="SeniorCitizen"),

gr.Dropdown(choices=["Yes","No"], label="Partner"),

gr.Dropdown(choices=["Yes","No"], label="Dependents"),

gr.Number(label="Tenure (months)"),

gr.Dropdown(choices=["Yes","No"], label="PhoneService"),

gr.Dropdown(choices=["Yes","No"], label="PaperlessBilling"),

gr.Number(label="MonthlyCharges"),

gr.Number(label="TotalCharges"),

gr.Dropdown(choices=["Month-to-month","One year","Two year"], label="Contract"),

gr.Dropdown(

choices=[

"Electronic check",

"Mailed check",

"Bank transfer (automatic)",

"Credit card (automatic)"

],

label="PaymentMethod"

)

]

# Launch App

gr.Interface(

fn=predict_churn,

inputs=inputs,

outputs="text",

title="Customer Churn Prediction"

).launch()

Explanation:

  • The function accepts customer details such as tenure, payment method, and services.
  • It applies the same preprocessing steps used during training, including feature engineering, encoding, and one-hot transformation.
  • The processed input is aligned with the model's features, ensuring accurate predictions.
  • The output shows churn probability, giving users immediate insights.
  • Gradio handles the interactive interface, making the model accessible without writing frontend code.