Downloads · 30 days
0
lihicarmeli/Boston-rideshare-pricing-prediction
Boston-rideshare-pricing-prediction is a machine learning model from lihicarmeli. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
[](https://huggingface.co/spaces/lihicarmeli/boston-fare-predictor) [](https://huggingface.co/lihicarmeli/Boston-rideshare-pricing-prediction/blob/main/LihiCarmeliAssignment2Classification%2CRegression%2CClustering%2C…
Downloads · 30 days
0
Access
Public
Updated May 9, 2026
Repo size
320 MB
Likes
0
Public
Click a slice to open those files.
.pkl296 MB · 97%
From the Hugging Face model README
An advanced AI system for predicting ride-sharing fares and classifying them into service tiers (Budget, Standard, or Premium). The model is based on a Random Forest Regressor trained on Boston's Uber and Lyft datasets.
You can test the model in real-time using the interface below:
This project explores the dynamic landscape of rideshare services in Boston, MA. The dataset provides a unique opportunity to analyze the interaction between urban mobility and environmental factors by integrating real-world rideshare transactions with high-resolution local weather data.
The dataset is sourced from Kaggle ("Uber and Lyft Dataset Boston, MA"). It encompasses a period of rideshare activity in Boston, meticulously merged with weather metrics corresponding to the exact time and location of each trip.
The dataset offers a rich mix of data types, making it ideal for advanced feature engineering and predictive modeling:
distance (miles), surge_multiplier.temp (Fahrenheit), humidity, precipIntensity, windSpeed.cab_type (Uber vs. Lyft).name (e.g., Black, XL, Shared, Lux, UberPool).source and destination (Specific Boston neighborhoods).short_summary (Weather descriptions like "Cloudy", "Rain", or "Clear").price: A continuous numerical value representing the cost of the ride."To what extent can we accurately predict rideshare prices in Boston based on trip characteristics, service levels, and real-time weather conditions?"
The following table summarizes the key variables and the central target variable used in the models:
| Category | Specific Features | Role & Description |
|---|---|---|
| Target Variable | price | The Core Objective. Represents the transaction cost of the ride in USD ($). This is the continuous value we aim to predict. |
| Service Level | name | Highest Impact. The primary differentiator for price (e.g., Shared vs. Lux/Black). |
| Trip Metrics | distance | Primary Baseline. Maintains a strong linear correlation with the final price. |
| Dynamic Pricing | surge_multiplier | Demand Factor. Captures real-time price increases during peak demand or extreme weather. |
| Environment | temp, precipIntensity | External Context. Accounts for weather conditions that influence rideshare demand and pricing. |
| Geography | source, destination | Localized Trends. Enables the model to learn pricing behaviors specific to Boston neighborhoods. |
Before diving into deep analysis, my first priority was ensuring the dataset's integrity. This phase focused on filtering noise and verifying that my "Bright Orange" visualizations represent a clean, reliable data source.
price column. The heatmap below confirms a 100% clean dataset ready for processing.

One of the most interesting parts of this research was investigating whether adverse weather in Boston directly translates to higher fares for passengers. I analyzed the relationship between precipitation and pricing dynamics.
precipIntensity) leads to an immediate increase in trip costs.

In this section, I analyzed how the time of day affects rideshare pricing in Boston, focusing on whether certain hours command higher fares on average.

In this critical stage of the EDA, I conducted a deep statistical dive into the mathematical relationships between all features—including the encoded service types—and the final trip price.
Black SUV and Lux Black XL) and the trip distance hold the highest positive correlation with the target variable.

In this phase, I conducted a direct comparative analysis between Uber and Lyft to determine if one brand consistently outprices the other.

This section analyzes the correlation between travel distance and fare pricing across various service categories from Uber and Lyft.

The goal of this phase is to predict rideshare trip prices in Boston as a continuous numerical value. Primary Metric: Our objective is to minimize prediction errors, specifically focusing on RMSE (Root Mean Squared Error) and MAE (Mean Absolute Error) to ensure the most reliable price estimations.
Based on the Exploratory Data Analysis (EDA), I identified the following features as the most significant predictors for price:
| Category | Features |
|---|---|
| Trip Characteristics | distance, surge_multiplier |
| Service Levels | name, cab_type |
| Location | source, destination |
| Temporal Factors | hour |
| Environmental Factors | temp, precipIntensity |
To optimize model performance and maintain interpretability, I performed a strategic reduction of the dataset:
Before training the predictive model, the dataset underwent a rigorous preprocessing pipeline to ensure data integrity and optimal model performance.
Applied One-Hot Encoding (via pd.get_dummies) to transform categorical variables such as name, source, and destination into numerical formats, enabling the regression algorithms to process categorical data effectively.
random_state=42 to ensure that the data split remains identical every time the code is executed. This ensures that any improvements in model performance are due to tuning and not random variations in the data distribution.I conducted a comparative analysis of the target variable (price) across both sets:

