基于django的新能源汽车租赁推荐分析系统,包括用户、商家、管理员三个角色,协同过滤+基于内容、用户画像的融合算法推荐

车辆推荐系统技术文档

目录

  1. 系统概述
  2. 技术架构
  3. 核心算法
  4. 数据库设计
  5. API接口
  6. 系统实现

系统概述

项目简介

新能源汽车租赁平台的智能推荐系统,基于用户行为、评分、租赁历史等多维度数据,为用户提供个性化的车辆推荐服务。

核心功能

  • 智能推荐:基于混合算法的车辆推荐
  • 个性化服务:为登录用户提供个性化推荐,未登录用户提供热门推荐
  • 实时更新:推荐结果随用户行为实时更新
  • 推荐理由展示:向用户展示推荐理由,增强信任度

技术栈

  • 后端框架:Django 6.0
  • 编程语言:Python 3.12
  • 数据库:SQLite(可切换至MySQL)
  • 前端框架:Bootstrap 5
  • 推荐算法:混合推荐系统(协同过滤 + 内容过滤 + 热门推荐 + 个性化)

技术架构

系统架构图

复制代码
┌─────────────────────────────────────────────────┐
│              前端展示层(Bootstrap 5)           │
│  ┌──────────────┐  ┌──────────────┐            │
│  │ 车辆列表页   │  │ 车辆详情页   │            │
│  └──────────────┘  └──────────────┘            │
└──────────────────┬──────────────────────────────┘
                   │
┌──────────────────▼──────────────────────────────┐
│             Django视图层(Views)                 │
│  ┌─────────────────────────────────────────┐   │
│  │  VehicleRecommendationEngine            │   │
│  │  - 协同过滤推荐                          │   │
│  │  - 基于内容推荐                          │   │
│  │  - 热门推荐                              │   │
│  │  - 个性化推荐                            │   │
│  └─────────────────────────────────────────┘   │
└──────────────────┬──────────────────────────────┘
                   │
┌──────────────────▼──────────────────────────────┐
│              Django模型层(Models)              │
│  ┌──────┐ ┌──────┐ ┌──────┐ ┌──────────────┐  │
│  │Vehicle│ │User  │ │Order │ │VehicleRating │  │
│  └──────┘ └──────┘ └──────┘ └──────────────┘  │
└──────────────────┬──────────────────────────────┘
                   │
┌──────────────────▼──────────────────────────────┐
│                SQLite数据库                       │
└──────────────────────────────────────────────────┘

文件结构

复制代码
ev_car_rental/
├── vehicles/
│   ├── models.py              # 车辆相关数据模型
│   ├── views.py               # 视图函数(集成推荐引擎)
│   ├── recommendations.py    # 推荐引擎核心算法
│   ├── forms.py               # 表单定义
│   └── templates/vehicles/
│       ├── vehicle_list.html  # 车辆列表页(含推荐)
│       └── vehicle_detail.html
├── users/
│   └── models.py              # 用户模型(含收藏)
├── orders/
│   └── models.py              # 订单模型
└── manage.py

核心算法

推荐算法概述

系统采用混合推荐算法,整合四种推荐策略:

  1. 协同过滤推荐(30%)

    • 基于相似用户的租赁行为
    • 找到有相似偏好的用户,推荐他们喜欢的车辆
    • 考虑用户多样性和车辆热度
  2. 基于内容推荐(25%)

    • 基于车辆属性(品牌、类型、价格等)
    • 分析用户历史租赁偏好
    • 匹配相似属性的车辆
  3. 热门推荐(25%)

    • 基于整体租赁热度
    • 考虑租赁次数、评分、浏览量
    • 为新用户提供可靠推荐
  4. 个性化推荐(20%)

    • 基于用户收藏、浏览历史
    • 结合用户最近行为
    • 提供实时动态推荐

算法权重配置

python 复制代码
weights = {
    'collaborative': 0.3,    # 协同过滤权重
    'content_based': 0.25,  # 基于内容权重
    'popularity': 0.25,      # 热门推荐权重
    'personal': 0.2,        # 个性化权重
}

协同过滤算法详解

算法原理

  • 找到与当前用户有相似偏好的用户群
  • 基于相似用户的租赁和评分行为推荐车辆
  • 使用用户多样性权重和订单热度权重计算推荐分数

