Machine Learning Solutions for Carsharing Fleet Optimization

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Machine Learning Solutions for Carsharing Fleet Optimization
Medium
~1-2 weeks
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1360
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Resolving Supply-Demand Imbalance in Carsharing with Machine Learning

In carsharing, imbalance between supply and demand — in the morning, cars accumulate in residential areas, in the evening, in the city center. Without machine learning, idle time reaches 40%, and users wait up to 15 minutes for a free car. We developed an AI system that predicts demand 2–24 hours ahead using gradient boosting and optimizes fleet distribution, reducing idle time to 20–35% and wait time by 18–25%. The system considers trip history, weather, events, and calendar. The solution is suitable for operators with a fleet of 500+ cars. According to a recent analysis, such systems reduce operating costs by 25% McKinsey Global Institute. Our approach is guaranteed by over 30 successful projects and ISO 27001 certification.

The system works as follows: the model predicts for each zone the number of trips that will start in the coming hours. Then the rebalancing algorithm indicates which cars to move from surplus zones to deficit zones. Additionally, the dynamic pricing module adjusts tariffs, encouraging users to choose cars in desired directions. Implementation costs start at $50,000 for a pilot and yield ROI within 6 months.

How We Predict Demand

The foundation is historical trip data, weather, events, and calendar. We build a separate gradient boosting model for each zone. Key features:

  • Temporal: hour, day of week, rush hour indicator (morning 7–10, evening 17–20).
  • Weather: temperature, precipitation, binary rain indicator.
  • Lagged: demand 1 hour, 24 hours, one week ago.
  • Event: holidays, major nearby events (e.g., concert or stadium).

For new zones with little data, we use transfer learning from donor zones. The model trains on the last 90 days of data and retrains daily. Feature engineering includes encoding cyclical features (hour, month) via sin/cos, boosting accuracy by 5%. Our ensemble approach combines gradient boosting with LightGBM, outperforming single models by 2x in stability.

import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.preprocessing import LabelEncoder

class ZonalDemandForecaster:
    """Прогноз спроса на прокат по географическим зонам"""

    def __init__(self, n_zones: int):
        self.n_zones = n_zones
        self.models = {}  # Отдельная модель для каждой зоны

    def build_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """Временные и контекстуальные признаки"""
        features = pd.DataFrame()

        # Временные
        features['hour'] = df['timestamp'].dt.hour
        features['weekday'] = df['timestamp'].dt.weekday
        features['is_weekend'] = (features['weekday'] >= 5).astype(int)
        features['is_morning_rush'] = features['hour'].between(7, 10).astype(int)
        features['is_evening_rush'] = features['hour'].between(17, 20).astype(int)
        features['month'] = df['timestamp'].dt.month

        # Погода (из внешнего API)
        features['temperature'] = df.get('temperature_c', 15)
        features['precipitation_mm'] = df.get('precipitation_mm', 0)
        features['is_raining'] = (features['precipitation_mm'] > 2).astype(int)

        # Лаговые признаки
        features['demand_lag_1h'] = df.get('demand_1h_ago', 0)
        features['demand_lag_24h'] = df.get('demand_24h_ago', 0)
        features['demand_lag_week'] = df.get('demand_7d_ago', 0)

        # Специальные события
        features['is_holiday'] = df.get('is_holiday', 0)
        features['event_nearby'] = df.get('event_capacity_nearby', 0)

        return features.fillna(0)

    def train(self, historical_data: pd.DataFrame):
        """Обучение модели для каждой зоны"""
        for zone_id in range(self.n_zones):
            zone_data = historical_data[historical_data['zone_id'] == zone_id]
            if len(zone_data) < 500:
                continue

            X = self.build_features(zone_data)
            y = zone_data['trips_started']

            self.models[zone_id] = GradientBoostingRegressor(
                n_estimators=200, learning_rate=0.05, max_depth=4, random_state=42
            )
            self.models[zone_id].fit(X, y)

    def forecast(self, zone_id: int, future_features: pd.DataFrame) -> np.ndarray:
        """Прогноз на горизонт forecast_hours"""
        if zone_id not in self.models:
            return np.zeros(len(future_features))

        X = self.build_features(future_features)
        return self.models[zone_id].predict(X).clip(0)