I initiated the modeling phase by implementing a Linear Regression model using the scikit-learn framework. The primary objective of this step is to establish a Baseline Performance Benchmark.
By starting with a simpler, interpretable model, I can evaluate the inherent complexity of the prediction task and set a standard for comparison. Linear Regression serves as an ideal baseline as it efficiently models the direct relationships between our features (e.g., distance, service tier) and the target variable (price).
This benchmark will be used to measure the "value-add" of more sophisticated algorithms (such as Ensemble methods) in subsequent stages of the project.
After training, the Linear Regression model was evaluated on the unseen test set (20% of the data) to measure its real-world predictive accuracy.
| Metric | Value | Interpretation |
|---|---|---|
| MAE (Mean Absolute Error) | $1.65 | On average, the model's price prediction deviates by only $1.65. |
| RMSE (Root Mean Squared Error) | $2.24 | Indicates a low frequency of large prediction errors. |
| R-squared ($R^2$) | 0.9345 | 93.45% of the price variance is accurately captured by the model. |
The evaluation reveals a high level of precision for a baseline model. Notably, the $R^2$ score on the test set is identical to the training score, demonstrating that the model generalizes exceptionally well and is not suffering from overfitting. These results establish a very strong benchmark for any future, more complex algorithms.
To further validate the baseline's performance, I implemented diagnostic plots to visualize the relationship between predicted values and actual market prices.
This scatter plot compares the model's estimations against the ground truth.
Analysis of the residuals (Errors = Actual - Predicted) is critical for assessing model bias.

To understand the underlying logic of the pricing model, I extracted and visualized the Linear Regression Coefficients. This analysis reveals how much each feature contributes to the final fare estimation.
surge_multiplier and premium service tiers like Lux Black XL have the strongest positive impact on price. This aligns with rideshare pricing strategies where vehicle class and real-time demand significantly inflate costs.UberPool, Shared, UberX) show strong negative coefficients. These represent the price reduction users receive when opting for high-capacity or standard vehicle types compared to the baseline luxury options.distance feature maintains a consistent positive coefficient, quantifying the marginal cost increase for every additional mile traveled.source_North End) show a minimal but measurable impact, suggesting that while the starting point matters, it is secondary to the chosen service tier and distance.The model effectively prioritizes Service Level and Demand (Surge) as the dominant predictors of price, proving that the user's choice of "how to ride" is often more influential than "where they go."

To capture complex, non-linear patterns in the data and enhance model accuracy, I implemented several advanced feature engineering techniques:
distance_surge interaction term. This variable accounts for the compounded effect of surge pricing over long distances, providing a more nuanced predictor than evaluating each feature in isolation.StandardScaler to transform numerical features (distance, temperature, distance_surge). By ensuring all features have a mean of 0 and a standard deviation of 1, I mitigated potential bias toward features with larger numerical magnitudes, ensuring stable and balanced model training.After generating the new features, I performed a visual validation to ensure they provide meaningful signals for the predictive model.
The K-Means Clustering visualization (left) illustrates the distinct "Trip Profiles" identified by the algorithm. By grouping rides based on price-distance coordinates, we successfully segmented the data into four density tiers (represented by the Viridis color scale). This adds a high-level context that helps the model differentiate between economy-short trips and luxury-long hauls.
The Interaction Plot (center) validates the logic behind the distance_surge feature. The strong positive slope of the red regression line confirms that the interaction between distance and the surge multiplier is a potent predictor of fare price, capturing price escalations that individual features might miss.
The Boxplot of Scaled Features (right) demonstrates the result of our standardization process.

In this section, I analyzed how external environmental and temporal factors influence pricing dynamics in the Boston rideshare market.
surge_multiplier) might be localized to specific high-intensity events rather than broad time windows.These visualizations justify the model's reliance on Service Tiers and Distance as the dominant predictors. By debunking the assumption that rain or hour-of-day universally inflate prices, we can focus our predictive power on the features that truly drive market variance.

To gain deeper insights into market structures, I performed a multi-stage cluster analysis combining K-Means Clustering with Principal Component Analysis (PCA).
By analyzing the centroids of the generated clusters, I identified and labeled four distinct business segments within the Boston rideshare market:
Since the dataset contains numerous high-dimensional features (encoded locations, service tiers, weather, etc.), I applied PCA to project the data into a 2D space.

