日撸java_day54-55

news2024/11/16 1:15:44

文章目录

  • 第 54 、55 天: 基于 M-distance 的推荐
    • 代码
    • 运行截图

第 54 、55 天: 基于 M-distance 的推荐

1.M-distance, 就是根据平均分来计算两个用户 (或项目) 之间的距离.
2.邻居不用 k 控制. 距离小于 radius (即 ϵ ) 的都是邻居. 使用 M-distance 时, 这种方式效果更好.
3. 使用 leave-one-out 的测试方式,
4. 原本代码是 item-based recommendation.增加了 user-based recommendation.,另造了个构造器。多打了个参数以作区别,方式是将压缩矩阵转置, 用户与项目关系互换.

代码

package machineLearning.knn;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

/**
 * ClassName: MBR
 * Package: machineLearning.knn
 * Description: M-distance.
 *
 * @Author: luv_x_c
 * @Create: 2023/6/14 14:32
 */
public class MBR {

    /**
     * Default rating for 1-5 points.
     */
    public static final double DEFAULT_RATING = 3.0;

    /**
     * The total number of users.
     */
    private int numUsers;

    /**
     * The total number of items.
     */
    private int numItems;

    /**
     * The total number of ratings.(None zero values)
     */
    private int numRatings;

    /**
     * The predictions.
     */
    private double[] predictions;

    /**
     * Compressed matrix. User-item-rating triples.
     */
    private int[][] compressRatingMatrix;

    /**
     * User-Item Rating Matrix, transposed from the compressRatingMatrix.
     * 用户-物品评分矩阵,为 compressRatingMatrix 的转置。
     */
    private int[][] userItemRatingMatrix;

    /**
     * The degree of users.(how many items he has rated).
     */
    private int[] userDegrees;

    /**
     * The average rating of the current user.
     */
    private double[] userAverageRatings;

    /**
     * The degree of items .(How many ratings it has.)
     */
    private int[] itemDegrees;

    /**
     * The average rating of the current item.
     */
    private double[] itemAverageRatings;

    /**
     * The first user start from 0. Let the first user hax x ratings, the second user will start from x.
     */
    private int[] userStartingIndices;

    /**
     * Number of non-neighbor objects.
     */
    private int numNoneNeighbors;

    /**
     * The radius (delta) for determining the neighborhood.
     */
    private double radius;

    /**
     * Construct the rating matrix.
     *
     * @param paraFilename   The rating filename.
     * @param paraNumUsers   Number of users.
     * @param paraNumItems   Number of items.
     * @param paraNumRatings Number of ratings.
     */
    public MBR(String paraFilename, int paraNumUsers, int paraNumItems, int paraNumRatings) throws Exception {
        // Step1. Initialize these arrays.
        numItems = paraNumItems;
        numUsers = paraNumUsers;
        numRatings = paraNumRatings;

        userDegrees = new int[numUsers];
        userStartingIndices = new int[numUsers + 1];
        userAverageRatings = new double[numUsers];
        itemDegrees = new int[numItems];
        compressRatingMatrix = new int[numRatings][3];
        itemAverageRatings = new double[numItems];

        predictions = new double[numRatings];

        System.out.println("Reading " + paraFilename);

        // Step2. Read the data file.
        File tempFile = new File(paraFilename);
        if (!tempFile.exists()) {
            System.out.println("File " + paraFilename + "  does not exists ");
            System.exit(0);
        }// Of if
        BufferedReader tempBufReader = new BufferedReader(new FileReader(tempFile));
        String tempString;
        String[] tempStrArray;
        int tempIndex = 0;
        userStartingIndices[0] = 0;
        userStartingIndices[numUsers] = numRatings;
        while ((tempString = tempBufReader.readLine()) != null) {
            // Each line has three values.
            tempStrArray = tempString.split(",");
            compressRatingMatrix[tempIndex][0] = Integer.parseInt(tempStrArray[0]);
            compressRatingMatrix[tempIndex][1] = Integer.parseInt(tempStrArray[1]);
            compressRatingMatrix[tempIndex][2] = Integer.parseInt(tempStrArray[2]);

            userDegrees[compressRatingMatrix[tempIndex][0]]++;
            itemDegrees[compressRatingMatrix[tempIndex][0]]++;

            if (tempIndex > 0) {
                // Starting to read the data of a new user.
                if (compressRatingMatrix[tempIndex][0] != compressRatingMatrix[tempIndex - 1][0]) {
                    userStartingIndices[compressRatingMatrix[tempIndex][0]] = tempIndex;
                }// OF if
            }// Of if
            tempIndex++;
        }// Of while
        tempBufReader.close();

        double[] tempUserTotalScore = new double[numUsers];
        double[] tempItemTotalScore = new double[numItems];
        for (int i = 0; i < numRatings; i++) {
            tempUserTotalScore[compressRatingMatrix[i][0]] += compressRatingMatrix[i][2];
            tempItemTotalScore[compressRatingMatrix[i][1]] += compressRatingMatrix[i][2];
        }// Of for i

        for (int i = 0; i < numUsers; i++) {
            userAverageRatings[i] = tempUserTotalScore[i] / userDegrees[i];
        }// OF for i
        for (int i = 0; i < numItems; i++) {
            itemAverageRatings[i] = tempItemTotalScore[i] / itemDegrees[i];
        }// Of for i
    }// OF the first constructor