实现代码

python 复制代码
def _get_collaborative_recommendations(self, limit=10):
    """协同过滤推荐 - 基于相似用户的行为"""
    # 获取用户的历史订单和评价
    user_orders = set(Order.objects.filter(user=self.user).values_list('vehicle_id', flat=True))
    user_ratings = list(VehicleRating.objects.filter(user=self.user).values('vehicle_id', 'rating'))
    
    # 构建用户偏好的车辆ID集合
    preferred_vehicles = user_orders.union({r['vehicle_id'] for r in user_ratings})
    
    # 找到相似用户(基于共同订单)
    similar_by_orders = Order.objects.filter(
        vehicle_id__in=user_orders
    ).exclude(user=self.user).values_list('user_id', flat=True)
    
    # 批量获取相似用户的偏好车辆
    similar_vehicles = Order.objects.filter(
        user_id__in=similar_user_ids
    ).exclude(vehicle_id__in=preferred_vehicles).values('vehicle_id').annotate(
        order_count=Count('id'),
        user_count=Count('user_id', distinct=True),
        avg_rating=Avg('vehicle__ratings__rating')
    ).order_by('-user_count', '-order_count', '-avg_rating')[:limit]
    
    # 计算推荐分数
    for item in similar_vehicles:
        diversity_weight = min(item['user_count'] * 0.3, 2.0)    # 用户多样性
        popularity_weight = min(item['order_count'] * 0.2, 1.0)  # 订单热度
        rating_weight = (item['avg_rating'] or 0) * 0.5          # 评分权重
        score = diversity_weight + popularity_weight + rating_weight

基于内容推荐算法详解

算法原理

  • 分析用户历史租赁的品牌、车型、价格偏好
  • 在偏好范围内寻找匹配的车辆
  • 综合考虑品牌匹配度、车型匹配度、车辆评分

实现代码

python 复制代码
def _get_content_based_recommendations(self, limit=10):
    """基于内容的推荐 - 基于用户偏好的车辆属性"""
    # 统计用户偏好
    brand_counts = {}
    type_counts = {}
    price_points = []
    
    for order in user_orders:
        brand_counts[vehicle.brand.id] = brand_counts.get(vehicle.brand.id, 0) + 1
        type_counts[vehicle.vehicle_type.id] = type_counts.get(vehicle.vehicle_type.id, 0) + 1
        price_points.append(float(vehicle.daily_price))
    
    # 计算价格范围
    avg_price = sum(price_points) / len(price_points)
    price_min, price_max = avg_price * 0.5, avg_price * 1.5
    
    # 构建推荐查询
    similar_vehicles = Vehicle.objects.filter(
        status='available'
    ).filter(
        Q(brand_id__in=brand_ids) | Q(vehicle_type_id__in=type_ids)
    ).filter(
        daily_price__range=(price_min, price_max)
    ).annotate(
        brand_match=Count(Case(When(brand_id__in=brand_ids, then=1))),
        type_match=Count(Case(When(vehicle_type_id__in=type_ids, then=1))),
        composite_score=F('rating') * 0.6 + Cast(F('total_rentals'), FloatField()) * 0.4
    ).order_by('-composite_score')[:limit]

热门推荐算法详解

算法原理

  • 基于整体租赁热度推荐车辆
  • 综合考虑租赁次数、评分、浏览量
  • 为未登录用户提供默认推荐

实现代码

python 复制代码
def get_popular_vehicles(self, limit=10):
    """获取热门车辆"""
    return Vehicle.objects.filter(
        status='available'
    ).annotate(
        popularity_score=F('total_rentals') * 0.5 + F('rating') * 2.0
    ).order_by('-popularity_score', '-rating')[:limit]

个性化推荐算法详解

算法原理

  • 基于用户收藏行为
  • 分析用户浏览历史
  • 结合用户最近评价行为

实现代码

python 复制代码
def _get_personal_recommendations(self, limit=10):
    """个性化推荐 - 基于用户收藏和浏览"""
    # 获取用户收藏的车辆
    favorited_vehicles = UserFavorite.objects.filter(
        user=self.user
    ).values_list('vehicle_id', flat=True)
    
    # 分析收藏车辆的品牌和类型偏好
    favorite_brands = Vehicle.objects.filter(
        id__in=favorited_vehicles
    ).values_list('brand_id', flat=True)
    
    # 基于收藏偏好推荐相似车辆
    recommendations = Vehicle.objects.filter(
        status='available',
        brand_id__in=favorite_brands
    ).exclude(id__in=favorited_vehicles)[:limit]