In this final modeling phase, I retrained the Linear Regression algorithm using the enriched dataset. By integrating the advanced features engineered in the previous steps, the model transitioned from processing raw inputs to understanding complex market dynamics.
The optimized model now accounts for:
distance_surge interaction.cluster_id labels and dist_to_centroid.is_raining) and temporal peaks (is_peak_hour).| Metric | Baseline Model | Optimized Model | Improvement |
|---|---|---|---|
| R-squared ($R^2$) | 0.9345 | 0.9690 | +3.45% |
| MAE | $1.65 | $1.15 | -$0.50 |
To push the boundaries of predictive accuracy, I transitioned from linear modeling to advanced Ensemble Learning algorithms. These models are designed to capture complex, non-linear interactions within the features that a standard regression might overlook.
The results represent the highest accuracy achieved in this project:
| Model | Mean Absolute Error (MAE) | R-squared ($R^2$) |
|---|---|---|
| Linear Regression (Optimized) | $1.15 | 0.9690 |
| Random Forest | $0.83 | 0.9798 |
The Random Forest model emerged as the superior predictor, explaining nearly 98% of the price variance. By effectively leveraging the engineered features (clusters and interactions), the model reduced the average prediction error to just $0.83, providing a highly precise solution for rideshare price estimation.
The core objective of this project was to transition from a general estimation to a high-precision predictive model. The final evaluation demonstrates a dramatic performance breakthrough, achieving an approximately 50% reduction in Mean Absolute Error (MAE).
| Model Tier | Complexity Level | Mean Absolute Error (MAE) |
|---|---|---|
| Baseline (Linear) | Simple Linear Relationship | $1.65 |
| Improved (Random Forest) | Advanced Ensemble Learning | $0.83 |
The significant leap in accuracy is attributed to two primary strategic factors:
Conclusion: By combining non-linear ensemble modeling with domain-specific feature engineering, the final model provides highly reliable fare estimations with an average error of less than one dollar ($0.83), making it a robust tool for real-world application.

To finalize the model analysis, I extracted the Gini Importance scores to identify which features were most influential in the Random Forest’s decision-making process.
The visualization reveals a critical insight: The top 3 most influential features are the Trip Clusters created during the Feature Engineering phase.
trip_cluster_2, trip_cluster_1, and trip_cluster_3 dominate the importance ranking proves that segmenting the market into distinct behavioral profiles provided more predictive power than any single raw input.distance_surge also ranks higher than standard distance, confirming that the relationship between demand and mileage is a more potent predictor than mileage alone.name_Shared, name_UberXL) follow as secondary predictors, showing that once the model understands the trip's "cluster context," it uses the specific service level to fine-tune the final price.Conclusion: This ranking validates the project's core hypothesis: sophisticated feature engineering, rather than just choosing a complex algorithm, is what truly "breaks the predictive ceiling" and drives model excellence.

After evaluating multiple models, the Random Forest Regressor emerged as the superior solution for predicting rideshare prices in Boston. It achieved an exceptional balance of precision, stability, and computational efficiency.
The victory of the Random Forest model is attributed to three core pillars:
distance_surge interaction and trip_cluster provided the model with "pre-digested" insights, allowing it to capture complex demand-price dynamics.Final Verdict: By leveraging ensemble-based complexity and high-quality engineered features, this model delivers a sub-dollar accuracy rate, setting a new standard for fare estimation in the Boston rideshare ecosystem.
To expand the analysis beyond continuous regression, I transformed the target variable into discrete categories. This allows for a Classification approach, focusing on identifying trip price segments rather than exact dollar values.
I implemented a Quantile Binning strategy to split the price data into three balanced classes: Low (0), Medium (1), and High (2).
pd.qcut on the training set to ensure an equal distribution of samples across categories.
pd.cut to maintain strict evaluation standards and prevent data leakage.Before proceeding to train the classification model, it is essential to ensure that the newly created target categories are well-balanced. An imbalanced dataset can lead to model bias, where the algorithm favors the majority class.
I generated a summary table and a corresponding visualization to inspect the distribution of the three price tiers within the training set:
Having a balanced training set ensures that the classifier will develop equal predictive sensitivity for all price segments. This prevents the model from becoming biased toward any specific tier and ensures that evaluation metrics (like Accuracy and F1-Score) remain reliable indicators of real-world performance.

