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,68 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class Ltr::DatasetAggregation::DatasetBuilder
|
|
4
|
+
# Combines the rows for each query and document pair into one row.
|
|
5
|
+
class UserQueryAggregator
|
|
6
|
+
def initialize(context)
|
|
7
|
+
@context = context
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
# Returns a row store with one row for each `qid`, `user_query` and document ID.
|
|
11
|
+
# Columns that end in `_count` are summed.
|
|
12
|
+
# Score columns come from the row with the most impressions, or the latest `timestamp` if they tie.
|
|
13
|
+
# A row with no `timestamp` loses a tie to a row that has one.
|
|
14
|
+
# A nil or false score is left out.
|
|
15
|
+
# All other columns, including `timestamp`, are dropped.
|
|
16
|
+
def call(query_id_aggregated_data)
|
|
17
|
+
grouped_data = query_id_aggregated_data.group_by do |doc_result|
|
|
18
|
+
[doc_result[:qid], doc_result[:user_query], doc_result[context.doc_id_field.to_sym]]
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
all_features = collect_unique_keys(query_id_aggregated_data)
|
|
22
|
+
aggregated_data = Ltr::Data::RowStore.new
|
|
23
|
+
grouped_data.each do |(key, doc_results)|
|
|
24
|
+
qid, user_query, doc_id = key
|
|
25
|
+
result = aggregate_query_doc_group(qid, user_query, doc_id, doc_results, all_features)
|
|
26
|
+
result.delete(:timestamp)
|
|
27
|
+
aggregated_data.append(result)
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
aggregated_data
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
private
|
|
34
|
+
|
|
35
|
+
attr_reader :context
|
|
36
|
+
|
|
37
|
+
def collect_unique_keys(data)
|
|
38
|
+
if data.is_a?(Ltr::Data::RowStore)
|
|
39
|
+
data.keys.to_set
|
|
40
|
+
else
|
|
41
|
+
keys = Set.new
|
|
42
|
+
data.each { |row| keys.merge(row.keys) }
|
|
43
|
+
keys
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def aggregate_query_doc_group(qid, user_query, doc_id, doc_results, features)
|
|
48
|
+
doc_id_key = context.doc_id_field.to_sym
|
|
49
|
+
identity_keys = [:qid, :user_query, doc_id_key, :timestamp]
|
|
50
|
+
aggregated_doc_result = { :qid => qid, :user_query => user_query, doc_id_key => doc_id }
|
|
51
|
+
rows = doc_results.is_a?(Ltr::Data::RowStore) ? doc_results.to_a : doc_results
|
|
52
|
+
most_recent_doc_result = rows.max_by { |doc_result| [doc_result[:impression_count].to_i, doc_result[:timestamp].nil? ? 0 : 1, doc_result[:timestamp].to_s] }
|
|
53
|
+
|
|
54
|
+
features.each do |key|
|
|
55
|
+
next if identity_keys.include?(key)
|
|
56
|
+
|
|
57
|
+
if key.to_s.end_with?("_count")
|
|
58
|
+
aggregated_doc_result[key] = rows.sum { |doc_result| doc_result[key] || 0 }
|
|
59
|
+
elsif context.feature_names.include?(key)
|
|
60
|
+
value = most_recent_doc_result[key]
|
|
61
|
+
aggregated_doc_result[key] = value if value
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
aggregated_doc_result
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Turns UBI queries and events into the labeled rows of the modelling dataset.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::DatasetBuilder
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(config, ubi_data, query_id_field: nil, doc_id_field: nil, should_shuffle_data: nil, debug_mode: nil)
|
|
9
|
+
@config = config
|
|
10
|
+
@ubi_data = ubi_data
|
|
11
|
+
@context = Context.build(
|
|
12
|
+
config,
|
|
13
|
+
query_id_field: query_id_field,
|
|
14
|
+
doc_id_field: doc_id_field,
|
|
15
|
+
should_shuffle_data: should_shuffle_data,
|
|
16
|
+
debug_mode: debug_mode
|
|
17
|
+
)
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Joins and aggregates the UBI queries and events, then labels and splits them.
|
|
21
|
+
# Empties the `ubi_data` hash it was given.
|
|
22
|
+
# Raises `ArgumentError` if the UBI data, the ID fields or the conversion rate targets are invalid.
|
|
23
|
+
# Returns the finished dataset as a `Rover::DataFrame`.
|
|
24
|
+
def call
|
|
25
|
+
validate_inputs!
|
|
26
|
+
queries, events = extract_queries_and_events
|
|
27
|
+
@ubi_data.clear
|
|
28
|
+
logger.info("Initial data: #{queries.length} queries, #{events.length} events")
|
|
29
|
+
|
|
30
|
+
queries_with_events = UbiJoiner.new(@context).call(queries, events)
|
|
31
|
+
query_id_aggregated_data = QueryAggregator.new(@context).call(queries_with_events)
|
|
32
|
+
queries_with_events.clear
|
|
33
|
+
logger.info("Query ID aggregated data: #{query_id_aggregated_data.length} records")
|
|
34
|
+
|
|
35
|
+
aggregated_data = UserQueryAggregator.new(@context).call(query_id_aggregated_data)
|
|
36
|
+
query_id_aggregated_data.clear
|
|
37
|
+
logger.info("User query aggregated data: #{aggregated_data.length} records")
|
|
38
|
+
aggregated_data = NegativeDownsampler.new(@context).call(aggregated_data) if @context.negative_downsample_ratio
|
|
39
|
+
|
|
40
|
+
Ltr::DatasetAggregation::DatasetFinalizer.call(@context, aggregated_data, debug_mode: @context.debug_mode)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# The feature transform steps that `call` applied to the dataset. Empty before `call`.
|
|
44
|
+
def feature_transform_steps
|
|
45
|
+
context.feature_transform_steps
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Doc id to feature name to value for each doc with no train rows, as `call` left them. Empty before `call`.
|
|
49
|
+
def fallback_feature_totals
|
|
50
|
+
context.fallback_feature_totals
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# The names of the one-hot columns that `call` made. Empty before `call`.
|
|
54
|
+
def one_hot_columns
|
|
55
|
+
context.one_hot_columns
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
attr_reader :ubi_data, :context
|
|
61
|
+
|
|
62
|
+
def validate_inputs!
|
|
63
|
+
raise ArgumentError, "UBI data must be a hash" unless ubi_data.is_a?(Hash)
|
|
64
|
+
raise ArgumentError, "UBI data must contain :queries key" unless ubi_data.key?(:queries)
|
|
65
|
+
raise ArgumentError, "UBI data must contain :events key" unless ubi_data.key?(:events)
|
|
66
|
+
raise ArgumentError, "UBI queries cannot be empty" if ubi_data[:queries].blank?
|
|
67
|
+
raise ArgumentError, "UBI events cannot be empty" if ubi_data[:events].blank?
|
|
68
|
+
raise ArgumentError, "Query ID field must be a string" unless context.query_id_field.is_a?(String)
|
|
69
|
+
raise ArgumentError, "Document ID field must be a string" unless context.doc_id_field.is_a?(String)
|
|
70
|
+
unless context.conversion_rate_targets.is_a?(Array) && !context.conversion_rate_targets.empty?
|
|
71
|
+
raise ArgumentError, "Conversion rate targets must be a non-empty array"
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def extract_queries_and_events
|
|
76
|
+
[ubi_data[:queries], ubi_data[:events]]
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def logger
|
|
80
|
+
Ltr.config.logger
|
|
81
|
+
end
|
|
82
|
+
end
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Base class for adding features to the dataset.
|
|
4
|
+
# Subclasses fetch the features.
|
|
5
|
+
|
|
6
|
+
class Ltr::DatasetAggregation::DatasetEnricher
|
|
7
|
+
extend Ltr::Callable
|
|
8
|
+
|
|
9
|
+
NO_FEATURES_MESSAGE = "DatasetEnricher: No features found, returning original dataset"
|
|
10
|
+
|
|
11
|
+
def initialize(dataset, config:)
|
|
12
|
+
@dataset = dataset
|
|
13
|
+
@config = config
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Looks up features for the unique doc IDs in the dataset and left-joins them on the `dataset_builder.doc_id_field` column.
|
|
17
|
+
# Rows with no doc ID are ignored in the lookup.
|
|
18
|
+
# A feature column becomes floats, and a nil is always NaN. A row with no doc ID keeps NaN features.
|
|
19
|
+
# A missing value is nil, a Float NaN, a blank string or the string `"NaN"`.
|
|
20
|
+
# A column is text when at least one non-missing value is a String. Each non-missing value becomes its `to_s`, and a missing value becomes nil.
|
|
21
|
+
# A column of only blank and `"NaN"` strings becomes blank strings. In a column of numbers, a missing value becomes NaN.
|
|
22
|
+
# The pipeline one-hot encodes the text columns afterwards.
|
|
23
|
+
# When the features hold a doc ID more than once, it keeps the first row and logs a warning.
|
|
24
|
+
# Doc IDs are strings. The features frame may hold Integer or String IDs, and both join as strings. A nil ID is skipped.
|
|
25
|
+
# Raises `ArgumentError` unless the dataset is a `Rover::DataFrame` with that column.
|
|
26
|
+
# Raises `ArgumentError` if an ID of the features frame is neither an Integer, a String nor nil, such as a Float.
|
|
27
|
+
# Raises `ArgumentError` if a feature column has the name of a dataset column other than the `dataset_builder.doc_id_field` column.
|
|
28
|
+
# Raises `Ltr::InvalidDatasetError` if the features frame has rows and none of their IDs are in the dataset.
|
|
29
|
+
# Logs how many of the dataset doc IDs the features frame matched.
|
|
30
|
+
# Returns the enriched dataset. Returns the dataset unchanged and logs `NO_FEATURES_MESSAGE` if it has no doc IDs or the features frame has no rows.
|
|
31
|
+
# When it joins, the id column of the dataset is replaced in place by its IDs, with nil for a row that has none. The result keeps that column, so one missing id does not turn the others into floats.
|
|
32
|
+
def call
|
|
33
|
+
validate_dataset!
|
|
34
|
+
doc_ids = normalized_doc_ids
|
|
35
|
+
if doc_ids.compact.empty?
|
|
36
|
+
logger.info(NO_FEATURES_MESSAGE)
|
|
37
|
+
return dataset
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
features = fetch_features(doc_ids.compact.uniq)
|
|
41
|
+
if features.size.zero?
|
|
42
|
+
logger.info(NO_FEATURES_MESSAGE)
|
|
43
|
+
return dataset
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
enrich_dataset_with_features(features, doc_ids)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Receives the unique doc IDs of the dataset as they are in the dataset.
|
|
50
|
+
# Subclasses must override it and return a `Rover::DataFrame` of features with a `dataset_builder.doc_id_field` column.
|
|
51
|
+
def fetch_features(unique_doc_ids)
|
|
52
|
+
raise NotImplementedError, "Subclasses must implement fetch_features method"
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
attr_reader :dataset, :config
|
|
58
|
+
|
|
59
|
+
def id_column
|
|
60
|
+
config.doc_id_field
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def validate_dataset!
|
|
64
|
+
unless dataset.is_a?(Rover::DataFrame) && dataset.vectors.key?(id_column)
|
|
65
|
+
raise ArgumentError, "Dataset must be a Rover::DataFrame with '#{id_column}' column. Got: #{dataset.class}"
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def normalized_doc_ids
|
|
70
|
+
dataset[id_column].to_a.map { |id| missing_id?(id) ? nil : id }
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def missing_id?(id)
|
|
74
|
+
id.nil? || (id.respond_to?(:nan?) && id.nan?)
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def enrich_dataset_with_features(features_df, doc_ids)
|
|
78
|
+
clean_features = normalize_features_df(features_df)
|
|
79
|
+
validate_ids_matched!(clean_features, doc_ids)
|
|
80
|
+
validate_no_column_clash!(clean_features)
|
|
81
|
+
|
|
82
|
+
doc_id_vector = Rover::Vector.new(doc_ids, type: :object)
|
|
83
|
+
dataset[id_column] = doc_id_vector
|
|
84
|
+
|
|
85
|
+
enriched = dataset.left_join(first_row_per_doc(clean_features), on: id_column)
|
|
86
|
+
enriched[id_column] = doc_id_vector
|
|
87
|
+
enriched
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def validate_ids_matched!(features_df, doc_ids)
|
|
91
|
+
dataset_ids = doc_ids.compact.uniq
|
|
92
|
+
features_ids = features_df[id_column].to_a.compact.uniq
|
|
93
|
+
matched = dataset_ids & features_ids
|
|
94
|
+
if matched.empty?
|
|
95
|
+
raise Ltr::InvalidDatasetError,
|
|
96
|
+
"DatasetEnricher: none of the #{dataset_ids.size} doc ids in '#{id_column}' matched the #{features_ids.size} ids in the features frame. " \
|
|
97
|
+
"Check that the host has the rows. " \
|
|
98
|
+
"To run without the enricher, set `dataset_enricher.class` to blank."
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
logger.info("DatasetEnricher: matched #{matched.size} of #{dataset_ids.size} doc ids in '#{id_column}'")
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def validate_no_column_clash!(features_df)
|
|
105
|
+
clashing = (features_df.keys - [id_column]) & dataset.keys
|
|
106
|
+
return if clashing.empty?
|
|
107
|
+
|
|
108
|
+
raise ArgumentError, "Enricher features would overwrite dataset columns: #{clashing.join(", ")}"
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def normalize_features_df(features_df)
|
|
112
|
+
features_data = {}
|
|
113
|
+
features_df.vectors.keys.each do |col|
|
|
114
|
+
features_data[col] = if col == id_column
|
|
115
|
+
string_ids(features_df[col].to_a)
|
|
116
|
+
else
|
|
117
|
+
normalized_values(features_df[col].to_a)
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
Rover::DataFrame.new(features_data)
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def normalized_values(values)
|
|
125
|
+
present = values.reject { |v| missing_value?(v) }
|
|
126
|
+
return text_values(values) if present.any?(String)
|
|
127
|
+
return values.map { "" } if present.empty? && values.any? { |v| missing_marker?(v) }
|
|
128
|
+
|
|
129
|
+
values.map { |v| missing_value?(v) ? Float::NAN : v.to_f }
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def text_values(values)
|
|
133
|
+
Rover::Vector.new(values.map { |v| missing_value?(v) ? nil : v.to_s }, type: :object)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def missing_value?(value)
|
|
137
|
+
value.nil? || missing_marker?(value) || (value.is_a?(Float) && value.nan?)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def missing_marker?(value)
|
|
141
|
+
value.is_a?(String) && (value.blank? || value == Ltr::Data::Csv::NAN_TOKEN)
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def string_ids(ids)
|
|
145
|
+
invalid_types = ids.compact.map(&:class).uniq - [Integer, String]
|
|
146
|
+
unless invalid_types.empty?
|
|
147
|
+
raise ArgumentError,
|
|
148
|
+
"Enricher ids for column '#{id_column}' are #{invalid_types.join(", ")}. Cast the ids to Integer or String."
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
ids.map { |id| id&.to_s }
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def first_row_per_doc(features_df)
|
|
155
|
+
ids = features_df[id_column].to_a
|
|
156
|
+
duplicated_ids = ids.tally.select { |_id, count| count > 1 }.keys
|
|
157
|
+
return features_df if duplicated_ids.empty?
|
|
158
|
+
|
|
159
|
+
seen = Set.new
|
|
160
|
+
keep = ids.map { |id| !seen.add?(id).nil? }
|
|
161
|
+
logger.warn("DatasetEnricher: #{keep.count(false)} duplicate #{id_column} row(s) in the features, keeping the first for each. Examples: #{duplicated_ids.first(5).join(", ")}")
|
|
162
|
+
features_df[Rover::Vector.new(keep)]
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
def logger
|
|
166
|
+
Ltr.config.logger
|
|
167
|
+
end
|
|
168
|
+
end
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Creates the labels and applies the filters, encoding and feature steps to the aggregated rows.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::DatasetFinalizer
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(context, aggregated_data, debug_mode: false)
|
|
9
|
+
@context = context
|
|
10
|
+
@aggregated_data = aggregated_data
|
|
11
|
+
@debug_mode = debug_mode
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Creates the labels, then runs the filter, encoding, split and feature steps.
|
|
15
|
+
# With `cascade_cutoff` off, rows with no impressions skip the labelling and get a label of 0.0.
|
|
16
|
+
# With `debug_mode`, the behavioural features are skipped. Otherwise `impression_count` is dropped.
|
|
17
|
+
# It leaves the feature transform steps it applied in `context.feature_transform_steps`, and the one-hot column names in `context.one_hot_columns`.
|
|
18
|
+
# It also leaves the val and test totals of the documents with no train rows in `context.fallback_feature_totals`, with the same steps applied.
|
|
19
|
+
# Returns the finished dataset as a `Rover::DataFrame` with a `split` column.
|
|
20
|
+
def call
|
|
21
|
+
examined_rows, negatives = split_negatives(aggregated_data)
|
|
22
|
+
data = Ltr::DatasetAggregation::DatasetBuilder::LabelCreator.new(context).call(examined_rows)
|
|
23
|
+
logger.info("Labels created for #{data.length} records")
|
|
24
|
+
|
|
25
|
+
data = apply_label_transformer(data)
|
|
26
|
+
data = append_negatives(data, negatives)
|
|
27
|
+
data = Ltr::DatasetAggregation::DatasetBuilder::DatasetFilters.new(context).filter_queries_below_min_documents(data)
|
|
28
|
+
data = Ltr::Features::FeatureEncoder.new(context).call(data)
|
|
29
|
+
data = apply_feature_engineering(data)
|
|
30
|
+
|
|
31
|
+
data = Ltr::DatasetAggregation::DatasetBuilder::SplitAssigner.new(context).call(data)
|
|
32
|
+
data = add_behavioural_features(data)
|
|
33
|
+
data = apply_feature_transformations(data)
|
|
34
|
+
transform_fallback_feature_totals
|
|
35
|
+
dataset = data.to_dataframe
|
|
36
|
+
logger.info("Dataset building completed. Final dataset: #{dataset.length} rows, #{dataset.keys.length} columns")
|
|
37
|
+
|
|
38
|
+
dataset
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
private
|
|
42
|
+
|
|
43
|
+
attr_reader :context, :aggregated_data, :debug_mode
|
|
44
|
+
|
|
45
|
+
def config
|
|
46
|
+
context.config
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# With the cascade cutoff on, the rows are already examined. Without it, zero-impression rows are set aside as negatives.
|
|
50
|
+
def split_negatives(aggregated_data)
|
|
51
|
+
return [aggregated_data, nil] if context.cascade_cutoff
|
|
52
|
+
|
|
53
|
+
impressions = aggregated_data.pluck(Ltr::DatasetAggregation::DatasetBuilder::LabelCreator::DEFAULT_DENOMINATOR)
|
|
54
|
+
negative_indices, examined_indices = (0...aggregated_data.length).partition { |index| impressions[index].to_i.zero? }
|
|
55
|
+
[aggregated_data.select_indices(examined_indices), aggregated_data.select_indices(negative_indices)]
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def apply_label_transformer(aggregated_data)
|
|
59
|
+
transformer_class = Ltr::DatasetAggregation::LabelTransformer.resolve(config.label_transformer)
|
|
60
|
+
logger.info("Applying label transformer: #{transformer_class}")
|
|
61
|
+
transformer_class.call(aggregated_data, config: config)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def append_negatives(data, negatives)
|
|
65
|
+
return data if negatives.nil? || negatives.empty?
|
|
66
|
+
|
|
67
|
+
negatives.add_column(:raw_label, default: 0.0)
|
|
68
|
+
negatives.add_column(:label, default: 0.0)
|
|
69
|
+
logger.info("Appended #{negatives.length} label-0 negatives to #{data.length} labelled records")
|
|
70
|
+
data.concat(negatives)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def apply_feature_engineering(aggregated_data)
|
|
74
|
+
Ltr::Features::FeatureEngineering.engineer_features(aggregated_data, config)
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def add_behavioural_features(data)
|
|
78
|
+
if debug_mode
|
|
79
|
+
warn_debug_mode_dataset
|
|
80
|
+
return data
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
data = Ltr::DatasetAggregation::DatasetBuilder::BehaviouralFeatureBuilder.new(context).call(data)
|
|
84
|
+
data.delete_column(Ltr::DatasetAggregation::DatasetBuilder::LabelCreator::DEFAULT_DENOMINATOR)
|
|
85
|
+
context.fallback_feature_totals.each_value { |totals| totals.delete(Ltr::DatasetAggregation::DatasetBuilder::LabelCreator::DEFAULT_DENOMINATOR.to_s) }
|
|
86
|
+
logger.info("Behavioural features calculated")
|
|
87
|
+
data
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def warn_debug_mode_dataset
|
|
91
|
+
dropped = (config.dataset_builder["conversion_features"] || []).filter_map { |feature| feature["name"] }
|
|
92
|
+
dropped_note = dropped.any? ? ", and conversion_features (#{dropped.join(", ")}) are absent entirely" : ""
|
|
93
|
+
logger.warn("debug_mode enabled: this dataset is for analysis, NOT training. Skipping " \
|
|
94
|
+
"BehaviouralFeatureBuilder means every *_count column (including impression_count) stays at its " \
|
|
95
|
+
"per-(qid, doc) grain rather than the per-doc train-split total that inference serves (a doc with no train rows gets its val and test total instead)#{dropped_note}. " \
|
|
96
|
+
"Training and feature optimization only warn about missing features and do not check how counts are grouped, so they will not catch this.")
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def apply_feature_transformations(aggregated_data)
|
|
100
|
+
transformer = Ltr::Features::FeatureTransformer.new(aggregated_data, config: config)
|
|
101
|
+
transformed = transformer.call
|
|
102
|
+
context.feature_transform_steps = transformer.steps
|
|
103
|
+
transformed
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def transform_fallback_feature_totals
|
|
107
|
+
steps = context.feature_transform_steps
|
|
108
|
+
context.fallback_feature_totals = context.fallback_feature_totals.transform_values do |totals|
|
|
109
|
+
totals.to_h { |feature, value| [feature, Ltr::Features::TransformSteps.apply(steps, feature, value)] }
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def logger
|
|
114
|
+
Ltr.config.logger
|
|
115
|
+
end
|
|
116
|
+
end
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Runs the dataset aggregation with the chosen engine and saves the result.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::DatasetPipeline
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
RUBY_ENGINE_NAME = "ruby"
|
|
9
|
+
SQLITE_ENGINE_NAME = "sqlite"
|
|
10
|
+
|
|
11
|
+
def initialize(config)
|
|
12
|
+
@config = config
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Builds the dataset with the sqlite engine if `dataset_builder.aggregation_engine` is `sqlite`, and with the ruby engine otherwise.
|
|
16
|
+
# Adds the enricher features if `dataset_enricher` is set, then saves the dataset.
|
|
17
|
+
# Text columns from the enricher are one-hot encoded, and their flag names are added to the one-hot column names.
|
|
18
|
+
# It also saves the feature transform steps, the one-hot column names and the fallback feature totals next to the dataset, in one `.serving.json` file.
|
|
19
|
+
# Raises `Ltr::ConfigurationError` before any download if the enricher or the label transformer class does not exist.
|
|
20
|
+
# Returns a `Ltr::PipelineResult`.
|
|
21
|
+
def call
|
|
22
|
+
logger.info("Starting dataset aggregation pipeline")
|
|
23
|
+
enricher_class = resolve_enricher_class
|
|
24
|
+
Ltr::DatasetAggregation::LabelTransformer.resolve(config.label_transformer)
|
|
25
|
+
dataset, feature_transform_steps, one_hot_columns, fallback_feature_totals = (aggregation_engine == SQLITE_ENGINE_NAME) ? build_with_sqlite_engine : build_with_ruby_engine
|
|
26
|
+
|
|
27
|
+
enriched_dataset, enriched_flag_names = enrich(dataset, enricher_class)
|
|
28
|
+
|
|
29
|
+
logger.info("Saving dataset...")
|
|
30
|
+
Ltr::Features::TransformStore.delete_dataset(config)
|
|
31
|
+
Ltr::DatasetAggregation::DatasetSaver.call(config, enriched_dataset)
|
|
32
|
+
Ltr::Features::TransformStore.write_dataset(config, feature_transform_steps, one_hot_columns + enriched_flag_names, fallback_feature_totals)
|
|
33
|
+
logger.info("Dataset aggregation pipeline completed successfully")
|
|
34
|
+
|
|
35
|
+
Ltr::PipelineResult.new(
|
|
36
|
+
rows: enriched_dataset.length,
|
|
37
|
+
columns: enriched_dataset.keys.length,
|
|
38
|
+
enriched: !enricher_class.nil?,
|
|
39
|
+
dataset_path: config.modelling_dataset_path
|
|
40
|
+
)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
attr_reader :config
|
|
46
|
+
|
|
47
|
+
def aggregation_engine
|
|
48
|
+
config.dataset_builder.dig("aggregation_engine").presence || RUBY_ENGINE_NAME
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def build_with_sqlite_engine
|
|
52
|
+
logger.info("Aggregating UBI data with the sqlite engine")
|
|
53
|
+
context = Ltr::DatasetAggregation::DatasetBuilder::Context.build(config)
|
|
54
|
+
staging = Ltr::DatasetAggregation::SqliteStaging.new(context)
|
|
55
|
+
phase = :download
|
|
56
|
+
outer_error = $!
|
|
57
|
+
|
|
58
|
+
begin
|
|
59
|
+
Ltr::DatasetAggregation::SqliteUbiDataLoader.call(config, staging, context)
|
|
60
|
+
|
|
61
|
+
phase = :aggregation
|
|
62
|
+
read_sql = Ltr::DatasetAggregation::SqliteAggregator.call(config, staging, context)
|
|
63
|
+
|
|
64
|
+
phase = :aggregate_load
|
|
65
|
+
aggregated_data = Ltr::DatasetAggregation::AggregatedSqliteLoader.call(staging, read_sql, context)
|
|
66
|
+
|
|
67
|
+
phase = :finalize
|
|
68
|
+
dataset = Ltr::DatasetAggregation::DatasetFinalizer.call(context, aggregated_data, debug_mode: context.debug_mode)
|
|
69
|
+
[dataset, context.feature_transform_steps, context.one_hot_columns, context.fallback_feature_totals]
|
|
70
|
+
ensure
|
|
71
|
+
# `$!` can still hold the host's error from its own rescue, so compare it with `outer_error`.
|
|
72
|
+
staging.log_failure_diagnostics(phase, $!) if $! && !$!.equal?(outer_error)
|
|
73
|
+
staging.cleanup!
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def build_with_ruby_engine
|
|
78
|
+
logger.info("Loading UBI data...")
|
|
79
|
+
ubi_data = Ltr::DatasetAggregation::UbiDataLoader.call(config)
|
|
80
|
+
|
|
81
|
+
logger.info("Building dataset from UBI data...")
|
|
82
|
+
builder = Ltr::DatasetAggregation::DatasetBuilder.new(config, ubi_data)
|
|
83
|
+
dataset = builder.call
|
|
84
|
+
[dataset, builder.feature_transform_steps, builder.one_hot_columns, builder.fallback_feature_totals]
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def resolve_enricher_class
|
|
88
|
+
class_name = config.dataset_enricher
|
|
89
|
+
return nil if class_name.blank?
|
|
90
|
+
|
|
91
|
+
class_name.constantize
|
|
92
|
+
rescue NameError => error
|
|
93
|
+
raise Ltr::ConfigurationError,
|
|
94
|
+
"Invalid dataset_enricher class '#{class_name}': #{error.message}"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def enrich(dataset, enricher_class)
|
|
98
|
+
if enricher_class.nil?
|
|
99
|
+
logger.info("No dataset enricher configured, using original dataset")
|
|
100
|
+
return [dataset, []]
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
logger.info("Applying dataset enricher: #{enricher_class}")
|
|
104
|
+
base_columns = dataset.keys
|
|
105
|
+
enriched_dataset = enricher_class.call(dataset, config:)
|
|
106
|
+
logger.info("Dataset enrichment completed. Rows: #{enriched_dataset.length}")
|
|
107
|
+
Ltr::Features::EnrichedColumnEncoder.call(enriched_dataset, base_columns:, doc_id_field: config.doc_id_field)
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def logger
|
|
111
|
+
Ltr.config.logger
|
|
112
|
+
end
|
|
113
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Writes the finished dataset to a CSV file locally or in S3.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::DatasetSaver
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(config, dataset)
|
|
9
|
+
@config = config
|
|
10
|
+
@dataset = dataset
|
|
11
|
+
@modelling_dataset_path = config.modelling_dataset_path
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Writes the dataset as gzipped CSV to the modelling dataset path with `.gz` added.
|
|
15
|
+
# The path is in S3 if it starts with `s3://`, and a local file otherwise. Missing local directories are created.
|
|
16
|
+
# Raises `ArgumentError` if the dataset is empty or not a `Rover::DataFrame`, or if the path does not end in `.csv`.
|
|
17
|
+
def call
|
|
18
|
+
validate_inputs!
|
|
19
|
+
save_dataset
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
private
|
|
23
|
+
|
|
24
|
+
def validate_inputs!
|
|
25
|
+
raise ArgumentError, "Dataset is required" if @dataset.blank?
|
|
26
|
+
raise ArgumentError, "Dataset must be a Rover::DataFrame" unless @dataset.is_a?(Rover::DataFrame)
|
|
27
|
+
raise ArgumentError, "Modelling dataset path must end with .csv" if !@modelling_dataset_path.end_with?(".csv")
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def save_dataset
|
|
31
|
+
if s3_storage?
|
|
32
|
+
logger.info("Saving dataset to S3...")
|
|
33
|
+
save_dataset_to_s3
|
|
34
|
+
else
|
|
35
|
+
logger.info("Saving dataset locally...")
|
|
36
|
+
save_dataset_locally
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def s3_storage?
|
|
41
|
+
@is_s3_storage ||= @modelling_dataset_path.start_with?("s3://")
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def save_dataset_to_s3
|
|
45
|
+
s3_client = Ltr.config.s3_client
|
|
46
|
+
s3_path = @modelling_dataset_path.delete_prefix("s3://")
|
|
47
|
+
s3_bucket, s3_key = s3_path.split("/", 2)
|
|
48
|
+
|
|
49
|
+
csv_data = @dataset.to_csv
|
|
50
|
+
compressed_data = Zlib.gzip(csv_data)
|
|
51
|
+
compressed_key = "#{s3_key}.gz"
|
|
52
|
+
logger.info("Uploading to S3 bucket: #{s3_bucket}, key: #{compressed_key}")
|
|
53
|
+
|
|
54
|
+
s3_client.put_object(
|
|
55
|
+
bucket: s3_bucket,
|
|
56
|
+
key: compressed_key,
|
|
57
|
+
body: compressed_data
|
|
58
|
+
)
|
|
59
|
+
logger.info("S3 upload completed successfully")
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def save_dataset_locally
|
|
63
|
+
path = File.dirname(@modelling_dataset_path)
|
|
64
|
+
filename = "#{File.basename(@modelling_dataset_path)}.gz"
|
|
65
|
+
FileUtils.mkdir_p(path)
|
|
66
|
+
|
|
67
|
+
csv_data = @dataset.to_csv
|
|
68
|
+
compressed_data = Zlib.gzip(csv_data)
|
|
69
|
+
|
|
70
|
+
full_path = File.join(path, filename)
|
|
71
|
+
logger.info("Writing to file: #{full_path}")
|
|
72
|
+
File.binwrite(full_path, compressed_data)
|
|
73
|
+
logger.info("Local file saved successfully")
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def logger
|
|
77
|
+
Ltr.config.logger
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Computes features derived from the query text and the BM25 scores.
|
|
4
|
+
|
|
5
|
+
module Ltr::DatasetAggregation::DerivedFeatures
|
|
6
|
+
BM25_PREFIX = "bm25_"
|
|
7
|
+
BM25_FIELDS_MATCHED = "bm25_fields_matched"
|
|
8
|
+
|
|
9
|
+
class << self
|
|
10
|
+
# Returns the number of words in the query text.
|
|
11
|
+
def query_length_tokens(user_query)
|
|
12
|
+
user_query.to_s.split.length
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Text is a feature too, which one-hot encoding turns into columns.
|
|
16
|
+
# A boolean becomes 1 or 0 because serving accepts only numbers, so training must see the same.
|
|
17
|
+
def scalar_scores(scores)
|
|
18
|
+
scores.each_with_object({}) do |(name, value), kept|
|
|
19
|
+
case value
|
|
20
|
+
when true then kept[name] = 1
|
|
21
|
+
when false then kept[name] = 0
|
|
22
|
+
when Numeric, String then kept[name] = value
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Returns the feature columns for one document's scores, as symbol keys: each scalar score, then bm25_fields_matched.
|
|
28
|
+
# The caller leaves out reserved names first.
|
|
29
|
+
def score_columns(scores)
|
|
30
|
+
kept = scalar_scores(scores)
|
|
31
|
+
kept.to_h { |name, value| [name.to_sym, value] }
|
|
32
|
+
.merge(BM25_FIELDS_MATCHED.to_sym => bm25_fields_matched(kept))
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Counts the field groups with a positive BM25 score. "bm25_title_en" and "bm25_title_fr" are one group, "title".
|
|
36
|
+
def bm25_fields_matched(scores)
|
|
37
|
+
scores.each_with_object(Set.new) do |(name, value), families|
|
|
38
|
+
name_s = name.to_s
|
|
39
|
+
next unless name_s.start_with?(BM25_PREFIX) && name_s != BM25_FIELDS_MATCHED && value.to_f > 0
|
|
40
|
+
|
|
41
|
+
families << name_s.delete_prefix(BM25_PREFIX).split("_").first
|
|
42
|
+
end.size
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|