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

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

【Python】 -- 趣味代码 - 小恐龙游戏

文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...

论文解读:交大港大上海AI Lab开源论文 | 宇树机器人多姿态起立控制强化学习框架(二)

HoST框架核心实现方法详解 - 论文深度解读(第二部分) 《Learning Humanoid Standing-up Control across Diverse Postures》 系列文章: 论文深度解读 + 算法与代码分析(二) 作者机构: 上海AI Lab, 上海交通大学, 香港大学, 浙江大学, 香港中文大学 论文主题: 人形机器人…...

2025年能源电力系统与流体力学国际会议 (EPSFD 2025)

2025年能源电力系统与流体力学国际会议&#xff08;EPSFD 2025&#xff09;将于本年度在美丽的杭州盛大召开。作为全球能源、电力系统以及流体力学领域的顶级盛会&#xff0c;EPSFD 2025旨在为来自世界各地的科学家、工程师和研究人员提供一个展示最新研究成果、分享实践经验及…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

12.找到字符串中所有字母异位词

&#x1f9e0; 题目解析 题目描述&#xff1a; 给定两个字符串 s 和 p&#xff0c;找出 s 中所有 p 的字母异位词的起始索引。 返回的答案以数组形式表示。 字母异位词定义&#xff1a; 若两个字符串包含的字符种类和出现次数完全相同&#xff0c;顺序无所谓&#xff0c;则互为…...

全面解析各类VPN技术:GRE、IPsec、L2TP、SSL与MPLS VPN对比

目录 引言 VPN技术概述 GRE VPN 3.1 GRE封装结构 3.2 GRE的应用场景 GRE over IPsec 4.1 GRE over IPsec封装结构 4.2 为什么使用GRE over IPsec&#xff1f; IPsec VPN 5.1 IPsec传输模式&#xff08;Transport Mode&#xff09; 5.2 IPsec隧道模式&#xff08;Tunne…...

Android 之 kotlin 语言学习笔记三(Kotlin-Java 互操作)

参考官方文档&#xff1a;https://developer.android.google.cn/kotlin/interop?hlzh-cn 一、Java&#xff08;供 Kotlin 使用&#xff09; 1、不得使用硬关键字 不要使用 Kotlin 的任何硬关键字作为方法的名称 或字段。允许使用 Kotlin 的软关键字、修饰符关键字和特殊标识…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

DeepSeek 技术赋能无人农场协同作业:用 AI 重构农田管理 “神经网”

目录 一、引言二、DeepSeek 技术大揭秘2.1 核心架构解析2.2 关键技术剖析 三、智能农业无人农场协同作业现状3.1 发展现状概述3.2 协同作业模式介绍 四、DeepSeek 的 “农场奇妙游”4.1 数据处理与分析4.2 作物生长监测与预测4.3 病虫害防治4.4 农机协同作业调度 五、实际案例大…...