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.
- checksums.yaml +7 -0
- data/ARCHITECTURE.md +92 -0
- data/CHANGELOG.md +5 -0
- data/LICENSE +21 -0
- data/README.md +186 -0
- data/docs/AGENTS.md +67 -0
- data/docs/aggregation-engines.md +80 -0
- data/docs/config.md +516 -0
- data/docs/data-contracts.md +94 -0
- data/docs/data-splits.md +34 -0
- data/docs/dataset-builder-steps.md +13 -0
- data/docs/dataset-csv.md +73 -0
- data/docs/dataset-enrichers.md +62 -0
- data/docs/errors.md +33 -0
- data/docs/feature-selection.md +108 -0
- data/docs/features.md +202 -0
- data/docs/glossary.md +56 -0
- data/docs/host-integration.md +128 -0
- data/docs/host-run-pipelines.md +48 -0
- data/docs/index.md +50 -0
- data/docs/inference.md +164 -0
- data/docs/label-transformers.md +242 -0
- data/docs/labels-from-behavior.md +94 -0
- data/docs/learning-to-rank.md +119 -0
- data/docs/metrics.md +166 -0
- data/docs/model-files.md +73 -0
- data/docs/optimization.md +72 -0
- data/docs/public-api.md +67 -0
- data/docs/rake-tasks.md +82 -0
- data/docs/relevance-grades.md +80 -0
- data/docs/run-locally.md +584 -0
- data/docs/run-on-aws.md +647 -0
- data/docs/training-objective.md +110 -0
- data/docs/ubi-documents.md +75 -0
- data/docs/ubi-logging.md +125 -0
- data/lib/ltr/README.md +28 -0
- data/lib/ltr/configuration/README.md +12 -0
- data/lib/ltr/configuration/config_loader.rb +326 -0
- data/lib/ltr/configuration/config_validator.rb +476 -0
- data/lib/ltr/configuration/configuration.rb +84 -0
- data/lib/ltr/configuration/example_config.yml +182 -0
- data/lib/ltr/data/README.md +20 -0
- data/lib/ltr/data/csv/README.md +9 -0
- data/lib/ltr/data/csv/typed_columns.rb +101 -0
- data/lib/ltr/data/csv.rb +126 -0
- data/lib/ltr/data/dataframe.rb +80 -0
- data/lib/ltr/data/dataset_loader.rb +29 -0
- data/lib/ltr/data/row_store.rb +188 -0
- data/lib/ltr/data/split_cache.rb +30 -0
- data/lib/ltr/data/splits.rb +86 -0
- data/lib/ltr/dataset_aggregation/README.md +32 -0
- data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
- data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
- data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
- data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
- data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
- data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
- data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
- data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
- data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
- data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
- data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
- data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
- data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
- data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
- data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
- data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
- data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
- data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
- data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
- data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
- data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
- data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
- data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
- data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
- data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
- data/lib/ltr/deploy/README.md +21 -0
- data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
- data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
- data/lib/ltr/deploy/feature_extractor.rb +94 -0
- data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
- data/lib/ltr/deploy/local_deployer.rb +61 -0
- data/lib/ltr/deploy/model_packager.rb +90 -0
- data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
- data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
- data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
- data/lib/ltr/errors/README.md +16 -0
- data/lib/ltr/errors/configuration_error.rb +5 -0
- data/lib/ltr/errors/deploy_error.rb +5 -0
- data/lib/ltr/errors/error.rb +5 -0
- data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
- data/lib/ltr/errors/missing_dependency_error.rb +5 -0
- data/lib/ltr/errors/sqlite_error.rb +14 -0
- data/lib/ltr/features/README.md +19 -0
- data/lib/ltr/features/encoders/README.md +10 -0
- data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
- data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
- data/lib/ltr/features/feature_engineering.rb +194 -0
- data/lib/ltr/features/feature_transformer.rb +92 -0
- data/lib/ltr/features/float32_range.rb +20 -0
- data/lib/ltr/features/transform_steps.rb +34 -0
- data/lib/ltr/features/transform_store.rb +123 -0
- data/lib/ltr/inference/README.md +11 -0
- data/lib/ltr/inference/base.rb +52 -0
- data/lib/ltr/inference/local_reranker.rb +147 -0
- data/lib/ltr/inference/sagemaker_client.rb +62 -0
- data/lib/ltr/metrics/README.md +12 -0
- data/lib/ltr/metrics/metric_scores.rb +67 -0
- data/lib/ltr/metrics/metrics.rb +139 -0
- data/lib/ltr/optimize/README.md +25 -0
- data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
- data/lib/ltr/optimize/candidate_selector.rb +97 -0
- data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
- data/lib/ltr/optimize/expected_improvement.rb +33 -0
- data/lib/ltr/optimize/feature_selection/README.md +15 -0
- data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
- data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
- data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
- data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
- data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
- data/lib/ltr/optimize/gaussian_process.rb +125 -0
- data/lib/ltr/optimize/optimization_dataset.rb +16 -0
- data/lib/ltr/optimize/optimize_features.rb +129 -0
- data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
- data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
- data/lib/ltr/optimize/search_space.rb +165 -0
- data/lib/ltr/optimize/update_config.rb +196 -0
- data/lib/ltr/ssm/README.md +11 -0
- data/lib/ltr/ssm/loader.rb +61 -0
- data/lib/ltr/ssm/parameter_paths.rb +19 -0
- data/lib/ltr/ssm/saver.rb +76 -0
- data/lib/ltr/support/README.md +13 -0
- data/lib/ltr/support/callable.rb +10 -0
- data/lib/ltr/support/optional_dependency.rb +31 -0
- data/lib/ltr/support/pipeline_result.rb +22 -0
- data/lib/ltr/support/pipeline_task.rb +81 -0
- data/lib/ltr/support/version.rb +7 -0
- data/lib/ltr/tasks/ltr.rake +24 -0
- data/lib/ltr/train/README.md +19 -0
- data/lib/ltr/train/deploy_gate.rb +77 -0
- data/lib/ltr/train/deploy_metric.rb +63 -0
- data/lib/ltr/train/eval_logger.rb +16 -0
- data/lib/ltr/train/evaluation_cache.rb +101 -0
- data/lib/ltr/train/modelling_pipeline.rb +82 -0
- data/lib/ltr/train/optimization_split_report.rb +54 -0
- data/lib/ltr/train/utils.rb +35 -0
- data/lib/ltr/train/xgb_evaluator.rb +96 -0
- data/lib/ltr/train/xgb_trainer.rb +154 -0
- data/lib/ltr/ubi.rb +86 -0
- data/lib/ltr.rb +61 -0
- data/scripts/seed_ubi.rb +75 -0
- metadata +346 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Calls a SageMaker endpoint to score a payload.
|
|
4
|
+
|
|
5
|
+
class Ltr::Inference::SagemakerClient
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
DEFAULT_OPEN_TIMEOUT = 0.5
|
|
9
|
+
DEFAULT_READ_TIMEOUT = 0.5
|
|
10
|
+
|
|
11
|
+
# Raises `ArgumentError` when `config` is nil and no endpoint is given.
|
|
12
|
+
def initialize(payload, config, custom_model_endpoint = nil)
|
|
13
|
+
@payload = payload
|
|
14
|
+
@config = config
|
|
15
|
+
@_model_endpoint = custom_model_endpoint.presence
|
|
16
|
+
raise ArgumentError, "custom_model_endpoint is required when config is nil" if config.nil? && @_model_endpoint.nil?
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Sends the payload to the endpoint and returns the parsed JSON response.
|
|
20
|
+
# The endpoint is the custom one, else `<model name>-endpoint`.
|
|
21
|
+
# The open and read timeouts are 0.5 seconds unless `inference.sagemaker` sets them.
|
|
22
|
+
def call
|
|
23
|
+
response = sagemaker_client.invoke_endpoint(
|
|
24
|
+
endpoint_name: model_endpoint,
|
|
25
|
+
content_type: "application/json",
|
|
26
|
+
body: payload.to_json
|
|
27
|
+
)
|
|
28
|
+
JSON.parse(response.body.read)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
attr_reader :payload, :config
|
|
34
|
+
|
|
35
|
+
def sagemaker_client
|
|
36
|
+
@_sagemaker_client ||= begin
|
|
37
|
+
Ltr::OptionalDependency.require!("aws-sdk-sagemakerruntime", feature: "SageMaker inference")
|
|
38
|
+
Aws::SageMakerRuntime::Client.new(
|
|
39
|
+
http_open_timeout: open_timeout,
|
|
40
|
+
http_read_timeout: read_timeout
|
|
41
|
+
)
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def open_timeout
|
|
46
|
+
sagemaker_settings.fetch("open_timeout", DEFAULT_OPEN_TIMEOUT)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def read_timeout
|
|
50
|
+
sagemaker_settings.fetch("read_timeout", DEFAULT_READ_TIMEOUT)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def sagemaker_settings
|
|
54
|
+
return {} if config.nil?
|
|
55
|
+
|
|
56
|
+
config.inference.fetch("sagemaker", {})
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def model_endpoint
|
|
60
|
+
@_model_endpoint ||= "#{config.model_name}-endpoint"
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# `lib/ltr/metrics`
|
|
2
|
+
|
|
3
|
+
Ranking evaluation metrics within the `Ltr::Metrics` namespace, used to score model predictions during training and optimization. Provides pure metric implementations plus a helper that computes a named set of metrics with optional `@k` cutoffs.
|
|
4
|
+
|
|
5
|
+
The [Metrics](../../../docs/metrics.md) guide has the formulas, the NDCG gain function, and the edge cases. [Relevance grades](../../../docs/relevance-grades.md) explains how a relevance percentile becomes a grade.
|
|
6
|
+
|
|
7
|
+
## Files
|
|
8
|
+
|
|
9
|
+
| File | Purpose |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `metrics.rb` | Pure implementations of ranking metrics: NDCG, MAP, MRR, precision, and recall, plus `relevance_threshold` for resolving a percentile to a label value. |
|
|
12
|
+
| `metric_scores.rb` | Computes a set of named metrics (e.g. `ndcg@5`, `map@10`) for given predictions and labels, parsing each metric's optional `@k` cutoff. |
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Calculates a set of ranking metrics for one list of predictions and labels.
|
|
4
|
+
|
|
5
|
+
class Ltr::Metrics::MetricScores
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
# Metric name to the lambda that scores it. The names `validate_spec!` accepts are these keys.
|
|
9
|
+
SCORERS = {
|
|
10
|
+
"ndcg" => ->(ranked, ideal, k:, order:, min_relevance_grade:, exp_gain:) { Ltr::Metrics::Metrics.ndcg_score(ranked, ideal, k:, exp_gain:) },
|
|
11
|
+
"map" => ->(ranked, ideal, k:, order:, min_relevance_grade:, exp_gain:) { Ltr::Metrics::Metrics.map_score(ranked, ideal, min_relevance_grade:, k:, order:) },
|
|
12
|
+
"mrr" => ->(ranked, ideal, k:, order:, min_relevance_grade:, exp_gain:) { Ltr::Metrics::Metrics.mrr_score(ranked, ideal, min_relevance_grade:, k:, order:) },
|
|
13
|
+
"precision" => ->(ranked, ideal, k:, order:, min_relevance_grade:, exp_gain:) { Ltr::Metrics::Metrics.precision_score(ranked, ideal, min_relevance_grade:, k:, order:) },
|
|
14
|
+
"recall" => ->(ranked, ideal, k:, order:, min_relevance_grade:, exp_gain:) { Ltr::Metrics::Metrics.recall_score(ranked, ideal, min_relevance_grade:, k:, order:) },
|
|
15
|
+
}.freeze
|
|
16
|
+
SPEC_PATTERN = /\A(?:#{SCORERS.keys.join("|")})(?:@[1-9]\d*)?\z/i
|
|
17
|
+
|
|
18
|
+
# Raises `Ltr::ConfigurationError` naming `label` unless `spec` is a metric name from `SCORERS` with an optional `@` and a cutoff of at least 1.
|
|
19
|
+
def self.validate_spec!(spec, label)
|
|
20
|
+
return if spec.is_a?(String) && SPEC_PATTERN.match?(spec)
|
|
21
|
+
|
|
22
|
+
raise Ltr::ConfigurationError,
|
|
23
|
+
"#{label} must be one of #{SCORERS.keys.join(", ")}, optionally followed by @ and a cutoff of at least 1 (got #{spec.inspect})"
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def self.normalize_name(spec)
|
|
27
|
+
spec.to_s.downcase
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def initialize(preds, labels, metrics, min_relevance_grade: 1, ndcg_exp_gain: false)
|
|
31
|
+
@preds = preds
|
|
32
|
+
@labels = labels
|
|
33
|
+
@metrics = metrics
|
|
34
|
+
@min_relevance_grade = min_relevance_grade
|
|
35
|
+
@ndcg_exp_gain = ndcg_exp_gain
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Returns a hash of metric spec to score, rounded to 4 places.
|
|
39
|
+
# A spec is a name with an optional cutoff, such as `ndcg@10`. Without a cutoff it uses every item.
|
|
40
|
+
# The case of the name does not matter. The keys are lowercase.
|
|
41
|
+
# A name not in `SCORERS` raises `ArgumentError`.
|
|
42
|
+
def call
|
|
43
|
+
order = Ltr::Metrics::Metrics.descending_indices(preds)
|
|
44
|
+
|
|
45
|
+
metrics.each_with_object({}) do |metric_spec, results|
|
|
46
|
+
results[self.class.normalize_name(metric_spec)] = calculate_metric(metric_spec, preds, labels, order)
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
private
|
|
51
|
+
|
|
52
|
+
attr_reader :preds, :labels, :metrics, :min_relevance_grade, :ndcg_exp_gain
|
|
53
|
+
|
|
54
|
+
def calculate_metric(metric_spec, ranked, ideal, order)
|
|
55
|
+
metric, k = parse_metric(metric_spec)
|
|
56
|
+
|
|
57
|
+
scorer = SCORERS.fetch(metric) { raise ArgumentError, "unsupported metric #{metric_spec.inspect}" }
|
|
58
|
+
|
|
59
|
+
scorer.call(ranked, ideal, k:, order:, min_relevance_grade:, exp_gain: ndcg_exp_gain).round(4)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def parse_metric(metric)
|
|
63
|
+
metric, k = metric.split("@")
|
|
64
|
+
k = k ? k.to_i : labels.size
|
|
65
|
+
[metric.downcase, k]
|
|
66
|
+
end
|
|
67
|
+
end
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Calculates ranking metrics such as NDCG, MAP, MRR, precision and recall.
|
|
4
|
+
|
|
5
|
+
class Ltr::Metrics::Metrics
|
|
6
|
+
class << self
|
|
7
|
+
# Returns NDCG for one ranked list, or 0.0 when the ideal DCG is zero.
|
|
8
|
+
# Docs with equal predictions share the average of their gains, as sklearn's `ndcg_score` does.
|
|
9
|
+
def ndcg_score(ranked, ideal, k: nil, exp_gain: false)
|
|
10
|
+
validate_k!(k)
|
|
11
|
+
raise ArgumentError, "ideal must contain numeric relevance scores." unless ideal.all?(Numeric)
|
|
12
|
+
dcg = discounted_sum(tie_averaged_gains(ranked, ideal, exp_gain).first(k || ranked.size))
|
|
13
|
+
|
|
14
|
+
ideal_sorted_true = ideal.sort.reverse
|
|
15
|
+
ideal_sorted_true = ideal_sorted_true.first(k) if k
|
|
16
|
+
ideal_dcg = dcg_score(ideal_sorted_true, exp_gain: exp_gain)
|
|
17
|
+
|
|
18
|
+
return 0.0 if ideal_dcg == 0.0
|
|
19
|
+
dcg / ideal_dcg
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# DCG = sum of gain / log2(position + 1), with positions starting at 1.
|
|
23
|
+
def dcg_score(relevance_scores, exp_gain: false)
|
|
24
|
+
discounted_sum(relevance_scores.map { |relevance| gain(relevance.to_f, exp_gain) })
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Returns the average precision of one ranked list.
|
|
28
|
+
# It divides by all relevant items, including those below the cutoff `k`. It returns 0.0 when there are none.
|
|
29
|
+
def map_score(ranked, ideal, min_relevance_grade: 1, k: nil, order: nil)
|
|
30
|
+
validate_k!(k)
|
|
31
|
+
indices = order || descending_indices(ranked)
|
|
32
|
+
indices = indices.first(k) if k
|
|
33
|
+
|
|
34
|
+
hits = 0
|
|
35
|
+
sum_precisions = 0.0
|
|
36
|
+
relevant_ideal_count = ideal.count { |l| relevant?(l, min_relevance_grade) }
|
|
37
|
+
|
|
38
|
+
indices.each_with_index do |idx, i|
|
|
39
|
+
if relevant?(ideal[idx], min_relevance_grade)
|
|
40
|
+
hits += 1
|
|
41
|
+
sum_precisions += hits.to_f / (i + 1)
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
denom = relevant_ideal_count
|
|
46
|
+
denom.zero? ? 0.0 : sum_precisions / denom
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Returns the reciprocal rank of the first relevant item, or 0.0 if there is none.
|
|
50
|
+
def mrr_score(ranked, ideal, min_relevance_grade: 1, k: nil, order: nil)
|
|
51
|
+
validate_k!(k)
|
|
52
|
+
indices = order || descending_indices(ranked)
|
|
53
|
+
indices = indices.first(k) if k
|
|
54
|
+
|
|
55
|
+
indices.each_with_index do |idx, i|
|
|
56
|
+
return 1.0 / (i + 1) if relevant?(ideal[idx], min_relevance_grade)
|
|
57
|
+
end
|
|
58
|
+
0.0
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Returns the share of the top `k` items that are relevant.
|
|
62
|
+
# It divides by `k` even when the list is shorter. Without `k` it divides by the list size.
|
|
63
|
+
def precision_score(ranked, ideal, min_relevance_grade: 1, k: nil, order: nil)
|
|
64
|
+
validate_k!(k)
|
|
65
|
+
indices = order || descending_indices(ranked)
|
|
66
|
+
indices = indices.first(k) if k
|
|
67
|
+
return 0.0 if indices.empty?
|
|
68
|
+
|
|
69
|
+
relevant_count = indices.count { |idx| relevant?(ideal[idx], min_relevance_grade) }
|
|
70
|
+
relevant_count.to_f / (k || indices.size)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# Returns the share of all relevant items that appear in the top `k`.
|
|
74
|
+
def recall_score(ranked, ideal, min_relevance_grade: 1, k: nil, order: nil)
|
|
75
|
+
validate_k!(k)
|
|
76
|
+
indices = order || descending_indices(ranked)
|
|
77
|
+
indices = indices.first(k) if k
|
|
78
|
+
relevant_total = ideal.count { |l| relevant?(l, min_relevance_grade) }
|
|
79
|
+
return 0.0 if relevant_total.zero?
|
|
80
|
+
relevant_found = indices.count { |idx| relevant?(ideal[idx], min_relevance_grade) }
|
|
81
|
+
relevant_found.to_f / relevant_total
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Returns the positions of `ranked` ordered from the highest value to the lowest.
|
|
85
|
+
# Equal values come out in no guaranteed order.
|
|
86
|
+
def descending_indices(ranked)
|
|
87
|
+
ranked.each_with_index.sort_by { |val, idx| -val }.map(&:last)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Returns true when `label` is at least `min_relevance_grade`.
|
|
91
|
+
def relevant?(label, min_relevance_grade)
|
|
92
|
+
label >= min_relevance_grade
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# Returns the lowest label value whose share of items at or above it is at most `100 - percentile` percent.
|
|
96
|
+
# When no value fits, such as when all labels tie, it returns the highest label.
|
|
97
|
+
# Raises `ArgumentError` for an empty list or a percentile that is not strictly between 0 and 100.
|
|
98
|
+
def relevance_threshold(labels, percentile)
|
|
99
|
+
raise ArgumentError, "percentile must be between 0 and 100 exclusive." unless percentile > 0 && percentile < 100
|
|
100
|
+
raise ArgumentError, "labels cannot be empty." if labels.empty?
|
|
101
|
+
|
|
102
|
+
sorted = labels.map(&:to_f).sort
|
|
103
|
+
count = sorted.length
|
|
104
|
+
requested_share = (100 - percentile) / 100.0
|
|
105
|
+
|
|
106
|
+
sorted.each_with_index do |value, index|
|
|
107
|
+
first_occurrence_of_value = index.zero? || sorted[index - 1] != value
|
|
108
|
+
next unless first_occurrence_of_value
|
|
109
|
+
|
|
110
|
+
relevant_share = (count - index).fdiv(count)
|
|
111
|
+
return value if relevant_share <= requested_share
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
sorted.last
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
private
|
|
118
|
+
|
|
119
|
+
def validate_k!(k)
|
|
120
|
+
return if k.nil?
|
|
121
|
+
raise ArgumentError, "k must be greater than 0 if specified." if k < 1
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def discounted_sum(gains)
|
|
125
|
+
gains.each_with_index.sum { |gain_value, i| gain_value / Math.log2(i + 2) }
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def tie_averaged_gains(ranked, ideal, exp_gain)
|
|
129
|
+
ranked.each_index.group_by { |i| ranked[i].to_f }.sort_by { |score, _| -score }.flat_map do |_, tied|
|
|
130
|
+
mean_gain = tied.sum { |i| gain(ideal[i].to_f, exp_gain) } / tied.size
|
|
131
|
+
Array.new(tied.size, mean_gain)
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def gain(relevance, exp_gain)
|
|
136
|
+
exp_gain ? (2**relevance) - 1 : relevance
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# `lib/ltr/optimize`
|
|
2
|
+
|
|
3
|
+
`OptimizePipeline.call(config)` and `ltr:optimize` run the optimization pipeline. It selects the features, then tunes the XGBoost hyperparameters with a Bayesian search, then writes both to the config file and to SSM when `ssm.enabled`. [Optimization](../../../docs/optimization.md) explains how it works.
|
|
4
|
+
|
|
5
|
+
## Subfolders
|
|
6
|
+
|
|
7
|
+
| Folder | Purpose |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `feature_selection/` | The interchangeable search strategies, selected by `optimization.feature_selection.strategy`: `greedy_backward` (default), `rfe` and `importance_ranked`. |
|
|
10
|
+
|
|
11
|
+
## Files
|
|
12
|
+
|
|
13
|
+
| File | Purpose |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `optimize_pipeline.rb` | `OptimizePipeline.call(config)` entry point that loads the dataset, runs feature and hyperparameter optimization, then writes the results back to the config file and SSM. |
|
|
16
|
+
| `optimize_features.rb` | Runs the configured `feature_selection/` strategy over the optimization features, owning the feature list and the shared evaluation cache. |
|
|
17
|
+
| `optimization_dataset.rb` | The dataset for one optimization run: the `Rover::DataFrame`, its `SplitCache`, and the resolved early stopping and optimization splits. |
|
|
18
|
+
| `optimize_hyperparameters.rb` | Tunes XGBoost hyperparameters via `BayesianOptimizer` over the configured search space, scoring candidates on the optimization split. |
|
|
19
|
+
| `bayesian_optimizer.rb` | Gaussian-process-based Bayesian optimization over a bounded search space using expected improvement, with early stopping and local refinement. |
|
|
20
|
+
| `candidate_selector.rb` | Draws global and local candidates for one iteration, scores them with `ExpectedImprovement` and returns the best one that was not evaluated yet, or `nil` when all were. |
|
|
21
|
+
| `expected_improvement.rb` | The expected improvement score and the normal pdf/cdf it uses. |
|
|
22
|
+
| `gaussian_process.rb` | Gaussian process regression with an RBF kernel used as the surrogate model, including kernel hyperparameter selection via log marginal likelihood. |
|
|
23
|
+
| `cholesky_decomposition.rb` | Pure linear-algebra utilities for Cholesky decomposition and forward/back substitution used by the Gaussian process. |
|
|
24
|
+
| `search_space.rb` | Bounded hyperparameter search space supporting random sampling, Latin hypercube sampling, and unit-cube normalization for int/float parameters. |
|
|
25
|
+
| `update_config.rb` | Writes optimized features and hyperparameters back into the YAML config file, replacing only the affected sections while preserving comments. `paths:` limits the rewrite to some sections. A section the file lacks is added. `ConfigLoader#save!` uses it too. |
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Finds the best hyperparameters by fitting a Gaussian process and picking points with expected improvement.
|
|
4
|
+
|
|
5
|
+
class Ltr::Optimize::BayesianOptimizer
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
DEFAULT_CONFIG = {
|
|
9
|
+
candidates_per_iteration: 1000,
|
|
10
|
+
noise_variance: 0.1,
|
|
11
|
+
kernel_lengthscale: 0.3,
|
|
12
|
+
kernel_variance: 1.0,
|
|
13
|
+
ei_xi: 0.5,
|
|
14
|
+
early_stopping_patience: 10,
|
|
15
|
+
early_stopping_threshold: 1e-4,
|
|
16
|
+
local_refinement_fraction: 0.2,
|
|
17
|
+
local_refinement_top_k: 5,
|
|
18
|
+
local_refinement_radius_start: 0.2,
|
|
19
|
+
local_refinement_radius_end: 0.02,
|
|
20
|
+
optimize_hyperparameters_every: 10,
|
|
21
|
+
}.freeze
|
|
22
|
+
|
|
23
|
+
# Raises `Ltr::ConfigurationError` for the first option with the wrong type or a value out of range. The message names the rule.
|
|
24
|
+
# `options` override the keys in `DEFAULT_CONFIG`.
|
|
25
|
+
def self.validate!(options)
|
|
26
|
+
config = DEFAULT_CONFIG.merge(options)
|
|
27
|
+
{
|
|
28
|
+
iterations: 0,
|
|
29
|
+
n_init: 1,
|
|
30
|
+
candidates_per_iteration: 1,
|
|
31
|
+
early_stopping_patience: 1,
|
|
32
|
+
local_refinement_top_k: 1,
|
|
33
|
+
optimize_hyperparameters_every: 0,
|
|
34
|
+
}.each do |key, minimum|
|
|
35
|
+
raise Ltr::ConfigurationError, "#{key} must be an integer of at least #{minimum}" unless config[key].is_a?(Integer) && config[key] >= minimum
|
|
36
|
+
end
|
|
37
|
+
%i[noise_variance ei_xi early_stopping_threshold local_refinement_radius_start local_refinement_radius_end].each do |key|
|
|
38
|
+
raise Ltr::ConfigurationError, "#{key} must be a number of at least 0" unless config[key].is_a?(Numeric) && config[key] >= 0
|
|
39
|
+
end
|
|
40
|
+
%i[kernel_lengthscale kernel_variance].each do |key|
|
|
41
|
+
raise Ltr::ConfigurationError, "#{key} must be a number above 0" unless config[key].is_a?(Numeric) && config[key] > 0
|
|
42
|
+
end
|
|
43
|
+
unless config[:local_refinement_fraction].is_a?(Numeric) && (0...1).cover?(config[:local_refinement_fraction])
|
|
44
|
+
raise Ltr::ConfigurationError, "local_refinement_fraction must be at least 0 and below 1"
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# `objective` takes a parameters hash and returns the number to minimize.
|
|
49
|
+
# `options` must include `iterations`, `n_init` and `seed`. They also override the keys in `DEFAULT_CONFIG`.
|
|
50
|
+
# See `validate!` for the checks. `seed` must be an integer.
|
|
51
|
+
def initialize(objective:, param_space:, **options)
|
|
52
|
+
self.class.validate!(options)
|
|
53
|
+
raise Ltr::ConfigurationError, "seed must be an integer. It comes from the top-level seed key" unless options[:seed].is_a?(Integer)
|
|
54
|
+
@objective = objective
|
|
55
|
+
@param_space = param_space
|
|
56
|
+
@config = DEFAULT_CONFIG.merge(options)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Runs `n_init` Latin hypercube points without the repeats, then up to `iterations` guided points.
|
|
60
|
+
# It stops early after `early_stopping_patience` guided points in a row with a very small expected improvement.
|
|
61
|
+
# It also stops when every point sampled for an iteration was already evaluated, so a guided point is never evaluated twice.
|
|
62
|
+
# The objective is minimized.
|
|
63
|
+
# Returns a hash with `:best_parameters`, `:best_value`, `:history` and `:iterations_run`.
|
|
64
|
+
# `:history` holds every evaluation. `:iterations_run` counts only the guided points.
|
|
65
|
+
def call
|
|
66
|
+
setup_optimization
|
|
67
|
+
run_initial_sampling
|
|
68
|
+
run_bayesian_iterations
|
|
69
|
+
return_final_results
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
private
|
|
73
|
+
|
|
74
|
+
attr_reader :objective, :param_space, :config
|
|
75
|
+
attr_reader :search_space, :candidate_selector, :unit_vectors, :objective_values, :parameter_history, :evaluation_history
|
|
76
|
+
|
|
77
|
+
def setup_optimization
|
|
78
|
+
@search_space = Ltr::Optimize::SearchSpace.new(param_space, random_seed: config[:seed])
|
|
79
|
+
@candidate_selector = Ltr::Optimize::CandidateSelector.new(search_space: search_space, config: config)
|
|
80
|
+
@unit_vectors = []
|
|
81
|
+
@objective_values = []
|
|
82
|
+
@parameter_history = []
|
|
83
|
+
@evaluation_history = []
|
|
84
|
+
|
|
85
|
+
logger.info("Starting Bayesian optimization with #{config[:iterations]} iterations and #{config[:n_init]} initial random points...")
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def run_initial_sampling
|
|
89
|
+
logger.info("Starting Latin Hypercube initial sampling...")
|
|
90
|
+
initial_points = search_space.latin_hypercube_sample(config[:n_init]).uniq
|
|
91
|
+
@initial_evaluation_count = initial_points.size
|
|
92
|
+
initial_points.each_with_index do |parameters, i|
|
|
93
|
+
value = objective.call(parameters)
|
|
94
|
+
store_evaluation(parameters, value)
|
|
95
|
+
logger.info("LHS init #{i + 1}/#{initial_points.size}: value = #{value.round(4)}, parameters = #{parameters}")
|
|
96
|
+
end
|
|
97
|
+
logger.info("Initial sampling completed")
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def store_evaluation(parameters, value)
|
|
101
|
+
unit_vectors << search_space.to_unit_vector(parameters)
|
|
102
|
+
objective_values << value.to_f
|
|
103
|
+
parameter_history << parameters
|
|
104
|
+
evaluation_history << { parameters: parameters, value: value }
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def run_bayesian_iterations
|
|
108
|
+
logger.info("Starting Bayesian optimization iterations...")
|
|
109
|
+
stale_iterations = 0
|
|
110
|
+
|
|
111
|
+
config[:iterations].times do |iteration_number|
|
|
112
|
+
max_ei = run_bayesian_iteration(iteration_number)
|
|
113
|
+
if max_ei.nil?
|
|
114
|
+
logger.info("Stopping: every sampled candidate point was already evaluated")
|
|
115
|
+
break
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
if below_early_stopping_threshold?(max_ei)
|
|
119
|
+
stale_iterations += 1
|
|
120
|
+
if stale_iterations >= config[:early_stopping_patience]
|
|
121
|
+
logger.info("Early stopping: max EI below relative threshold for #{stale_iterations} consecutive iterations")
|
|
122
|
+
break
|
|
123
|
+
end
|
|
124
|
+
else
|
|
125
|
+
stale_iterations = 0
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
logger.info("Bayesian optimization iterations completed")
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def run_bayesian_iteration(iteration_number)
|
|
133
|
+
maybe_optimize_hyperparameters(iteration_number)
|
|
134
|
+
parameters, max_ei = candidate_selector.select_next_point(
|
|
135
|
+
build_gaussian_process, objective_values.min, iteration_number, parameter_history
|
|
136
|
+
)
|
|
137
|
+
return if parameters.nil?
|
|
138
|
+
|
|
139
|
+
value = objective.call(parameters)
|
|
140
|
+
store_evaluation(parameters, value)
|
|
141
|
+
log_iteration_result(iteration_number, parameters, value, max_ei)
|
|
142
|
+
max_ei
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def maybe_optimize_hyperparameters(iteration_number)
|
|
146
|
+
interval = config[:optimize_hyperparameters_every]
|
|
147
|
+
return if interval.zero?
|
|
148
|
+
return unless iteration_number % interval == 0
|
|
149
|
+
|
|
150
|
+
result = Ltr::Optimize::GaussianProcess.optimize_hyperparameters(
|
|
151
|
+
unit_vectors, objective_values, noise_variance: config[:noise_variance]
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
@learned_lengthscale = result[:kernel_lengthscale]
|
|
155
|
+
@learned_signal_variance = result[:kernel_variance]
|
|
156
|
+
|
|
157
|
+
logger.info("Hyperparameter optimization: lengthscale=#{@learned_lengthscale}, signal_variance=#{@learned_signal_variance}, LML=#{result.fetch(:log_marginal_likelihood).round(4)}")
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def build_gaussian_process
|
|
161
|
+
Ltr::Optimize::GaussianProcess.new(
|
|
162
|
+
training_inputs: unit_vectors,
|
|
163
|
+
training_outputs: objective_values,
|
|
164
|
+
noise_variance: config[:noise_variance],
|
|
165
|
+
kernel_lengthscale: @learned_lengthscale || config[:kernel_lengthscale],
|
|
166
|
+
kernel_variance: @learned_signal_variance || config[:kernel_variance]
|
|
167
|
+
)
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def log_iteration_result(iteration_number, parameters, value, max_ei)
|
|
171
|
+
current_best_index = argmin(objective_values)
|
|
172
|
+
current_best_value = objective_values[current_best_index]
|
|
173
|
+
previous_best_value = objective_values[0...-1].min || Float::INFINITY
|
|
174
|
+
is_new_best = current_best_value == value && value < previous_best_value
|
|
175
|
+
|
|
176
|
+
status = is_new_best ? " (NEW BEST!)" : ""
|
|
177
|
+
logger.info("Iteration #{iteration_number + 1}/#{config[:iterations]}: value = #{value.round(4)}, EI = #{max_ei.round(6)}, parameters = #{parameters}#{status}")
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def argmin(array)
|
|
181
|
+
array.each_with_index.min_by { |value, _| value }[1]
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def below_early_stopping_threshold?(max_ei)
|
|
185
|
+
objective_range = objective_values.max - objective_values.min
|
|
186
|
+
return false if objective_range <= 0.0
|
|
187
|
+
|
|
188
|
+
max_ei < config[:early_stopping_threshold] * objective_range
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def return_final_results
|
|
192
|
+
best_index = argmin(objective_values)
|
|
193
|
+
total_evaluations = objective_values.length
|
|
194
|
+
iterations_run = total_evaluations - @initial_evaluation_count
|
|
195
|
+
|
|
196
|
+
logger.info("Bayesian optimization complete!")
|
|
197
|
+
logger.info("Final best value: #{objective_values[best_index].round(4)}")
|
|
198
|
+
logger.info("Final best parameters: #{parameter_history[best_index]}")
|
|
199
|
+
logger.info("Total evaluations: #{total_evaluations} (#{iterations_run}/#{config[:iterations]} iterations)")
|
|
200
|
+
|
|
201
|
+
{
|
|
202
|
+
best_parameters: parameter_history[best_index],
|
|
203
|
+
best_value: objective_values[best_index],
|
|
204
|
+
history: evaluation_history,
|
|
205
|
+
iterations_run: iterations_run,
|
|
206
|
+
}
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
def logger
|
|
210
|
+
Ltr.config.logger
|
|
211
|
+
end
|
|
212
|
+
end
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Picks the next point to try by scoring random and local candidates with expected improvement.
|
|
4
|
+
|
|
5
|
+
class Ltr::Optimize::CandidateSelector
|
|
6
|
+
def initialize(search_space:, config:)
|
|
7
|
+
@search_space = search_space
|
|
8
|
+
@config = config
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
# Returns `[parameters, expected_improvement]` for the best candidate, or `nil` when every sampled candidate was already evaluated.
|
|
12
|
+
# `evaluated_parameters` lists the parameter hashes that were tried before. Those candidates are never returned.
|
|
13
|
+
# `candidates_per_iteration` candidates are scored. `local_refinement_fraction` of them are local.
|
|
14
|
+
# Local candidates are small random changes to the global candidates with the highest expected improvement.
|
|
15
|
+
# At most `local_refinement_top_k` global candidates are used.
|
|
16
|
+
def select_next_point(gaussian_process, current_best_value, iteration_number, evaluated_parameters)
|
|
17
|
+
seen = evaluated_parameters.to_set
|
|
18
|
+
xi = exploration_parameter_for_iteration(iteration_number)
|
|
19
|
+
|
|
20
|
+
total = config[:candidates_per_iteration]
|
|
21
|
+
n_local = (total * config[:local_refinement_fraction]).to_i
|
|
22
|
+
n_global = total - n_local
|
|
23
|
+
|
|
24
|
+
best_candidate_from_global_and_local_search(
|
|
25
|
+
gaussian_process, n_global, n_local, iteration_number, current_best_value, xi, seen
|
|
26
|
+
)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Returns the exploration weight for the iteration. It falls in a straight line from `ei_xi` at iteration 0.
|
|
30
|
+
# It would reach zero at iteration `iterations`, which never runs, so the last iteration still gets a small weight.
|
|
31
|
+
def exploration_parameter_for_iteration(iteration_number)
|
|
32
|
+
config[:ei_xi] * (1.0 - iteration_number.to_f / config[:iterations])
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
private
|
|
36
|
+
|
|
37
|
+
attr_reader :search_space, :config
|
|
38
|
+
|
|
39
|
+
def best_candidate_from_global_and_local_search(gaussian_process, n_global, n_local, iteration_number, current_best_value, xi, seen)
|
|
40
|
+
global_candidates, global_unit_vectors, global_scores =
|
|
41
|
+
generate_and_score_global_candidates(gaussian_process, n_global, current_best_value, xi)
|
|
42
|
+
|
|
43
|
+
return best_unseen_candidate(global_candidates, global_scores, seen) if n_local.zero?
|
|
44
|
+
|
|
45
|
+
local_candidates, local_scores = generate_and_score_local_candidates(
|
|
46
|
+
global_unit_vectors, global_scores, gaussian_process, iteration_number, n_local, current_best_value, xi
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
best_unseen_candidate(global_candidates + local_candidates, global_scores + local_scores, seen)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def best_unseen_candidate(candidates, scores, seen)
|
|
53
|
+
best_idx = scores.each_index.reject { |i| seen.include?(candidates[i]) }.max_by { |i| scores[i] }
|
|
54
|
+
best_idx && [candidates[best_idx], scores[best_idx]]
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def generate_and_score_global_candidates(gaussian_process, n_global, current_best_value, xi)
|
|
58
|
+
candidates = Array.new(n_global) { search_space.random_point }
|
|
59
|
+
unit_vectors = candidates.map { |params| search_space.to_unit_vector(params) }
|
|
60
|
+
scores = unit_vectors.map { |uv| Ltr::Optimize::ExpectedImprovement.score(gaussian_process, uv, current_best_value, xi) }
|
|
61
|
+
[candidates, unit_vectors, scores]
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def generate_and_score_local_candidates(global_unit_vectors, global_scores, gaussian_process, iteration_number, n_local, current_best_value, xi)
|
|
65
|
+
effective_top_k = [config[:local_refinement_top_k], n_local, global_unit_vectors.length].min
|
|
66
|
+
top_indices = global_scores.each_with_index.sort_by { |score, _| -score }.first(effective_top_k).map(&:last)
|
|
67
|
+
top_unit_vectors = top_indices.map { |i| global_unit_vectors[i] }
|
|
68
|
+
|
|
69
|
+
radius = local_refinement_radius(iteration_number)
|
|
70
|
+
candidates_per_center, remainder = n_local.divmod(effective_top_k)
|
|
71
|
+
|
|
72
|
+
local_unit_vectors = top_unit_vectors.flat_map.with_index do |center, i|
|
|
73
|
+
count = candidates_per_center + ((i < remainder) ? 1 : 0)
|
|
74
|
+
Array.new(count) { perturb_unit_vector(center, radius) }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
local_candidates = local_unit_vectors.map { |uv| search_space.from_unit_vector(uv) }
|
|
78
|
+
local_scores = local_unit_vectors.map { |uv| Ltr::Optimize::ExpectedImprovement.score(gaussian_process, uv, current_best_value, xi) }
|
|
79
|
+
|
|
80
|
+
[local_candidates, local_scores]
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def local_refinement_radius(iteration_number)
|
|
84
|
+
r_start = config[:local_refinement_radius_start]
|
|
85
|
+
r_end = config[:local_refinement_radius_end]
|
|
86
|
+
progress = iteration_number.to_f / [config[:iterations] - 1, 1].max
|
|
87
|
+
r_start + (r_end - r_start) * progress
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def perturb_unit_vector(center, radius)
|
|
91
|
+
center.map { |v| (v + perturbation_rng.rand(-radius..radius)).clamp(0.0, 1.0) }
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def perturbation_rng
|
|
95
|
+
@perturbation_rng ||= Random.new(config[:seed] + 1)
|
|
96
|
+
end
|
|
97
|
+
end
|