    /**
     * Construct the rating matrix and transpose it.
     * 构造评分矩阵并进行转置。
     *
     * @param paraFilename   The rating filename.
     * @param paraNumUsers   Number of users.
     * @param paraNumItems   Number of items.
     * @param paraNumRatings Number of ratings.
     */
    public MBR(String paraFilename, int paraNumUsers, int paraNumItems, int paraNumRatings,int paraConstructor) throws Exception {
        // Step1. Initialize these arrays.
        numItems = paraNumItems;
        numUsers = paraNumUsers;
        numRatings = paraNumRatings;

        userDegrees = new int[numUsers];
        userStartingIndices = new int[numUsers + 1];
        userAverageRatings = new double[numUsers];
        itemDegrees = new int[numItems];
        compressRatingMatrix = new int[numRatings][3];
        itemAverageRatings = new double[numItems];

        predictions = new double[numRatings];

        // Step2. Read the data file and construct the userItemRatingMatrix.
        System.out.println("Reading " + paraFilename);
        userItemRatingMatrix = new int[numItems][numUsers]; // Transposed matrix

        File tempFile = new File(paraFilename);
        if (!tempFile.exists()) {
            System.out.println("File " + paraFilename + " does not exist");
            System.exit(0);
        }

        BufferedReader tempBufReader = new BufferedReader(new FileReader(tempFile));
        String tempString;
        String[] tempStrArray;
        int tempIndex = 0;
        userStartingIndices[0] = 0;
        userStartingIndices[numUsers] = numRatings;
        while ((tempString = tempBufReader.readLine()) != null) {
            tempStrArray = tempString.split(",");
            int userIndex = Integer.parseInt(tempStrArray[0]);
            int itemIndex = Integer.parseInt(tempStrArray[1]);
            int rating = Integer.parseInt(tempStrArray[2]);

            compressRatingMatrix[tempIndex][0] = userIndex;
            compressRatingMatrix[tempIndex][1] = itemIndex;
            compressRatingMatrix[tempIndex][2] = rating;

            // Transpose and store in the userItemRatingMatrix
            userItemRatingMatrix[itemIndex][userIndex] = rating;

            userDegrees[userIndex]++;
            itemDegrees[itemIndex]++;

            if (tempIndex > 0 && compressRatingMatrix[tempIndex][0] != compressRatingMatrix[tempIndex - 1][0]) {
                userStartingIndices[compressRatingMatrix[tempIndex][0]] = tempIndex;
            }

            tempIndex++;
        }
        tempBufReader.close();

        // Calculate average ratings for users and items.
        double[] tempUserTotalScore = new double[numUsers];
        double[] tempItemTotalScore = new double[numItems];
        for (int i = 0; i < numRatings; i++) {
            tempUserTotalScore[compressRatingMatrix[i][0]] += compressRatingMatrix[i][2];
            tempItemTotalScore[compressRatingMatrix[i][1]] += compressRatingMatrix[i][2];
        }
        for (int i = 0; i < numUsers; i++) {
            userAverageRatings[i] = tempUserTotalScore[i] / userDegrees[i];
        }
        for (int i = 0; i < numItems; i++) {
            itemAverageRatings[i] = tempItemTotalScore[i] / itemDegrees[i];
        }
    }

