% Tony Hyun Kim
% CS 246, PS #2, Problem 1(d)

%% Collaborative filtering
clear all;

% Load data
R = sparse(load('user-shows.txt')); % Gotta save memory
% R(5000,1:100) = zeros(1,100);
fid = fopen('shows.txt','r'); 
C = textscan(fid,'%q'); C = C{1};
fclose(fid);

% Compute P and Q
% P = diag(sum(R,2));
% Q = diag(sum(R));

% User-user collaborative filtering
% Pinvsqrt = sparse(diag(1./sqrt(sum(R,2))));
% Rn = Pinvsqrt*R;
% Su = Rn*Rn'; % This is a 1 GB matrix
% Gamma = Su*R;

% Item-item collaborative filtering
Qinvsqrt = sparse(diag(1./sqrt(sum(R))));
Rn = R*Qinvsqrt;
Si = Rn'*Rn;
Gamma = R*Si;

% Recommendations for Alex (ID = 5000)
id = 500;
alex = full(Gamma(id,1:100)); % Look at the first 100 entries only
[~, sortIdx] = sort(alex,'descend');

% Print out top recommendations
for i = 1:5
    fprintf('%d: %s (%.3f)\n',i,C{sortIdx(i)},alex(sortIdx(i)));
end

%% Test the predictions against Alex's true ratings
alex0 = load('alex.txt');

ks = 1:19;
precision = zeros(1,length(ks));
for k = ks
    precision(k) = sum(alex0(sortIdx(1:k)))/k;
end
plot(ks,precision,'r.-','MarkerSize',14);
xlabel('Number of recommendations, k');
ylabel('Fraction of top-k shows watched by Alex');
grid on;
hold on;
ylim([0 1]);