当前位置: 首页 > news >正文

Day 69-70:矩阵分解

代码:

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 ifBufferedReader 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 itempBufferReader.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 iitemSubspace = 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 itemresultValue += userSubspace[paraUser][i] * itemSubspace[paraItem][i];} // Of for ireturn 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 processSystem.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 subspacedouble 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 subspacefor (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 ifdouble tempError = tempRate - tempPrediction;resultRsme += tempError * tempError;tempTestCount++;} // Of for ireturn 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 ifif (tempPrediction > ratingUpperBound) {tempPrediction = ratingUpperBound;} // Of ifdouble tempError = tempRate - tempPrediction;resultMae += Math.abs(tempError);// System.out.println("resultMae: " + resultMae);tempTestCount++;} // Of for ireturn (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 dataMatrixFactorization tempMF = new MatrixFactorization(paraFilename, paraNumUsers,paraNumItems, paraNumRatings, paraRatingLowerBound, paraRatingUpperBound);tempMF.setParameters(5, 0.0001, 0.005);// Step 3. update and predictSystem.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 mainpublic 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

结果:

 

相关文章:

Day 69-70:矩阵分解

代码&#xff1a; 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…...

数据结构:树的存储结构

学习树之前&#xff0c;我们已经了解了二叉树的顺序存储和链式存储&#xff0c;哪么我们如何来存储普通型的树结构的数据&#xff1f;如下图1&#xff1a; 如图1所示&#xff0c;这是一颗普通的树&#xff0c;我们要如何来存储呢&#xff1f;通常&#xff0c;存储这种树结构的数…...

Vue前端渲染blob二进制对象图片的方法

近期做开发&#xff0c;联调接口。接口返回的是一张图片&#xff0c;是对二进制图片处理并渲染&#xff0c;特此记录一下。 本文章是转载文章&#xff0c;原文章&#xff1a;Vue前端处理blob二进制对象图片的方法 接口response是下图 显然&#xff0c;获取到的是一堆乱码&…...

Java的标记接口(Marker Interface)

Java中的标记接口&#xff08;Marker Interface&#xff09;是一个空接口&#xff0c;接口内什么也没有定义。它标识了一种能力&#xff0c;标识继承自该接口的接口、实现了此接口的类具有某种能力。 例如&#xff0c;jdk的com.sun.org.apache.xalan.internal.xsltc.trax.Temp…...

Kafka基础架构与核心概念

Kafka简介 Kafka是由Apache软件基金会开发的一个开源流处理平台&#xff0c;由Scala和Java编写。Kafka是一种高吞吐量的分布式发布订阅消息系统&#xff0c;它可以处理消费者在网站中的所有动作流数据。架构特点是分区、多副本、多生产者、多订阅者&#xff0c;性能特点主要是…...

观察者模式与观察者模式实例EventBus

什么是观察者模式 顾名思义&#xff0c;观察者模式就是在多个对象之间&#xff0c;定义一个一对多的依赖&#xff0c;当一个对象状态改变时&#xff0c;所有依赖这个对象的对象都会自动收到通知。 观察者模式也称为发布订阅模式(Publish-Subscribe Design Pattern)&#xff0…...

科普 | OSI模型

本文简要地介绍 OSI 模型 1’ 2’ 3。 更新&#xff1a;2023 / 7 / 23 科普 | OSI模型 术语节点链路协议网络拓扑 概念作用结构应用层表示层会话层传输层网络层数据链路层物理层 数据如何流动OSI 和TCP/IP 的对应关系和协议参考链接 术语 节点 节点&#xff08; Node &#…...

redis相关异常之RedisConnectionExceptionRedisCommandTimeoutException

本文只是分析Letture类型的Redis 池化连接出现的连接超时异常、读超时异常问题。 1.RedisConnectionException 默认是10秒。 通过如下可以配置&#xff1a; public class MyLettuceClientConfigurationBuilderCustomizer implements LettuceClientConfigurationBuilderCusto…...

Merge the squares! 2023牛客暑期多校训练营4-H

登录—专业IT笔试面试备考平台_牛客网 题目大意&#xff1a;有n*n个边长为1的小正方形摆放在边长为n的大正方形中&#xff0c;每次可以选择不超过50个正方形&#xff0c;将其合并为一个更大的正方形&#xff0c;求一种可行的操作使所有小正方形都被合并成一个n*n的大正方形 1…...