    /**
     * Set the radius.
     *
     * @param paraRadius The given radius.
     */
    public void setRadius(double paraRadius) {
        if (paraRadius > 0) {
            radius = paraRadius;
        } else {
            radius = 0.1;
        }// OF if
    }// Of setRadius

    /**
     * Leave-one-out prediction. The predicted values are stored in predictions.
     */
    public void leaveOneOutPrediction() {
        double tempItemAverageRating;
        // Make each line of the code shorter.
        int tempUser, tempItem, tempRating;
        System.out.println("\r\nLeaveOneOutPrediction for radius " + radius);

        numNoneNeighbors = 0;
        for (int i = 0; i < numRatings; i++) {
            tempUser = compressRatingMatrix[i][0];
            tempItem = compressRatingMatrix[i][1];
            tempRating = compressRatingMatrix[i][2];

            // Step1. Recompute average rating of the current item.
            tempItemAverageRating =
                    (itemAverageRatings[tempItem] * itemDegrees[tempItem] - tempRating) / (itemDegrees[tempItem] - 1);

            // Step2. Recompute neighbors, at the same time obtain the ratings
            // OF neighbors
            int tempNeighbors = 0;
            double tempTotal = 0;
            int tempComparedItem;
            for (int j = userStartingIndices[tempUser]; j < userStartingIndices[tempUser + 1]; j++) {
                tempComparedItem = compressRatingMatrix[j][1];
                if (tempItem == tempComparedItem) {
                    continue;// Ignore itself
                }// Of if

                if (Math.abs(tempItemAverageRating - itemAverageRatings[tempComparedItem]) < radius) {
                    tempTotal += compressRatingMatrix[j][2];
                    tempNeighbors++;
                }// Of if
            }// OF for j

            //Step3. Predict as the average value of neighbors.
            if (tempNeighbors > 0) {
                predictions[i] = tempTotal / tempNeighbors;
            } else {
                predictions[i] = DEFAULT_RATING;
                numNoneNeighbors++;
            }// Of if
        }// OF for i
    }// of LeaveOneOutPrediction

    /**
     * Compute the MAE based on the deviation of each leave-one-out.
     */
    public double computeMAE() throws Exception {
        double tempTotalError = 0;
        for (int i = 0; i < predictions.length; i++) {
            tempTotalError += Math.abs(predictions[i] - compressRatingMatrix[i][2]);
        }// OF for i

        return tempTotalError / predictions.length;
    }// OF computeMAE

    /**
     * ************************
     * Compute the MAE based on the deviation of each leave-one-out.
     * ************************
     */
    public double computeRSME() throws Exception {
        double tempTotalError = 0;
        for (int i = 0; i < predictions.length; i++) {
            tempTotalError += (predictions[i] - compressRatingMatrix[i][2])
                    * (predictions[i] - compressRatingMatrix[i][2]);
        } // Of for i

        double tempAverage = tempTotalError / predictions.length;

        return Math.sqrt(tempAverage);
    }// Of computeRSME

    /**
     * The entrance of the program.
     *
     * @param args Not used now.
     */
    public static void main(String[] args) {
        try {
            MBR tempRecommender = new MBR("E:\\java_code\\data\\sampledata\\movielens-943u1682m.txt", 943, 1682,
                    100000,22);
            for (double tempRadius = 0.2; tempRadius < 0.6; tempRadius += 0.1) {
                tempRecommender.setRadius(tempRadius);

                tempRecommender.leaveOneOutPrediction();
                double tempMAE = tempRecommender.computeMAE();
                double tempRSME = tempRecommender.computeRSME();

                System.out.println("Radius = " + tempRadius + ", MAE = " + tempMAE + ", RSME = " + tempRSME
                        + ", numNonNeighbors = " + tempRecommender.numNoneNeighbors);
            } // Of for tempRadius
        } catch (Exception ee) {
            System.out.println(ee);
        } // Of try
    }// Of main
}// Of class MBR

