CoolFace
Apppublic

omankesh95/Laptop_Rate_Prdiction

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
streamlit_app.py107 linesDownload Raw Back to src
1import streamlit as st2import numpy as np3import pandas as pd4import pickle5import json6import os7 8# Get current and parent directory9current_dir = os.path.dirname(os.path.abspath(__file__))  # /src/10parent_dir = os.path.dirname(current_dir)  # project root11 12# Define paths13xgb_model_path = os.path.join(parent_dir, "xgboost_log_model.pkl")14lgbm_model_path = os.path.join(parent_dir, "lightgbm_log_model.pkl")15scaler_path = os.path.join(parent_dir, "scaler.pkl")16label_encoders_path = os.path.join(parent_dir, "label_encoders.pkl")17weights_path = os.path.join(parent_dir, "ensemble_weights.json")18 19# Load files20try:21    with open(xgb_model_path, "rb") as f:22        xgb_model = pickle.load(f)23    with open(lgbm_model_path, "rb") as f:24        lgbm_model = pickle.load(f)25    with open(scaler_path, "rb") as f:26        scaler = pickle.load(f)27    with open(label_encoders_path, "rb") as f:28        label_encoders = pickle.load(f)29    with open(weights_path, "r") as f:30        weights = json.load(f)31except FileNotFoundError as e:32    st.error(f"โŒ Error loading model/preprocessing files: {e}")33    st.stop()34 35# Streamlit App UI36st.set_page_config(page_title="Laptop Price Predictor", page_icon="๐Ÿ’ป")37st.title("๐Ÿ’ป Laptop Price Predictor (Ensemble Model)")38st.markdown("Predict laptop prices using XGBoost and LightGBM models.")39 40# User Input41company = st.selectbox('Brand (Company)', label_encoders['Company'].classes_)42typename = st.selectbox('Laptop Type', label_encoders['TypeName'].classes_)43ram = st.slider('RAM (GB)', 2, 64, step=2)44weight = st.number_input('Weight (kg)', min_value=0.5, max_value=4.0, step=0.1)45cpu_type = st.selectbox('CPU Type', label_encoders['Cpu_type'].classes_)46touchscreen = st.radio('Touchscreen?', ['No', 'Yes'])47ips = st.radio('IPS Display?', ['No', 'Yes'])48hdd = st.selectbox('HDD (GB)', [0, 128, 256, 512, 1024, 2048])49ssd = st.selectbox('SSD (GB)', [0, 128, 256, 512, 1024])50gpu_type = st.selectbox('GPU Type', label_encoders['Gpu_type'].classes_)51os = st.selectbox('Operating System', label_encoders['OS'].classes_)52 53# Display Details54st.markdown("### ๐Ÿ“บ Display Details (PPI Auto Calculated)")55screen_size = st.selectbox('Screen Size (inches)', [13.3, 14.0, 15.6, 16.0, 17.3])56res_label = st.selectbox('Screen Resolution', {57    'HD (1366x768)': (1366, 768),58    'Full HD (1920x1080)': (1920, 1080),59    '2K (2560x1440)': (2560, 1440),60    '4K (3840x2160)': (3840, 2160)61})62res_width, res_height = res_label63ppi_value = round((res_width**2 + res_height**2) ** 0.5 / screen_size, 2)64st.caption(f"๐Ÿ” **Calculated PPI**: {ppi_value} based on resolution {res_width}x{res_height} and screen size {screen_size}\".")65 66# Prepare Input Data67input_dict = {68    'Company': company,69    'TypeName': typename,70    'Ram': ram,71    'Weight': weight,72    'Cpu_type': cpu_type,73    'Touchscreen': 1 if touchscreen == 'Yes' else 0,74    'IPS': 1 if ips == 'Yes' else 0,75    'ppi': ppi_value,76    'HDD': hdd,77    'SSD': ssd,78    'Gpu_type': gpu_type,79    'OS': os80}81 82# Create DataFrame and Apply Label Encoding83input_df = pd.DataFrame([input_dict])84for col in label_encoders:85    input_df[col] = label_encoders[col].transform(input_df[col])86 87# Scale Numeric Features88scaled_input = scaler.transform(input_df)89 90# Model Predictions (Log values)91log_pred_xgb = xgb_model.predict(scaled_input)[0]92log_pred_lgbm = lgbm_model.predict(scaled_input)[0]93 94# Ensemble Prediction95final_log_price = (96    log_pred_xgb * weights['XGBoost'] +97    log_pred_lgbm * weights['LightGBM']98)99final_price = np.exp(final_log_price)100 101# Output102st.subheader("๐Ÿ“ˆ Predicted Laptop Price:")103st.success(f"๐Ÿ’ฐ โ‚น {final_price:,.2f}")104 105st.markdown("---")106st.caption("Built with โค๏ธ using XGBoost and LightGBM models in an ensemble format.")107