Here, we imagine that we want to use linear regression with a Gaussian kernel to fit a noisy sine wave.
using PyPlot
using Random
using LinearAlgebra
import Statistics.mean
Random.seed!(123456);
N = 10000; # size of data set
x = 6 * rand(N);
y = sin.(x.^2) .+ 0.2 * randn(N);
scatter(x,y; s=1);
plot(collect(0:0.01:6), sin.(collect(0:0.01:6).^2), "--k"; linewidth=1);
xlabel("x");
ylabel("y");
title("Training Set");
gamma = 100;
function K(x1, x2)
return exp(-gamma*(x1 - x2)^2/2);
end
# compute the Gram matrix
@time begin
G = zeros(N, N);
for i = 1:N
for j = 1:N
G[i,j] = K(x[i], x[j]);
end
end
end
# actually solve the regularized linear regression problem
@time w = (G + 0.001 * LinearAlgebra.I) \ y;
function predict(xt :: Float64)
rv = 0.0;
for i = 1:N
rv += w[i] * K(x[i], xt);
end
return rv;
end
scatter(x,y; s=1);
x_test = collect(0:0.01:6);
y_test = sin.(x_test.^2);
y_pred = predict.(x_test);
plot(x_test, y_pred, "k"; linewidth=1);
xlabel("x");
ylabel("y");
title("Learned model: Gram matrix");
println("average test error: $(sqrt(mean((y_test - y_pred).^2)))")
D = 1000;
U = randn(D) * sqrt(gamma);
b = 2 * pi * rand(D);
# compute the feature map
@time begin
phi = zeros(N, D);
for i = 1:N
for j = 1:D
phi[i,j] = sqrt(2)*cos(U[j] * x[i] + b[j]);
end
end
end
# actually solve the (now not regularized) linear regression problem
@time w_rff = (phi' * phi + 0.001 * LinearAlgebra.I) \ (phi' * y);
function predict_rff(xt :: Float64)
phi_xt = sqrt(2)*cos.(U .* xt .+ b);
return dot(phi_xt, w_rff);
end
scatter(x,y; s=1);
x_test = collect(0:0.01:6);
y_test = sin.(x_test.^2);
y_pred = predict_rff.(x_test);
plot(x_test, y_pred, "k"; linewidth=1);
xlabel("x");
ylabel("y");
title("Learned model: Random Fourier features");
println("average test error: $(sqrt(mean((y_test - y_pred).^2)))")