当前位置: 首页 > 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是以加州大学…...

基于ASP.NET+ SQL Server实现(Web)医院信息管理系统

医院信息管理系统 1. 课程设计内容 在 visual studio 2017 平台上&#xff0c;开发一个“医院信息管理系统”Web 程序。 2. 课程设计目的 综合运用 c#.net 知识&#xff0c;在 vs 2017 平台上&#xff0c;进行 ASP.NET 应用程序和简易网站的开发&#xff1b;初步熟悉开发一…...

【Java学习笔记】Arrays类

Arrays 类 1. 导入包&#xff1a;import java.util.Arrays 2. 常用方法一览表 方法描述Arrays.toString()返回数组的字符串形式Arrays.sort()排序&#xff08;自然排序和定制排序&#xff09;Arrays.binarySearch()通过二分搜索法进行查找&#xff08;前提&#xff1a;数组是…...

相机从app启动流程

一、流程框架图 二、具体流程分析 1、得到cameralist和对应的静态信息 目录如下: 重点代码分析: 启动相机前,先要通过getCameraIdList获取camera的个数以及id,然后可以通过getCameraCharacteristics获取对应id camera的capabilities(静态信息)进行一些openCamera前的…...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

Python基于历史模拟方法实现投资组合风险管理的VaR与ES模型项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档&#xff09;&#xff0c;如需数据代码文档可以直接到文章最后关注获取。 1.项目背景 在金融市场日益复杂和波动加剧的背景下&#xff0c;风险管理成为金融机构和个人投资者关注的核心议题之一。VaR&…...

Go 语言并发编程基础:无缓冲与有缓冲通道

在上一章节中&#xff0c;我们了解了 Channel 的基本用法。本章将重点分析 Go 中通道的两种类型 —— 无缓冲通道与有缓冲通道&#xff0c;它们在并发编程中各具特点和应用场景。 一、通道的基本分类 类型定义形式特点无缓冲通道make(chan T)发送和接收都必须准备好&#xff0…...

Spring AI Chat Memory 实战指南:Local 与 JDBC 存储集成

一个面向 Java 开发者的 Sring-Ai 示例工程项目&#xff0c;该项目是一个 Spring AI 快速入门的样例工程项目&#xff0c;旨在通过一些小的案例展示 Spring AI 框架的核心功能和使用方法。 项目采用模块化设计&#xff0c;每个模块都专注于特定的功能领域&#xff0c;便于学习和…...

Spring Security 认证流程——补充

一、认证流程概述 Spring Security 的认证流程基于 过滤器链&#xff08;Filter Chain&#xff09;&#xff0c;核心组件包括 UsernamePasswordAuthenticationFilter、AuthenticationManager、UserDetailsService 等。整个流程可分为以下步骤&#xff1a; 用户提交登录请求拦…...

在 Visual Studio Code 中使用驭码 CodeRider 提升开发效率:以冒泡排序为例

目录 前言1 插件安装与配置1.1 安装驭码 CodeRider1.2 初始配置建议 2 示例代码&#xff1a;冒泡排序3 驭码 CodeRider 功能详解3.1 功能概览3.2 代码解释功能3.3 自动注释生成3.4 逻辑修改功能3.5 单元测试自动生成3.6 代码优化建议 4 驭码的实际应用建议5 常见问题与解决建议…...

QT开发技术【ffmpeg + QAudioOutput】音乐播放器

一、 介绍 使用ffmpeg 4.2.2 在数字化浪潮席卷全球的当下&#xff0c;音视频内容犹如璀璨繁星&#xff0c;点亮了人们的生活与工作。从短视频平台上令人捧腹的搞笑视频&#xff0c;到在线课堂中知识渊博的专家授课&#xff0c;再到影视平台上扣人心弦的高清大片&#xff0c;音…...