STM32 串口学习(二)

要用跳线帽将PA9与RXD相连&#xff0c;PA10与TXD相连。 软件设计 void uart_init(u32 baud) {//UART 初始化设置UART1_Handler.InstanceUSART1; //USART1UART1_Handler.Init.BaudRatebound; //波特率UART1_Handler.Init.WordLengthUART_WORDLENGTH_8B; //字长为 8 位数据格式U…...

点大商城V2_2.5.0 全开源版 商家自营+多商户入驻 百度+支付宝+QQ+头条+小程序端+unipp开源前端安装测试教程

安装测试环境&#xff1a;Nginx 1.20PHP7.2MySQL 5.6 修复了无法上传开放平台问题 安装说明&#xff1a; 1、上传后端目录至网站 2、导入提供的数据库文件 3、修改数据库配置文件根目录下config.php&#xff0c;增加数据库用户名和密码 4、网站后台直接访问网址&#xff…...

“深入理解SpringBoot:从入门到精通“

标题&#xff1a;深入理解Spring Boot&#xff1a;从入门到精通 摘要&#xff1a;本文将介绍Spring Boot的基本概念和核心特性&#xff0c;并通过示例代码演示如何使用Spring Boot构建一个简单的Web应用程序。 1. 简介 Spring Boot是一个开源的Java框架&#xff0c;旨在简化基…...

PCB绘制时踩的坑 - SOT-223封装

SOT-223封装并不是同一的&#xff0c;细分的话可以分为两种常用的封装。尤其是tab脚的属性很容易搞错。如果你想着用tab脚连接有属性的铺铜&#xff0c;来提高散热效率&#xff0c;那么你一定要注意你购买的器件tab脚的属性。 第一种如下图&#xff0c;第1脚为GND&#xff0c;第…...

Go语法入门 + 项目实战

&#x1f442; Take me Hand Acoustic - Ccile Corbel - 单曲 - 网易云音乐 第3个小项目有问题&#xff0c;不能在Windows下跑&#xff0c;懒得去搜Linux上怎么跑了&#xff0c;已经落下进度了.... 目录 &#x1f633;前言 &#x1f349;Go两小时 &#x1f511;小项目实战 …...

QT控件通过qss设置子控件的对齐方式、大小自适应等

一些复杂控件&#xff0c;是有子控件的&#xff0c;每个子控件&#xff0c;都可以通过qss的双冒号选择器来选中&#xff0c;进行独特的样式定义。很多控件都有子控件&#xff0c;太多了&#xff0c;后面单独写一篇文章来介绍各个控件的子控件。这里就随便来几个例子 例如下拉列…...

基于java在线收银系统设计与实现

摘要 科技的力量总是在关键的地方改变着人们的生活&#xff0c;不仅如此&#xff0c;我们的生活也是离不开这样或者那样的科技改变&#xff0c;有的消费者没有时间去商场购物&#xff0c;那么电商和快递的结合让端口到消费者的距离不再遥远&#xff1b;有的房客因地域或者工作的…...

Linux--进程的新建状态

新建状态&#xff1a; 操作系统创建了进程的内核数据结构&#xff08;task_struct、mm_struct、页表&#xff09;&#xff0c;但是页表没有创建映射关系&#xff0c;而且磁盘里的程序的代码和数据未加载到物理内存...

区间dp,合并石子模板题

设有 N 堆石子排成一排&#xff0c;其编号为 1,2,3,…,N。 每堆石子有一定的质量&#xff0c;可以用一个整数来描述&#xff0c;现在要将这 N 堆石子合并成为一堆。 每次只能合并相邻的两堆&#xff0c;合并的代价为这两堆石子的质量之和&#xff0c;合并后与这两堆石子相邻的…...

C++代码格式化工具clang-format详细介绍

文章目录 clang-format思考代码风格指南生成您的配置运行 clang-format禁用一段代码的格式设置clang-format的设置预览 clang-format 我曾在许多编程团队工作过&#xff0c;这些团队名义上都有“编程风格指南”。该指南经常被写下来并放置在开发人员很少查看的地方。几乎在每种…...

