ltr 0.1.0

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.
Files changed (169) hide show
  1. checksums.yaml +7 -0
  2. data/ARCHITECTURE.md +92 -0
  3. data/CHANGELOG.md +5 -0
  4. data/LICENSE +21 -0
  5. data/README.md +186 -0
  6. data/docs/AGENTS.md +67 -0
  7. data/docs/aggregation-engines.md +80 -0
  8. data/docs/config.md +516 -0
  9. data/docs/data-contracts.md +94 -0
  10. data/docs/data-splits.md +34 -0
  11. data/docs/dataset-builder-steps.md +13 -0
  12. data/docs/dataset-csv.md +73 -0
  13. data/docs/dataset-enrichers.md +62 -0
  14. data/docs/errors.md +33 -0
  15. data/docs/feature-selection.md +108 -0
  16. data/docs/features.md +202 -0
  17. data/docs/glossary.md +56 -0
  18. data/docs/host-integration.md +128 -0
  19. data/docs/host-run-pipelines.md +48 -0
  20. data/docs/index.md +50 -0
  21. data/docs/inference.md +164 -0
  22. data/docs/label-transformers.md +242 -0
  23. data/docs/labels-from-behavior.md +94 -0
  24. data/docs/learning-to-rank.md +119 -0
  25. data/docs/metrics.md +166 -0
  26. data/docs/model-files.md +73 -0
  27. data/docs/optimization.md +72 -0
  28. data/docs/public-api.md +67 -0
  29. data/docs/rake-tasks.md +82 -0
  30. data/docs/relevance-grades.md +80 -0
  31. data/docs/run-locally.md +584 -0
  32. data/docs/run-on-aws.md +647 -0
  33. data/docs/training-objective.md +110 -0
  34. data/docs/ubi-documents.md +75 -0
  35. data/docs/ubi-logging.md +125 -0
  36. data/lib/ltr/README.md +28 -0
  37. data/lib/ltr/configuration/README.md +12 -0
  38. data/lib/ltr/configuration/config_loader.rb +326 -0
  39. data/lib/ltr/configuration/config_validator.rb +476 -0
  40. data/lib/ltr/configuration/configuration.rb +84 -0
  41. data/lib/ltr/configuration/example_config.yml +182 -0
  42. data/lib/ltr/data/README.md +20 -0
  43. data/lib/ltr/data/csv/README.md +9 -0
  44. data/lib/ltr/data/csv/typed_columns.rb +101 -0
  45. data/lib/ltr/data/csv.rb +126 -0
  46. data/lib/ltr/data/dataframe.rb +80 -0
  47. data/lib/ltr/data/dataset_loader.rb +29 -0
  48. data/lib/ltr/data/row_store.rb +188 -0
  49. data/lib/ltr/data/split_cache.rb +30 -0
  50. data/lib/ltr/data/splits.rb +86 -0
  51. data/lib/ltr/dataset_aggregation/README.md +32 -0
  52. data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
  53. data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
  54. data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
  55. data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
  56. data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
  57. data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
  58. data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
  59. data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
  60. data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
  61. data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
  62. data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
  63. data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
  64. data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
  65. data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
  66. data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
  67. data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
  68. data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
  69. data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
  70. data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
  71. data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
  72. data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
  73. data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
  74. data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
  75. data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
  76. data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
  77. data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
  78. data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
  79. data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
  80. data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
  81. data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
  82. data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
  83. data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
  84. data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
  85. data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
  86. data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
  87. data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
  88. data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
  89. data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
  90. data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
  91. data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
  92. data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
  93. data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
  94. data/lib/ltr/deploy/README.md +21 -0
  95. data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
  96. data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
  97. data/lib/ltr/deploy/feature_extractor.rb +94 -0
  98. data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
  99. data/lib/ltr/deploy/local_deployer.rb +61 -0
  100. data/lib/ltr/deploy/model_packager.rb +90 -0
  101. data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
  102. data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
  103. data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
  104. data/lib/ltr/errors/README.md +16 -0
  105. data/lib/ltr/errors/configuration_error.rb +5 -0
  106. data/lib/ltr/errors/deploy_error.rb +5 -0
  107. data/lib/ltr/errors/error.rb +5 -0
  108. data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
  109. data/lib/ltr/errors/missing_dependency_error.rb +5 -0
  110. data/lib/ltr/errors/sqlite_error.rb +14 -0
  111. data/lib/ltr/features/README.md +19 -0
  112. data/lib/ltr/features/encoders/README.md +10 -0
  113. data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
  114. data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
  115. data/lib/ltr/features/feature_engineering.rb +194 -0
  116. data/lib/ltr/features/feature_transformer.rb +92 -0
  117. data/lib/ltr/features/float32_range.rb +20 -0
  118. data/lib/ltr/features/transform_steps.rb +34 -0
  119. data/lib/ltr/features/transform_store.rb +123 -0
  120. data/lib/ltr/inference/README.md +11 -0
  121. data/lib/ltr/inference/base.rb +52 -0
  122. data/lib/ltr/inference/local_reranker.rb +147 -0
  123. data/lib/ltr/inference/sagemaker_client.rb +62 -0
  124. data/lib/ltr/metrics/README.md +12 -0
  125. data/lib/ltr/metrics/metric_scores.rb +67 -0
  126. data/lib/ltr/metrics/metrics.rb +139 -0
  127. data/lib/ltr/optimize/README.md +25 -0
  128. data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
  129. data/lib/ltr/optimize/candidate_selector.rb +97 -0
  130. data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
  131. data/lib/ltr/optimize/expected_improvement.rb +33 -0
  132. data/lib/ltr/optimize/feature_selection/README.md +15 -0
  133. data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
  134. data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
  135. data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
  136. data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
  137. data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
  138. data/lib/ltr/optimize/gaussian_process.rb +125 -0
  139. data/lib/ltr/optimize/optimization_dataset.rb +16 -0
  140. data/lib/ltr/optimize/optimize_features.rb +129 -0
  141. data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
  142. data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
  143. data/lib/ltr/optimize/search_space.rb +165 -0
  144. data/lib/ltr/optimize/update_config.rb +196 -0
  145. data/lib/ltr/ssm/README.md +11 -0
  146. data/lib/ltr/ssm/loader.rb +61 -0
  147. data/lib/ltr/ssm/parameter_paths.rb +19 -0
  148. data/lib/ltr/ssm/saver.rb +76 -0
  149. data/lib/ltr/support/README.md +13 -0
  150. data/lib/ltr/support/callable.rb +10 -0
  151. data/lib/ltr/support/optional_dependency.rb +31 -0
  152. data/lib/ltr/support/pipeline_result.rb +22 -0
  153. data/lib/ltr/support/pipeline_task.rb +81 -0
  154. data/lib/ltr/support/version.rb +7 -0
  155. data/lib/ltr/tasks/ltr.rake +24 -0
  156. data/lib/ltr/train/README.md +19 -0
  157. data/lib/ltr/train/deploy_gate.rb +77 -0
  158. data/lib/ltr/train/deploy_metric.rb +63 -0
  159. data/lib/ltr/train/eval_logger.rb +16 -0
  160. data/lib/ltr/train/evaluation_cache.rb +101 -0
  161. data/lib/ltr/train/modelling_pipeline.rb +82 -0
  162. data/lib/ltr/train/optimization_split_report.rb +54 -0
  163. data/lib/ltr/train/utils.rb +35 -0
  164. data/lib/ltr/train/xgb_evaluator.rb +96 -0
  165. data/lib/ltr/train/xgb_trainer.rb +154 -0
  166. data/lib/ltr/ubi.rb +86 -0
  167. data/lib/ltr.rb +61 -0
  168. data/scripts/seed_ubi.rb +75 -0
  169. metadata +346 -0
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Factors a kernel matrix into a lower triangle and solves linear systems with it.
4
+
5
+ module Ltr::Optimize::CholeskyDecomposition
6
+ JITTER_INITIAL = 1e-8
7
+ JITTER_MAX = 1e-2
8
+ MIN_PIVOT = 1e-10
9
+
10
+ class << self
11
+ # Returns the lower triangle of the matrix as nested arrays.
12
+ # It tries the matrix as given first. When a pivot is too small, it retries with a small value added to the diagonal.
13
+ # That value starts at `JITTER_INITIAL` and grows ten times per retry.
14
+ # Raises `RuntimeError` once the value passes `JITTER_MAX`.
15
+ def decompose(kernel_matrix)
16
+ matrix_array = kernel_matrix.to_a.map(&:dup)
17
+
18
+ jitter = 0.0
19
+ loop do
20
+ lower = factorize(matrix_array, jitter)
21
+ return lower if lower
22
+
23
+ # Adding a small value to the diagonal makes a near-singular matrix factorable.
24
+ jitter = jitter.zero? ? JITTER_INITIAL : jitter * 10.0
25
+ raise "Cholesky decomposition failed: matrix not positive definite even with jitter #{jitter}" if jitter > JITTER_MAX
26
+ end
27
+ end
28
+
29
+ # Returns the lower triangle, or nil when a pivot is too small.
30
+ def factorize(matrix_array, jitter)
31
+ size = matrix_array.length
32
+ lower = Array.new(size) { Array.new(size, 0.0) }
33
+
34
+ size.times do |row|
35
+ (0..row).each do |column|
36
+ sum = (0...column).sum { |k| lower[row][k] * lower[column][k] }
37
+
38
+ if row == column
39
+ pivot = matrix_array[row][row] + jitter - sum
40
+ return nil if pivot < MIN_PIVOT
41
+
42
+ lower[row][column] = Math.sqrt(pivot)
43
+ else
44
+ lower[row][column] = (matrix_array[row][column] - sum) / lower[column][column]
45
+ end
46
+ end
47
+ end
48
+
49
+ lower
50
+ end
51
+ private :factorize
52
+
53
+ # Returns `x` where `lower * lower.transpose * x = right_hand_side`.
54
+ def solve(lower, right_hand_side)
55
+ intermediate = forward_substitute(lower, right_hand_side)
56
+ back_substitute_transpose(lower, intermediate)
57
+ end
58
+
59
+ # Solves `lower * x = right_hand_side` for `x`, from the first row down.
60
+ def forward_substitute(lower, right_hand_side)
61
+ size = lower.length
62
+ solution = Array.new(size, 0.0)
63
+ size.times do |row|
64
+ sum = (0...row).sum { |column| lower[row][column] * solution[column] }
65
+ solution[row] = (right_hand_side[row] - sum) / lower[row][row]
66
+ end
67
+ solution
68
+ end
69
+
70
+ # Solves `lower.transpose * x = intermediate` for `x`, from the last row up.
71
+ def back_substitute_transpose(lower, intermediate)
72
+ size = lower.length
73
+ solution = Array.new(size, 0.0)
74
+ (size - 1).downto(0) do |row|
75
+ sum = ((row + 1)...size).sum { |column| lower[column][row] * solution[column] }
76
+ solution[row] = (intermediate[row] - sum) / lower[row][row]
77
+ end
78
+ solution
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Scores how much a point is expected to beat the best value so far.
4
+
5
+ module Ltr::Optimize::ExpectedImprovement
6
+ module_function
7
+
8
+ # Returns the expected improvement of the point over `best_value_so_far - exploration_parameter * gaussian_process.output_std`.
9
+ # The result is never negative.
10
+ # A larger `exploration_parameter` favors points that are more uncertain.
11
+ def score(gaussian_process, unit_vector, best_value_so_far, exploration_parameter)
12
+ predicted_mean, predicted_variance = gaussian_process.predict(unit_vector)
13
+ predicted_std = Math.sqrt(predicted_variance)
14
+
15
+ # The optimizer minimizes, so improvement means a prediction below the best value.
16
+ improvement_threshold = best_value_so_far - exploration_parameter * gaussian_process.output_std
17
+ expected_improvement_raw = improvement_threshold - predicted_mean
18
+ standardized_score = expected_improvement_raw / predicted_std
19
+ improvement = expected_improvement_raw * standard_normal_cdf(standardized_score) +
20
+ predicted_std * standard_normal_pdf(standardized_score)
21
+ improvement.clamp(0.0, Float::INFINITY)
22
+ end
23
+
24
+ # Returns the standard normal density at `z_score`.
25
+ def standard_normal_pdf(z_score)
26
+ Math.exp(-0.5 * z_score * z_score) / Math.sqrt(2.0 * Math::PI)
27
+ end
28
+
29
+ # Returns the standard normal cumulative probability at `z_score`.
30
+ def standard_normal_cdf(z_score)
31
+ 0.5 * (1.0 + Math.erf(z_score / Math.sqrt(2.0)))
32
+ end
33
+ end
@@ -0,0 +1,15 @@
1
+ # `lib/ltr/optimize/feature_selection`
2
+
3
+ The interchangeable search strategies `Optimize::OptimizeFeatures` runs, selected by `optimization.feature_selection.strategy`. Everything here lives in the `Ltr::Optimize::FeatureSelection::` namespace. `OptimizeFeatures` still owns the feature list, the split resolution and the shared `Train::EvaluationCache`; a strategy only decides which candidate sets to try and which one to keep.
4
+
5
+ The [Feature selection](../../../../docs/feature-selection.md) guide compares the three strategies and their cost.
6
+
7
+ ## Files
8
+
9
+ | File | Purpose |
10
+ |---|---|
11
+ | `strategy.rb` | Base class holding the shared trial plumbing, the complexity penalty, the `total_gain` importance ranking and the shrinking `sweep` the one-drop-per-step strategies fill in with `next_set`, plus `Strategy.build` mapping a configured strategy name onto one of the classes below and `Strategy.validate!`, which `ConfigValidator` calls so the name is checked in one place. |
12
+ | `trial.rb` | One trial: trains a booster on a candidate feature set and scores it on the optimization split, returning the score and the booster. |
13
+ | `greedy_backward.rb` | Greedy backward elimination — the default, and the historical behaviour. |
14
+ | `importance_ranked.rb` | Ranks features once by the booster's `total_gain` importance, then sweeps the cut point. |
15
+ | `rfe.rb` | Recursive feature elimination: drops the least important feature and re-ranks, every step. |
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Feature selection strategy that drops the one feature whose removal helps the score most until none helps.
4
+
5
+ class Ltr::Optimize::FeatureSelection::GreedyBackward < Ltr::Optimize::FeatureSelection::Strategy
6
+ # Returns the best feature set found. Each round it tries removing every feature.
7
+ # It keeps the best removal only if it raises the penalized score.
8
+ # It stops when no removal helps or the set reaches `min_features`.
9
+ def call(features)
10
+ logger.info("Starting reverse feature selection with #{features.size} features...")
11
+
12
+ best = evaluate(features)
13
+ logger.info("Initial score with all features - Penalized score: #{best[:score].round(4)}, Raw score: #{best[:raw_score].round(4)}")
14
+
15
+ while best[:features].size > min_features
16
+ removal = best_removal(best)
17
+ unless removal
18
+ logger.info("No further improvements found. Stopping feature removal.")
19
+ break
20
+ end
21
+
22
+ logger.info("Removed feature: #{removal[:removed]} (Penalized score: #{removal[:score].round(4)}, Raw score: #{removal[:raw_score].round(4)})")
23
+ best = removal
24
+ end
25
+
26
+ log_selection(best)
27
+ best[:features]
28
+ end
29
+
30
+ private
31
+
32
+ def best_removal(best)
33
+ best[:features]
34
+ .map { |feature| evaluate(best[:features] - [feature]).merge(removed: feature) }
35
+ .select { |result| result[:score] > best[:score] }
36
+ .max_by { |result| result[:score] }
37
+ end
38
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Feature selection strategy that drops features one by one in order of a single importance ranking.
4
+
5
+ class Ltr::Optimize::FeatureSelection::ImportanceRanked < Ltr::Optimize::FeatureSelection::Strategy
6
+ # Returns the best feature set found. It ranks features by `total_gain` once, using the model trained on all features.
7
+ # Then it drops the last ranked feature each round until `min_features` is reached.
8
+ # It returns the set with the best penalized score. A tie goes to the smaller set.
9
+ # A feature the model never uses counts as zero importance.
10
+ def call(features)
11
+ logger.info("Ranking #{features.size} features by #{IMPORTANCE_TYPE}...")
12
+ sweep(features)
13
+ end
14
+
15
+ private
16
+
17
+ def next_set(remaining, model)
18
+ @ranking ||= rank(model, remaining)
19
+ .tap { |ranking| logger.info("Feature ranking (most important first): #{ranking}") }
20
+
21
+ remaining & @ranking.first(remaining.size - 1)
22
+ end
23
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Feature selection strategy that retrains and drops the least important feature each round.
4
+
5
+ class Ltr::Optimize::FeatureSelection::Rfe < Ltr::Optimize::FeatureSelection::Strategy
6
+ # Returns the best feature set found. Each round it drops the feature that the latest model ranks last by `total_gain`.
7
+ # It stops at `min_features` and returns the set with the best penalized score. A tie goes to the smaller set.
8
+ # A feature the model never uses counts as zero importance.
9
+ def call(features)
10
+ logger.info("Starting recursive feature elimination with #{features.size} features...")
11
+ sweep(features)
12
+ end
13
+
14
+ private
15
+
16
+ def next_set(remaining, model)
17
+ dropped = rank(model, remaining).last
18
+ logger.info("Dropping #{dropped} (#{remaining.size - 1} left)")
19
+
20
+ remaining - [dropped]
21
+ end
22
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Base class for feature selection strategies with shared scoring, ranking and a lookup by name.
4
+
5
+ class Ltr::Optimize::FeatureSelection::Strategy
6
+ STRATEGIES = {
7
+ "greedy_backward" => "GreedyBackward",
8
+ "importance_ranked" => "ImportanceRanked",
9
+ "rfe" => "Rfe",
10
+ }.freeze
11
+
12
+ DEFAULT = "greedy_backward"
13
+ IMPORTANCE_TYPE = "total_gain"
14
+ FEATURE_INDEX_KEY = /\Af(\d+)\z/
15
+
16
+ # Returns a new strategy for `name`, or a `greedy_backward` one when `name` is nil.
17
+ # `options` are passed to the strategy: `trial:`, `min_features:` and `complexity_penalty:`.
18
+ # Raises `Ltr::ConfigurationError` for an unknown name.
19
+ def self.build(name, **options)
20
+ validate!(name)
21
+
22
+ Ltr::Optimize::FeatureSelection.const_get(STRATEGIES.fetch(name.nil? ? DEFAULT : name.to_s)).new(**options)
23
+ end
24
+
25
+ # Raises `Ltr::ConfigurationError` for an unknown name. A nil name is allowed.
26
+ def self.validate!(name)
27
+ return if name.nil? || known?(name)
28
+
29
+ raise Ltr::ConfigurationError,
30
+ "optimization.feature_selection.strategy must be one of " \
31
+ "#{STRATEGIES.keys.join(", ")} (got #{name.inspect})"
32
+ end
33
+
34
+ # Returns true when `name` is a registered strategy name.
35
+ def self.known?(name)
36
+ STRATEGIES.key?(name.to_s)
37
+ end
38
+
39
+ def initialize(trial:, min_features:, complexity_penalty:)
40
+ @trial = trial
41
+ @min_features = min_features
42
+ @complexity_penalty = complexity_penalty
43
+ end
44
+
45
+ # Subclasses return the selected feature list. The base class raises `NotImplementedError`.
46
+ def call(features)
47
+ raise NotImplementedError, "#{self.class} must implement #call"
48
+ end
49
+
50
+ private
51
+
52
+ attr_reader :trial, :min_features, :complexity_penalty
53
+
54
+ def sweep(features)
55
+ current, model = evaluate_with_model(features)
56
+ best = current
57
+ logger.info("Score with all #{features.size} features - Penalized score: #{best[:score].round(4)}, Raw score: #{best[:raw_score].round(4)}")
58
+
59
+ while current[:features].size > min_features
60
+ current, model = evaluate_with_model(next_set(current[:features], model))
61
+ logger.info("#{current[:features].size} features - Penalized score: #{current[:score].round(4)}, Raw score: #{current[:raw_score].round(4)}")
62
+
63
+ # `>=` keeps the smaller set when scores tie.
64
+ best = current if current[:score] >= best[:score]
65
+ end
66
+
67
+ log_selection(best)
68
+ best[:features]
69
+ end
70
+
71
+ def next_set(_remaining, _model)
72
+ raise NotImplementedError, "#{self.class} must implement #next_set"
73
+ end
74
+
75
+ def evaluate(features)
76
+ result, = evaluate_with_model(features)
77
+ result
78
+ end
79
+
80
+ def evaluate_with_model(features)
81
+ raw_score, model = trial.call(features)
82
+
83
+ [{ features: features, score: penalized(raw_score, features.size), raw_score: raw_score }, model]
84
+ end
85
+
86
+ def log_selection(result)
87
+ logger.info("Final feature set: #{result[:features]}")
88
+ logger.info("Feature count: #{result[:features].size}, Penalized score: #{result[:score].round(4)}, Raw score: #{result[:raw_score].round(4)}")
89
+ end
90
+
91
+ def penalized(raw_score, feature_count)
92
+ raw_score - (feature_count * complexity_penalty)
93
+ end
94
+
95
+ def rank(model, features)
96
+ scores = importance_scores(model, features)
97
+ positions = features.each_with_index.to_h
98
+
99
+ features.sort_by { |feature| [-scores.fetch(feature, 0.0), positions.fetch(feature)] }
100
+ end
101
+
102
+ def importance_scores(model, features)
103
+ model.score(importance_type: IMPORTANCE_TYPE).to_h do |key, value|
104
+ index = key.to_s[FEATURE_INDEX_KEY, 1]
105
+ [index ? features[index.to_i] : key, value]
106
+ end
107
+ end
108
+
109
+ def logger
110
+ Ltr.config.logger
111
+ end
112
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Trains a model on a feature set and returns its score and the model.
4
+
5
+ class Ltr::Optimize::FeatureSelection::Trial
6
+ def initialize(dataset, config, hyperparameters:, metric_to_optimize:, evaluation_cache:, nthread: nil)
7
+ @df = dataset.df
8
+ @split_cache = dataset.split_cache
9
+ @early_stopping_split = dataset.early_stopping_split
10
+ @config = config
11
+ @hyperparameters = hyperparameters
12
+ @metric_to_optimize = metric_to_optimize
13
+ @evaluation_cache = evaluation_cache
14
+ @nthread = nthread
15
+ end
16
+
17
+ # Trains a model on `features` and returns `[score, model]`.
18
+ # It trains on the train split and uses the early stopping split as the eval set.
19
+ # The score is `metric_to_optimize` from the evaluation cache, so it comes from the cache's split.
20
+ def call(features)
21
+ dtrain = split_cache.dmatrix(Ltr::Data::Splits::TRAIN, features)
22
+ deval = split_cache.dmatrix(early_stopping_split, features)
23
+ model = Ltr::Train::XgbTrainer.train_model(dtrain, deval, hyperparameters, seed: config.seed, nthread:)
24
+ scores = Ltr::Train::XgbEvaluator.evaluate_model(
25
+ model,
26
+ df,
27
+ features,
28
+ config,
29
+ evaluation_cache: evaluation_cache
30
+ )
31
+
32
+ [scores.fetch(metric_to_optimize), model]
33
+ end
34
+
35
+ private
36
+
37
+ attr_reader :df, :config, :hyperparameters, :metric_to_optimize, :evaluation_cache, :split_cache,
38
+ :early_stopping_split, :nthread
39
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Models the objective with a Gaussian process and predicts the mean and variance at a point.
4
+
5
+ class Ltr::Optimize::GaussianProcess
6
+ MIN_PREDICTED_VARIANCE = 1e-12
7
+ MIN_OUTPUT_STD = 1e-8
8
+
9
+ # Tries each lengthscale and signal variance pair and returns the one with the highest log marginal likelihood.
10
+ # The hash has `:kernel_lengthscale`, `:kernel_variance` and `:log_marginal_likelihood`.
11
+ # It skips pairs that fail to factor.
12
+ # When no pair works, it returns 0.3, 1.0 and negative infinity.
13
+ def self.optimize_hyperparameters(inputs, outputs, noise_variance:,
14
+ lengthscales: [0.05, 0.1, 0.2, 0.3, 0.5, 0.8],
15
+ signal_variances: [0.3, 0.5, 1.0, 2.0])
16
+ best = { kernel_lengthscale: 0.3, kernel_variance: 1.0, log_marginal_likelihood: -Float::INFINITY }
17
+
18
+ lengthscales.product(signal_variances).each do |lengthscale, signal_variance|
19
+ process = new(
20
+ training_inputs: inputs,
21
+ training_outputs: outputs,
22
+ noise_variance: noise_variance,
23
+ kernel_lengthscale: lengthscale,
24
+ kernel_variance: signal_variance
25
+ )
26
+ likelihood = process.log_marginal_likelihood
27
+ next unless likelihood > best[:log_marginal_likelihood]
28
+
29
+ best = { kernel_lengthscale: lengthscale, kernel_variance: signal_variance, log_marginal_likelihood: likelihood }
30
+ rescue RuntimeError
31
+ next
32
+ end
33
+
34
+ best
35
+ end
36
+
37
+ # Factors the kernel matrix here, so it raises `RuntimeError` when the matrix cannot be factored.
38
+ def initialize(training_inputs:, training_outputs:, noise_variance:, kernel_lengthscale:, kernel_variance:)
39
+ @training_inputs = training_inputs
40
+ @training_outputs = training_outputs
41
+ @noise_variance = noise_variance
42
+ @lengthscale = kernel_lengthscale
43
+ @signal_variance = kernel_variance
44
+ precompute_kernel_matrices!
45
+ end
46
+
47
+ attr_reader :output_std
48
+
49
+ # Returns how well the model fits its training data. Higher is better.
50
+ # Returns negative infinity when there is no training data.
51
+ def log_marginal_likelihood
52
+ return -Float::INFINITY if @cholesky_lower.nil? || @alpha_coefficients.nil?
53
+
54
+ n = @centered_outputs.length
55
+
56
+ data_fit = -0.5 * @centered_outputs.each_with_index.sum { |y, i| y * @alpha_coefficients[i] }
57
+
58
+ complexity = -@cholesky_lower.each_with_index.sum { |row, i| Math.log(row[i]) }
59
+
60
+ normalization = -n / 2.0 * Math.log(2.0 * Math::PI)
61
+
62
+ data_fit + complexity + normalization
63
+ end
64
+
65
+ # Returns `[mean, variance]` predicted at the query point. The variance is never below `MIN_PREDICTED_VARIANCE * output_std**2`, so it is always above 0.
66
+ # It needs at least one training point.
67
+ def predict(query_point)
68
+ k_star = @training_inputs.map { |training_point| rbf_kernel(training_point, query_point) }
69
+
70
+ predicted_mean = @output_mean + @output_std * k_star.each_with_index.sum { |k, i| k * @alpha_coefficients[i] }
71
+
72
+ query_self_covariance = @signal_variance
73
+
74
+ v = Ltr::Optimize::CholeskyDecomposition.forward_substitute(@cholesky_lower, k_star)
75
+
76
+ # Rounding error can push the variance slightly below zero, so it is floored below.
77
+ predicted_variance = query_self_covariance - v.sum { |vi| vi * vi }
78
+
79
+ predicted_variance = [predicted_variance, MIN_PREDICTED_VARIANCE].max
80
+
81
+ [predicted_mean, predicted_variance * @output_std**2]
82
+ end
83
+
84
+ private
85
+
86
+ def precompute_kernel_matrices!
87
+ num_training_points = @training_inputs.length
88
+ return if num_training_points == 0
89
+
90
+ kernel_matrix = build_kernel_matrix_vectorized
91
+
92
+ @cholesky_lower = Ltr::Optimize::CholeskyDecomposition.decompose(kernel_matrix)
93
+
94
+ @output_mean = @training_outputs.sum.fdiv(num_training_points)
95
+ variance = @training_outputs.sum { |output| (output - @output_mean)**2 }.fdiv(num_training_points)
96
+ spread = Math.sqrt(variance)
97
+ @output_std = (spread < MIN_OUTPUT_STD) ? 1.0 : spread
98
+ @centered_outputs = @training_outputs.map { |output| (output - @output_mean) / @output_std }
99
+ @alpha_coefficients = Ltr::Optimize::CholeskyDecomposition.solve(@cholesky_lower, @centered_outputs)
100
+ end
101
+
102
+ def build_kernel_matrix_vectorized
103
+ inputs_array = Numo::DFloat.cast(@training_inputs)
104
+ n = inputs_array.shape[0]
105
+
106
+ # Uses |a - b|^2 = |a|^2 + |b|^2 - 2 a.b so all pairwise distances come from one matrix product.
107
+ norms_sq = (inputs_array * inputs_array).sum(axis: 1)
108
+ dot_products = inputs_array.dot(inputs_array.transpose)
109
+ squared_distances = norms_sq.reshape(n, 1) + norms_sq.reshape(1, n) - 2 * dot_products
110
+
111
+ kernel_values = @signal_variance * Numo::NMath.exp(-0.5 * squared_distances / (@lengthscale**2))
112
+
113
+ kernel_matrix = Matrix.rows(kernel_values.to_a)
114
+ n.times { |i| kernel_matrix[i, i] += @noise_variance }
115
+
116
+ kernel_matrix
117
+ end
118
+
119
+ def rbf_kernel(point1, point2)
120
+ diff = Numo::DFloat.cast(point1) - Numo::DFloat.cast(point2)
121
+ squared_distance = (diff * diff).sum
122
+
123
+ @signal_variance * Math.exp(-0.5 * squared_distance / (@lengthscale**2))
124
+ end
125
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Holds the dataframe, the split cache and the split names that the optimizers share.
4
+
5
+ class Ltr::Optimize::OptimizationDataset
6
+ def initialize(df, config)
7
+ raise ArgumentError, "df must be a dataframe" unless df.is_a?(Rover::DataFrame)
8
+
9
+ @df = df
10
+ @split_cache = Ltr::Data::SplitCache.new(df)
11
+ @early_stopping_split = Ltr::Data::Splits.early_stopping_in(df, config)
12
+ @optimization_split = Ltr::Data::Splits.optimization_in(df, config)
13
+ end
14
+
15
+ attr_reader :df, :split_cache, :early_stopping_split, :optimization_split
16
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Selects the best feature set with the configured feature selection strategy.
4
+
5
+ class Ltr::Optimize::OptimizeFeatures
6
+ extend Ltr::Callable
7
+
8
+ # Raises `ArgumentError` when `dataset` is not an `OptimizationDataset`.
9
+ def initialize(dataset, config)
10
+ raise ArgumentError, "dataset must be an OptimizationDataset" unless dataset.is_a?(Ltr::Optimize::OptimizationDataset)
11
+
12
+ @dataset = dataset
13
+ @df = dataset.df
14
+ @split_cache = dataset.split_cache
15
+ @optimization_split = dataset.optimization_split
16
+ @config = config
17
+ @hyperparameters = config.hyperparameters
18
+ @complexity_penalty = config.optimization["complexity_penalty"] || 0
19
+ @search_time_features = config.optimization["search_time_features"] || []
20
+ @feature_store_features = config.optimization["feature_store_features"] || []
21
+ @metric_to_optimize = config.metric_to_optimize
22
+ @min_features = config.optimization["min_features"] || 1
23
+ @strategy_name = config.optimization.dig("feature_selection", "strategy")
24
+ @nthread = config.nthread
25
+ end
26
+
27
+ # Returns a hash with `:search_time_features` and `:feature_store_features` holding the selected features.
28
+ # Derived features go in the search time list.
29
+ # Features that are not in the dataframe are left out and logged.
30
+ # It trains with `verbose_eval: false` on a copy of the hyperparameters. The config's hash is not changed.
31
+ # Raises `ArgumentError` for invalid settings, or when the features do not outnumber `min_features`.
32
+ # Raises `Ltr::ConfigurationError` for an unknown `optimization.feature_selection.strategy`.
33
+ def call
34
+ validate_inputs!
35
+ select_features
36
+ end
37
+
38
+ private
39
+
40
+ attr_reader :dataset, :df, :hyperparameters, :metric_to_optimize, :complexity_penalty, :min_features, :search_time_features, :feature_store_features, :config, :split_cache, :nthread, :strategy_name, :optimization_split
41
+
42
+ def validate_inputs!
43
+ logger.info("Validating feature optimization inputs...")
44
+ raise ArgumentError, "hyperparameters must be a hash" unless hyperparameters.is_a?(Hash)
45
+ raise ArgumentError, "search_time_features must be an array of strings" unless search_time_features.is_a?(Array) && search_time_features.all? { |feature| feature.is_a?(String) }
46
+ raise ArgumentError, "feature_store_features must be an array of strings" unless feature_store_features.is_a?(Array) && feature_store_features.all? { |feature| feature.is_a?(String) }
47
+ raise ArgumentError, "total features must be larger than min_features" if all_features.size <= min_features
48
+ raise ArgumentError, "metric_to_optimize must be specified" if metric_to_optimize.nil? || metric_to_optimize.empty?
49
+
50
+ logger.info("Feature optimization inputs validated successfully")
51
+ end
52
+
53
+ def all_features
54
+ search_time_features + derived_feature_names + feature_store_features
55
+ end
56
+
57
+ def derived_feature_names
58
+ Ltr::Features::FeatureEngineering.derived_feature_names(search_time_features, config.feature_engineering)
59
+ end
60
+
61
+ def select_features
62
+ @hyperparameters = @hyperparameters.transform_keys(&:to_sym).merge(verbose_eval: false)
63
+ logger.info("Scoring feature subsets on the '#{optimization_split}' split")
64
+
65
+ features = get_features_to_optimize
66
+ logger.info("Optimizing for: #{metric_to_optimize} (with complexity penalty: #{complexity_penalty})")
67
+ separate_optimized_features(strategy.call(features))
68
+ end
69
+
70
+ def get_features_to_optimize
71
+ features_to_optimize = all_features.dup
72
+ missing_features = features_to_optimize - df.names
73
+ if missing_features.any?
74
+ logger.warn("The following features are not in the dataframe: #{missing_features}")
75
+ end
76
+ available_features = features_to_optimize - missing_features
77
+ logger.info("Features available for optimization: #{available_features.size} out of #{features_to_optimize.size}")
78
+ available_features
79
+ end
80
+
81
+ def strategy
82
+ Ltr::Optimize::FeatureSelection::Strategy.build(
83
+ strategy_name,
84
+ trial: trial,
85
+ min_features: min_features,
86
+ complexity_penalty: complexity_penalty
87
+ )
88
+ end
89
+
90
+ def trial
91
+ Ltr::Optimize::FeatureSelection::Trial.new(
92
+ dataset,
93
+ config,
94
+ hyperparameters: hyperparameters,
95
+ metric_to_optimize: metric_to_optimize,
96
+ evaluation_cache: evaluation_cache,
97
+ nthread: nthread
98
+ )
99
+ end
100
+
101
+ def evaluation_cache
102
+ @evaluation_cache ||= Ltr::Train::EvaluationCache.for_metric(
103
+ df,
104
+ split: optimization_split,
105
+ config: config,
106
+ metric: metric_to_optimize,
107
+ split_cache: split_cache
108
+ )
109
+ end
110
+
111
+ def separate_optimized_features(optimized_features)
112
+ optimized_search_time_features = optimized_features & search_time_features
113
+ optimized_derived_features = optimized_features & derived_feature_names
114
+ optimized_feature_store_features = optimized_features & feature_store_features
115
+
116
+ logger.info("Optimized search time features: #{optimized_search_time_features}")
117
+ logger.info("Optimized derived features: #{optimized_derived_features}")
118
+ logger.info("Optimized feature store features: #{optimized_feature_store_features}")
119
+
120
+ {
121
+ search_time_features: optimized_search_time_features + optimized_derived_features,
122
+ feature_store_features: optimized_feature_store_features,
123
+ }
124
+ end
125
+
126
+ def logger
127
+ Ltr.config.logger
128
+ end
129
+ end