lib/svmkit/kernel_approximation/rbf.rb in svmkit-0.2.7 vs lib/svmkit/kernel_approximation/rbf.rb in svmkit-0.2.8
- old
+ new
@@ -35,28 +35,34 @@
#
# @param gamma [Float] The parameter of RBF kernel: exp(-gamma * x^2).
# @param n_components [Integer] The number of dimensions of the RBF kernel feature space.
# @param random_seed [Integer] The seed value using to initialize the random generator.
def initialize(gamma: 1.0, n_components: 128, random_seed: nil)
+ SVMKit::Validation.check_params_float(gamma: gamma)
+ SVMKit::Validation.check_params_integer(n_components: n_components)
+ SVMKit::Validation.check_params_type_or_nil(Integer, random_seed: random_seed)
+
@params = {}
@params[:gamma] = gamma
@params[:n_components] = n_components
@params[:random_seed] = random_seed
@params[:random_seed] ||= srand
- @rng = Random.new(@params[:random_seed])
@random_mat = nil
@random_vec = nil
+ @rng = Random.new(@params[:random_seed])
end
# Fit the model with given training data.
#
# @overload fit(x) -> RBF
#
# @param x [Numo::NArray] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
# This method uses only the number of features of the data.
# @return [RBF] The learned transformer itself.
def fit(x, _y = nil)
+ SVMKit::Validation.check_sample_array(x)
+
n_features = x.shape[1]
@params[:n_components] = 2 * n_features if @params[:n_components] <= 0
@random_mat = rand_normal([n_features, @params[:n_components]]) * (2.0 * @params[:gamma])**0.5
n_half_components = @params[:n_components] / 2
@random_vec = Numo::DFloat.zeros(@params[:n_components] - n_half_components).concatenate(
@@ -70,19 +76,23 @@
# @overload fit_transform(x) -> Numo::DFloat
#
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
# @return [Numo::DFloat] (shape: [n_samples, n_components]) The transformed data
def fit_transform(x, _y = nil)
+ SVMKit::Validation.check_sample_array(x)
+
fit(x).transform(x)
end
# Transform the given data with the learned model.
#
# @overload transform(x) -> Numo::DFloat
#
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The data to be transformed with the learned model.
# @return [Numo::DFloat] (shape: [n_samples, n_components]) The transformed data.
def transform(x)
+ SVMKit::Validation.check_sample_array(x)
+
n_samples, = x.shape
projection = x.dot(@random_mat) + @random_vec.tile(n_samples, 1)
Numo::NMath.sin(projection) * ((2.0 / @params[:n_components])**0.5)
end