Day 69-70:矩阵分解

news2024/9/27 12:07:22

代码:

package dl;

import java.io.*;
import java.util.Random;

/*
 * Matrix factorization for recommender systems.
 */

public class MatrixFactorization {
    /**
     * Used to generate random numbers.
     */
    Random rand = new Random();

    /**
     * Number of users.
     */
    int numUsers;

    /**
     * Number of items.
     */
    int numItems;

    /**
     * Number of ratings.
     */
    int numRatings;

    /**
     * Training data.
     */
    Triple[] dataset;

    /**
     * A parameter for controlling learning regular.
     */
    double alpha;

    /**
     * A parameter for controlling the learning speed.
     */
    double lambda;

    /**
     * The low rank of the small matrices.
     */
    int rank;

    /**
     * The user matrix U.
     */
    double[][] userSubspace;

    /**
     * The item matrix V.
     */
    double[][] itemSubspace;

    /**
     * The lower bound of the rating value.
     */
    double ratingLowerBound;

    /**
     * The upper bound of the rating value.
     */
    double ratingUpperBound;

    /**
     ************************
     * The first constructor.
     *
     * @param paraFilename
     *            The data filename.
     * @param paraNumUsers
     *            The number of users.
     * @param paraNumItems
     *            The number of items.
     * @param paraNumRatings
     *            The number of ratings.
     ************************
     */
    public MatrixFactorization(String paraFilename, int paraNumUsers, int paraNumItems,
                               int paraNumRatings, double paraRatingLowerBound, double paraRatingUpperBound) {
        numUsers = paraNumUsers;
        numItems = paraNumItems;
        numRatings = paraNumRatings;
        ratingLowerBound = paraRatingLowerBound;
        ratingUpperBound = paraRatingUpperBound;

        try {
            readData(paraFilename, paraNumUsers, paraNumItems, paraNumRatings);
            // adjustUsingMeanRating();
        } catch (Exception ee) {
            System.out.println("File " + paraFilename + " cannot be read! " + ee);
            System.exit(0);
        } // Of try
    }// Of the first constructor

    /**
     ************************
     * Set parameters.
     *
     * @param paraRank
     *            The given rank.
     * @throws IOException
     ************************
     */
    public void setParameters(int paraRank, double paraAlpha, double paraLambda) {
        rank = paraRank;
        alpha = paraAlpha;
        lambda = paraLambda;
    }// Of setParameters

    /**
     ************************
     * Read the data from the file.
     *
     * @param paraFilename
     *            The given file.
     * @throws IOException
     ************************
     */
    public void readData(String paraFilename, int paraNumUsers, int paraNumItems,
                         int paraNumRatings) throws IOException {
        File tempFile = new File(paraFilename);
        if (!tempFile.exists()) {
            System.out.println("File " + paraFilename + " does not exists.");
            System.exit(0);
        } // Of if
        BufferedReader tempBufferReader = new BufferedReader(new FileReader(tempFile));

        // Allocate space.
        dataset = new Triple[paraNumRatings];
        String tempString;
        String[] tempStringArray;
        for (int i = 0; i < paraNumRatings; i++) {
            tempString = tempBufferReader.readLine();
            tempStringArray = tempString.split(",");
            dataset[i] = new Triple(Integer.parseInt(tempStringArray[0]),
                    Integer.parseInt(tempStringArray[1]), Double.parseDouble(tempStringArray[2]));
        } // Of for i

        tempBufferReader.close();
    }// Of readData

    /**
     ************************
     * Initialize subspaces. Each value is in [0, 1].
     ************************
     */
    void initializeSubspaces() {
        userSubspace = new double[numUsers][rank];

        for (int i = 0; i < numUsers; i++) {
            for (int j = 0; j < rank; j++) {
                userSubspace[i][j] = rand.nextDouble();
            } // Of for j
        } // Of for i

        itemSubspace = new double[numItems][rank];
        for (int i = 0; i < numItems; i++) {
            for (int j = 0; j < rank; j++) {
                itemSubspace[i][j] = rand.nextDouble();
            } // Of for j
        } // Of for i
    }// Of initializeSubspaces

    /**
     ************************
     * Predict the rating of the user to the item
     *
     * @param paraUser
     *            The user index.
     ************************
     */
    public double predict(int paraUser, int paraItem) {
        double resultValue = 0;
        for (int i = 0; i < rank; i++) {
            // The row vector of an user and the column vector of an item
            resultValue += userSubspace[paraUser][i] * itemSubspace[paraItem][i];
        } // Of for i
        return resultValue;
    }// Of predict