To ensure a high-quality classification model, I generated a detailed distribution table for the newly defined price tiers within the training dataset.
The following table illustrates the balance between the three price segments:
| Price Tier | Count | Percentage (%) | Label |
|---|---|---|---|
| 0 | 30,120 | 37.65% | Budget |
| 1 | 23,332 | 29.17% | Standard |
| 2 | 26,548 | 33.19% | Premium |
In this phase, I transitioned from price estimation (regression) to price tier prediction (classification). The objective is to identify the most accurate algorithm for categorizing rides into the predefined Budget, Standard, and Premium tiers.
I implemented a competitive evaluation pipeline using three distinct classification algorithms:
Using an automated training loop, each model was fitted on the categorized training set and evaluated using the Accuracy Score metric on the unseen test set.
Initial Accuracy Results:
Key Insight: All models demonstrated high predictive reliability, consistently exceeding 90% accuracy. The Random Forest Classifier emerged as the early leader, further confirming the model's suitability for the intricate pricing structures of the Boston rideshare market.
To gain a granular understanding of the classifier's performance, I implemented a diagnostic pipeline using Confusion Matrices and detailed Classification Reports for each model.
ConfusionMatrixDisplay, I mapped the predicted vs. actual labels to visualize where the models were most successful and where they faced "confusion."


To ensure the highest level of transparency and diagnostic rigor, I implemented two industry-standard evaluation techniques: ROC/AUC Analysis and SHAP Explanations.
I evaluated the models' ability to distinguish the Premium tier from other categories using the Receiver Operating Characteristic (ROC) curve.
To move beyond "Black Box" modeling, I utilized SHAP (SHapley Additive exPlanations) to visualize the global impact of each feature on the model's output.


After a rigorous evaluation involving Accuracy metrics, Confusion Matrices, and Interpretability tools, the Random Forest Classifier has been selected as the optimal model for this project.
Superior Class Separation (AUC/ROC): The model demonstrated the highest AUC score, proving its exceptional ability to distinguish between Budget, Standard, and Premium tiers with minimal false positives. Its decision threshold is the most robust among all tested candidates.
Logical Interpretability (SHAP): Through SHAP analysis, we validated that the model's predictions are grounded in meaningful data relationships. It successfully prioritized our engineered features—specifically the Trip Clusters and Distance-Surge interactions—proving that it "understands" the economic drivers of the Boston rideshare market.
High-Precision Reliability: With an Accuracy score exceeding 92%, the Random Forest model provides the most stable performance across all segments. Its confusion matrix showed nearly zero errors between extreme classes (Budget vs. Premium), ensuring that high-stakes pricing decisions remain accurate.
The Random Forest Classifier isn't just a "Black Box"; it is a highly calibrated engine that leverages complex feature interactions to provide actionable, sub-dollar-precise classifications. It stands as the most reliable model for real-world dynamic pricing applications.
To further validate the economic relevance of the price tiers, I performed a comparative analysis between the two primary market players in the dataset.
Using pd.crosstab with index normalization, I mapped the percentage distribution of each price tier—Budget (0), Standard (1), and Premium (2)—across Uber and Lyft. This approach reveals the pricing strategy and market positioning of each brand.
The Stacked Bar Chart (above) illustrates the pricing composition of each fleet:

To ensure the classification model's transparency and understand the drivers behind its predictions, I implemented SHAP (SHapley Additive exPlanations) analysis. This method quantifies the contribution of each feature to the final classification across all three price tiers.
shap.TreeExplainer optimized for Random Forest, I calculated the impact of each variable on the model's output magnitude.The SHAP Summary Bar Plot provides a clear breakdown of feature importance, categorized by class (Budget, Standard, and Premium):
name_Shared or distance_surge influence specific classes more than others, providing a nuanced view of what drives a trip to be classified as "Budget" versus "Premium."Conclusion: This analysis validates that the model relies on logically sound economic indicators, with engineered features providing the most significant predictive signal.

To squeeze every bit of predictive power out of the Random Forest Classifier, I moved beyond default settings and performed a systematic Hyperparameter Optimization phase.
I utilized RandomizedSearchCV to explore the parameter space efficiently. This approach balances computational cost with high-quality results by sampling a fixed number of parameter combinations.
n_estimators: The number of decision trees in the forest.max_depth: The maximum depth of each tree (controlling for potential over-fitting).min_samples_split: The minimum number of samples required to split an internal node.The search identified the following "Best Parameters" for the final model:
Outcome: By applying these optimized settings, the model is now fine-tuned to the specific nuances of the Boston rideshare market, ensuring higher stability and more precise classification across all price tiers.
The final stage of this project involved transitioning from static analysis to a functional AI-powered application. I developed an interactive web interface that allows users to experience the model's predictive power in real-time.
The Boston Ride Fare Predictor enables users to input specific trip parameters:
To ensure accurate predictions, the application runs a streamlined version of our data pipeline on every user input:
StandardScaler to maintain consistency with the training environment.Outcome: This deployment demonstrates the practical utility of the project, turning complex machine learning logic into a user-friendly tool for strategic ride planning.
