octave实现协同过滤推荐算法

2024-04-25 12:18

本文主要是介绍octave实现协同过滤推荐算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

octave实现协同过滤推荐算法

标签:推荐算法

这是对关于电影评分的数据集使用协同过滤算法,实现推荐系统。

数据来源为:电影数据

  1. 先从本地导入数据(代码如下):
%  导入数据
load ('ex8_movies.mat');
  1. 现在对矩阵可视化看看:
    矩阵可视化图片

  2. 我们可以看出,该图为Y的输出,横轴为用户,纵轴为电影,所以 Y Y 矩阵是
    nummoviesnumusers

另外对于 R R 矩阵,其Rij=1ij
另外代码中常会看到两个矩阵:
矩阵图
X大小为电影数*特征数,第i行代表第i部电影的特征,Theta大小为用户数*特征数,第j行代表第j个用户对应的参数。

4.现在开始求代价函数
代码如下:

J = 1/2 * (sum(sum(R .* (((X * Theta') - Y).^2) ))) ;
%正则化
J = J + lambda/2 * (sum(sum(X.^2))) + lambda/2 * (sum(sum(Theta.^2))) ;%梯度下降
X_grad = (R .* (X * Theta' - Y)) * Theta ;
X_grad = X_grad + lambda * X ;Theta_grad = (R .* (X * Theta' - Y))' * X ;
Theta_grad = Theta_grad + lambda * Theta ;

其中,经过正则化的公式为:
公式图片

我们更新参数公式中,损失函数梯度(这里没打出正则化,代码里正则化了)为:
梯度下降图片

调用为:

%% ========= Part 4: Collaborative Filtering Cost Regularization ========
%  Now, you should implement regularization for the cost function for 
%  collaborative filtering. You can implement it by adding the cost of
%  regularization to the original cost computation.
%  %  Evaluate cost function
J = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...num_features, 1.5);fprintf(['Cost at loaded parameters (lambda = 1.5): %f '...'\n(this value should be about 31.34)\n'], J);fprintf('\nProgram paused. Press enter to continue.\n');
pause;

好,有了这些,再加上Octave中的无约束最小化优化函数,就可以直接训练了(下面是这个优化函数调用的代码):

theta = fmincg (@(t)(cofiCostFunc(t, Y, R, num_users, num_movies, ...num_features, lambda)), ...initial_parameters, options);

现在可以看看对于一个用户它的效果了:


这里来了一个用户,且有该用户对几个电影的评分,代码如下:

%% ============== Part 6: Entering ratings for a new user ===============
%  Before we will train the collaborative filtering model, we will first
%  add ratings that correspond to a new user that we just observed. This
%  part of the code will also allow you to put in your own ratings for the
%  movies in our dataset!
%
movieList = loadMovieList();%  Initialize my ratings
my_ratings = zeros(1682, 1);% Check the file movie_idx.txt for id of each movie in our dataset
% For example, Toy Story (1995) has ID 1, so to rate it "4", you can set
my_ratings(1) = 4;% Or suppose did not enjoy Silence of the Lambs (1991), you can set
my_ratings(98) = 2;% We have selected a few movies we liked / did not like and the ratings we
% gave are as follows:
my_ratings(7) = 3;
my_ratings(12)= 10;
my_ratings(54) = 4;
my_ratings(64)= 10;
my_ratings(66)= 3;
my_ratings(69) = 10;
my_ratings(183) = 4;
my_ratings(226) = 10;
my_ratings(355)= 10;fprintf('\n\nNew user ratings:\n');
for i = 1:length(my_ratings)if my_ratings(i) > 0 fprintf('Rated %d for %s\n', my_ratings(i), ...movieList{i});end
endfprintf('\nProgram paused. Press enter to continue.\n');
pause;

其中LoadmovieList()导入了如下的电影(其实是我选了几个,另外几个随便选的)

New user ratings:
Rated 4 for Toy Story (1995)
Rated 3 for Twelve Monkeys (1995)
Rated 10 for Usual Suspects, The (1995)
Rated 4 for Outbreak (1995)
Rated 10 for Shawshank Redemption, The (1994)
Rated 3 for While You Were Sleeping (1995)
Rated 10 for Forrest Gump (1994)
Rated 2 for Silence of the Lambs, The (1991)
Rated 4 for Alien (1979)
Rated 10 for Die Hard 2 (1990)
Rated 10 for Sphere (1998)

现在开始训练参数了:

%% ================== Part 7: Learning Movie Ratings ====================
%  Now, you will train the collaborative filtering model on a movie rating 
%  dataset of 1682 movies and 943 users
%fprintf('\nTraining collaborative filtering...\n');%  Load data
load('ex8_movies.mat');%  Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies by 
%  943 users
%
%  R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a
%  rating to movie i%  Add our own ratings to the data matrix
Y = [my_ratings Y];
R = [(my_ratings ~= 0) R];%  Normalize Ratings
[Ynorm, Ymean] = normalizeRatings(Y, R);%  Useful Values
num_users = size(Y, 2);
num_movies = size(Y, 1);
num_features = 10;% Set Initial Parameters (Theta, X)
X = randn(num_movies, num_features);
Theta = randn(num_users, num_features);initial_parameters = [X(:); Theta(:)];% Set options for fmincg
options = optimset('GradObj', 'on', 'MaxIter', 100);% Set Regularization
lambda = 10;
theta = fmincg (@(t)(cofiCostFunc(t, Ynorm, R, num_users, num_movies, ...num_features, lambda)), ...initial_parameters, options);% Unfold the returned theta back into U and W
X = reshape(theta(1:num_movies*num_features), num_movies, num_features);
Theta = reshape(theta(num_movies*num_features+1:end), ...num_users, num_features);fprintf('Recommender system learning completed.\n');fprintf('\nProgram paused. Press enter to continue.\n');
pause;

然后,开始推荐:

%% ================== Part 8: Recommendation for you ====================
%  After training the model, you can now make recommendations by computing
%  the predictions matrix.
%p = X * Theta';
my_predictions = p(:,1) + Ymean;movieList = loadMovieList();[r, ix] = sort(my_predictions, 'descend');
fprintf('\nTop recommendations for you:\n');
for i=1:10j = ix(i);fprintf('Predicting rating %.1f for movie %s\n', my_predictions(j), ...movieList{j});
endfprintf('\n\nOriginal ratings provided:\n');
for i = 1:length(my_ratings)if my_ratings(i) > 0 fprintf('Rated %d for %s\n', my_ratings(i), ...movieList{i});end
end

结果推荐了这几部电影:

Top recommendations for you:
Predicting rating 6.5 for movie Forrest Gump (1994)
Predicting rating 6.3 for movie Return of the Jedi (1983)
Predicting rating 6.3 for movie Star Wars (1977)
Predicting rating 6.2 for movie Raiders of the Lost Ark (1981)
Predicting rating 6.1 for movie Shawshank Redemption, The (1994)
Predicting rating 6.1 for movie Empire Strikes Back, The (1980)
Predicting rating 6.0 for movie Braveheart (1995)
Predicting rating 6.0 for movie Titanic (1997)
Predicting rating 5.8 for movie Back to the Future (1985)
Predicting rating 5.8 for movie Game, The (1997)

好吧,我也没看过,都是很老的电影。。。我也不知道推荐的准不准。。。

这篇关于octave实现协同过滤推荐算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/934663

相关文章

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦

Java实现本地缓存的四种方法实现与对比

《Java实现本地缓存的四种方法实现与对比》本地缓存的优点就是速度非常快,没有网络消耗,本地缓存比如caffine,guavacache这些都是比较常用的,下面我们来看看这四种缓存的具体实现吧... 目录1、HashMap2、Guava Cache3、Caffeine4、Encache本地缓存比如 caff

Java高效实现Word转PDF的完整指南

《Java高效实现Word转PDF的完整指南》这篇文章主要为大家详细介绍了如何用Spire.DocforJava库实现Word到PDF文档的快速转换,并解析其转换选项的灵活配置技巧,希望对大家有所帮助... 目录方法一:三步实现核心功能方法二:高级选项配置性能优化建议方法补充ASPose 实现方案Libre

Go中select多路复用的实现示例

《Go中select多路复用的实现示例》Go的select用于多通道通信,实现多路复用,支持随机选择、超时控制及非阻塞操作,建议合理使用以避免协程泄漏和死循环,感兴趣的可以了解一下... 目录一、什么是select基本语法:二、select 使用示例示例1:监听多个通道输入三、select的特性四、使用se

Java 中编码与解码的具体实现方法

《Java中编码与解码的具体实现方法》在Java中,字符编码与解码是处理数据的重要组成部分,正确的编码和解码可以确保字符数据在存储、传输、读取时不会出现乱码,本文将详细介绍Java中字符编码与解码的... 目录Java 中编码与解码的实现详解1. 什么是字符编码与解码?1.1 字符编码(Encoding)1

Python Flask实现定时任务的不同方法详解

《PythonFlask实现定时任务的不同方法详解》在Flask中实现定时任务,最常用的方法是使用APScheduler库,本文将提供一个完整的解决方案,有需要的小伙伴可以跟随小编一起学习一下... 目录完js整实现方案代码解释1. 依赖安装2. 核心组件3. 任务类型4. 任务管理5. 持久化存储生产环境

详解Java中三种状态机实现方式来优雅消灭 if-else 嵌套

《详解Java中三种状态机实现方式来优雅消灭if-else嵌套》这篇文章主要为大家详细介绍了Java中三种状态机实现方式从而优雅消灭if-else嵌套,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录1. 前言2. 复现传统if-else实现的业务场景问题3. 用状态机模式改造3.1 定义状态接口3

基于Python实现温度单位转换器(新手版)

《基于Python实现温度单位转换器(新手版)》这篇文章主要为大家详细介绍了如何基于Python实现温度单位转换器,主要是将摄氏温度(C)和华氏温度(F)相互转换,下面小编就来和大家简单介绍一下吧... 目录为什么选择温度转换器作为第一个项目项目概述所需基础知识实现步骤详解1. 温度转换公式2. 用户输入处

MySQL实现多源复制的示例代码

《MySQL实现多源复制的示例代码》MySQL的多源复制允许一个从服务器从多个主服务器复制数据,这在需要将多个数据源汇聚到一个数据库实例时非常有用,下面就来详细的介绍一下,感兴趣的可以了解一下... 目录一、多源复制原理二、多源复制配置步骤2.1 主服务器配置Master1配置Master2配置2.2 从服