File size: 24,405 Bytes
4f9db42 52509c8 4f9db42 52509c8 4f9db42 52509c8 4f9db42 52509c8 4f9db42 52509c8 4f9db42 52509c8 4f9db42 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
"""
Wellness Tourism Package Prediction App
Production-grade Streamlit application for predicting customer purchase likelihood
"""
import streamlit as st
import pandas as pd
import numpy as np
import joblib
from huggingface_hub import hf_hub_download
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import os
# Page configuration
st.set_page_config(
page_title="Wellness Tourism Predictor",
page_icon="โ๏ธ",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better UI
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #1f77b4;
text-align: center;
margin-bottom: 2rem;
}
.sub-header {
font-size: 1.2rem;
color: #555;
text-align: center;
margin-bottom: 2rem;
}
.prediction-box {
padding: 2rem;
border-radius: 10px;
text-align: center;
font-size: 1.5rem;
font-weight: bold;
margin: 2rem 0;
}
.prediction-positive {
background-color: #d4edda;
color: #155724;
border: 2px solid #c3e6cb;
}
.prediction-negative {
background-color: #f8d7da;
color: #721c24;
border: 2px solid #f5c6cb;
}
.metric-card {
background-color: #f0f2f6;
padding: 1rem;
border-radius: 5px;
margin: 0.5rem 0;
}
.stDownloadButton button {
width: 100%;
}
</style>
""", unsafe_allow_html=True)
@st.cache_resource
def load_model():
"""
Load the trained model from Hugging Face Hub
Uses caching to avoid reloading on every interaction
"""
try:
model_path = hf_hub_download(
repo_id="TheHumanAgent/tour_pkg_pred_model",
filename="final_tour_pkg_pred_model_v1.joblib",
repo_type="model"
)
model = joblib.load(model_path)
return model
except Exception as e:
st.error(f"Error loading model: {str(e)}")
st.error("Please ensure the model is uploaded to Hugging Face Hub")
st.stop()
def create_input_features():
"""
Create input form for all features required by the model
Returns a dictionary with user inputs based on actual data ranges
"""
st.sidebar.header("๐ Customer Information")
# Initialize session state for form
if 'prediction_made' not in st.session_state:
st.session_state.prediction_made = False
with st.sidebar:
st.subheader("๐ค Personal Details")
# Age: Range from 18-61 based on data
age = st.slider("Age",
min_value=18,
max_value=61,
value=36, # median
help="Customer's age (18-61 years)")
# Gender: Male, Female, Fe Male (as seen in data)
gender = st.selectbox("Gender",
["Female", "Male", "Fe Male"],
help="Customer's gender")
# MaritalStatus: Single, Married, Divorced, Unmarried
marital_status = st.selectbox("Marital Status",
["Single", "Divorced", "Married", "Unmarried"],
help="Customer's marital status")
# CityTier: 1, 2, 3
city_tier = st.selectbox("City Tier",
[1, 2, 3],
index=0, # median is 1
help="City development level (1=Most developed, 3=Least developed)")
st.markdown("---")
st.subheader("๐ผ Professional Details")
# Occupation: Salaried, Small Business, Large Business, Free Lancer
occupation = st.selectbox("Occupation",
["Salaried", "Free Lancer", "Small Business", "Large Business"],
help="Customer's occupation type")
# Designation: Executive, Manager, Senior Manager, AVP, VP
designation = st.selectbox("Designation",
["Manager", "Executive", "Senior Manager", "AVP", "VP"],
help="Customer's job designation")
# MonthlyIncome: Range from 1000 to 98678
monthly_income = st.number_input("Monthly Income (โน)",
min_value=1000,
max_value=100000,
value=22418, # median
step=1000,
help="Gross monthly income in Rupees (โน1,000 - โน98,678)")
st.markdown("---")
st.subheader("โ๏ธ Travel Preferences")
# NumberOfTrips: Range from 1-22
num_trips = st.slider("Number of Trips (Annually)",
min_value=1,
max_value=22,
value=3, # median
help="Average annual trips taken (1-22)")
# Passport: 0 or 1
passport = st.selectbox("Valid Passport",
[0, 1],
format_func=lambda x: "Yes" if x == 1 else "No",
index=0, # median is 0
help="Does customer have a valid passport?")
# OwnCar: 0 or 1
own_car = st.selectbox("Own Car",
[0, 1],
format_func=lambda x: "Yes" if x == 1 else "No",
index=1, # median is 1
help="Does customer own a car?")
# PreferredPropertyStar: 3, 4, 5
preferred_property_star = st.selectbox("Preferred Hotel Rating",
[3, 4, 5],
index=0, # median is 3
help="Preferred hotel star rating (3-5 stars)")
st.markdown("---")
st.subheader("๐จโ๐ฉโ๐งโ๐ฆ Trip Details")
# NumberOfPersonVisiting: Range from 1-5
num_persons = st.slider("Number of Persons Visiting",
min_value=1,
max_value=5,
value=3, # median
help="Total people in the group (1-5)")
# NumberOfChildrenVisiting: Range from 0-3
num_children = st.slider("Number of Children (<5 years)",
min_value=0,
max_value=3,
value=1, # median
help="Number of children under 5 years (0-3)")
st.markdown("---")
st.subheader("๐ Interaction Details")
# TypeofContact: Company Invited, Self Enquiry
type_of_contact = st.selectbox("Type of Contact",
["Self Enquiry", "Company Invited"],
help="How was the customer contacted?")
# ProductPitched: Basic, Standard, Deluxe, Super Deluxe, King
product_pitched = st.selectbox("Product Pitched",
["Deluxe", "Basic", "Standard", "Super Deluxe", "King"],
help="Type of package pitched to the customer")
# DurationOfPitch: Range from 5-127 minutes
duration_of_pitch = st.slider("Duration of Pitch (minutes)",
min_value=5,
max_value=127,
value=14, # median
help="Sales pitch duration in minutes (5-127)")
# NumberOfFollowups: Range from 1-6
num_followups = st.slider("Number of Follow-ups",
min_value=1,
max_value=6,
value=4, # median
help="Total follow-ups after initial pitch (1-6)")
# PitchSatisfactionScore: Range from 1-5
pitch_satisfaction = st.slider("Pitch Satisfaction Score",
min_value=1,
max_value=5,
value=3, # median
help="Customer satisfaction with the pitch (1=Very Low, 5=Very High)")
# Create feature dictionary matching exact column names from training data
features = {
'Age': age,
'CityTier': city_tier,
'DurationOfPitch': duration_of_pitch,
'NumberOfPersonVisiting': num_persons,
'NumberOfFollowups': num_followups,
'PreferredPropertyStar': preferred_property_star,
'NumberOfTrips': num_trips,
'Passport': passport,
'PitchSatisfactionScore': pitch_satisfaction,
'NumberOfChildrenVisiting': num_children,
'MonthlyIncome': monthly_income,
'TypeofContact': type_of_contact,
'Occupation': occupation,
'Gender': gender,
'OwnCar': own_car,
'ProductPitched': product_pitched,
'MaritalStatus': marital_status,
'Designation': designation
}
return features
def create_gauge_chart(probability):
"""
Create a gauge chart to visualize purchase probability
"""
fig = go.Figure(go.Indicator(
mode = "gauge+number+delta",
value = probability * 100,
domain = {'x': [0, 1], 'y': [0, 1]},
title = {'text': "Purchase Probability (%)", 'font': {'size': 24}},
delta = {'reference': 45, 'increasing': {'color': "green"}},
gauge = {
'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "darkblue"},
'bgcolor': "white",
'borderwidth': 2,
'bordercolor': "gray",
'steps': [
{'range': [0, 30], 'color': '#ffcccc'},
{'range': [30, 70], 'color': '#ffffcc'},
{'range': [70, 100], 'color': '#ccffcc'}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 45
}
}
))
fig.update_layout(
height=300,
margin=dict(l=20, r=20, t=50, b=20)
)
return fig
def create_feature_importance_chart(features_df):
"""
Create a bar chart showing key customer metrics
"""
# Select key features for visualization
key_features = {
'Monthly Income (โนK)': features_df['MonthlyIncome'].values[0] / 1000,
'Age': features_df['Age'].values[0],
'Annual Trips': features_df['NumberOfTrips'].values[0],
'Pitch Duration (min)': features_df['DurationOfPitch'].values[0],
'Follow-ups': features_df['NumberOfFollowups'].values[0],
'Satisfaction': features_df['PitchSatisfactionScore'].values[0],
'Hotel Rating': features_df['PreferredPropertyStar'].values[0],
'Group Size': features_df['NumberOfPersonVisiting'].values[0]
}
fig = px.bar(
x=list(key_features.values()),
y=list(key_features.keys()),
orientation='h',
title='Key Customer Metrics Overview',
labels={'x': 'Value', 'y': 'Feature'},
color=list(key_features.values()),
color_continuous_scale='Blues'
)
fig.update_layout(
height=400,
showlegend=False,
margin=dict(l=20, r=20, t=50, b=20)
)
return fig
def get_recommendation(probability, features):
"""
Generate actionable recommendations based on prediction and customer profile
"""
recommendations = []
# Priority level based on probability
if probability >= 0.7:
recommendations.append("โ
**HIGH PRIORITY LEAD** - Strong purchase likelihood")
recommendations.append("๐ฏ **Action**: Schedule immediate follow-up call within 24 hours")
recommendations.append("๐ **Strategy**: Offer premium package options and exclusive benefits")
elif probability >= 0.45:
recommendations.append("โ ๏ธ **MEDIUM PRIORITY LEAD** - Moderate purchase likelihood")
recommendations.append("๐ง **Action**: Send personalized email highlighting package benefits")
recommendations.append("๐ **Strategy**: Consider offering limited-time discount (5-10%)")
else:
recommendations.append("โ **LOW PRIORITY LEAD** - Lower purchase likelihood")
recommendations.append("๐ฌ **Action**: Add to nurture email campaign")
recommendations.append("๐ **Strategy**: Re-engage after 2-3 months with seasonal offers")
recommendations.append("") # Spacing
# Additional contextual recommendations based on specific features
if features['NumberOfFollowups'] <= 2:
recommendations.append("๐ **Insight**: Low follow-up count - Increase engagement frequency")
if features['PitchSatisfactionScore'] <= 2:
recommendations.append("โ ๏ธ **Alert**: Low satisfaction score - Review and improve pitch approach")
elif features['PitchSatisfactionScore'] >= 4:
recommendations.append("โญ **Positive**: High satisfaction - Customer is engaged, act quickly!")
if features['MonthlyIncome'] >= 30000:
recommendations.append("๐ฐ **Insight**: High-income customer - Emphasize luxury and premium features")
if features['NumberOfTrips'] >= 5:
recommendations.append("โ๏ธ **Insight**: Frequent traveler - Highlight loyalty benefits and travel perks")
if features['Passport'] == 0:
recommendations.append("๐ **Note**: No passport - Consider domestic package options")
if features['NumberOfChildrenVisiting'] >= 2:
recommendations.append("๐จโ๐ฉโ๐งโ๐ฆ **Insight**: Family with children - Emphasize family-friendly amenities")
if features['DurationOfPitch'] < 10:
recommendations.append("โฑ๏ธ **Note**: Short pitch duration - May need more detailed product information")
return recommendations
def display_customer_summary(features):
"""
Display a formatted summary of customer information
"""
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("๐ค Age", f"{features['Age']} years")
st.metric("๐๏ธ City Tier", f"Tier {features['CityTier']}")
with col2:
st.metric("๐ฐ Income", f"โน{features['MonthlyIncome']:,}")
st.metric("โ๏ธ Annual Trips", features['NumberOfTrips'])
with col3:
st.metric("๐ Follow-ups", features['NumberOfFollowups'])
st.metric("โญ Satisfaction", f"{features['PitchSatisfactionScore']}/5")
with col4:
st.metric("๐ฅ Group Size", features['NumberOfPersonVisiting'])
st.metric("๐จ Hotel Pref", f"{features['PreferredPropertyStar']} Star")
def main():
"""
Main application function
"""
# Header
st.markdown('<p class="main-header">โ๏ธ Wellness Tourism Package Predictor</p>',
unsafe_allow_html=True)
st.markdown('<p class="sub-header">AI-Powered Customer Purchase Prediction System</p>',
unsafe_allow_html=True)
# Load model
with st.spinner("๐ Loading ML model..."):
model = load_model()
st.success("โ
Model loaded successfully!")
# Create input form
features = create_input_features()
# Main content area
st.markdown("---")
st.subheader("๐ Customer Profile Summary")
display_customer_summary(features)
# Show detailed information in expandable section
with st.expander("๐ View Complete Customer Details"):
df_display = pd.DataFrame([features]).T
df_display.columns = ['Value']
st.dataframe(df_display, use_container_width=True, height=600)
st.markdown("---")
# Prediction section
col_left, col_right = st.columns([2, 1])
with col_right:
st.subheader("๐ฏ Make Prediction")
predict_button = st.button("๐ฎ Predict Purchase Likelihood",
type="primary",
use_container_width=True)
if st.button("๐ Reset", use_container_width=True):
st.session_state.prediction_made = False
st.rerun()
with col_left:
if predict_button:
with st.spinner("๐ค Analyzing customer data..."):
# Create DataFrame with exact feature order
input_df = pd.DataFrame([features])
# Make prediction
try:
prediction_proba = model.predict_proba(input_df)[0, 1]
prediction = 1 if prediction_proba >= 0.45 else 0
# Store in session state
st.session_state.prediction_made = True
st.session_state.prediction = prediction
st.session_state.probability = prediction_proba
st.session_state.features = features
st.session_state.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
st.error(f"โ Prediction Error: {str(e)}")
st.error("Please check that all input values are valid.")
st.stop()
# Display prediction results
if st.session_state.prediction_made:
st.markdown("---")
st.subheader("๐ Prediction Results")
prediction = st.session_state.prediction
probability = st.session_state.probability
# Prediction box with color coding
if prediction == 1:
st.markdown(f"""
<div class="prediction-box prediction-positive">
โ
LIKELY TO PURCHASE<br>
<span style="font-size: 2rem;">{probability*100:.1f}%</span><br>
Confidence Level
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="prediction-box prediction-negative">
โ UNLIKELY TO PURCHASE<br>
<span style="font-size: 2rem;">{(1-probability)*100:.1f}%</span><br>
Confidence Level (Not Buying)
</div>
""", unsafe_allow_html=True)
# Visualization section
st.markdown("---")
st.subheader("๐ Visual Analysis")
viz_col1, viz_col2 = st.columns([1, 1])
with viz_col1:
st.plotly_chart(create_gauge_chart(probability),
use_container_width=True)
with viz_col2:
input_df = pd.DataFrame([st.session_state.features])
st.plotly_chart(create_feature_importance_chart(input_df),
use_container_width=True)
# Recommendations section
st.markdown("---")
st.subheader("๐ก Actionable Recommendations")
recommendations = get_recommendation(probability, st.session_state.features)
for rec in recommendations:
if rec: # Skip empty strings
st.markdown(f"{rec}")
# Model explanation
with st.expander("๐ค How does the model work?"):
st.markdown("""
**Model Details:**
- **Algorithm**: XGBoost (Extreme Gradient Boosting)
- **Classification Threshold**: 45%
- **Training Data**: 4,128 customer records
- **Features**: 18 input variables including demographics, travel preferences, and interaction history
**Prediction Logic:**
- Probability โฅ 45% โ Customer likely to purchase
- Probability < 45% โ Customer unlikely to purchase
**Key Factors Considered:**
- Customer demographics (age, income, occupation)
- Travel behavior (past trips, preferences)
- Sales interaction (pitch satisfaction, follow-ups)
- Family situation (marital status, children)
The model has been trained to identify patterns that indicate purchase likelihood based on historical customer data.
""")
# Export functionality
st.markdown("---")
st.subheader("๐ฅ Export Prediction Report")
report_col1, report_col2 = st.columns([2, 1])
with report_col1:
st.info("๐พ Download a detailed report with all customer information and prediction results")
with report_col2:
# Create comprehensive report
report_data = {
'Timestamp': [st.session_state.timestamp],
'Prediction': ['Will Purchase' if prediction == 1 else 'Will Not Purchase'],
'Purchase_Probability': [f"{probability*100:.2f}%"],
'Confidence_Level': ['High' if abs(probability - 0.5) > 0.2 else 'Medium'],
**st.session_state.features
}
report_df = pd.DataFrame(report_data)
csv = report_df.to_csv(index=False)
st.download_button(
label="๐ Download CSV Report",
data=csv,
file_name=f"customer_prediction_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv",
use_container_width=True
)
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: #888; padding: 1rem;'>
<p><b>๐ข Visit with Us</b> - Wellness Tourism Package Prediction System</p>
<p>Powered by XGBoost ML Model | Classification Threshold: 45% | Trained on 4,128 customers</p>
<p style='font-size: 0.85rem;'>Model Version: v1.0 | Last Updated: December 2024</p>
</div>
""", unsafe_allow_html=True)
# Sidebar footer with statistics
with st.sidebar:
st.markdown("---")
st.info("""
**โน๏ธ About This Application**
This ML-powered system predicts whether a customer will purchase
the Wellness Tourism Package based on their profile and interaction history.
**๐ Model Statistics:**
- **Training Data**: 4,128 customers
- **Purchase Rate**: 19.3%
- **Algorithm**: XGBoost Classifier
- **Threshold**: 45%
- **Features**: 18 variables
**๐ฏ How to Use:**
1. Enter customer details in the form
2. Click 'Predict Purchase Likelihood'
3. Review prediction and recommendations
4. Download detailed report (optional)
**๐ Prediction Accuracy:**
The model considers demographics, travel preferences,
and sales interaction history to make accurate predictions.
""")
st.warning("""
**โ ๏ธ Important Notes:**
- Ensure all fields are filled accurately
- Income should be in Indian Rupees (โน)
- Follow-ups range from 1-6
- Pitch duration in minutes (5-127)
""")
if __name__ == "__main__":
main()
|