运行截图

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/815070.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

tinkerCAD案例:28. Build a Mobile Amplifier 构建移动放大器(3)

tinkerCAD案例&#xff1a;28. Build a Mobile Amplifier 构建移动放大器(3) 原文 step 1 “爵士乐”放大器 Lesson Overview: 课程概述&#xff1a; Now we’re going to decorate our design! 现在我们要装饰我们的设计&#xff01; step 2 In this step we will ref…

纯CSS实现手风琴效果(常用样式)

【效果图】&#xff1a; 【html代码】&#xff1a; <div class"rowd"><ul class"fold_wrap"><li><a href"#"><div class"pic_auto pic_auto1 trans"></div><div class"adv_intro flex&…

qt子进程和父进程读写数据通信

进程A&#xff08;例如主程序&#xff09;创建了一个QProcess B&#xff0c;这个B就称为A的子进程&#xff0c;而A称为B的父进程。 这也称为进程间通信&#xff0c;有多种方式&#xff1a; TCP/IPLocal Server/Socket共享内存D-Bus &#xff08;Unix库&#xff09;QProcess会…

Java版本企业电子招投标采购系统源码+功能模块功能描述+数字化采购管理 采购招投标

功能模块&#xff1a; 待办消息&#xff0c;招标公告&#xff0c;中标公告&#xff0c;信息发布 描述&#xff1a; 全过程数字化采购管理&#xff0c;打造从供应商管理到采购招投标、采购合同、采购执行的全过程数字化管理。通供应商门户具备内外协同的能力&#xff0c;为外部…

Android复习(Android基础-四大组件)—— Activity

Activity作为四大组件之首&#xff0c;是使用最为频繁的一种组件&#xff0c;中文直接翻译为"活动"&#xff0c;不过如果被翻译为"界面"会更好理解。正常情况&#xff0c;除了Window&#xff0c;Dialog和Toast &#xff0c; 我们能见到的界面只有Activity。…

【phaser微信抖音小游戏开发003】游戏状态state场景规划

经过目录优化后的执行结果&#xff1a; 经历过上001&#xff0c;002的规划&#xff0c;我们虽然实现了helloworld .但略显有些繁杂&#xff0c;我们将做以下的修改。修改后的目录和文件结构如图。 game.js//小游戏的重要文件&#xff0c;从这个开始。 main.js 游戏的初始化&a…

集合框架、多线程、IO流

目录 集合框架 Java迭代器&#xff08;Iterator&#xff09; Java集合类 Collection派生 Map接口派生&#xff1a; Java集合List ArrayList Vector LinkedList Java集合Set HashSet LinkedHashSet TreeSet Java集合Queue&#xff08;队列&#xff09; PriorityQue…

AP5101 高压线性恒流电源驱动 输入 24-36V 输出3串18V LED线性恒流驱动方案

1,输入 24V-36V 输出3串18V 直亮 参考BOM 表如下 2,输入 24V-36V 输出3串18V 直亮 参考线路图 如下​ 3&#xff0c;产品描述 AP5101B 是一款高压线性 LED 恒流芯片&#xff0c;外围简单、内置功率管&#xff0c;适用于6- 60V 输入的高精度降压 LED 恒流驱动芯片。最大…

cloudstack之advanced network

cloudstack网络模式的介绍&#xff0c;可参考【cloudstack之basic network】 一、添加资源 访问UI&#xff0c;默认端口为8080&#xff0c;默认用户民和密码是admin/password。点击【continue with installation】。修改默认密码选择zone type&#xff1a;core 选择advanced模…

python中的单引号、双引号和多引号

目录 python中的单引号 python中的双引号 python中的多引号 三者分别在什么时候使用&#xff0c;有什么区别 总结 python中的单引号 在Python中&#xff0c;单引号&#xff08;&#xff09;可以用来表示字符串。 可以使用单引号创建一个简单的字符串&#xff0c;例如&…

