java实现矩阵分解推荐算法的代码
时间: 2024-04-14 08:10:28 浏览: 138
一种基于矩阵分解的电影推荐算法
以下是一个 Java 实现的矩阵分解推荐算法代码示例:
```
import java.util.*;
import java.io.*;
public class MatrixFactorization {
int numUsers;
int numItems;
double[][] userFactors;
double[][] itemFactors;
double learningRate;
double regularization;
int numIterations;
public MatrixFactorization(int numUsers, int numItems, int numFactors,
double learningRate, double regularization, int numIterations) {
this.numUsers = numUsers;
this.numItems = numItems;
userFactors = new double[numUsers][numFactors];
itemFactors = new double[numItems][numFactors];
this.learningRate = learningRate;
this.regularization = regularization;
this.numIterations = numIterations;
}
public void train(int[][] ratings) {
for (int iter = 0; iter < numIterations; iter++) {
for (int u = 0; u < numUsers; u++) {
for (int i = 0; i < numItems; i++) {
if (ratings[u][i] > 0) {
double prediction = 0;
for (int f = 0; f < userFactors[u].length; f++) {
prediction += userFactors[u][f] * itemFactors[i][f];
}
double error = ratings[u][i] - prediction;
for (int f = 0; f < userFactors[u].length; f++) {
userFactors[u][f] += learningRate * (error * itemFactors[i][f] - regularization * userFactors[u][f]);
itemFactors[i][f] += learningRate * (error * userFactors[u][f] - regularization * itemFactors[i][f]);
}
}
}
}
}
}
public double[][] getUserFactors() {
return userFactors;
}
public double[][] getItemFactors() {
return itemFactors;
}
public static void main(String[] args) {
int numUsers = 5;
int numItems = 4;
int[][] ratings = {{5, 3, 0, 1},
{4, 0, 0, 1},
{1, 1, 0, 5},
{0, 0, 4, 4},
{0, 1, 5, 4}};
int numFactors = 2;
double learningRate = 0.01;
double regularization = 0.1;
int numIterations = 100;
MatrixFactorization mf = new MatrixFactorization(numUsers, numItems, numFactors, learningRate, regularization, numIterations);
mf.train(ratings);
double[][] userFactors = mf.getUserFactors();
double[][] itemFactors = mf.getItemFactors();
System.out.println("User factors:");
for (int u = 0; u < numUsers; u++) {
System.out.print("User " + u + ": ");
for (int f = 0; f < numFactors; f++) {
System.out.print(userFactors[u][f] + " ");
}
System.out.println();
}
System.out.println("Item factors:");
for (int i = 0; i < numItems; i++) {
System.out.print("Item " + i + ": ");
for (int f = 0; f < numFactors; f++) {
System.out.print(itemFactors[i][f] + " ");
}
System.out.println();
}
}
}
```
该代码实现了基于梯度下降的矩阵分解推荐算法。在本例中,我们使用一个大小为 5 x 4 的评分矩阵作为输入,其中每行代表一个用户,每列代表一个物品。为了简化问题,使用了隐含因子数量为 2 的模型。在模型训练期间,每次迭代都会使用随机梯度下降更新用户矩阵和物品矩阵的值,以尝试最小化预测值与实际值之间的误差。在训练完成后,输出用户因子矩阵和物品因子矩阵的值,以便进行推荐。
阅读全文