协同过滤算法毕业设计SpringBoot实现理财产品推荐系统完整教程

85 阅读4分钟

一、个人简介

💖💖作者:计算机编程果茶熊 💙💙个人简介:曾长期从事计算机专业培训教学,担任过编程老师,同时本人也热爱上课教学,擅长Java、微信小程序、Python、Golang、安卓Android等多个IT方向。会做一些项目定制化开发、代码讲解、答辩教学、文档编写、也懂一些降重方面的技巧。平常喜欢分享一些自己开发中遇到的问题的解决办法,也喜欢交流技术,大家有技术代码这一块的问题可以问我! 💛💛想说的话:感谢大家的关注与支持! 💜💜 网站实战项目 安卓/小程序实战项目 大数据实战项目 计算机毕业设计选题 💕💕文末获取源码联系计算机编程果茶熊

二、系统介绍

开发语言:Java+Python 数据库:MySQL 系统架构:B/S 后端框架:SpringBoot(Spring+SpringMVC+Mybatis)+Django 前端:Vue+HTML+CSS+JavaScript+jQuery

本基于协同过滤算法的理财产品推荐系统采用Spring Boot框架作为后端核心,结合MySQL数据库和Vue+ElementUI前端技术栈,构建了一个完整的B/S架构智能推荐平台。系统的核心特色在于运用协同过滤算法对用户的理财偏好进行分析和预测,通过挖掘用户行为数据和产品特征信息,为不同类型的用户提供个性化的理财产品推荐服务。系统首页提供直观的产品展示和推荐结果呈现,用户管理模块实现用户注册、登录、权限控制等基础功能,产品类型管理和理财产品管理模块负责产品信息的分类维护和详细管理,包括产品的收益率、风险等级、投资期限等关键属性。理财订单管理模块记录用户的购买历史和交易行为,为协同过滤算法提供重要的数据支撑,反馈信息管理模块收集用户对推荐结果的评价,用于算法的持续优化。个人中心允许用户查看推荐历史、管理个人偏好设置和投资组合。整个系统通过Spring Boot的微服务架构实现模块化设计,具备良好的扩展性和维护性,协同过滤算法的引入使得推荐精度相比传统规则推荐有了明显提升,能够较好地满足个性化理财推荐的业务需求。

三、基于协同过滤算法的理财产品推荐系统-视频解说

协同过滤算法毕业设计SpringBoot实现理财产品推荐系统完整教程

四、基于协同过滤算法的理财产品推荐系统-功能展示

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

五、基于协同过滤算法的理财产品推荐系统-代码展示



