% Random Kitchen Sinks (RKS) for Least squares kernel classification
% 
% We are given the following training-test data matrices
% Xtrain: N x d, Xtest: M x d
% Ytrain: N x 1, Ytest: M x 1

close all, clear, clc

% synthetic sample data
N = 1e4;M = 1e3;d = 2;
Xtrain = [randn(N/2,d); 3+randn(N/2,d)];Ytrain = [ones(N/2,1); -ones(N/2,1)];
Xtest = [randn(M/2,d); 3+randn(M/2,d)];Ytest = [ones(M/2,1); -ones(M/2,1)];

% Training
D      = 100; % number of random features
lambda = 1e-9;    % regularization parameter
sigma  = 2; % kernel parameter
W      = (1/sigma)*randn(D,d);   % Random projection matrix
Z      = exp(1i*Xtrain*W');  % Explicitly projected features, N x D
alpha  = (Z'*Z + lambda*eye(D) )\(Z'*Ytrain);  % Primal weights, D x 1

% Testing
Ztest  = exp(1i*Xtest*W'); % M x D
Ypred  = sign(real(Ztest*alpha)); % M x 1

% Overall Accuracy
acc = sum(Ypred == Ytest)/length(Ypred)

% Plot
figure,scatter(Xtrain(1:N/2,1),Xtrain(1:N/2,2),'+'), hold on,
scatter(Xtrain(N/2+1:end,1),Xtrain(N/2+1:end,2),'ro')
x=(min(Xtrain(:,1)):.05:max(Xtrain(:,1)))';
y=(min(Xtrain(:,2)):.05:max(Xtrain(:,2)))';
for i=1:length(x)
    for j=1:length(y)
        if abs(real(exp(1i*[x(i) y(j)]*W')*alpha)) < 1e-1
            plot(x(i),y(j),'k-')
        end
    end
end
xlabel('feature 1'), ylabel('feature 2')
legend('class +1', 'class -1','decission boundary'),grid on