    /**
     ************************
     * Train.
     *
     * @param paraRounds
     *            The number of rounds.
     ************************
     */
    public void train(int paraRounds) {
        initializeSubspaces();

        for (int i = 0; i < paraRounds; i++) {
            updateNoRegular();
            if (i % 50 == 0) {
                // Show the process
                System.out.println("Round " + i);
                System.out.println("MAE: " + mae());
            } // Of if
        } // Of for i
    }// Of train

    /**
     ************************
     * Update sub-spaces using the training data.
     ************************
     */
    public void updateNoRegular() {
        for (int i = 0; i < numRatings; i++) {
            int tempUserId = dataset[i].user;
            int tempItemId = dataset[i].item;
            double tempRate = dataset[i].rating;

            double tempResidual = tempRate - predict(tempUserId, tempItemId); // Residual

            // Update user subspace
            double tempValue = 0;
            for (int j = 0; j < rank; j++) {
                tempValue = 2 * tempResidual * itemSubspace[tempItemId][j];
                userSubspace[tempUserId][j] += alpha * tempValue;
            } // Of for j

            // Update item subspace
            for (int j = 0; j < rank; j++) {
                tempValue = 2 * tempResidual * userSubspace[tempUserId][j];

                itemSubspace[tempItemId][j] += alpha * tempValue;
            } // Of for j
        } // Of for i
    }// Of updateNoRegular

    /**
     ************************
     * Compute the RSME.
     *
     * @return RSME of the current factorization.
     ************************
     */
    public double rsme() {
        double resultRsme = 0;
        int tempTestCount = 0;

        for (int i = 0; i < numRatings; i++) {
            int tempUserIndex = dataset[i].user;
            int tempItemIndex = dataset[i].item;
            double tempRate = dataset[i].rating;

            double tempPrediction = predict(tempUserIndex, tempItemIndex);// +
            // DataInfo.mean_rating;

            if (tempPrediction < ratingLowerBound) {
                tempPrediction = ratingLowerBound;
            } else if (tempPrediction > ratingUpperBound) {
                tempPrediction = ratingUpperBound;
            } // Of if

            double tempError = tempRate - tempPrediction;
            resultRsme += tempError * tempError;
            tempTestCount++;
        } // Of for i

        return Math.sqrt(resultRsme / tempTestCount);
    }// Of rsme

    /**
     ************************
     * Compute the MAE.
     *
     * @return MAE of the current factorization.
     ************************
     */
    public double mae() {
        double resultMae = 0;
        int tempTestCount = 0;

        for (int i = 0; i < numRatings; i++) {
            int tempUserIndex = dataset[i].user;
            int tempItemIndex = dataset[i].item;
            double tempRate = dataset[i].rating;

            double tempPrediction = predict(tempUserIndex, tempItemIndex);

            if (tempPrediction < ratingLowerBound) {
                tempPrediction = ratingLowerBound;
            } // Of if
            if (tempPrediction > ratingUpperBound) {
                tempPrediction = ratingUpperBound;
            } // Of if

            double tempError = tempRate - tempPrediction;

            resultMae += Math.abs(tempError);
            // System.out.println("resultMae: " + resultMae);
            tempTestCount++;
        } // Of for i

        return (resultMae / tempTestCount);
    }// Of mae

    /**
     ************************
     * Compute the MAE.
     *
     * @return MAE of the current factorization.
     ************************
     */
    public static void testTrainingTesting(String paraFilename, int paraNumUsers, int paraNumItems,
                                           int paraNumRatings, double paraRatingLowerBound, double paraRatingUpperBound,
                                           int paraRounds) {
        try {
            // Step 1. read the training and testing data
            MatrixFactorization tempMF = new MatrixFactorization(paraFilename, paraNumUsers,
                    paraNumItems, paraNumRatings, paraRatingLowerBound, paraRatingUpperBound);

            tempMF.setParameters(5, 0.0001, 0.005);

            // Step 3. update and predict
            System.out.println("Begin Training ! ! !");
            tempMF.train(paraRounds);

            double tempMAE = tempMF.mae();
            double tempRSME = tempMF.rsme();
            System.out.println("Finally, MAE = " + tempMAE + ", RSME = " + tempRSME);
        } catch (Exception e) {
            e.printStackTrace();
        } // Of try
    }// Of testTrainingTesting

    /**
     ************************
     * @param args
     ************************
     */
    public static void main(String args[]) {
        testTrainingTesting("C:\\Users\\86183\\IdeaProjects\\deepLearning\\src\\main\\java\\resources\\movielens-943u1682m.txt", 943, 1682, 10000, 1, 5, 2000);
    }// Of main

    public class Triple {
        public int user;
        public int item;
        public double rating;