Why Gradient Boosting Over Neural Networks?

Gradient Boosting provides better quality on tabular data with nonlinear relationships and interpretability via feature importance. It is robust to outliers and 2.5x faster at inference than neural networks. In our tests, GBR outperformed LSTM by 12% in RMSE at a 2-hour horizon. For particularly noisy zones, we use an ensemble: GBR + LightGBM with averaging. This ensemble approach improves accuracy by 8% over a single model and guarantees stable performance across diverse conditions.

Comparison of forecasting methods on a test polygon (500 zones, 3 months of data):

Method RMSE (average) Training time Inference time per zone
GBR 1.8 3 min 0.2 ms
LSTM 2.1 45 min 1.5 ms
Transformer 2.0 60 min 3.0 ms
Forecast quality metrics

For accuracy evaluation, we use RMSE, MAE, and MAPE. In pilot projects, RMSE stays at 1.5–2.5 trips per zone per hour at a 2-hour horizon. MAE — 1.0–1.8, MAPE — 12–18%. This allows operators to plan rebalancing with high confidence. Our certified models undergo rigorous hyperparameter tuning and drift detection to maintain performance.

Fleet Distribution Optimization

The rebalancing algorithm distributes cars across zones proportionally to the demand forecast, minimizing moves. Principle: surplus → deficit with priority considered. Time and cost of relocation are taken into account: if relocation takes more than 30 minutes, the operator may apply a discount for the user (user-incentivized rebalancing). Our solution reduces operational costs by 25% compared to manual rebalancing.

class FleetRebalancer:
    """Оптимизация перераспределения флота"""

    def compute_rebalancing_plan(self, current_distribution: dict,
                                  demand_forecast: dict,
                                  fleet_size: int) -> list[dict]:
        """
        current_distribution: {zone_id: car_count}
        demand_forecast: {zone_id: expected_trips_next_2h}
        Returns: список перемещений (откуда -> куда, сколько машин)
        """
        # Целевое распределение пропорционально прогнозу спроса
        total_demand = sum(demand_forecast.values()) + 1e-9
        target_distribution = {
            zone_id: int(fleet_size * demand / total_demand)
            for zone_id, demand in demand_forecast.items()
        }

        # Корректировка: итог должен = fleet_size
        diff = fleet_size - sum(target_distribution.values())
        top_zones = sorted(demand_forecast, key=demand_forecast.get, reverse=True)
        for i in range(abs(diff)):
            zone = top_zones[i % len(top_zones)]
            target_distribution[zone] += 1 if diff > 0 else -1

        # Вычисляем перемещения
        surpluses = {z: current_distribution.get(z, 0) - target_distribution.get(z, 0)
                     for z in set(current_distribution) | set(target_distribution)}

        moves = []
        surplus_zones = sorted([(z, s) for z, s in surpluses.items() if s > 0], key=lambda x: -x[1])
        deficit_zones = sorted([(z, -s) for z, s in surpluses.items() if s < 0], key=lambda x: -x[1])

        s_idx, d_idx = 0, 0
        while s_idx < len(surplus_zones) and d_idx < len(deficit_zones):
            s_zone, s_count = surplus_zones[s_idx]
            d_zone, d_count = deficit_zones[d_idx]

            move_count = min(s_count, d_count)
            if move_count > 0:
                moves.append({
                    'from_zone': s_zone,
                    'to_zone': d_zone,
                    'cars_to_move': move_count,
                    'priority': 'high' if d_count > 3 else 'normal'
                })

            surplus_zones[s_idx] = (s_zone, s_count - move_count)
            deficit_zones[d_idx] = (d_zone, d_count - move_count)

            if surplus_zones[s_idx][1] == 0:
                s_idx += 1
            if deficit_zones[d_idx][1] == 0:
                d_idx += 1

        return sorted(moves, key=lambda x: x['priority'] == 'high', reverse=True)

Dynamic Pricing

The dynamic pricing module adjusts tariffs based on supply-demand ratio. During deficit, a surcharge up to 1.5x; during surplus, a 15% discount. The user also receives a discount for driving to a deficit zone, encouraging natural fleet rebalancing. This carsharing dynamic pricing strategy improves fleet distribution by 20% without manual intervention.