CentOS 7安装PostgreSQL 15版本数据库

目录 一、何为PostgreSQL&#xff1f; 二、PostgreSQL安装 2.1安装依赖 2.2 执行安装 2.3 数据库初始化 2.4 配置环境变量 2.5 创建数据库 2.6 配置远程 2.7 测试远程 三、常用命令 四、用户创建和数据库权限 一、何为PostgreSQL&#xff1f; PostgreSQL是以加州大学…...

Ubuntu系统下交叉编译openssl

一、参考资料 OpenSSL&&libcurl库的交叉编译 - hesetone - 博客园 二、准备工作 1. 编译环境 宿主机&#xff1a;Ubuntu 20.04.6 LTSHost&#xff1a;ARM32位交叉编译器&#xff1a;arm-linux-gnueabihf-gcc-11.1.0 2. 设置交叉编译工具链 在交叉编译之前&#x…...

React hook之useRef

React useRef 详解 useRef 是 React 提供的一个 Hook&#xff0c;用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途&#xff0c;下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...

工程地质软件市场:发展现状、趋势与策略建议

一、引言 在工程建设领域&#xff0c;准确把握地质条件是确保项目顺利推进和安全运营的关键。工程地质软件作为处理、分析、模拟和展示工程地质数据的重要工具&#xff0c;正发挥着日益重要的作用。它凭借强大的数据处理能力、三维建模功能、空间分析工具和可视化展示手段&…...

linux 错误码总结

1,错误码的概念与作用 在Linux系统中,错误码是系统调用或库函数在执行失败时返回的特定数值,用于指示具体的错误类型。这些错误码通过全局变量errno来存储和传递,errno由操作系统维护,保存最近一次发生的错误信息。值得注意的是,errno的值在每次系统调用或函数调用失败时…...

Java 加密常用的各种算法及其选择

在数字化时代&#xff0c;数据安全至关重要&#xff0c;Java 作为广泛应用的编程语言&#xff0c;提供了丰富的加密算法来保障数据的保密性、完整性和真实性。了解这些常用加密算法及其适用场景&#xff0c;有助于开发者在不同的业务需求中做出正确的选择。​ 一、对称加密算法…...

06 Deep learning神经网络编程基础 激活函数 --吴恩达

深度学习激活函数详解 一、核心作用 引入非线性:使神经网络可学习复杂模式控制输出范围:如Sigmoid将输出限制在(0,1)梯度传递:影响反向传播的稳定性二、常见类型及数学表达 Sigmoid σ ( x ) = 1 1 +...

tree 树组件大数据卡顿问题优化

问题背景 项目中有用到树组件用来做文件目录&#xff0c;但是由于这个树组件的节点越来越多&#xff0c;导致页面在滚动这个树组件的时候浏览器就很容易卡死。这种问题基本上都是因为dom节点太多&#xff0c;导致的浏览器卡顿&#xff0c;这里很明显就需要用到虚拟列表的技术&…...

Typeerror: cannot read properties of undefined (reading ‘XXX‘)

最近需要在离线机器上运行软件&#xff0c;所以得把软件用docker打包起来&#xff0c;大部分功能都没问题&#xff0c;出了一个奇怪的事情。同样的代码&#xff0c;在本机上用vscode可以运行起来&#xff0c;但是打包之后在docker里出现了问题。使用的是dialog组件&#xff0c;…...

学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”

2025年#高考 将在近日拉开帷幕&#xff0c;#AI 监考一度冲上热搜。当AI深度融入高考&#xff0c;#时间同步 不再是辅助功能&#xff0c;而是决定AI监考系统成败的“生命线”。 AI亮相2025高考&#xff0c;40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕&#xff0c;江西、…...

【笔记】WSL 中 Rust 安装与测试完整记录

#工作记录 WSL 中 Rust 安装与测试完整记录 1. 运行环境 系统&#xff1a;Ubuntu 24.04 LTS (WSL2)架构&#xff1a;x86_64 (GNU/Linux)Rust 版本&#xff1a;rustc 1.87.0 (2025-05-09)Cargo 版本&#xff1a;cargo 1.87.0 (2025-05-06) 2. 安装 Rust 2.1 使用 Rust 官方安…...