        /**
         *********************
         * The constructor.
         *********************
         */
        public Triple() {
            user = -1;
            item = -1;
            rating = -1;
        }// Of the first constructor

        /**
         *********************
         * The constructor.
         *********************
         */
        public Triple(int paraUser, int paraItem, double paraRating) {
            user = paraUser;
            item = paraItem;
            rating = paraRating;
        }// Of the first constructor

        /**
         *********************
         * Show me.
         *********************
         */
        public String toString() {
            return "" + user + ", " + item + ", " + rating;
        }// Of toString
    }// Of class Triple

}// Of class MatrixFactorization

结果:

 

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

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

相关文章

使用贝叶斯算法完成文档分类问题

贝叶斯原理 贝叶斯原理&#xff08;Bayes theorem&#xff09;是一种用于计算条件概率的数学公式。它是以18世纪英国数学家托马斯贝叶斯&#xff08;Thomas Bayes&#xff09;的名字命名的。贝叶斯原理表达了在已知某个事件发生的情况下&#xff0c;另一个事件发生的概率。具体…

【Golang系统开发】搜索引擎(1) 如何快速判断网页是否已经被爬取

文章目录 1. 写在前面2. 数组存储3. 位图存储3.1 位图简介3.2 链表法3.3 开放寻址法 1. 写在前面 在实际工作中&#xff0c;我们经常需要判断一个对象是否存在&#xff0c;比如判断用户注册登陆时候&#xff0c;需要判断用户是否存在&#xff0c;再比如搜索引擎中的爬虫&#x…

大数据面试题之Elasticsearch:每日三题(七)

大数据面试题之Elasticsearch:每日三题 1.Elasticsearch索引文档的流程&#xff1f;2.Elasticsearch更新和删除文档的流程&#xff1f;3.Elasticsearch搜索的流程&#xff1f; 1.Elasticsearch索引文档的流程&#xff1f; 协调节点默认使用文档ID参与计算(也支持通过routing)&a…

【UE4】给角色添加脚步声

步骤&#xff1a; 1. 导入一个脚步声音频文件&#xff08;.wav格式&#xff09; 2. 打开角色蓝图&#xff0c;这里以第三人称角色模板蓝图“ThirdPersonCharacter”为例&#xff0c;在事件图表中添加一个生成音效的自定义事件。 3. 打开动画序列“ThirdPersonRun” 找到小白人…

Python编程——while循环嵌套讲解(附案例)

作者&#xff1a;Insist-- 个人主页&#xff1a;insist--个人主页 本文专栏&#xff1a;Python专栏 专栏介绍&#xff1a;本专栏为免费专栏&#xff0c;并且会持续更新python基础知识&#xff0c;欢迎各位订阅关注。 目录 一、while嵌套的语法 二、注意事项 三、while嵌套循…

【Java】分支结构习题

【Java】分支结构 文章目录 【Java】分支结构题1 &#xff1a;数字9 出现的次数题2 &#xff1a;计算1/1-1/21/3-1/41/5 …… 1/99 - 1/100 的值。题3 &#xff1a;猜数字题4 &#xff1a;牛客BC110 X图案题5 &#xff1a;输出一个整数的每一位题6 &#xff1a; 模拟三次密码输…

统信UOS安装mysql数据库(mariadb)-统信UOS安装JDK-统信UOS安装nginx(附安装包)

统信UOS离线全套安装教程&#xff08;手把手教程&#xff09; 银河麒麟的各种离线全套安装教程&#xff1a; https://blog.csdn.net/ACCPluzhiqi/article/details/131988147 1.统信UOS桌面系统安装mysql&#xff08;mariadb&#xff09; 2.统信UOS桌面系统安装JDK 3.统信UOS桌…

CAN学习笔记3:STM32 CAN控制器介绍

STM32 CAN控制器 1 概述 STM32 CAN控制器&#xff08;bxCAN&#xff09;&#xff0c;支持CAN 2.0A 和 CAN 2.0B Active版本协议。CAN 2.0A 只能处理标准数据帧且扩展帧的内容会识别错误&#xff0c;而CAN 2.0B Active 可以处理标准数据帧和扩展数据帧。 2 bxCAN 特性 波特率…

【JavaWeb】正则表达式

&#x1f384;欢迎来到边境矢梦的csdn博文&#xff0c;本文主要讲解Java 中正则表达式 的相关知识&#x1f384; &#x1f308;我是边境矢梦&#xff0c;一个正在为秋招和算法竞赛做准备的学生&#x1f308; &#x1f386;喜欢的朋友可以关注一下&#x1faf0;&#x1faf0;&am…

Metabase RCE漏洞复现(CVE-2023-38646)