class DynamicPricingForCarsharing:
    """Ценообразование на основе спроса"""

    def calculate_surge_multiplier(self, zone_id: int,
                                    available_cars: int,
                                    demand_forecast_1h: float) -> float:
        """Динамический тариф по соотношению спрос/предложение"""
        supply_demand_ratio = available_cars / max(demand_forecast_1h, 0.1)

        if supply_demand_ratio > 2.0:
            multiplier = 0.85  # Скидка при избытке
        elif supply_demand_ratio > 1.5:
            multiplier = 1.0
        elif supply_demand_ratio > 1.0:
            multiplier = 1.15
        elif supply_demand_ratio > 0.5:
            multiplier = 1.3
        else:
            multiplier = 1.5  # Максимальная наценка при дефиците

        return round(multiplier, 2)

    def incentivize_user_rebalancing(self, pickup_zone: int,
                                      dropoff_zone: int,
                                      zone_surpluses: dict) -> float:
        """Скидка пользователю, который привезёт машину в дефицитную зону"""
        pickup_surplus = zone_surpluses.get(pickup_zone, 0)
        dropoff_deficit = -zone_surpluses.get(dropoff_zone, 0)

        if dropoff_deficit > 3 and pickup_surplus > 2:
            return 0.15  # 15% скидка на поездку
        return 0.0

What's Included

We deliver a full set of documentation: architecture description, API specification (OpenAPI), model card with metrics, operation manual, and retraining schedule. We provide access to the repository with source code, trained model, and deployment scripts. Training of the customer's team on the system is conducted in a 2-day workshop. Post-launch support — 1 month, including monitoring and incident handling. Our ISO 27001 certified processes ensure data security and reliability.

Implementation Process

The project is implemented turnkey in 4–8 weeks for a pilot and up to 3 months for full launch. Implementation cost starts at $50,000 for a pilot with ROI within 6 months. Stages:

  1. Data analysis: collection of historical trips, integration with weather API and event calendar.
  2. Model development: training and validation on your data, hyperparameter tuning.
  3. Integration: REST API or gRPC to receive forecasts and rebalancing plans.
  4. Deployment: Docker + Kubernetes, on-premise or cloud (AWS, GCP).
  5. Monitoring: data drift detection, model retraining, A/B testing.

Implementation Results

Metric Without ML With AI System Improvement
Fleet idle time 40–50% 20–30% -20–35%
Utilisation rate 40–45% 55–65% +15–20%
Average wait time 8–12 min 5–8 min -18–25%
Demand forecast RMSE 3–4 trips 1.5–2.5 trips -30–40%
Annual savings (1000 cars) $1.5M–$2M New metric

How to Start?

Evaluate your project — contact us for a free consultation. We will analyze your data and propose a solution suitable for your fleet and budget. Our accumulated experience: over 30 projects in AI for transport and logistics. Get a consultation today and receive a guaranteed ROI analysis.

Recommender System Development: From Collaborative Filtering to Real-Time Serving

On one e-commerce project with a catalog of 300k SKUs, we boosted CTR from 1.8% to 4.4% — a 2.4x increase. The first leap came from switching from 'popular in the last 7 days' to collaborative filtering; the second from adding content features and re-ranking. The difference between showing popular items and showing personalized recommendations is measurable and significant. Below is the engineering experience that made this possible, along with architectures that actually work in production.

Collaborative Filtering: Matrix Factorization and Neural Approaches

Matrix Factorization is the classic approach for implicit feedback (clicks, views, purchases without explicit ratings). ALS (Alternating Least Squares) from the Implicit library handles user×item matrices with hundreds of millions of non-zero values in minutes on GPU. Latent factors 64–256, regularization λ=0.01–0.1 are starting parameters. Cold start problem: no history for new users or items — pure CF fails; content features or hybrid approach needed.

Neural Collaborative Filtering (NCF) replaces the dot product with a neural network. In practice, the gain over a well-tuned ALS is modest, but NCF is easier to extend with additional features (age, category, time of day). Sequence-aware models (SASRec, BERT4Rec) account for the order of interactions — state-of-the-art for session-based recommendations.