数据库设计

核心数据表

1. vehicles(车辆表)
sql 复制代码
CREATE TABLE vehicles (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100),
    brand_id INTEGER,
    vehicle_type_id INTEGER,
    merchant_id INTEGER,
    daily_price DECIMAL(8,2),
    deposit DECIMAL(8,2),
    status VARCHAR(20),
    rating DECIMAL(3,2),
    total_rentals INTEGER,
    is_featured BOOLEAN,
    range_km INTEGER,
    seats INTEGER,
    created_at DATETIME,
    updated_at DATETIME,
    FOREIGN KEY (brand_id) REFERENCES vehicle_brands(id),
    FOREIGN KEY (vehicle_type_id) REFERENCES vehicle_types(id),
    FOREIGN KEY (merchant_id) REFERENCES merchants(id)
);
2. vehicle_ratings(车辆评价表)
sql 复制代码
CREATE TABLE vehicle_ratings (
    id INTEGER PRIMARY KEY,
    vehicle_id INTEGER,
    user_id INTEGER,
    order_id INTEGER,
    rating INTEGER,
    comment TEXT,
    created_at DATETIME,
    FOREIGN KEY (vehicle_id) REFERENCES vehicles(id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (order_id) REFERENCES orders(id),
    UNIQUE(vehicle_id, user_id, order_id)
);
3. user_favorites(用户收藏表)
sql 复制代码
CREATE TABLE user_favorites (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    vehicle_id INTEGER,
    created_at DATETIME,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (vehicle_id) REFERENCES vehicles(id),
    UNIQUE(user_id, vehicle_id)
);
4. vehicle_view_histories(浏览历史表)
sql 复制代码
CREATE TABLE vehicle_view_histories (
    id INTEGER PRIMARY KEY,
    vehicle_id INTEGER,
    user_id INTEGER,
    viewed_at DATETIME,
    ip_address VARCHAR(45),
    FOREIGN KEY (vehicle_id) REFERENCES vehicles(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

数据索引优化

python 复制代码
class Vehicle(models.Model):
    class Meta:
        indexes = [
            models.Index(fields=['status', 'is_featured']),
            models.Index(fields=['brand', 'vehicle_type']),
            models.Index(fields=['daily_price']),
            models.Index(fields=['rating', 'total_rentals']),
        ]

API接口

获取推荐车辆

接口路径GET /vehicles/

请求参数

复制代码
无(自动识别登录状态)

响应示例

json 复制代码
{
  "recommended_vehicles": [
    {
      "vehicle": {
        "id": 1,
        "name": "特斯拉 Model 3",
        "brand": "特斯拉",
        "vehicle_type": "轿车",
        "daily_price": 450.00,
        "deposit": 2000.00,
        "rating": 4.8,
        "total_rentals": 25,
        "range_km": 500,
        "seats": 5,
        "main_image": "/media/vehicle_images/model3.jpg"
      },
      "score": 8.5,
      "reason": "基于您的租赁偏好"
    }
  ],
  "vehicles": [...], // 普通车辆列表
  "favorited_vehicles": [1, 3, 5] // 已登录用户的收藏车辆ID
}

获取推荐详情

接口路径GET /vehicles/recommendations/

请求参数

复制代码
limit: int (可选,默认8)

响应示例

json 复制代码
{
  "recommendations": [
    {
      "vehicle": {...},
      "score": 8.5,
      "reason": "基于您的租赁偏好"
    }
  ]
}

Q1: 推荐结果为空怎么办?

A: 检查以下几点:

  1. 数据库中是否有可用的车辆(status='available')
  2. 用户是否有足够的历史数据
  3. 推荐引擎是否有异常(查看日志)

解决方案

python 复制代码
# 在views.py中添加后备方案
try:
    recommendations = recommendation_engine.get_recommendations(limit=6)
except Exception as e:
    logger.error(f"推荐引擎出错: {e}")
    # 使用热门车辆作为后备
    recommendations = Vehicle.objects.filter(
        status='available'
    ).order_by('-total_rentals', '-rating')[:6]

Q2: 推荐算法性能慢怎么办?

A: 优化方案:

  1. 使用数据库索引加速查询
  2. 使用缓存减少重复计算
  3. 使用异步处理大规模推荐
  4. 批量查询避免N+1问题

Q3: 如何调整推荐算法权重?

A: 修改recommendations.py中的权重配置:

python 复制代码
weights = {
    'collaborative': 0.4,    # 增加协同过滤权重
    'content_based': 0.2,   # 减少内容过滤权重
    'popularity': 0.2,       # 调整热门推荐权重
    'personal': 0.2,         # 保持个性化权重
}

Q4: 如何添加新的推荐策略?

A: 扩展VehicleRecommendationEngine类:

python 复制代码
def _get_new_strategy_recommendations(self, limit=10):
    """新增推荐策略"""
    # 实现新的推荐逻辑
    recommendations = []
    # ...
    return recommendations

def get_recommendations(self, limit=8):
    """获取推荐车辆列表"""
    # 获取各种推荐
    collaborative_vehicles = self._get_collaborative_recommendations()
    content_based_vehicles = self._get_content_based_recommendations()
    popular_vehicles = self.get_popular_vehicles()
    personal_vehicles = self._get_personal_recommendations()
    new_strategy_vehicles = self._get_new_strategy_recommendations()  # 新增
    
    # 合并和加权
    self._merge_recommendations([
        (collaborative_vehicles, self.weights['collaborative']),
        (content_based_vehicles, self.weights['content_based']),
        (popular_vehicles, self.weights['popularity']),
        (personal_vehicles, self.weights['personal']),
        (new_strategy_vehicles, 0.1),  # 新增权重
    ])

Q5: 如何监控推荐效果?

A: 添加推荐效果跟踪:

  1. 记录推荐展示
python 复制代码
def get_recommendations(self, limit=8):
    recommendations = self._compute_recommendations(limit)
    
    # 记录推荐展示
    for vehicle in recommendations:
        RecommendationLog.objects.create(
            user=self.user,
            vehicle=vehicle,
            algorithm=self._get_algorithm_name(vehicle),
            action='show'
        )
    
    return recommendations
  1. 跟踪用户点击
python 复制代码
def track_recommendation_click(user, vehicle):
    """跟踪推荐点击"""
    RecommendationLog.objects.create(
        user=user,
        vehicle=vehicle,
        algorithm='recommendation',
        action='click'
    )
  1. 计算推荐转化率
python 复制代码
def calculate_recommendation_performance():
    """计算推荐性能指标"""
    from django.db.models import Count, Q
    
    total_shows = RecommendationLog.objects.filter(action='show').count()
    total_clicks = RecommendationLog.objects.filter(action='click').count()
    
    click_through_rate = total_clicks / total_shows * 100 if total_shows > 0 else 0
    
    return {
        'total_shows': total_shows,
        'total_clicks': total_clicks,
        'click_through_rate': click_through_rate
    }

C. 系统运行截图

首页

注册页

登录页

用户界面








商户界面





管理员界面






相关推荐
Hello.Reader2 小时前
Flink ML StandardScaler 标准化(去均值 + 除以标准差)让特征“同量纲”更好学
机器学习·均值算法·flink
艾莉丝努力练剑2 小时前
艾莉丝努力练剑的2025年度总结
java·大数据·linux·开发语言·c++·人工智能·python
大叔_爱编程2 小时前
基于深度神经网络的课程教学评价系统-django
django·毕业设计·tensorflow·源码·scikit-learn·课程设计·深度神经网络
后端小张4 小时前
【AI学习】深入探秘AI之神经网络的奥秘
人工智能·深度学习·神经网络·opencv·学习·机器学习·自然语言处理
xu_yule6 小时前
算法基础(数论)—费马小定理
c++·算法·裴蜀定理·欧拉定理·费马小定理·同余方程·扩展欧几里得定理
girl-07267 小时前
2025.12.28代码分析总结
算法
NAGNIP9 小时前
GPT-5.1 发布:更聪明,也更有温度的 AI
人工智能·算法
NAGNIP9 小时前
激活函数有什么用?有哪些常用的激活函数?
人工智能·算法
2501_9444522310 小时前
字数统计 Cordova 与 OpenHarmony 混合开发实战
python