0x01 产品简介 Metabase是一个开源的数据分析和可视化工具&#xff0c;它可以帮助用户轻松地连接到各种数据源&#xff0c;包括数据库、云服务和API&#xff0c;然后使用直观的界面进行数据查询、分析和可视化。 0x02 漏洞概述 未经身份认证的远程攻击者利用该漏洞可以在服务器…

【C语言趣味教程】(4) 变量:代码注释 | 变量的声明 | 初始化与赋值 | 变量的命名 | 关键字 | 标识符 | 变量名的命名规范

&#x1f517; 《C语言趣味教程》&#x1f448; 猛戳订阅&#xff01;&#xff01;&#xff01; Ⅰ. 代码注释&#xff08;Comment&#xff09; 0x00 引入&#xff1a;注释的作用 "程序员最讨厌两种人&#xff1a;一种是不写注释的人&#xff0c;一种是让我写注释的人。…

如何用DHTMLX组件为Web应用创建甘特图?(一)

dhtmlxGantt是用于跨浏览器和跨平台应用程序的功能齐全的Gantt图表。可满足项目管理应用程序的所有需求&#xff0c;是最完善的甘特图图表库。甘特图仍然是项目管理应用程序中最需要的工具之一&#xff0c;DHTMLX Gantt组件提供了能提升研发甘特图功能所需的重要工具。 在这篇…

【深度学习】InST,Inversion-Based Style Transfer with Diffusion Models,论文

代码&#xff1a;https://github.com/zyxElsa/InST 论文&#xff1a;https://arxiv.org/abs/2211.13203 文章目录 AbstractIntroductionRelated WorkImage style transferText-to-image synthesisInversion of diffusion models MethodOverview ExperimentsComparison with Sty…

我的第一个后端项目(环境搭建,Springboot项目,运行,接口验证)

一. 安装Java开发工具包&#xff08;JDK&#xff09;&#xff1a; 访问Java Software | OracleOracle官方网站&#xff0c;下载适合你操作系统的最新版本的JDK。安装JDK并设置好JAVA_HOME环境变量。 二. 安装集成开发环境&#xff08;IDE&#xff09;&#xff1a; 推荐使用In…

Appium+python自动化(二十八)- 高级滑动(超详解)

高级溜冰的滑动 滑动操作一般是两点之间的滑动&#xff0c;这种滑动在这里称其为低级的溜冰滑动&#xff1b;就是上一节给小伙伴们分享的。然而实际使用过程中用户可能要进行一些多点连续滑动操作。如九宫格滑动操作&#xff0c;连续拖动图片移动等场景。那么这种高级绚丽的溜…

word里的页码问题

一份文档写完&#xff0c;如果需要页码&#xff0c;第一页是封面&#xff0c;封面不需要页码怎么办&#xff1f; 解决&#xff1a;打开页眉页脚&#xff0c;然后把首页不同勾选上&#xff0c;这一页就没有页码了。 目录页&#xff0c;往往要使用罗马数字&#xff0c;其他正文又…

《遗留系统现代化》读书笔记(模式篇-代码现代化(一))

本文地址&#xff1a;http://t.csdn.cn/vS0Za 文章目录 代码现代化&#xff1a;你的代码可测吗&#xff1f;你的代码可测吗&#xff1f;标题如何让代码变得可测&#xff1f;接缝的位置接缝的类型新生和外覆为代码添加测试决策表模式测试的类型和组织遗留系统中的测试策略 代码…

【深度学习笔记】Softmax 回归

本专栏是网易云课堂人工智能课程《神经网络与深度学习》的学习笔记&#xff0c;视频由网易云课堂与 deeplearning.ai 联合出品&#xff0c;主讲人是吴恩达 Andrew Ng 教授。感兴趣的网友可以观看网易云课堂的视频进行深入学习&#xff0c;视频的链接如下&#xff1a; 神经网络和…

QuantMania!《快乐机器学习》和《Python 从入门到入迷》作者,FRM,CAIA

王的机器主理人 王圣元 (FRM, CAIA) 某加密货币公司 Head of Quant 冬海集团 SeaMoney 建模负责人 八方咨询 量化总监 新加坡国立大学金融数学硕士 新加坡国立大学量化金融学士 《快乐机器学习》的作者 《Python 从入门到入迷》的作者 第一本书 《快乐机器学习》 第二本书《Pyt…

MySQL 8.0详细安装配置教程

一. 前言 MySQL是目前最为流行的开源数据库产品&#xff0c;是完全网络化跨平台的关系型数据库系统。它起初是由瑞典MySQLAB公司开发&#xff0c;后来被Oracle公司收购&#xff0c;目前属于Oracle公司。因为开源&#xff0c;所以任何人都能从官网免费下载MySQL软件&#xff0c…