rumale 0.18.6 → 0.19.3
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/.rubocop.yml +80 -3
- data/CHANGELOG.md +45 -0
- data/Gemfile +2 -0
- data/README.md +5 -36
- data/lib/rumale.rb +5 -0
- data/lib/rumale/base/base_estimator.rb +2 -0
- data/lib/rumale/clustering/dbscan.rb +4 -0
- data/lib/rumale/clustering/gaussian_mixture.rb +2 -0
- data/lib/rumale/clustering/hdbscan.rb +3 -1
- data/lib/rumale/clustering/k_means.rb +2 -1
- data/lib/rumale/clustering/k_medoids.rb +5 -1
- data/lib/rumale/clustering/mini_batch_k_means.rb +139 -0
- data/lib/rumale/clustering/power_iteration.rb +2 -0
- data/lib/rumale/clustering/single_linkage.rb +2 -0
- data/lib/rumale/dataset.rb +5 -3
- data/lib/rumale/decomposition/factor_analysis.rb +2 -0
- data/lib/rumale/decomposition/pca.rb +24 -5
- data/lib/rumale/ensemble/ada_boost_classifier.rb +3 -0
- data/lib/rumale/ensemble/ada_boost_regressor.rb +3 -0
- data/lib/rumale/evaluation_measure/function.rb +2 -1
- data/lib/rumale/evaluation_measure/normalized_mutual_information.rb +2 -0
- data/lib/rumale/evaluation_measure/precision_recall.rb +5 -0
- data/lib/rumale/evaluation_measure/roc_auc.rb +3 -0
- data/lib/rumale/evaluation_measure/silhouette_score.rb +2 -0
- data/lib/rumale/feature_extraction/feature_hasher.rb +14 -1
- data/lib/rumale/feature_extraction/hash_vectorizer.rb +1 -0
- data/lib/rumale/feature_extraction/tfidf_transformer.rb +113 -0
- data/lib/rumale/kernel_approximation/nystroem.rb +1 -1
- data/lib/rumale/kernel_machine/kernel_ridge.rb +2 -0
- data/lib/rumale/kernel_machine/kernel_svc.rb +1 -1
- data/lib/rumale/linear_model/base_linear_model.rb +3 -1
- data/lib/rumale/linear_model/base_sgd.rb +1 -1
- data/lib/rumale/linear_model/linear_regression.rb +1 -0
- data/lib/rumale/linear_model/ridge.rb +1 -0
- data/lib/rumale/manifold/mds.rb +2 -0
- data/lib/rumale/manifold/tsne.rb +4 -0
- data/lib/rumale/metric_learning/neighbourhood_component_analysis.rb +14 -1
- data/lib/rumale/model_selection/cross_validation.rb +3 -2
- data/lib/rumale/model_selection/grid_search_cv.rb +1 -0
- data/lib/rumale/model_selection/k_fold.rb +1 -1
- data/lib/rumale/model_selection/shuffle_split.rb +1 -1
- data/lib/rumale/multiclass/one_vs_rest_classifier.rb +2 -2
- data/lib/rumale/nearest_neighbors/k_neighbors_classifier.rb +1 -0
- data/lib/rumale/nearest_neighbors/k_neighbors_regressor.rb +2 -0
- data/lib/rumale/nearest_neighbors/vp_tree.rb +1 -1
- data/lib/rumale/neural_network/adam.rb +1 -1
- data/lib/rumale/neural_network/base_mlp.rb +2 -1
- data/lib/rumale/optimizer/ada_grad.rb +3 -0
- data/lib/rumale/optimizer/adam.rb +3 -0
- data/lib/rumale/optimizer/nadam.rb +5 -0
- data/lib/rumale/optimizer/rmsprop.rb +3 -0
- data/lib/rumale/optimizer/sgd.rb +3 -0
- data/lib/rumale/optimizer/yellow_fin.rb +3 -0
- data/lib/rumale/pipeline/pipeline.rb +3 -0
- data/lib/rumale/polynomial_model/base_factorization_machine.rb +6 -1
- data/lib/rumale/polynomial_model/factorization_machine_classifier.rb +5 -0
- data/lib/rumale/polynomial_model/factorization_machine_regressor.rb +5 -0
- data/lib/rumale/preprocessing/binarizer.rb +60 -0
- data/lib/rumale/preprocessing/l1_normalizer.rb +62 -0
- data/lib/rumale/preprocessing/l2_normalizer.rb +2 -1
- data/lib/rumale/preprocessing/max_normalizer.rb +62 -0
- data/lib/rumale/preprocessing/one_hot_encoder.rb +3 -0
- data/lib/rumale/preprocessing/ordinal_encoder.rb +2 -0
- data/lib/rumale/preprocessing/polynomial_features.rb +1 -0
- data/lib/rumale/probabilistic_output.rb +2 -0
- data/lib/rumale/tree/base_decision_tree.rb +2 -0
- data/lib/rumale/tree/decision_tree_classifier.rb +1 -0
- data/lib/rumale/tree/gradient_tree_regressor.rb +1 -0
- data/lib/rumale/utils.rb +1 -0
- data/lib/rumale/validation.rb +7 -0
- data/lib/rumale/version.rb +1 -1
- data/rumale.gemspec +1 -3
- metadata +11 -34
@@ -71,6 +71,7 @@ module Rumale
|
|
71
71
|
def fit(x, _y = nil)
|
72
72
|
x = check_convert_sample_array(x)
|
73
73
|
raise ArgumentError, 'Expect the input affinity matrix to be square.' if @params[:affinity] == 'precomputed' && x.shape[0] != x.shape[1]
|
74
|
+
|
74
75
|
fit_predict(x)
|
75
76
|
self
|
76
77
|
end
|
@@ -107,6 +108,7 @@ module Rumale
|
|
107
108
|
new_embedded_line /= new_embedded_line.abs.sum
|
108
109
|
new_error = (new_embedded_line - embedded_line).abs
|
109
110
|
break if (new_error - error).abs.max <= tol
|
111
|
+
|
110
112
|
embedded_line = new_embedded_line
|
111
113
|
error = new_error
|
112
114
|
end
|
@@ -54,6 +54,7 @@ module Rumale
|
|
54
54
|
def fit(x, _y = nil)
|
55
55
|
x = check_convert_sample_array(x)
|
56
56
|
raise ArgumentError, 'Expect the input distance matrix to be square.' if @params[:metric] == 'precomputed' && x.shape[0] != x.shape[1]
|
57
|
+
|
57
58
|
fit_predict(x)
|
58
59
|
self
|
59
60
|
end
|
@@ -66,6 +67,7 @@ module Rumale
|
|
66
67
|
def fit_predict(x)
|
67
68
|
x = check_convert_sample_array(x)
|
68
69
|
raise ArgumentError, 'Expect the input distance matrix to be square.' if @params[:metric] == 'precomputed' && x.shape[0] != x.shape[1]
|
70
|
+
|
69
71
|
distance_mat = @params[:metric] == 'precomputed' ? x : Rumale::PairwiseMetric.euclidean_distance(x)
|
70
72
|
@labels = partial_fit(distance_mat)
|
71
73
|
end
|
data/lib/rumale/dataset.rb
CHANGED
@@ -65,6 +65,7 @@ module Rumale
|
|
65
65
|
Rumale::Validation.check_params_numeric_or_nil(noise: noise, random_seed: random_seed)
|
66
66
|
raise ArgumentError, 'The number of samples must be more than 2.' if n_samples <= 1
|
67
67
|
raise RangeError, 'The interval of factor is (0, 1).' if factor <= 0 || factor >= 1
|
68
|
+
|
68
69
|
# initialize some variables.
|
69
70
|
rs = random_seed
|
70
71
|
rs ||= srand
|
@@ -80,7 +81,7 @@ module Rumale
|
|
80
81
|
y = Numo::Int32.hstack([Numo::Int32.zeros(n_samples_out), Numo::Int32.ones(n_samples_in)])
|
81
82
|
# shuffle data indices.
|
82
83
|
if shuffle
|
83
|
-
rand_ids =
|
84
|
+
rand_ids = Array(0...n_samples).shuffle(random: rng.dup)
|
84
85
|
x = x[rand_ids, true].dup
|
85
86
|
y = y[rand_ids].dup
|
86
87
|
end
|
@@ -101,6 +102,7 @@ module Rumale
|
|
101
102
|
Rumale::Validation.check_params_boolean(shuffle: shuffle)
|
102
103
|
Rumale::Validation.check_params_numeric_or_nil(noise: noise, random_seed: random_seed)
|
103
104
|
raise ArgumentError, 'The number of samples must be more than 2.' if n_samples <= 1
|
105
|
+
|
104
106
|
# initialize some variables.
|
105
107
|
rs = random_seed
|
106
108
|
rs ||= srand
|
@@ -116,7 +118,7 @@ module Rumale
|
|
116
118
|
y = Numo::Int32.hstack([Numo::Int32.zeros(n_samples_out), Numo::Int32.ones(n_samples_in)])
|
117
119
|
# shuffle data indices.
|
118
120
|
if shuffle
|
119
|
-
rand_ids =
|
121
|
+
rand_ids = Array(0...n_samples).shuffle(random: rng.dup)
|
120
122
|
x = x[rand_ids, true].dup
|
121
123
|
y = y[rand_ids].dup
|
122
124
|
end
|
@@ -171,7 +173,7 @@ module Rumale
|
|
171
173
|
end
|
172
174
|
# shuffle data.
|
173
175
|
if shuffle
|
174
|
-
rand_ids =
|
176
|
+
rand_ids = Array(0...n_samples).shuffle(random: rng.dup)
|
175
177
|
x = x[rand_ids, true].dup
|
176
178
|
y = y[rand_ids].dup
|
177
179
|
end
|
@@ -90,9 +90,11 @@ module Rumale
|
|
90
90
|
@components = (sqrt_noise_variance.diag.dot(u) * scaler).transpose.dup
|
91
91
|
@noise_variance = Numo::DFloat.maximum(sample_vars - @components.transpose.dot(@components).diagonal, 1e-12)
|
92
92
|
next if @params[:tol].nil?
|
93
|
+
|
93
94
|
new_loglike = log_likelihood(cov_mat, @components, @noise_variance)
|
94
95
|
@loglike.push(new_loglike)
|
95
96
|
break if (old_loglike - new_loglike).abs <= @params[:tol]
|
97
|
+
|
96
98
|
old_loglike = new_loglike
|
97
99
|
end
|
98
100
|
|
@@ -9,7 +9,7 @@ module Rumale
|
|
9
9
|
# PCA is a class that implements Principal Component Analysis.
|
10
10
|
#
|
11
11
|
# @example
|
12
|
-
# decomposer = Rumale::Decomposition::PCA.new(n_components: 2)
|
12
|
+
# decomposer = Rumale::Decomposition::PCA.new(n_components: 2, solver: 'fpt')
|
13
13
|
# representaion = decomposer.fit_transform(samples)
|
14
14
|
#
|
15
15
|
# # If Numo::Linalg is installed, you can specify 'evd' for the solver option.
|
@@ -17,6 +17,11 @@ module Rumale
|
|
17
17
|
# decomposer = Rumale::Decomposition::PCA.new(n_components: 2, solver: 'evd')
|
18
18
|
# representaion = decomposer.fit_transform(samples)
|
19
19
|
#
|
20
|
+
# # If Numo::Linalg is loaded and the solver option is not given,
|
21
|
+
# # the solver option is choosen 'evd' automatically.
|
22
|
+
# decomposer = Rumale::Decomposition::PCA.new(n_components: 2)
|
23
|
+
# representaion = decomposer.fit_transform(samples)
|
24
|
+
#
|
20
25
|
# *Reference*
|
21
26
|
# - Sharma, A., and Paliwal, K K., "Fast principal component analysis using fixed-point algorithm," Pattern Recognition Letters, 28, pp. 1151--1155, 2007.
|
22
27
|
class PCA
|
@@ -38,18 +43,24 @@ module Rumale
|
|
38
43
|
# Create a new transformer with PCA.
|
39
44
|
#
|
40
45
|
# @param n_components [Integer] The number of principal components.
|
41
|
-
# @param solver [String] The algorithm for the optimization ('fpt' or 'evd').
|
42
|
-
# '
|
46
|
+
# @param solver [String] The algorithm for the optimization ('auto', 'fpt' or 'evd').
|
47
|
+
# 'auto' chooses the 'evd' solver if Numo::Linalg is loaded. Otherwise, it chooses the 'fpt' solver.
|
48
|
+
# 'fpt' uses the fixed-point algorithm.
|
49
|
+
# 'evd' performs eigen value decomposition of the covariance matrix of samples.
|
43
50
|
# @param max_iter [Integer] The maximum number of iterations. If solver = 'evd', this parameter is ignored.
|
44
51
|
# @param tol [Float] The tolerance of termination criterion. If solver = 'evd', this parameter is ignored.
|
45
52
|
# @param random_seed [Integer] The seed value using to initialize the random generator.
|
46
|
-
def initialize(n_components: 2, solver: '
|
53
|
+
def initialize(n_components: 2, solver: 'auto', max_iter: 100, tol: 1.0e-4, random_seed: nil)
|
47
54
|
check_params_numeric(n_components: n_components, max_iter: max_iter, tol: tol)
|
48
55
|
check_params_string(solver: solver)
|
49
56
|
check_params_numeric_or_nil(random_seed: random_seed)
|
50
57
|
check_params_positive(n_components: n_components, max_iter: max_iter, tol: tol)
|
51
58
|
@params = {}
|
52
|
-
@params[:solver] = solver
|
59
|
+
@params[:solver] = if solver == 'auto'
|
60
|
+
load_linalg? ? 'evd' : 'fpt'
|
61
|
+
else
|
62
|
+
solver != 'evd' ? 'fpt' : 'evd'
|
63
|
+
end
|
53
64
|
@params[:n_components] = n_components
|
54
65
|
@params[:max_iter] = max_iter
|
55
66
|
@params[:tol] = tol
|
@@ -87,6 +98,7 @@ module Rumale
|
|
87
98
|
@params[:max_iter].times do
|
88
99
|
updated = orthogonalize(covariance_mat.dot(comp_vec))
|
89
100
|
break if (updated.dot(comp_vec) - 1).abs < @params[:tol]
|
101
|
+
|
90
102
|
comp_vec = updated
|
91
103
|
end
|
92
104
|
@components = @components.nil? ? comp_vec : Numo::NArray.vstack([@components, comp_vec])
|
@@ -127,6 +139,13 @@ module Rumale
|
|
127
139
|
|
128
140
|
private
|
129
141
|
|
142
|
+
def load_linalg?
|
143
|
+
return false if defined?(Numo::Linalg).nil?
|
144
|
+
return false if Numo::Linalg::VERSION < '0.1.4'
|
145
|
+
|
146
|
+
true
|
147
|
+
end
|
148
|
+
|
130
149
|
def orthogonalize(pcvec)
|
131
150
|
unless @components.nil?
|
132
151
|
delta = @components.dot(pcvec) * @components.transpose
|
@@ -105,6 +105,7 @@ module Rumale
|
|
105
105
|
# Fit classfier.
|
106
106
|
ids = Rumale::Utils.choice_ids(n_samples, observation_weights, sub_rng)
|
107
107
|
break if y[ids].to_a.uniq.size != n_classes
|
108
|
+
|
108
109
|
tree = Tree::DecisionTreeClassifier.new(
|
109
110
|
criterion: @params[:criterion], max_depth: @params[:max_depth],
|
110
111
|
max_leaf_nodes: @params[:max_leaf_nodes], min_samples_leaf: @params[:min_samples_leaf],
|
@@ -120,12 +121,14 @@ module Rumale
|
|
120
121
|
@estimators.push(tree)
|
121
122
|
@feature_importances += tree.feature_importances
|
122
123
|
break if error.zero?
|
124
|
+
|
123
125
|
# Update observation weights.
|
124
126
|
log_proba = Numo::NMath.log(proba)
|
125
127
|
observation_weights *= Numo::NMath.exp(-1.0 * (n_classes - 1).fdiv(n_classes) * (y_codes * log_proba).sum(1))
|
126
128
|
observation_weights = observation_weights.clip(1.0e-15, nil)
|
127
129
|
sum_observation_weights = observation_weights.sum
|
128
130
|
break if sum_observation_weights.zero?
|
131
|
+
|
129
132
|
observation_weights /= sum_observation_weights
|
130
133
|
end
|
131
134
|
@feature_importances /= @feature_importances.sum
|
@@ -93,6 +93,7 @@ module Rumale
|
|
93
93
|
check_sample_tvalue_size(x, y)
|
94
94
|
# Check target values
|
95
95
|
raise ArgumentError, 'Expect target value vector to be 1-D arrray' unless y.shape.size == 1
|
96
|
+
|
96
97
|
# Initialize some variables.
|
97
98
|
n_samples, n_features = x.shape
|
98
99
|
@params[:max_features] = n_features unless @params[:max_features].is_a?(Integer)
|
@@ -117,6 +118,7 @@ module Rumale
|
|
117
118
|
abs_err = ((p - y) / y).abs
|
118
119
|
err = observation_weights[abs_err.gt(@params[:threshold])].sum
|
119
120
|
break if err <= 0.0
|
121
|
+
|
120
122
|
# Calculate weight.
|
121
123
|
beta = err**@params[:exponent]
|
122
124
|
weight = Math.log(1.fdiv(beta))
|
@@ -131,6 +133,7 @@ module Rumale
|
|
131
133
|
observation_weights = observation_weights.clip(1.0e-15, nil)
|
132
134
|
sum_observation_weights = observation_weights.sum
|
133
135
|
break if sum_observation_weights.zero?
|
136
|
+
|
134
137
|
observation_weights /= sum_observation_weights
|
135
138
|
end
|
136
139
|
@estimator_weights = Numo::DFloat.asarray(@estimator_weights)
|
@@ -86,7 +86,8 @@ module Rumale
|
|
86
86
|
weighted_recall = (Numo::DFloat.cast(recalls) * weights).sum
|
87
87
|
weighted_fscore = (Numo::DFloat.cast(fscores) * weights).sum
|
88
88
|
# output reults.
|
89
|
-
target_name ||= classes
|
89
|
+
target_name ||= classes
|
90
|
+
target_name.map!(&:to_s)
|
90
91
|
if output_hash
|
91
92
|
res = {}
|
92
93
|
target_name.each_with_index do |label, n|
|
@@ -28,8 +28,10 @@ module Rumale
|
|
28
28
|
# calculate entropies.
|
29
29
|
class_entropy = entropy(y_true)
|
30
30
|
return 0.0 if class_entropy.zero?
|
31
|
+
|
31
32
|
cluster_entropy = entropy(y_pred)
|
32
33
|
return 0.0 if cluster_entropy.zero?
|
34
|
+
|
33
35
|
# calculate mutual information.
|
34
36
|
mi = MutualInformation.new
|
35
37
|
mi.score(y_true, y_pred) / Math.sqrt(class_entropy * cluster_entropy)
|
@@ -14,6 +14,7 @@ module Rumale
|
|
14
14
|
y_true.sort.to_a.uniq.map do |label|
|
15
15
|
target_positions = y_pred.eq(label)
|
16
16
|
next 0.0 if y_pred[target_positions].empty?
|
17
|
+
|
17
18
|
n_true_positives = Numo::Int32.cast(y_true[target_positions].eq(y_pred[target_positions])).sum.to_f
|
18
19
|
n_false_positives = Numo::Int32.cast(y_true[target_positions].ne(y_pred[target_positions])).sum.to_f
|
19
20
|
n_true_positives / (n_true_positives + n_false_positives)
|
@@ -25,6 +26,7 @@ module Rumale
|
|
25
26
|
y_true.sort.to_a.uniq.map do |label|
|
26
27
|
target_positions = y_true.eq(label)
|
27
28
|
next 0.0 if y_pred[target_positions].empty?
|
29
|
+
|
28
30
|
n_true_positives = Numo::Int32.cast(y_true[target_positions].eq(y_pred[target_positions])).sum.to_f
|
29
31
|
n_false_negatives = Numo::Int32.cast(y_true[target_positions].ne(y_pred[target_positions])).sum.to_f
|
30
32
|
n_true_positives / (n_true_positives + n_false_negatives)
|
@@ -35,6 +37,7 @@ module Rumale
|
|
35
37
|
def f_score_each_class(y_true, y_pred)
|
36
38
|
precision_each_class(y_true, y_pred).zip(recall_each_class(y_true, y_pred)).map do |p, r|
|
37
39
|
next 0.0 if p.zero? && r.zero?
|
40
|
+
|
38
41
|
(2.0 * p * r) / (p + r)
|
39
42
|
end
|
40
43
|
end
|
@@ -44,6 +47,7 @@ module Rumale
|
|
44
47
|
evaluated_values = y_true.sort.to_a.uniq.map do |label|
|
45
48
|
target_positions = y_pred.eq(label)
|
46
49
|
next [0.0, 0.0] if y_pred[target_positions].empty?
|
50
|
+
|
47
51
|
n_true_positives = Numo::Int32.cast(y_true[target_positions].eq(y_pred[target_positions])).sum.to_f
|
48
52
|
n_false_positives = Numo::Int32.cast(y_true[target_positions].ne(y_pred[target_positions])).sum.to_f
|
49
53
|
[n_true_positives, n_true_positives + n_false_positives]
|
@@ -57,6 +61,7 @@ module Rumale
|
|
57
61
|
evaluated_values = y_true.sort.to_a.uniq.map do |label|
|
58
62
|
target_positions = y_true.eq(label)
|
59
63
|
next 0.0 if y_pred[target_positions].empty?
|
64
|
+
|
60
65
|
n_true_positives = Numo::Int32.cast(y_true[target_positions].eq(y_pred[target_positions])).sum.to_f
|
61
66
|
n_false_negatives = Numo::Int32.cast(y_true[target_positions].ne(y_pred[target_positions])).sum.to_f
|
62
67
|
[n_true_positives, n_true_positives + n_false_negatives]
|
@@ -64,6 +64,7 @@ module Rumale
|
|
64
64
|
y_score = Numo::DFloat.cast(y_score) unless y_score.is_a?(Numo::DFloat)
|
65
65
|
raise ArgumentError, 'Expect y_true to be 1-D arrray.' unless y_true.shape[1].nil?
|
66
66
|
raise ArgumentError, 'Expect y_score to be 1-D arrray.' unless y_score.shape[1].nil?
|
67
|
+
|
67
68
|
labels = y_true.to_a.uniq
|
68
69
|
if pos_label.nil?
|
69
70
|
raise ArgumentError, 'y_true must be binary labels or pos_label must be specified if y_true is multi-label' unless labels.size == 2
|
@@ -96,8 +97,10 @@ module Rumale
|
|
96
97
|
y = Numo::NArray.asarray(y) unless y.is_a?(Numo::NArray)
|
97
98
|
raise ArgumentError, 'Expect x to be 1-D arrray.' unless x.shape[1].nil?
|
98
99
|
raise ArgumentError, 'Expect y to be 1-D arrray.' unless y.shape[1].nil?
|
100
|
+
|
99
101
|
n_samples = [x.shape[0], y.shape[0]].min
|
100
102
|
raise ArgumentError, 'At least two points are required to calculate area under curve.' if n_samples < 2
|
103
|
+
|
101
104
|
(0...n_samples).to_a.each_cons(2).map { |i, j| 0.5 * (x[i] - x[j]).abs * (y[i] + y[j]) }.reduce(&:+)
|
102
105
|
end
|
103
106
|
|
@@ -47,6 +47,7 @@ module Rumale
|
|
47
47
|
cls_pos = y.eq(labels[n])
|
48
48
|
sz_cluster = cls_pos.count
|
49
49
|
next unless sz_cluster > 1
|
50
|
+
|
50
51
|
cls_dist_mat = dist_mat[cls_pos, cls_pos].dup
|
51
52
|
cls_dist_mat[cls_dist_mat.diag_indices] = 0.0
|
52
53
|
intra_dists[cls_pos] = cls_dist_mat.sum(0) / (sz_cluster - 1)
|
@@ -57,6 +58,7 @@ module Rumale
|
|
57
58
|
cls_pos = y.eq(labels[m])
|
58
59
|
n_clusters.times do |n|
|
59
60
|
next if m == n
|
61
|
+
|
60
62
|
not_cls_pos = y.eq(labels[n])
|
61
63
|
inter_dists[cls_pos] = Numo::DFloat.minimum(
|
62
64
|
inter_dists[cls_pos], dist_mat[cls_pos, not_cls_pos].mean(1)
|
@@ -1,6 +1,5 @@
|
|
1
1
|
# frozen_string_literal: true
|
2
2
|
|
3
|
-
require 'mmh3'
|
4
3
|
require 'rumale/base/base_estimator'
|
5
4
|
require 'rumale/base/transformer'
|
6
5
|
|
@@ -11,11 +10,15 @@ module Rumale
|
|
11
10
|
# This encoder employs signed 32-bit Murmurhash3 as the hash function.
|
12
11
|
#
|
13
12
|
# @example
|
13
|
+
# require 'mmh3'
|
14
|
+
# require 'rumale'
|
15
|
+
#
|
14
16
|
# encoder = Rumale::FeatureExtraction::FeatureHasher.new(n_features: 10)
|
15
17
|
# x = encoder.transform([
|
16
18
|
# { dog: 1, cat: 2, elephant: 4 },
|
17
19
|
# { dog: 2, run: 5 }
|
18
20
|
# ])
|
21
|
+
#
|
19
22
|
# # > pp x
|
20
23
|
# # Numo::DFloat#shape=[2,10]
|
21
24
|
# # [[0, 0, -4, -1, 0, 0, 0, 0, 0, 2],
|
@@ -62,6 +65,8 @@ module Rumale
|
|
62
65
|
# @param x [Array<Hash>] (shape: [n_samples]) The array of hash consisting of feature names and values.
|
63
66
|
# @return [Numo::DFloat] (shape: [n_samples, n_features]) The encoded sample array.
|
64
67
|
def transform(x)
|
68
|
+
raise 'FeatureHasher#transform requires Mmh3 but that is not loaded.' unless enable_mmh3?
|
69
|
+
|
65
70
|
x = [x] unless x.is_a?(Array)
|
66
71
|
n_samples = x.size
|
67
72
|
|
@@ -85,6 +90,14 @@ module Rumale
|
|
85
90
|
|
86
91
|
private
|
87
92
|
|
93
|
+
def enable_mmh3?
|
94
|
+
if defined?(Mmh3).nil?
|
95
|
+
warn('FeatureHasher#transform requires Mmh3 but that is not loaded. You should intall and load mmh3 gem in advance.')
|
96
|
+
return false
|
97
|
+
end
|
98
|
+
true
|
99
|
+
end
|
100
|
+
|
88
101
|
def n_features
|
89
102
|
@params[:n_features]
|
90
103
|
end
|
@@ -0,0 +1,113 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'rumale/base/base_estimator'
|
4
|
+
require 'rumale/base/transformer'
|
5
|
+
require 'rumale/preprocessing/l1_normalizer'
|
6
|
+
require 'rumale/preprocessing/l2_normalizer'
|
7
|
+
|
8
|
+
module Rumale
|
9
|
+
module FeatureExtraction
|
10
|
+
# Transform sample matrix with term frequecy (tf) to a normalized tf-idf (inverse document frequency) reprensentation.
|
11
|
+
#
|
12
|
+
# @example
|
13
|
+
# encoder = Rumale::FeatureExtraction::HashVectorizer.new
|
14
|
+
# x = encoder.fit_transform([
|
15
|
+
# { foo: 1, bar: 2 },
|
16
|
+
# { foo: 3, baz: 1 }
|
17
|
+
# ])
|
18
|
+
#
|
19
|
+
# # > pp x
|
20
|
+
# # Numo::DFloat#shape=[2,3]
|
21
|
+
# # [[2, 0, 1],
|
22
|
+
# # [0, 1, 3]]
|
23
|
+
#
|
24
|
+
# transformer = Rumale::FeatureExtraction::TfidfTransformer.new
|
25
|
+
# x_tfidf = transformer.fit_transform(x)
|
26
|
+
#
|
27
|
+
# # > pp x_tfidf
|
28
|
+
# # Numo::DFloat#shape=[2,3]
|
29
|
+
# # [[0.959056, 0, 0.283217],
|
30
|
+
# # [0, 0.491506, 0.870874]]
|
31
|
+
#
|
32
|
+
# *Reference*
|
33
|
+
# - Manning, C D., Raghavan, P., and Schutze, H., "Introduction to Information Retrieval," Cambridge University Press., 2008.
|
34
|
+
class TfidfTransformer
|
35
|
+
include Base::BaseEstimator
|
36
|
+
include Base::Transformer
|
37
|
+
|
38
|
+
# Return the vector consists of inverse document frequency.
|
39
|
+
# @return [Numo::DFloat] (shape: [n_features])
|
40
|
+
attr_reader :idf
|
41
|
+
|
42
|
+
# Create a new transfomer for converting tf vectors to tf-idf vectors.
|
43
|
+
#
|
44
|
+
# @param norm [String] The normalization method to be used ('l1', 'l2' and 'none').
|
45
|
+
# @param use_idf [Boolean] The flag indicating whether to use inverse document frequency weighting.
|
46
|
+
# @param smooth_idf [Boolean] The flag indicating whether to apply idf smoothing by log((n_samples + 1) / (df + 1)) + 1.
|
47
|
+
# @param sublinear_tf [Boolean] The flag indicating whether to perform subliner tf scaling by 1 + log(tf).
|
48
|
+
def initialize(norm: 'l2', use_idf: true, smooth_idf: false, sublinear_tf: false)
|
49
|
+
check_params_string(norm: norm)
|
50
|
+
check_params_boolean(use_idf: use_idf, smooth_idf: smooth_idf, sublinear_tf: sublinear_tf)
|
51
|
+
@params = {}
|
52
|
+
@params[:norm] = norm
|
53
|
+
@params[:use_idf] = use_idf
|
54
|
+
@params[:smooth_idf] = smooth_idf
|
55
|
+
@params[:sublinear_tf] = sublinear_tf
|
56
|
+
@idf = nil
|
57
|
+
end
|
58
|
+
|
59
|
+
# Calculate the inverse document frequency for weighting.
|
60
|
+
#
|
61
|
+
# @overload fit(x) -> TfidfTransformer
|
62
|
+
#
|
63
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to calculate the idf values.
|
64
|
+
# @return [TfidfTransformer]
|
65
|
+
def fit(x, _y = nil)
|
66
|
+
return self unless @params[:use_idf]
|
67
|
+
|
68
|
+
x = check_convert_sample_array(x)
|
69
|
+
|
70
|
+
n_samples = x.shape[0]
|
71
|
+
df = x.class.cast(x.gt(0.0).count(0))
|
72
|
+
|
73
|
+
if @params[:smooth_idf]
|
74
|
+
df += 1
|
75
|
+
n_samples += 1
|
76
|
+
end
|
77
|
+
|
78
|
+
@idf = Numo::NMath.log(n_samples / df) + 1
|
79
|
+
|
80
|
+
self
|
81
|
+
end
|
82
|
+
|
83
|
+
# Calculate the idf values, and then transfrom samples to the tf-idf representation.
|
84
|
+
#
|
85
|
+
# @overload fit_transform(x) -> Numo::DFloat
|
86
|
+
#
|
87
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to calculate idf and be transformed to tf-idf representation.
|
88
|
+
# @return [Numo::DFloat] The transformed samples.
|
89
|
+
def fit_transform(x, _y = nil)
|
90
|
+
fit(x).transform(x)
|
91
|
+
end
|
92
|
+
|
93
|
+
# Perform transforming the given samples to the tf-idf representation.
|
94
|
+
#
|
95
|
+
# @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to be transformed.
|
96
|
+
# @return [Numo::DFloat] The transformed samples.
|
97
|
+
def transform(x)
|
98
|
+
x = check_convert_sample_array(x)
|
99
|
+
z = x.dup
|
100
|
+
|
101
|
+
z[z.ne(0)] = Numo::NMath.log(z[z.ne(0)]) + 1 if @params[:sublinear_tf]
|
102
|
+
z *= @idf if @params[:use_idf]
|
103
|
+
case @params[:norm]
|
104
|
+
when 'l2'
|
105
|
+
z = Rumale::Preprocessing::L2Normalizer.new.fit_transform(z)
|
106
|
+
when 'l1'
|
107
|
+
z = Rumale::Preprocessing::L1Normalizer.new.fit_transform(z)
|
108
|
+
end
|
109
|
+
z
|
110
|
+
end
|
111
|
+
end
|
112
|
+
end
|
113
|
+
end
|