import org.apache.spark.sql.SparkSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/recommendation")
public class CollaborativeFilteringController {
    private SparkSession spark = SparkSession.builder().appName("FinancialRecommendation").config("spark.executor.memory", "1g").getOrCreate();
    @Autowired
    private UserBehaviorService userBehaviorService;
    @Autowired
    private FinancialProductService productService;
    @PostMapping("/generate")
    public ResponseEntity<Map<String, Object>> generateRecommendations(@RequestParam Long userId) {
        List<UserBehavior> allBehaviors = userBehaviorService.getAllUserBehaviors();
        Map<Long, Map<Long, Double>> userItemMatrix = buildUserItemMatrix(allBehaviors);
        Map<Long, Double> userSimilarities = calculateUserSimilarity(userId, userItemMatrix);
        List<Long> targetUserProducts = userItemMatrix.getOrDefault(userId, new HashMap<>()).keySet().stream().collect(Collectors.toList());
        Map<Long, Double> productScores = new HashMap<>();
        for (Map.Entry<Long, Double> entry : userSimilarities.entrySet()) {
            Long similarUserId = entry.getKey();
            Double similarity = entry.getValue();
            if (similarity > 0.1 && !similarUserId.equals(userId)) {
                Map<Long, Double> similarUserProducts = userItemMatrix.getOrDefault(similarUserId, new HashMap<>());
                for (Map.Entry<Long, Double> productEntry : similarUserProducts.entrySet()) {
                    Long productId = productEntry.getKey();
                    Double rating = productEntry.getValue();
                    if (!targetUserProducts.contains(productId)) {
                        productScores.put(productId, productScores.getOrDefault(productId, 0.0) + similarity * rating);
                    }
                }
            }
        }
        List<Map.Entry<Long, Double>> sortedProducts = productScores.entrySet().stream().sorted(Map.Entry.<Long, Double>comparingByValue().reversed()).limit(10).collect(Collectors.toList());
        List<FinancialProduct> recommendedProducts = new ArrayList<>();
        for (Map.Entry<Long, Double> entry : sortedProducts) {
            FinancialProduct product = productService.getProductById(entry.getKey());
            if (product != null) {
                recommendedProducts.add(product);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("status", "success");
        result.put("recommendations", recommendedProducts);
        result.put("algorithm", "collaborative_filtering");
        return ResponseEntity.ok(result);
    }
    @PostMapping("/product/manage")
    public ResponseEntity<Map<String, Object>> manageFinancialProduct(@RequestBody FinancialProductRequest request) {
        FinancialProduct product = new FinancialProduct();
        product.setProductName(request.getProductName());
        product.setProductType(request.getProductType());
        product.setExpectedReturn(request.getExpectedReturn());
        product.setRiskLevel(request.getRiskLevel());
        product.setMinInvestment(request.getMinInvestment());
        product.setInvestmentPeriod(request.getInvestmentPeriod());
        product.setProductDescription(request.getProductDescription());
        product.setIssuer(request.getIssuer());
        product.setStatus(request.getStatus() != null ? request.getStatus() : 1);
        product.setCreateTime(new Date());
        if (request.getProductId() != null) {
            product.setProductId(request.getProductId());
            productService.updateProduct(product);
        } else {
            productService.saveProduct(product);
        }
        List<FinancialProduct> updatedProducts = productService.getAllProducts();
        Map<Long, Integer> productPopularity = calculateProductPopularity();
        for (FinancialProduct p : updatedProducts) {
            p.setPopularityScore(productPopularity.getOrDefault(p.getProductId(), 0));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("status", "success");
        result.put("message", request.getProductId() != null ? "产品更新成功" : "产品添加成功");
        result.put("productList", updatedProducts);
        return ResponseEntity.ok(result);
    }
    @PostMapping("/behavior/analyze")
    public ResponseEntity<Map<String, Object>> analyzeUserBehavior(@RequestParam Long userId) {
        List<UserBehavior> userBehaviors = userBehaviorService.getUserBehaviorsByUserId(userId);
        Map<String, Object> behaviorAnalysis = new HashMap<>();
        Map<String, Integer> productTypePreference = new HashMap<>();
        Map<String, Integer> riskLevelPreference = new HashMap<>();
        BigDecimal totalInvestment = BigDecimal.ZERO;
        int totalTransactions = userBehaviors.size();
        for (UserBehavior behavior : userBehaviors) {
            FinancialProduct product = productService.getProductById(behavior.getProductId());
            if (product != null) {
                String productType = product.getProductType();
                String riskLevel = product.getRiskLevel();
                productTypePreference.put(productType, productTypePreference.getOrDefault(productType, 0) + 1);
                riskLevelPreference.put(riskLevel, riskLevelPreference.getOrDefault(riskLevel, 0) + 1);
                if (behavior.getBehaviorType().equals("purchase")) {
                    totalInvestment = totalInvestment.add(behavior.getInvestmentAmount());
                }
            }
        }
        String preferredProductType = productTypePreference.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse("未知");
        String preferredRiskLevel = riskLevelPreference.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse("未知");
        double avgInvestmentAmount = totalInvestment.divide(BigDecimal.valueOf(Math.max(totalTransactions, 1)), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
        List<FinancialProduct> personalizedRecommendations = productService.getProductsByTypeAndRisk(preferredProductType, preferredRiskLevel).stream().limit(5).collect(Collectors.toList());
        behaviorAnalysis.put("totalTransactions", totalTransactions);
        behaviorAnalysis.put("totalInvestment", totalInvestment);
        behaviorAnalysis.put("avgInvestmentAmount", avgInvestmentAmount);
        behaviorAnalysis.put("preferredProductType", preferredProductType);
        behaviorAnalysis.put("preferredRiskLevel", preferredRiskLevel);
        behaviorAnalysis.put("productTypeDistribution", productTypePreference);
        behaviorAnalysis.put("riskLevelDistribution", riskLevelPreference);
        behaviorAnalysis.put("personalizedRecommendations", personalizedRecommendations);
        Map<String, Object> result = new HashMap<>();
        result.put("status", "success");
        result.put("behaviorAnalysis", behaviorAnalysis);
        return ResponseEntity.ok(result);
    }
    private Map<Long, Map<Long, Double>> buildUserItemMatrix(List<UserBehavior> behaviors) {
        Map<Long, Map<Long, Double>> matrix = new HashMap<>();
        for (UserBehavior behavior : behaviors) {
            Long userId = behavior.getUserId();
            Long productId = behavior.getProductId();
            double rating = calculateRating(behavior);
            matrix.computeIfAbsent(userId, k -> new HashMap<>()).put(productId, rating);
        }
        return matrix;
    }
    private Map<Long, Double> calculateUserSimilarity(Long targetUserId, Map<Long, Map<Long, Double>> userItemMatrix) {
        Map<Long, Double> similarities = new HashMap<>();
        Map<Long, Double> targetUserRatings = userItemMatrix.get(targetUserId);
        if (targetUserRatings == null) return similarities;
        for (Map.Entry<Long, Map<Long, Double>> entry : userItemMatrix.entrySet()) {
            Long userId = entry.getKey();
            Map<Long, Double> userRatings = entry.getValue();
            if (!userId.equals(targetUserId)) {
                double similarity = calculateCosineSimilarity(targetUserRatings, userRatings);
                similarities.put(userId, similarity);
            }
        }
        return similarities;
    }
    private double calculateCosineSimilarity(Map<Long, Double> ratingsA, Map<Long, Double> ratingsB) {
        Set<Long> commonItems = new HashSet<>(ratingsA.keySet());
        commonItems.retainAll(ratingsB.keySet());
        if (commonItems.isEmpty()) return 0.0;
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;
        for (Long item : commonItems) {
            double ratingA = ratingsA.get(item);
            double ratingB = ratingsB.get(item);
            dotProduct += ratingA * ratingB;
            normA += ratingA * ratingA;
            normB += ratingB * ratingB;
        }
        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }
    private double calculateRating(UserBehavior behavior) {
        double rating = 3.0;
        if ("purchase".equals(behavior.getBehaviorType())) {
            rating = 5.0;
        } else if ("view".equals(behavior.getBehaviorType())) {
            rating = 2.0;
        } else if ("favorite".equals(behavior.getBehaviorType())) {
            rating = 4.0;
        }
        return rating;
    }
    private Map<Long, Integer> calculateProductPopularity() {
        List<UserBehavior> allBehaviors = userBehaviorService.getAllUserBehaviors();
        Map<Long, Integer> popularity = new HashMap<>();
        for (UserBehavior behavior : allBehaviors) {
            popularity.put(behavior.getProductId(), popularity.getOrDefault(behavior.getProductId(), 0) + 1);
        }
        return popularity;
    }
}

六、基于协同过滤算法的理财产品推荐系统-文档展示

在这里插入图片描述

七、END

💕💕文末获取源码联系计算机编程果茶熊