cad文件删除了怎么找回来?这7种方法帮你找回

用户咨询&#xff1a;我存在D盘的文件在今天中午突然不见了&#xff1f;全都是些CAD图纸&#xff0c;不知道是不是被我误删了&#xff0c;怎么才能找到这些图纸&#xff0c;对我很重要呢&#xff01;&#xff01;&#xff01; ——CAD文件删除了怎么找回来&#xff1f;误删除了…

测试平台——项目工程创建和配置

这里写目录标题 一、配置开发环境二、配置MySql数据库三、配置工程日志 一、配置开发环境 项目的环境分为开发环境和生产环境。 开发环境:用于编写和调试项目代码。 生产环境:用于项目线上部署运行。 base.py 修改BASE_DIR&#xff1a;拼接.parent 原因&#xff1a;原BASE_D…

数据包在网络中传输的过程

ref: 【先把这个视频看完了】&#xff1a;数据包的传输过程【网络常识10】_哔哩哔哩_bilibili 常识都看看 》Ref&#xff1a; 1. 这个写的嘎嘎好&#xff0c;解释了为啥4层7层5层&#xff0c;还有数据包封装的问题:数据包在网络中的传输过程详解_数据包传输_张孟浩_jay的博客…

ALLEGRO之File

本文主要讨论ALLEGRO软件中的File菜单。 &#xff08;1&#xff09;New&#xff1a;新建&#xff0c;用于新建Board/Package symbol等&#xff1b; &#xff08;2&#xff09;Open&#xff1a;打开&#xff0c;用于打开brd、dra等文件&#xff1b; &#xff08;3&#xff09;S…

C语言题目总结--操作符运用

&#x1f636;‍&#x1f32b;️Take your time ! &#x1f636;‍&#x1f32b;️ &#x1f4a5;个人主页&#xff1a;&#x1f525;&#x1f525;&#x1f525;大魔王&#x1f525;&#x1f525;&#x1f525; &#x1f4a5;代码仓库&#xff1a;&#x1f525;&#x1f525;魔…

【RabbitMQ(day3)】扇形交换机和主题交换机的应用

文章目录 第三种模型&#xff08;Publish/Subscribe 发布/订阅&#xff09;扇型&#xff08;funout&#xff09;交换机Public/Subscribe 模型绑定 第四、第五种模型&#xff08;Routing、Topics&#xff09;第四种模型&#xff08;Routing&#xff09;主题交换机&#xff08;To…

京东LBS推荐算法实践

1、推荐LBS业务介绍 1.1 业务场景 现有的同城购业务围绕京东即时零售能力搭建了到店、到家两种业务场景。同城业务与现有业务进行互补&#xff0c;利用高频&#xff0c;时效性快的特点&#xff0c;可以有效提升主站复访复购频次&#xff0c;是零售的重要战略方向。 1.2 名词…

运行vue项目显示找不到vue-cli

直接下载ruoyi源码到本地&#xff0c;启动ruoyi-ui的时候报错&#xff1a; 原来是电脑没配置nodejs。 所以先去官网下载nodejs&#xff0c;然后安装完之后&#xff0c;在命令行窗口输入&#xff1a; 显示安装成功。 但还没有结束&#xff0c;还要配置npm的全局模块的存放路径…

Apache Doris 巨大飞跃:存算分离新架构

作者&#xff1a;马如悦 Apache Doris 创始人 历史上&#xff0c;数据分析需求的不断提升&#xff08;更大的数据规模、更快的处理速度、更低的使用成本&#xff09;和计算基础设施的不断进化&#xff08;从专用的高端硬件、到低成本的商用硬件、到云计算服务&#xff09;&…

高忆管理:k线分析股票走势?

K线是一种经典的技术剖析工具&#xff0c;经过制作股票价格的收盘、开盘、最高和最低价&#xff0c;形成实体和影线&#xff0c;以反映股票价格的动摇和趋势。本文将从多个角度剖析K线剖析股票走势的重要性及使用。 1. 提醒价格趋势 K线图能够清晰显现股票价格走势的趋势&…