% Random Kitchen Sinks (RKS) for Least squares kernel regression
% 
% 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 = 1;
Xtrain = randn(N,d);Ytrain = sin(Xtrain) + .1*randn(N,d);
Xtest = randn(M,d);Ytest = sin(Xtest) + .1*randn(M,d);

% Training
D      = 100; % number of random features
lambda = 1e-3;    % regularization parameter
sigma  = 1; % 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  = real(Ztest*alpha); % M x 1

% RMSE
norm(Ypred - Ytest)/sqrt(length(Ypred))

figure,plot(Xtrain,Ytrain,'.'), hold on,
x=(min(Xtrain):.01:max(Xtrain))';
plot(x,real(exp(1i*x*W')*alpha),'r-','linewidth',2)
legend('training set', 'fitted curve'), grid on