Get form data
Machine learning has revolutionized many industries in recent years, enabling computers to learn patterns from data and make intelligent predictions without being explicitly programmed. One interesting application of machine learning is predicting the prices of used cars based on their attributes.
In this article, we‘ll walk through the process of building a machine learning model to predict car prices and deploying it as a web application that anyone can use. Whether you‘re looking to sell your car, buy a used vehicle, or just learn about the latest data science techniques, this guide has you covered!
The Car Price Prediction Problem
When buying or selling a used car, it can be challenging to determine a fair price. Many factors can influence a vehicle‘s value, such as its make and model, age, mileage, horsepower, and more. Pricing guides like Kelley Blue Book provide estimates, but they don‘t take into account the specific combination of attributes of an individual car.
This is where machine learning comes in. By analyzing historical sales data of many used cars, an ML model can learn the complex relationships between a car‘s features and its sales price. The model can then be used to predict the price of any car given its particular attributes.
Such a tool would be valuable for both buyers and sellers looking to negotiate fair deals with confidence. It could also help car dealerships optimize their inventory pricing. Let‘s see how to build it!
Building the Machine Learning Model
The first step is to build a machine learning model capable of predicting car prices with high accuracy. Here‘s an overview of the process:
1. Gather and prepare the data
First, we need a dataset of historical used car sales to train our ML models on. For this example, we‘ll use this Kaggle dataset containing records of car sales in India.
The raw dataset looks like this:
Car_Name Year Selling_Price Present_Price Kms_Driven Fuel_Type Seller_Type Transmission Owner Jeep Wrangler unlimited 2017 995000 1600000 14000 Diesel Dealer Automatic 0 BMW X3 Expedition 2013 1175000 1400000 41038 Diesel Dealer Automatic 0 Mahindra Jeep MM 540 DP 2000 124999 190000 35000 Diesel Individual Manual 1
Before training our models, we need to preprocess the data:
- Check for missing values and outliers
- Convert categorical variables like fuel type and transmission to numerical using one-hot encoding
- Normalize numerical features to a consistent scale
- Split the data into training and test sets (e.g. 80% train / 20% test)
2. Perform exploratory data analysis
Next we should explore the data to understand the distributions of the features, visualize relationships between variables, and gain insights that can guide feature engineering. Some useful plots include:
- Histogram of car price
- Scatterplots of price vs. year, mileage, etc.
- Box plots of price segmented by fuel type, transmission type, etc.

3. Engineer and select features
Based on insights from EDA, we can create new features to help the model, such as:
- Car age (current year – year)
- Price per kilometer driven
- Luxury car brand indicator
We should also remove features that are irrelevant to price like car name. Techniques like correlation analysis and feature importance scores can help identify predictive features to keep in the model.
4. Train and evaluate machine learning models
Now we‘re ready to train some ML models! Since this is a regression task (predicting a number), we can try algorithms like:
- Linear Regression
- Decision Tree
- Random Forest
- Gradient Boosting
We train each model on the training set and evaluate performance on the test set using metrics like:
- Mean absolute error (MAE)
- Root mean squared error (RMSE)
- R-squared
We can compare the models to see which performs best on this dataset. If the dataset is large, we should use k-fold cross validation to get reliable estimates of model performance.
5. Fine-tune the best model
Let‘s say Random Forest looked promising. We can optimize it further by tuning its hyperparameters, the knobs we can turn to control model complexity and performance. Examples include:
- n_estimators: number of trees in the forest
- max_depth: maximum depth of each tree
- min_samples_leaf: minimum number of samples in a leaf node
We can use techniques like grid search or random search with cross-validation to find the best combination of hyperparameter values.
After tuning, we have our final trained model! We evaluate it one last time on the held-out test set to estimate real-world performance. Let‘s say it achieves an RMSE of $1,500 – not bad for a first attempt!
Deploying the Car Price Predictor
Now that we have a trained ML model, let‘s deploy it as a web app so anyone can easily use it to get car price predictions. We‘ll use the Flask web framework and host the app on Heroku. Here‘s how:
1. Save the trained model
First we save our trained Random Forest model to a file using Python‘s pickle module:
import picklewith open(‘model.pkl‘, ‘wb‘) as file: pickle.dump(rf_model, file)
2. Create a Flask web app
Next we create a new Python file app.py for our Flask web app. It will contain routes to:
- Render the homepage containing the input form
- Handle form submission and return the model‘s prediction
from flask import Flask, render_template, request import pickleapp = Flask(name)
@app.route(‘/‘) def home(): return render_template(‘index.html‘)
@app.route(‘/predict‘, methods=[‘POST‘]) def predict():
year = int(request.form[‘year‘]) mileage = int(request.form[‘mileage‘]) # ... # Load model and make prediction model = pickle.load(open(‘model.pkl‘, ‘rb‘)) price = model.predict([[year, mileage, ...]]) return render_template(‘index.html‘, price=price)The homepage is defined in a separate HTML file templates/index.html:
<!DOCTYPE html> <html> <head> <title>Car Price Predictor</title> </head> <body> <h1>Used Car Price Predictor</h1><form action="/predict" method="post"> Year: <input type="number" name="year"><br> Mileage: <input type="number" name="mileage"><br> <!-- ... --> <input type="submit" value="Predict Price"> </form> {% if price %} <h2>Predicted price: ${{ price }}</h2> {% endif %}</body>
</html>3. Deploy to Heroku
Finally, we can deploy our app to Heroku so it‘s live on the web for anyone to access.
After installing the Heroku CLI, we create a few configuration files:
requirements.txt lists the Python dependencies:
Flask gunicorn scikit-learnProcfile specifies the command to run the app:
web: gunicorn app:appruntime.txt specifies the Python version:
python-3.9.12We can then deploy straight from the command line:
$ git init $ heroku create $ git add . $ git commit -m "Deploy to Heroku" $ git push heroku mainAfter a minute, the app is live! Anyone can now visit the URL, input their car‘s details, and get a price prediction.
Next Steps
We‘ve seen how to build a machine learning model to predict used car prices and deploy it as a user-friendly web app. This is an exciting proof of concept, but there are many ways to improve it:
- Gather more training data for a more robust model
- Extract new features from car descriptions using NLP
- Experiment with more ML algorithms and ensembles
- Allow users to input more details about car condition, location, etc.
- Display estimated price ranges and confidence scores
- Retrain the model over time as new data comes in
Machine learning offers huge opportunities to build intelligent applications and bring them to users at scale. I encourage you to think of other problems an ML model could help solve and try implementing your own solutions. The possibilities are endless!