Skip to content

Commit

Permalink
🎨 Refactor KernelPCA for performance
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshoku committed Apr 5, 2020
1 parent f17183b commit 2d6d95d
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/rumale/kernel_machine/kernel_pca.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def initialize(n_components: 2)
@params[:n_components] = n_components
@alphas = nil
@lambdas = nil
@transform_mat = nil
@row_mean = nil
@all_mean = nil
end
Expand All @@ -63,6 +64,7 @@ def fit(x, _y = nil)
eig_vals, eig_vecs = Numo::Linalg.eigh(centered_kernel_mat, vals_range: (n_samples - @params[:n_components])...n_samples)
@alphas = eig_vecs.reverse(1).dup
@lambdas = eig_vals.reverse.dup
@transform_mat = @alphas.dot((1.0 / Numo::NMath.sqrt(@lambdas)).diag)
self
end

Expand All @@ -87,8 +89,7 @@ def transform(x)
x = check_convert_sample_array(x)
col_mean = x.sum(1) / @row_mean.shape[0]
centered_kernel_mat = x - col_mean.expand_dims(1) - @row_mean + @all_mean
transform_mat = @alphas.dot((1.0 / Numo::NMath.sqrt(@lambdas)).diag)
transformed = centered_kernel_mat.dot(transform_mat)
transformed = centered_kernel_mat.dot(@transform_mat)
@params[:n_components] == 1 ? transformed[true, 0].dup : transformed
end
end
Expand Down

0 comments on commit 2d6d95d

Please sign in to comment.