mobileai / mobile.py
Nurag's picture
Update mobile.py
20fb29f verified
Raw History Blame Contribute Delete
2.95 kB
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
import joblib
import gradio as gr
# Load the dataset
data = pd.read_csv('https://raw.githubusercontent.com/Senka2112/VIS2023-datasets/refs/heads/main/MobilePhonePrice.csv')
# Data Cleaning
data.drop_duplicates(inplace=True)
data.fillna(method='ffill', inplace=True)
# Convert categorical variables to numerical
label_encoders = {}
for column in ['Brand', 'Model']:
le = LabelEncoder()
data[column] = le.fit_transform(data[column])
label_encoders[column] = le
# Normalize numerical features
scaler = MinMaxScaler()
data[['Storage', 'RAM', 'Screen Size (inches)', 'Camera (MP)', 'Battery Capacity (mAh)', 'Price ($)']] = scaler.fit_transform(data[['Storage', 'RAM', 'Screen Size (inches)', 'Camera (MP)', 'Battery Capacity (mAh)', 'Price ($)']])
# Split the data into features and target
X = data.drop('Price ($)', axis=1)
y = data['Price ($)']
# Train the model
model = RandomForestRegressor()
model.fit(X, y)
# Save the model and scaler
joblib.dump(model, 'mobile_price_model.pkl')
joblib.dump(scaler, 'scaler.pkl')
joblib.dump(label_encoders, 'label_encoders.pkl')
# Define the prediction function
def predict_price(brand, model_name, storage, ram, screen_size, camera, battery):
input_data = {
'Brand': brand,
'Model': model_name,
'Storage': storage,
'RAM': ram,
'Screen Size (inches)': screen_size,
'Camera (MP)': camera,
'Battery Capacity (mAh)': battery
}
input_df = pd.DataFrame([input_data])
# Encode categorical variables
for column in ['Brand', 'Model']:
input_df[column] = label_encoders[column].transform(input_df[column])
# Scale numerical features
input_df[['Storage', 'RAM', 'Screen Size (inches)', 'Camera (MP)', 'Battery Capacity (mAh)']] = scaler.transform(input_df[['Storage', 'RAM', 'Screen Size (inches)', 'Camera (MP)', 'Battery Capacity (mAh)']])
# Make prediction
prediction = model.predict(input_df)
return prediction[0]
# Create Gradio interface
iface = gr.Interface(
fn=predict_price,
inputs=[
gr.inputs.Dropdown(choices=data['Brand'].unique().tolist(), label="Brand"),
gr.inputs.Dropdown(choices=data['Model'].unique().tolist(), label="Model"),
gr.inputs.Slider(minimum=32, maximum=512, label="Storage (GB)"),
gr.inputs.Slider(minimum=2, maximum=16, label="RAM (GB)"),
gr.inputs.Slider(minimum=4.0, maximum=7.0, label="Screen Size (inches)"),
gr.inputs.Textbox(label="Camera (MP)"),
gr.inputs.Slider(minimum=1000, maximum=7000, label="Battery Capacity (mAh)")
],
outputs="number",
title="Mobile Phone Price Predictor",
description="Enter the specifications of the mobile phone to predict its price."
)
iface.launch()