packages = [ "pandas", "scikit-learn", "numpy" ]

Buying Used Cars In A Smart Way


Use AI to evaluate a used car’s quality based on its price, maintenance costs, and physical features. Trained on a dataset of car evaluations, our model rates cars as Unacceptable, Acceptable, Good, or Very Good to help you make smarter buying decisions.

Car Purchase AI Main Image

① Train Your Model



Value between 0.1 and 0.5
Loading...

Training Result Summary


Selected Model:

Not available

Test Split:

Not available

Accuracy Score:

Not available

Weighted F1 Score:

Not available

② Get AI Recommendation


Please Enter Your Car Parameters

import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import accuracy_score, f1_score from sklearn.preprocessing import StandardScaler from pyodide.http import open_url from pyodide.ffi import create_proxy from js import document, console import asyncio trained_model = None trained_scaler = None async def datasetPreProcessing(): try: console.log("Attempting to fetch data from URL...") csv_url_content = open_url("https://raw.githubusercontent.com/entzyeung/car-purchase-ai/main/car.csv") console.log("Data fetched successfully, reading CSV...") data = pd.read_csv(csv_url_content) console.log("CSV read successfully") console.log("Starting preprocessing...") document.getElementById("headingText").innerText = "Pre-Processing the Dataset..." data = data.drop_duplicates() data['buying'] = data['buying'].map({'low':0, 'med':1, 'high':2, 'vhigh':3}) data['maint'] = data['maint'].map({'low':0, 'med':1, 'high':2, 'vhigh':3}) data['doors'] = data['doors'].map({'2':0, '3':1, '4':2, '5more':3}) data['persons'] = data['persons'].map({'2':0, '4':1, 'more':2}) data['lug_boot'] = data['lug_boot'].map({'small':0, 'med':1, 'big':2}) data['safety'] = data['safety'].map({'low':0, 'med':1, 'high':2}) data['score'] = data['score'].map({'unacc':0, 'acc':1, 'good':2, 'vgood':3}) console.log("Preprocessing completed, starting upsampling...") result = upSampling(data) console.log("Upsampling completed") return result except Exception as e: console.log(f"Error in preprocessing: {str(e)}") document.getElementById("headingText").innerText = f"Error loading or processing data: {str(e)}" raise def upSampling(data): console.log("Starting upSampling...") from sklearn.utils import resample df_majority = data[data['score'] == 0] samples_in_majority = df_majority.shape[0] df_minority_1 = data[data['score'] == 1] df_minority_2 = data[data['score'] == 2] df_minority_3 = data[data['score'] == 3] df_minority_upsampled_1 = resample(df_minority_1, replace=True, n_samples=samples_in_majority, random_state=42) df_minority_upsampled_2 = resample(df_minority_2, replace=True, n_samples=samples_in_majority, random_state=42) df_minority_upsampled_3 = resample(df_minority_3, replace=True, n_samples=samples_in_majority, random_state=42) console.log("upSampling completed") return pd.concat([df_minority_upsampled_1, df_minority_upsampled_2, df_minority_upsampled_3, df_majority]) def model_selection(): console.log("Selecting model...") selectedModel = document.querySelector('input[name="modelSelection"]:checked').value if selectedModel == "lr": document.getElementById("selectedModelContentBox").innerText = "Logistic Regression" return LogisticRegression(max_iter=1000) else: document.getElementById("selectedModelContentBox").innerText = "Gradient Boosting Classifier" return GradientBoostingClassifier(n_estimators=100, max_depth=4) async def classifier(model, X_train, X_test, y_train, y_test): try: console.log("Starting model training...") scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) clf = model clf.fit(X_train_scaled, y_train) console.log("Model fitted, making predictions...") y_pred = clf.predict(X_test_scaled) acc_score = accuracy_score(y_test, y_pred) f1Score = f1_score(y_test, y_pred, average='weighted') console.log("Training completed, scores calculated") return acc_score, clf, f1Score, scaler except Exception as e: console.log(f"Error in training: {str(e)}") document.getElementById("headingText").innerText = f"Training error: {str(e)}" raise async def trainModel(e=None): global trained_model, trained_scaler try: console.log("trainModel function called!") train_btn = document.getElementById("trainModelBtn") train_btn.disabled = True document.getElementById("trainSpinner").style.display = "inline-block" processed_data = await datasetPreProcessing() console.log("Data preprocessing completed") test_split = float(document.getElementById("test_split").value) console.log(f"Test split value: {test_split}") if test_split > 0.5 or test_split < 0.1: console.log("Test split out of range") document.getElementById("headingText").innerText = "Please enter a test size between 0.1 and 0.5" train_btn.disabled = False document.getElementById("trainSpinner").style.display = "none" return document.getElementById("testSplitContentBox").innerText = test_split console.log("Test split updated in UI") X = processed_data[['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety']] y = processed_data['score'] console.log("Data split into X and y") X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_split, random_state=42) console.log("Data split into train and test sets") model = model_selection() console.log("Model selected") document.getElementById("headingText").innerText = "Training Model... Please Wait" await asyncio.sleep(0.1) acc_score, trained_model, f1Score, trained_scaler = await classifier(model, X_train, X_test, y_train, y_test) console.log(f"Training completed: Accuracy={acc_score}, F1={f1Score}") document.getElementById("accuracyContentBox").innerText = f"{round(acc_score*100, 2)}%" document.getElementById("f1ContentBox").innerText = f"{round(f1Score*100, 2)}%" console.log("UI updated with scores") submit_btn = document.getElementById("submitBtn") submit_btn.classList.remove("disabled") submit_btn.disabled = False console.log("Submit button enabled") train_btn.disabled = False document.getElementById("trainSpinner").style.display = "none" document.getElementById("headingText").innerText = "Model Training Completed Successfully" console.log("Training process fully completed") except Exception as e: console.log(f"Error in trainModel: {str(e)}") document.getElementById("headingText").innerText = f"Training failed: {str(e)}" train_btn.disabled = False document.getElementById("trainSpinner").style.display = "none" async def testModel(e=None): try: console.log("testModel function called!") if not trained_model: console.log("No trained model available") document.getElementById("resultText").innerText = "Please train the model first!" document.getElementById("resultExplanation").innerText = "" return buying_price = int(document.getElementById("buying_price").value) maintenance_price = int(document.getElementById("maintenance_price").value) doors = int(document.getElementById("doors").value) persons = int(document.getElementById("persons").value) lug_boot = int(document.getElementById("lug_boot").value) safety = int(document.getElementById("safety").value) input_data = pd.DataFrame({ 'buying': [buying_price], 'maint': [maintenance_price], 'doors': [doors], 'persons': [persons], 'lug_boot': [lug_boot], 'safety': [safety] }) console.log("Input data prepared as DataFrame") arr_scaled = trained_scaler.transform(input_data) console.log("Input data scaled") result = trained_model.predict(arr_scaled) console.log(f"Prediction result: {result}") condition = { 0: "Unacceptable", 1: "Acceptable", 2: "Good", 3: "Very Good" }.get(result[0], "Unknown result") explanation = "This rating reflects the car's price, maintenance cost, and features like safety and capacity." if result[0] >= 2: explanation += " It scores well due to a balanced cost and desirable attributes." elif result[0] == 0: explanation += " It may have high costs or limited safety/capacity." document.getElementById("resultText").innerText = f"AI Rating: This car is {condition}" document.getElementById("resultExplanation").innerText = explanation console.log("Prediction displayed") except Exception as e: console.log(f"Error in testModel: {str(e)}") document.getElementById("resultText").innerText = "Prediction Error" document.getElementById("resultExplanation").innerText = f"Something went wrong: {str(e)}" console.log("Setting up event listeners...") def trainModelHandler(event): asyncio.ensure_future(trainModel(event)) def testModelHandler(event): asyncio.ensure_future(testModel(event)) train_proxy = create_proxy(trainModelHandler) submit_proxy = create_proxy(testModelHandler) train_btn = document.getElementById("trainModelBtn") train_btn.addEventListener("click", train_proxy) console.log("Train button listener set up with proxy") submit_btn = document.getElementById("submitBtn") submit_btn.addEventListener("click", submit_proxy) console.log("Submit button listener set up with proxy")