gracysapra1911's picture
Create app.py
1f0e0c5 verified
import gradio as gr
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# Load dataset
data = pd.read_csv('knn.csv')
# Separate features and target
x = data.drop('price_range', axis=1).values # Features
y = data['price_range'].values # Target
# Train-test split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
# Train the KNN classifier
knnClassifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=1)
knnClassifier.fit(x_train, y_train)
# Define the prediction function for Gradio
def predict_price_range(battery_power, blue, clock_speed, dual_sim, fc, four_g, int_memory, m_dep, mobile_wt, n_cores, pc, px_height, px_width, ram, sc_h, sc_w, talk_time, three_g, touch_screen, wifi):
# Prepare the input for prediction
input_data = np.array([[battery_power, blue, clock_speed, dual_sim, fc, four_g, int_memory, m_dep, mobile_wt, n_cores, pc, px_height, px_width, ram, sc_h, sc_w, talk_time, three_g, touch_screen, wifi]])
# Make prediction using the trained KNN model
prediction = knnClassifier.predict(input_data)
# Return the predicted price range
price_ranges = ['Low', 'Medium', 'High', 'Very High'] # Modify this according to your dataset
return f"Predicted Price Range: {price_ranges[prediction[0]]}"
# Create Gradio interface with all the features as inputs using the updated Gradio components
interface = gr.Interface(
fn=predict_price_range, # Function that does the prediction
inputs=[
gr.Slider(500, 2000, step=1, label="Battery Power"),
gr.Checkbox(label="Bluetooth"), # 1 for Yes, 0 for No
gr.Slider(0.5, 3.0, step=0.1, label="Clock Speed"),
gr.Checkbox(label="Dual SIM"), # 1 for Yes, 0 for No
gr.Slider(0, 20, step=1, label="Front Camera (FC)"),
gr.Checkbox(label="4G"), # 1 for Yes, 0 for No
gr.Slider(4, 64, step=1, label="Internal Memory (GB)"),
gr.Slider(0.1, 1.0, step=0.1, label="Mobile Depth (cm)"),
gr.Slider(80, 250, step=1, label="Mobile Weight (g)"),
gr.Slider(1, 8, step=1, label="Number of Cores"),
gr.Slider(0, 20, step=1, label="Primary Camera (PC)"),
gr.Slider(0, 1960, step=1, label="Pixel Height"),
gr.Slider(500, 2000, step=1, label="Pixel Width"),
gr.Slider(500, 4000, step=1, label="RAM"),
gr.Slider(5, 20, step=1, label="Screen Height (cm)"),
gr.Slider(0, 18, step=1, label="Screen Width (cm)"),
gr.Slider(2, 20, step=1, label="Talk Time (hours)"),
gr.Checkbox(label="3G"), # 1 for Yes, 0 for No
gr.Checkbox(label="Touch Screen"), # 1 for Yes, 0 for No
gr.Checkbox(label="WiFi"), # 1 for Yes, 0 for No
],
outputs=gr.Textbox(label="Predicted Price Range"), # Output format
title="Mobile Price Range Prediction",
description="Predict the price range of a mobile based on its specifications."
)
# Launch the Gradio app
interface.launch()