rumale 0.22.0 → 0.22.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.coveralls.yml +1 -0
- data/.github/workflows/build.yml +6 -3
- data/.github/workflows/coverage.yml +28 -0
- data/.gitignore +1 -0
- data/.rubocop.yml +1 -0
- data/CHANGELOG.md +35 -0
- data/Gemfile +6 -4
- data/LICENSE.txt +1 -1
- data/README.md +56 -19
- data/ext/rumale/tree.c +24 -12
- data/lib/rumale.rb +8 -0
- data/lib/rumale/base/base_estimator.rb +5 -3
- data/lib/rumale/dataset.rb +7 -3
- data/lib/rumale/decomposition/pca.rb +1 -1
- data/lib/rumale/ensemble/stacking_classifier.rb +215 -0
- data/lib/rumale/ensemble/stacking_regressor.rb +163 -0
- data/lib/rumale/ensemble/voting_classifier.rb +126 -0
- data/lib/rumale/ensemble/voting_regressor.rb +82 -0
- data/lib/rumale/feature_extraction/feature_hasher.rb +1 -1
- data/lib/rumale/feature_extraction/hash_vectorizer.rb +1 -1
- data/lib/rumale/kernel_approximation/nystroem.rb +29 -9
- data/lib/rumale/kernel_machine/kernel_ridge_classifier.rb +92 -0
- data/lib/rumale/kernel_machine/kernel_svc.rb +4 -3
- data/lib/rumale/linear_model/elastic_net.rb +1 -1
- data/lib/rumale/linear_model/lasso.rb +1 -1
- data/lib/rumale/linear_model/linear_regression.rb +63 -34
- data/lib/rumale/linear_model/logistic_regression.rb +1 -1
- data/lib/rumale/linear_model/nnls.rb +137 -0
- data/lib/rumale/linear_model/ridge.rb +70 -33
- data/lib/rumale/linear_model/svc.rb +4 -3
- data/lib/rumale/linear_model/svr.rb +4 -3
- data/lib/rumale/metric_learning/mlkr.rb +161 -0
- data/lib/rumale/metric_learning/neighbourhood_component_analysis.rb +7 -4
- data/lib/rumale/pairwise_metric.rb +1 -1
- data/lib/rumale/preprocessing/kernel_calculator.rb +92 -0
- data/lib/rumale/validation.rb +13 -1
- data/lib/rumale/version.rb +1 -1
- data/rumale.gemspec +1 -1
- metadata +14 -4
@@ -181,7 +181,7 @@ module Rumale
|
|
181
181
|
@classes.size > 2
|
182
182
|
end
|
183
183
|
|
184
|
-
def fit_lbfgs(base_x, base_y)
|
184
|
+
def fit_lbfgs(base_x, base_y) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
|
185
185
|
if multiclass_problem?
|
186
186
|
fnc = proc do |w, x, y, a|
|
187
187
|
n_features = x.shape[1]
|
@@ -0,0 +1,137 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'lbfgsb'
|
4
|
+
|
5
|
+
require 'rumale/base/base_estimator'
|
6
|
+
require 'rumale/base/regressor'
|
7
|
+
|
8
|
+
module Rumale
|
9
|
+
module LinearModel
|
10
|
+
# NNLS is a class that implements non-negative least squares regression.
|
11
|
+
# NNLS solves least squares problem under non-negative constraints on the coefficient using L-BFGS-B method.
|
12
|
+
#
|
13
|
+
# @example
|
14
|
+
# estimator = Rumale::LinearModel::NNLS.new(reg_param: 0.01, random_seed: 1)
|
15
|
+
# estimator.fit(training_samples, traininig_values)
|
16
|
+
# results = estimator.predict(testing_samples)
|
17
|
+
#
|
18
|
+
class NNLS
|
19
|
+
include Base::BaseEstimator
|
20
|
+
include Base::Regressor
|
21
|
+
|
22
|
+
# Return the weight vector.
|
23
|
+
# @return [Numo::DFloat] (shape: [n_outputs, n_features])
|
24
|
+
attr_reader :weight_vec
|
25
|
+
|
26
|
+
# Return the bias term (a.k.a. intercept).
|
27
|
+
# @return [Numo::DFloat] (shape: [n_outputs])
|
28
|
+
attr_reader :bias_term
|
29
|
+
|
30
|
+
# Returns the number of iterations when converged.
|
31
|
+
# @return [Integer]
|
32
|
+
attr_reader :n_iter
|
33
|
+
|
34
|
+
# Return the random generator for initializing weight.
|
35
|
+
# @return [Random]
|
36
|
+
attr_reader :rng
|
37
|
+
|
38
|
+
# Create a new regressor with non-negative least squares method.
|
39
|
+
#
|
40
|
+
# @param reg_param [Float] The regularization parameter for L2 regularization term.
|
41
|
+
# @param fit_bias [Boolean] The flag indicating whether to fit the bias term.
|
42
|
+
# @param bias_scale [Float] The scale of the bias term.
|
43
|
+
# @param max_iter [Integer] The maximum number of epochs that indicates
|
44
|
+
# how many times the whole data is given to the training process.
|
45
|
+
# @param tol [Float] The tolerance of loss for terminating optimization.
|
46
|
+
# If solver = 'svd', this parameter is ignored.
|
47
|
+
# @param verbose [Boolean] The flag indicating whether to output loss during iteration.
|
48
|
+
# @param random_seed [Integer] The seed value using to initialize the random generator.
|
49
|
+
def initialize(reg_param: 1.0, fit_bias: true, bias_scale: 1.0,
|
50
|
+
max_iter: 1000, tol: 1e-4, verbose: false, random_seed: nil)
|
51
|
+
check_params_numeric(reg_param: reg_param, bias_scale: bias_scale, max_iter: max_iter, tol: tol)
|
52
|
+
check_params_boolean(fit_bias: fit_bias, verbose: verbose)
|
53
|
+
check_params_numeric_or_nil(random_seed: random_seed)
|
54
|
+
check_params_positive(reg_param: reg_param, max_iter: max_iter)
|
55
|
+
@params = method(:initialize).parameters.each_with_object({}) { |(_, prm), obj| obj[prm] = binding.local_variable_get(prm) }
|
56
|
+
@params[:random_seed] ||= srand
|
57
|
+
@n_iter = nil
|
58
|
+
@weight_vec = nil
|
59
|
+
@bias_term = nil
|
60
|
+
@rng = Random.new(@params[:random_seed])
|
61
|
+
end
|
62
|
+
|
63
|
+
# Fit the model with given training data.
|
64
|
+
#
|
65
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
|
66
|
+
# @param y [Numo::DFloat] (shape: [n_samples, n_outputs]) The target values to be used for fitting the model.
|
67
|
+
# @return [NonneagtiveLeastSquare] The learned regressor itself.
|
68
|
+
def fit(x, y)
|
69
|
+
x = check_convert_sample_array(x)
|
70
|
+
y = check_convert_tvalue_array(y)
|
71
|
+
check_sample_tvalue_size(x, y)
|
72
|
+
|
73
|
+
x = expand_feature(x) if fit_bias?
|
74
|
+
|
75
|
+
n_features = x.shape[1]
|
76
|
+
n_outputs = single_target?(y) ? 1 : y.shape[1]
|
77
|
+
|
78
|
+
w_init = Rumale::Utils.rand_normal([n_outputs, n_features], @rng.dup).flatten.dup
|
79
|
+
w_init[w_init.lt(0)] = 0
|
80
|
+
bounds = Numo::DFloat.zeros(n_outputs * n_features, 2)
|
81
|
+
bounds.shape[0].times { |n| bounds[n, 1] = Float::INFINITY }
|
82
|
+
|
83
|
+
res = Lbfgsb.minimize(
|
84
|
+
fnc: method(:nnls_fnc), jcb: true, x_init: w_init, args: [x, y, @params[:reg_param]], bounds: bounds,
|
85
|
+
maxiter: @params[:max_iter], factr: @params[:tol] / Lbfgsb::DBL_EPSILON, verbose: @params[:verbose] ? 1 : -1
|
86
|
+
)
|
87
|
+
|
88
|
+
@n_iter = res[:n_iter]
|
89
|
+
w = single_target?(y) ? res[:x] : res[:x].reshape(n_outputs, n_features).transpose
|
90
|
+
|
91
|
+
if fit_bias?
|
92
|
+
@weight_vec = single_target?(y) ? w[0...-1].dup : w[0...-1, true].dup
|
93
|
+
@bias_term = single_target?(y) ? w[-1] : w[-1, true].dup
|
94
|
+
else
|
95
|
+
@weight_vec = w.dup
|
96
|
+
@bias_term = single_target?(y) ? 0 : Numo::DFloat.zeros(y.shape[1])
|
97
|
+
end
|
98
|
+
|
99
|
+
self
|
100
|
+
end
|
101
|
+
|
102
|
+
# Predict values for samples.
|
103
|
+
#
|
104
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to predict the values.
|
105
|
+
# @return [Numo::DFloat] (shape: [n_samples, n_outputs]) Predicted values per sample.
|
106
|
+
def predict(x)
|
107
|
+
x = check_convert_sample_array(x)
|
108
|
+
x.dot(@weight_vec.transpose) + @bias_term
|
109
|
+
end
|
110
|
+
|
111
|
+
private
|
112
|
+
|
113
|
+
def nnls_fnc(w, x, y, alpha)
|
114
|
+
n_samples, n_features = x.shape
|
115
|
+
w = w.reshape(y.shape[1], n_features) unless y.shape[1].nil?
|
116
|
+
z = x.dot(w.transpose)
|
117
|
+
d = z - y
|
118
|
+
loss = (d**2).sum.fdiv(n_samples) + alpha * (w * w).sum
|
119
|
+
gradient = 2.fdiv(n_samples) * d.transpose.dot(x) + 2.0 * alpha * w
|
120
|
+
[loss, gradient.flatten.dup]
|
121
|
+
end
|
122
|
+
|
123
|
+
def expand_feature(x)
|
124
|
+
n_samples = x.shape[0]
|
125
|
+
Numo::NArray.hstack([x, Numo::DFloat.ones([n_samples, 1]) * @params[:bias_scale]])
|
126
|
+
end
|
127
|
+
|
128
|
+
def fit_bias?
|
129
|
+
@params[:fit_bias] == true
|
130
|
+
end
|
131
|
+
|
132
|
+
def single_target?(y)
|
133
|
+
y.ndim == 1
|
134
|
+
end
|
135
|
+
end
|
136
|
+
end
|
137
|
+
end
|
@@ -1,12 +1,15 @@
|
|
1
1
|
# frozen_string_literal: true
|
2
2
|
|
3
|
+
require 'lbfgsb'
|
4
|
+
|
3
5
|
require 'rumale/linear_model/base_sgd'
|
4
6
|
require 'rumale/base/regressor'
|
5
7
|
|
6
8
|
module Rumale
|
7
9
|
module LinearModel
|
8
10
|
# Ridge is a class that implements Ridge Regression
|
9
|
-
# with stochastic gradient descent (SGD) optimization
|
11
|
+
# with stochastic gradient descent (SGD) optimization,
|
12
|
+
# singular value decomposition (SVD), or L-BFGS optimization.
|
10
13
|
#
|
11
14
|
# @example
|
12
15
|
# estimator =
|
@@ -41,32 +44,33 @@ module Rumale
|
|
41
44
|
#
|
42
45
|
# @param learning_rate [Float] The initial value of learning rate.
|
43
46
|
# The learning rate decreases as the iteration proceeds according to the equation: learning_rate / (1 + decay * t).
|
44
|
-
# If solver
|
47
|
+
# If solver is not 'sgd', this parameter is ignored.
|
45
48
|
# @param decay [Float] The smoothing parameter for decreasing learning rate as the iteration proceeds.
|
46
49
|
# If nil is given, the decay sets to 'reg_param * learning_rate'.
|
47
|
-
# If solver
|
50
|
+
# If solver is not 'sgd', this parameter is ignored.
|
48
51
|
# @param momentum [Float] The momentum factor.
|
49
|
-
# If solver
|
52
|
+
# If solver is not 'sgd', this parameter is ignored.
|
50
53
|
# @param reg_param [Float] The regularization parameter.
|
51
54
|
# @param fit_bias [Boolean] The flag indicating whether to fit the bias term.
|
52
55
|
# @param bias_scale [Float] The scale of the bias term.
|
53
56
|
# @param max_iter [Integer] The maximum number of epochs that indicates
|
54
57
|
# how many times the whole data is given to the training process.
|
55
|
-
# If solver
|
58
|
+
# If solver is 'svd', this parameter is ignored.
|
56
59
|
# @param batch_size [Integer] The size of the mini batches.
|
57
|
-
# If solver
|
60
|
+
# If solver is not 'sgd', this parameter is ignored.
|
58
61
|
# @param tol [Float] The tolerance of loss for terminating optimization.
|
59
|
-
# If solver
|
60
|
-
# @param solver [String] The algorithm to calculate weights. ('auto', 'sgd' or '
|
62
|
+
# If solver is 'svd', this parameter is ignored.
|
63
|
+
# @param solver [String] The algorithm to calculate weights. ('auto', 'sgd', 'svd', or 'lbfgs').
|
61
64
|
# 'auto' chooses the 'svd' solver if Numo::Linalg is loaded. Otherwise, it chooses the 'sgd' solver.
|
62
65
|
# 'sgd' uses the stochastic gradient descent optimization.
|
63
66
|
# 'svd' performs singular value decomposition of samples.
|
67
|
+
# 'lbfgs' uses the L-BFGS method for optimization.
|
64
68
|
# @param n_jobs [Integer] The number of jobs for running the fit method in parallel.
|
65
69
|
# If nil is given, the method does not execute in parallel.
|
66
70
|
# If zero or less is given, it becomes equal to the number of processors.
|
67
|
-
# This parameter is ignored if the Parallel gem is not loaded or
|
71
|
+
# This parameter is ignored if the Parallel gem is not loaded or solver is not 'sgd'.
|
68
72
|
# @param verbose [Boolean] The flag indicating whether to output loss during iteration.
|
69
|
-
# If solver
|
73
|
+
# If solver is 'svd', this parameter is ignored.
|
70
74
|
# @param random_seed [Integer] The seed value using to initialize the random generator.
|
71
75
|
def initialize(learning_rate: 0.01, decay: nil, momentum: 0.9,
|
72
76
|
reg_param: 1.0, fit_bias: true, bias_scale: 1.0,
|
@@ -83,9 +87,9 @@ module Rumale
|
|
83
87
|
super()
|
84
88
|
@params.merge!(method(:initialize).parameters.map { |_t, arg| [arg, binding.local_variable_get(arg)] }.to_h)
|
85
89
|
@params[:solver] = if solver == 'auto'
|
86
|
-
|
90
|
+
enable_linalg?(warning: false) ? 'svd' : 'sgd'
|
87
91
|
else
|
88
|
-
solver
|
92
|
+
solver.match?(/^svd$|^sgd$|^lbfgs$/) ? solver : 'sgd'
|
89
93
|
end
|
90
94
|
@params[:decay] ||= @params[:reg_param] * @params[:learning_rate]
|
91
95
|
@params[:random_seed] ||= srand
|
@@ -99,15 +103,17 @@ module Rumale
|
|
99
103
|
# Fit the model with given training data.
|
100
104
|
#
|
101
105
|
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
|
102
|
-
# @param y [Numo::
|
106
|
+
# @param y [Numo::DFloat] (shape: [n_samples, n_outputs]) The target values to be used for fitting the model.
|
103
107
|
# @return [Ridge] The learned regressor itself.
|
104
108
|
def fit(x, y)
|
105
109
|
x = check_convert_sample_array(x)
|
106
110
|
y = check_convert_tvalue_array(y)
|
107
111
|
check_sample_tvalue_size(x, y)
|
108
112
|
|
109
|
-
if @params[:solver] == 'svd' && enable_linalg?
|
113
|
+
if @params[:solver] == 'svd' && enable_linalg?(warning: false)
|
110
114
|
fit_svd(x, y)
|
115
|
+
elsif @params[:solver] == 'lbfgs'
|
116
|
+
fit_lbfgs(x, y)
|
111
117
|
else
|
112
118
|
fit_sgd(x, y)
|
113
119
|
end
|
@@ -127,27 +133,51 @@ module Rumale
|
|
127
133
|
private
|
128
134
|
|
129
135
|
def fit_svd(x, y)
|
130
|
-
|
136
|
+
x = expand_feature(x) if fit_bias?
|
131
137
|
|
132
|
-
s, u, vt = Numo::Linalg.svd(
|
138
|
+
s, u, vt = Numo::Linalg.svd(x, driver: 'sdd', job: 'S')
|
133
139
|
d = (s / (s**2 + @params[:reg_param])).diag
|
134
140
|
w = vt.transpose.dot(d).dot(u.transpose).dot(y)
|
135
141
|
|
136
|
-
|
137
|
-
if @params[:fit_bias]
|
138
|
-
@weight_vec = is_single_target_vals ? w[0...-1].dup : w[0...-1, true].dup
|
139
|
-
@bias_term = is_single_target_vals ? w[-1] : w[-1, true].dup
|
140
|
-
else
|
141
|
-
@weight_vec = w.dup
|
142
|
-
@bias_term = is_single_target_vals ? 0 : Numo::DFloat.zeros(y.shape[1])
|
143
|
-
end
|
142
|
+
@weight_vec, @bias_term = single_target?(y) ? split_weight(w) : split_weight_mult(w)
|
144
143
|
end
|
145
144
|
|
146
|
-
def
|
147
|
-
|
145
|
+
def fit_lbfgs(x, y)
|
146
|
+
fnc = proc do |w, x, y, a| # rubocop:disable Lint/ShadowingOuterLocalVariable
|
147
|
+
n_samples, n_features = x.shape
|
148
|
+
w = w.reshape(y.shape[1], n_features) unless y.shape[1].nil?
|
149
|
+
z = x.dot(w.transpose)
|
150
|
+
d = z - y
|
151
|
+
loss = (d**2).sum.fdiv(n_samples) + a * (w * w).sum
|
152
|
+
gradient = 2.fdiv(n_samples) * d.transpose.dot(x) + 2.0 * a * w
|
153
|
+
[loss, gradient.flatten.dup]
|
154
|
+
end
|
155
|
+
|
156
|
+
x = expand_feature(x) if fit_bias?
|
157
|
+
|
148
158
|
n_features = x.shape[1]
|
159
|
+
n_outputs = single_target?(y) ? 1 : y.shape[1]
|
160
|
+
|
161
|
+
res = Lbfgsb.minimize(
|
162
|
+
fnc: fnc, jcb: true, x_init: init_weight(n_features, n_outputs), args: [x, y, @params[:reg_param]],
|
163
|
+
maxiter: @params[:max_iter], factr: @params[:tol] / Lbfgsb::DBL_EPSILON,
|
164
|
+
verbose: @params[:verbose] ? 1 : -1
|
165
|
+
)
|
166
|
+
|
167
|
+
@weight_vec, @bias_term =
|
168
|
+
if single_target?(y)
|
169
|
+
split_weight(res[:x])
|
170
|
+
else
|
171
|
+
split_weight_mult(res[:x].reshape(n_outputs, n_features).transpose)
|
172
|
+
end
|
173
|
+
end
|
149
174
|
|
150
|
-
|
175
|
+
def fit_sgd(x, y)
|
176
|
+
if single_target?(y)
|
177
|
+
@weight_vec, @bias_term = partial_fit(x, y)
|
178
|
+
else
|
179
|
+
n_outputs = y.shape[1]
|
180
|
+
n_features = x.shape[1]
|
151
181
|
@weight_vec = Numo::DFloat.zeros(n_outputs, n_features)
|
152
182
|
@bias_term = Numo::DFloat.zeros(n_outputs)
|
153
183
|
if enable_parallel?
|
@@ -156,16 +186,23 @@ module Rumale
|
|
156
186
|
else
|
157
187
|
n_outputs.times { |n| @weight_vec[n, true], @bias_term[n] = partial_fit(x, y[true, n]) }
|
158
188
|
end
|
159
|
-
else
|
160
|
-
@weight_vec, @bias_term = partial_fit(x, y)
|
161
189
|
end
|
162
190
|
end
|
163
191
|
|
164
|
-
def
|
165
|
-
|
166
|
-
|
192
|
+
def single_target?(y)
|
193
|
+
y.ndim == 1
|
194
|
+
end
|
195
|
+
|
196
|
+
def init_weight(n_features, n_outputs)
|
197
|
+
Rumale::Utils.rand_normal([n_outputs, n_features], @rng.dup).flatten.dup
|
198
|
+
end
|
167
199
|
|
168
|
-
|
200
|
+
def split_weight_mult(w)
|
201
|
+
if fit_bias?
|
202
|
+
[w[0...-1, true].dup, w[-1, true].dup]
|
203
|
+
else
|
204
|
+
[w.dup, Numo::DFloat.zeros(w.shape[1])]
|
205
|
+
end
|
169
206
|
end
|
170
207
|
end
|
171
208
|
end
|
@@ -11,9 +11,10 @@ module Rumale
|
|
11
11
|
# with stochastic gradient descent optimization.
|
12
12
|
# For multiclass classification problem, it uses one-vs-the-rest strategy.
|
13
13
|
#
|
14
|
-
#
|
15
|
-
#
|
16
|
-
#
|
14
|
+
# @note
|
15
|
+
# Rumale::SVM provides linear support vector classifier based on LIBLINEAR.
|
16
|
+
# If you prefer execution speed, you should use Rumale::SVM::LinearSVC.
|
17
|
+
# https://github.com/yoshoku/rumale-svm
|
17
18
|
#
|
18
19
|
# @example
|
19
20
|
# estimator =
|
@@ -8,9 +8,10 @@ module Rumale
|
|
8
8
|
# SVR is a class that implements Support Vector Regressor
|
9
9
|
# with stochastic gradient descent optimization.
|
10
10
|
#
|
11
|
-
#
|
12
|
-
#
|
13
|
-
#
|
11
|
+
# @note
|
12
|
+
# Rumale::SVM provides linear and kernel support vector regressor based on LIBLINEAR and LIBSVM.
|
13
|
+
# If you prefer execution speed, you should use Rumale::SVM::LinearSVR.
|
14
|
+
# https://github.com/yoshoku/rumale-svm
|
14
15
|
#
|
15
16
|
# @example
|
16
17
|
# estimator =
|
@@ -0,0 +1,161 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'rumale/base/base_estimator'
|
4
|
+
require 'rumale/base/transformer'
|
5
|
+
require 'rumale/decomposition/pca'
|
6
|
+
require 'rumale/pairwise_metric'
|
7
|
+
require 'rumale/utils'
|
8
|
+
require 'lbfgsb'
|
9
|
+
|
10
|
+
module Rumale
|
11
|
+
module MetricLearning
|
12
|
+
# MLKR is a class that implements Metric Learning for Kernel Regression.
|
13
|
+
#
|
14
|
+
# @example
|
15
|
+
# transformer = Rumale::MetricLearning::MLKR.new
|
16
|
+
# transformer.fit(training_samples, traininig_target_values)
|
17
|
+
# low_samples = transformer.transform(testing_samples)
|
18
|
+
#
|
19
|
+
# *Reference*
|
20
|
+
# - Weinberger, K. Q. and Tesauro, G., "Metric Learning for Kernel Regression," Proc. AISTATS'07, pp. 612--629, 2007.
|
21
|
+
class MLKR
|
22
|
+
include Base::BaseEstimator
|
23
|
+
include Base::Transformer
|
24
|
+
|
25
|
+
# Returns the metric components.
|
26
|
+
# @return [Numo::DFloat] (shape: [n_components, n_features])
|
27
|
+
attr_reader :components
|
28
|
+
|
29
|
+
# Return the number of iterations run for optimization
|
30
|
+
# @return [Integer]
|
31
|
+
attr_reader :n_iter
|
32
|
+
|
33
|
+
# Return the random generator.
|
34
|
+
# @return [Random]
|
35
|
+
attr_reader :rng
|
36
|
+
|
37
|
+
# Create a new transformer with MLKR.
|
38
|
+
#
|
39
|
+
# @param n_components [Integer] The number of components.
|
40
|
+
# @param init [String] The initialization method for components ('random' or 'pca').
|
41
|
+
# @param max_iter [Integer] The maximum number of iterations.
|
42
|
+
# @param tol [Float] The tolerance of termination criterion.
|
43
|
+
# This value is given as tol / Lbfgsb::DBL_EPSILON to the factr argument of Lbfgsb.minimize method.
|
44
|
+
# @param verbose [Boolean] The flag indicating whether to output loss during iteration.
|
45
|
+
# If true is given, 'iterate.dat' file is generated by lbfgsb.rb.
|
46
|
+
# @param random_seed [Integer] The seed value using to initialize the random generator.
|
47
|
+
def initialize(n_components: nil, init: 'random', max_iter: 100, tol: 1e-6, verbose: false, random_seed: nil)
|
48
|
+
check_params_numeric_or_nil(n_components: n_components, random_seed: random_seed)
|
49
|
+
check_params_numeric(max_iter: max_iter, tol: tol)
|
50
|
+
check_params_string(init: init)
|
51
|
+
check_params_boolean(verbose: verbose)
|
52
|
+
@params = {}
|
53
|
+
@params[:n_components] = n_components
|
54
|
+
@params[:init] = init
|
55
|
+
@params[:max_iter] = max_iter
|
56
|
+
@params[:tol] = tol
|
57
|
+
@params[:verbose] = verbose
|
58
|
+
@params[:random_seed] = random_seed
|
59
|
+
@params[:random_seed] ||= srand
|
60
|
+
@components = nil
|
61
|
+
@n_iter = nil
|
62
|
+
@rng = Random.new(@params[:random_seed])
|
63
|
+
end
|
64
|
+
|
65
|
+
# Fit the model with given training data.
|
66
|
+
#
|
67
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
|
68
|
+
# @param y [Numo::DFloat] (shape: [n_samples]) The target values to be used for fitting the model.
|
69
|
+
# @return [MLKR] The learned classifier itself.
|
70
|
+
def fit(x, y)
|
71
|
+
x = check_convert_sample_array(x)
|
72
|
+
y = check_convert_tvalue_array(y)
|
73
|
+
check_sample_tvalue_size(x, y)
|
74
|
+
n_features = x.shape[1]
|
75
|
+
n_components = if @params[:n_components].nil?
|
76
|
+
n_features
|
77
|
+
else
|
78
|
+
[n_features, @params[:n_components]].min
|
79
|
+
end
|
80
|
+
@components, @n_iter = optimize_components(x, y, n_features, n_components)
|
81
|
+
@prototypes = x.dot(@components.transpose)
|
82
|
+
@values = y
|
83
|
+
self
|
84
|
+
end
|
85
|
+
|
86
|
+
# Fit the model with training data, and then transform them with the learned model.
|
87
|
+
#
|
88
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
|
89
|
+
# @param y [Numo::DFloat] (shape: [n_samples]) The target values to be used for fitting the model.
|
90
|
+
# @return [Numo::DFloat] (shape: [n_samples, n_components]) The transformed data
|
91
|
+
def fit_transform(x, y)
|
92
|
+
x = check_convert_sample_array(x)
|
93
|
+
y = check_convert_tvalue_array(y)
|
94
|
+
check_sample_tvalue_size(x, y)
|
95
|
+
fit(x, y).transform(x)
|
96
|
+
end
|
97
|
+
|
98
|
+
# Transform the given data with the learned model.
|
99
|
+
#
|
100
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The data to be transformed with the learned model.
|
101
|
+
# @return [Numo::DFloat] (shape: [n_samples, n_components]) The transformed data.
|
102
|
+
def transform(x)
|
103
|
+
x = check_convert_sample_array(x)
|
104
|
+
x.dot(@components.transpose)
|
105
|
+
end
|
106
|
+
|
107
|
+
private
|
108
|
+
|
109
|
+
def init_components(x, n_features, n_components)
|
110
|
+
if @params[:init] == 'pca'
|
111
|
+
pca = Rumale::Decomposition::PCA.new(n_components: n_components)
|
112
|
+
pca.fit(x).components.flatten.dup
|
113
|
+
else
|
114
|
+
Rumale::Utils.rand_normal([n_features, n_components], @rng.dup).flatten.dup
|
115
|
+
end
|
116
|
+
end
|
117
|
+
|
118
|
+
def optimize_components(x, y, n_features, n_components)
|
119
|
+
# initialize components.
|
120
|
+
comp_init = init_components(x, n_features, n_components)
|
121
|
+
# initialize optimization results.
|
122
|
+
res = {}
|
123
|
+
res[:x] = comp_init
|
124
|
+
res[:n_iter] = 0
|
125
|
+
# perform optimization.
|
126
|
+
verbose = @params[:verbose] ? 1 : -1
|
127
|
+
res = Lbfgsb.minimize(
|
128
|
+
fnc: method(:mlkr_fnc), jcb: true, x_init: comp_init, args: [x, y],
|
129
|
+
maxiter: @params[:max_iter], factr: @params[:tol] / Lbfgsb::DBL_EPSILON, verbose: verbose
|
130
|
+
)
|
131
|
+
# return the results.
|
132
|
+
n_iter = res[:n_iter]
|
133
|
+
comps = n_components == 1 ? res[:x].dup : res[:x].reshape(n_components, n_features)
|
134
|
+
[comps, n_iter]
|
135
|
+
end
|
136
|
+
|
137
|
+
def mlkr_fnc(w, x, y)
|
138
|
+
# initialize some variables.
|
139
|
+
n_features = x.shape[1]
|
140
|
+
n_components = w.size / n_features
|
141
|
+
# projection.
|
142
|
+
w = w.reshape(n_components, n_features)
|
143
|
+
z = x.dot(w.transpose)
|
144
|
+
# predict values.
|
145
|
+
kernel_mat = Numo::NMath.exp(-Rumale::PairwiseMetric.squared_error(z))
|
146
|
+
kernel_mat[kernel_mat.diag_indices] = 0.0
|
147
|
+
norm = kernel_mat.sum(1)
|
148
|
+
norm[norm.eq(0)] = 1
|
149
|
+
y_pred = kernel_mat.dot(y) / norm
|
150
|
+
# calculate loss.
|
151
|
+
y_diff = y_pred - y
|
152
|
+
loss = (y_diff**2).sum
|
153
|
+
# calculate gradient.
|
154
|
+
weight_mat = y_diff * y_diff.expand_dims(1) * kernel_mat
|
155
|
+
weight_mat = weight_mat.sum(0).diag - weight_mat
|
156
|
+
gradient = 8 * z.transpose.dot(weight_mat).dot(x)
|
157
|
+
[loss, gradient.flatten.dup]
|
158
|
+
end
|
159
|
+
end
|
160
|
+
end
|
161
|
+
end
|