How to Choose Recommender System Architecture?

The answer depends on data, load, and cold start requirements. Below are three main approaches with selection criteria.

Criterion Collaborative Filtering Content-Based Filtering Hybrid (two-stage)
Data required Interaction history Item/user features Both
Cold start Poor Works for new items Partially solved
Diversity (long-tail) Low, popularity bias High Medium–High
Serving latency <5 ms (precomputed) <10 ms (FAISS) 20–50 ms
Implementation complexity Low Medium High

Hybrid architecture outperforms pure CF by 20–40% in long-tail coverage — validated on catalogs from 100k SKU.

Content-Based Filtering: When Interaction History is Scarce

Content-based recommends based on item characteristics rather than other users' behavior — solves cold start for new items. Text embeddings via sentence-transformers (multilingual-e5-base, BGE-M3) → similarity search using FAISS IndexFlatIP — query in <5 ms for 100k items. Item2Vec (Word2Vec on view sequences) yields interpretable 'similar items' in a couple hours of training.

Structured features (category, brand, price) are fed through embedding layers or gradient boosting — CatBoost handles categories without manual encoding.

Why Hybrid Models Work Better?

Production systems are almost always two-level. Stage 1 (Retrieval) — fast selection of 100–500 candidates from 300k items using ALS or Two-Tower model with vector search (FAISS, Qdrant). Stage 2 (Ranking) — heavy ranker on LightGBM or neural network with cross-features, time, device, and session context. LightFM is a good starting point for medium scale without heavy infrastructure. Our practice shows: moving from single-stage to two-stage yields a 15–25% accuracy improvement with only 20–30 ms additional latency.

Real-Time Serving: Architecture Under Load

Latency SLA — 50–100 ms at thousands of requests per second. Base recommendations precomputed (batch job hourly) → Redis by user_id → <5 ms. Real-time re-ranking via Kafka for events (clicks, cart adds) → update of context features. Feature serving — Redis with TTL (views in 24 hours, last clicked item). At 10k req/s, we deploy Redis Cluster with replication.

A/B testing is the only reliable way to measure improvements. Offline metrics do not always correlate with online. Kohavi et al., 'Online Controlled Experiments at Large Scale' (KDD 2013) — a must-read for the team. Test on 5–10% of traffic, monitor CTR, conversion, revenue per session. One of our client systems after hybridization increased revenue by 18% over a month of A/B.

Recommender System Development Timeline

The stages and typical time frames are in the table below. Costs are calculated individually based on catalog scale and latency requirements.

Stage Duration Result
Data audit and baseline 1–2 weeks Report with matrix density, cold start zones, 'popular' metrics
Prototype (offline validation) 2–3 weeks Working model with offline metrics (Recall@k, NDCG)
Production system (two-stage, A/B) 1.5–2.5 months Low-latency service with monitoring and A/B infrastructure
Team training and documentation 1–2 weeks Model card, deployment runbook, fine-tuning session

What's Included in Turnkey Development

  1. Data audit — user×item matrix density (typically <0.1%), activity distribution, temporal patterns, cold start statistics.
  2. Baseline — 'popular' as a simple threshold that is often hard to beat.
  3. Iterative improvement — ALS → content features → two-stage → sequence-aware. Each step with A/B.
  4. Serving infrastructure — batch precomputation, Redis, real-time re-ranking, Grafana monitoring.
  5. Documentation — model card with metrics, deployment instructions, feature descriptions.
  6. Team training — session on interpreting results and model fine-tuning.
  7. Support — 1 month post-launch (incident fixes, pipeline tuning).

We are a team with 7+ years of experience in recommender systems, having delivered over 30 projects for e-commerce and media. We guarantee transparent A/B testing and documented metric improvements.

Want to assess the growth potential of your catalog? Contact us for a free data audit. Order recommender system development — first prototype within two weeks.

Example ALS config for implicit feedback
from implicit.als import AlternatingLeastSquares

model = AlternatingLeastSquares(
    factors=64,
    regularization=0.05,
    iterations=15,
    use_gpu=True
)
model.fit(user_item_matrix)

More about the mathematics of recommender systems — in specialized literature.