日撸java_day54-55

chatgpt/2023/10/4 7:42:39

文章目录

  • 第 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 ifBufferedReader 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 iftempIndex++;}// Of whiletempBufReader.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 ifor (int i = 0; i < numUsers; i++) {userAverageRatings[i] = tempUserTotalScore[i] / userDegrees[i];}// OF for ifor (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 matrixFile 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 userItemRatingMatrixuserItemRatingMatrix[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 neighborsint 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 ifif (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 ireturn 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 idouble 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.exyb.cn/news/show-5312876.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

1.0 python环境安装

1 python环境安装 python安装教程原文 2 PyCharm安装教程 PyCharm安装教程

CS5213 国产HDMI转VGA带音频方案芯片|CS5213规格书|CS5213原理图

集睿致远/ASL推出的CS5213芯片是一个国产HDMI&#xff08;高清多媒体接口&#xff09;到VGA桥接芯片。它将HDMI信号转换为标准VGA信号它可以在适配器、智能电缆等设备中设计 CS5213特征 将HDMI信号转换为VGA输出 支持数字信号到模似信号的转换 支持 HDCP 1.0/1.1/1.2 操作简…

71. ElasticSearch 5.0.0 安装部署常见错误或问题

文章目录 ElasticSearch 5.0.0 安装部署常见错误或问题问题一&#xff1a;UnsupportedOperationException问题二&#xff1a;ERROR: bootstrap checks failed问题三&#xff1a;max number of threads [1024] for user [es] likely too low, increase to at least [2048]问题四…

史上最全免费在线 PDF 格式转换网站集合,10款利器赶紧收藏

hi&#xff0c;大家好我是技术苟&#xff0c;每天晚上22点准时上线为你带来实用黑科技&#xff01;由于公众号改版&#xff0c;现在的公众号消息已经不再按照时间顺序排送了。因此小伙伴们就很容易错过精彩内容。喜欢黑科技的小伙伴&#xff0c;可以将黑科技百科公众号设为标星…

day53|● 1143.最长公共子序列 ● 1035.不相交的线 ● 53. 最大子序和

最长重复子数组 Input: nums1 [1,2,3,2,1], nums2 [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1]. dp[i][j] &#xff1a;以下标i - 1为结尾的A&#xff0c;和以下标j - 1为结尾的B&#xff0c;最长重复子数组长度为dp[i][j]。 …

达梦数据库食用说明

环境准备 达梦数据库支持Windows、Linux和Unix操作系统&#xff0c;达梦正式版需要授权&#xff0c;我们学习的话选择试用即可&#xff0c;在本机使用VM安装一个Centos&#xff0c;然后去达梦官网下载适用自己平台的安装包。 本教程使用的是VM安装的centos7.9。所以选择X86架…

Intellij IDEA代码后缀补齐功能-自动补全

后缀补全 每当你有一个现有的表达式时&#xff0c;你可以在一个点后面附加一个特定的后缀&#xff0c;并使用Tab键来应用它。IntelliJ IDEA接收表达式&#xff0c;并根据提供的后缀对其进行转换。 加入&#xff0c;你有一个字符串列表名为items&#xff0c;现在你需要遍历它&…

职工管理系统-C++面向对象

首先创建头文件、源文件&#xff0c;再编程。&#xff08;B站黑马程序员视频笔记&#xff09; 一、头文件.h 1、boss.h #pragma once #include<iostream> using namespace std; #include "worker.h"//老板类 class Boss :public Worker { public://构造函数B…
推荐文章