Extending LiR by creating a custom component
LiR is designed to be easily extensible, allowing developers to add new features and functionality without modifying the core code. This document outlines the process for creating a custom component that can be used in an experiment setup configuration file.
Any part of LiR can be replaced by custom components, such as experiment types, LR system architectures, metrics, etc. See the default component registry for a list of components shipped with LiR. In this guide, we describe in detail how to design a custom module, and how to apply these principles to create other types of components.
Creating a custom module
In this example, we will create a custom module that calculates the cosine similarity between two vectors. The module will be integrated into the LiR framework and can be used in experiments just like any other built-in component.
Step 1: setup a new project
Let’s start by setting up a new project for an experiment with a simple LR system. The following example shows a configuration file for an experiment:
output_path: ./output/${timestamp}_single_run_example # This is where generated output is saved.
experiments:
- name: my_experiment # Choose a descriptive name for the experiment.
strategy: single_run # single_run is the most basic strategy.
# The data section: which data to use and how to use it.
data:
setup: splits # Use a single dataset to be split into a training set and a test set
provider: # The data provider specifies which data to use.
method: parse_features_from_csv_url # We use the generic CSV parser to get glass data.
url: https://raw.githubusercontent.com/NetherlandsForensicInstitute/elemental_composition_glass/main/training.csv
source_id_column: Item # This column identifies the source.
feature_columns: # The features that are used to characterize the glass fragments.
- K39
- Ti49
- Mn55
- Rb85
- Sr88
- Zr90
- Ba137
- La139
- Ce140
- Pb208
splits: # The data splitter specifies how to split the data into training and test sets.
strategy: train_test_sources # Use a single train/test split, and split on the source IDs.
test_size: 0.5 # Split the data 50/50.
# The LR system section: this is where the action is.
lrsystem:
architecture: score_based
preprocessing: standard_scaler # The preprocessing is applied on the single measurements, before pairing.
pairing: # The pairing method governs the way the measurements are paired.
method: source_pairs # The source_pairing method generates one pair for each combination of sources.
ratio_limit: 1 # Subsample different-source pairs until their number is the same as the number of
# same-source pairs.
comparing: # The comparing module is applied on pairs.
method: pipeline # We need two modules, so we combine them in a pipeline.
steps:
score: manhattan_distance # First, we use the manhattan distance to calculate a "score".
to_llr: logistic_calibrator # Next, we turn the scores into LLRs.
# The output section: where results are aggregated.
output:
- method: metrics
columns:
- cllr
- cllr_min
It uses glass data in CSV format, fetched from a URL.
The LR system uses the score-based architecture, ScoreBasedSystem.
Manhattan distance is used to calculate the distance between pairs, and discriminate between same-source and
different-source pairs.
To run this experiment, save this snippet as config.yaml and run it with the following command:
lir run config.yaml
Step 2: implement cosine similarity
Our goal is to replace manhattan distance by cosine similarity. The first thing we need to do is to implement cosine
similarity. We create a file named cosine_similarity.py and implement the cosine similarity class.
from pathlib import Path
import numpy as np
from numpy.linalg import norm
from lir import FeatureData, InstanceData, PairedFeatureData, Transformer
class CosineSimilarity(Transformer):
def apply(self, pairs: InstanceData) -> FeatureData:
# make sure that we have pairs of feature vectors
pairs = check_type(PairedFeatureData, pairs)
# get the feature vectors for the trace and reference data
features_trace = pairs.features_trace[:, 0, :]
features_ref = pairs.features_ref[:, 0, :]
# calculate the similarities between the trace and the reference feature vectors
dot_products = np.sum(features_trace * features_ref, axis=1)
norms = norm(features_trace, axis=1) * norm(features_ref, axis=1)
cosine_similarities = dot_products / norms
# return a FeatureData object with the same attributes as the input pairs, but with the calculated similarities
# as the features
return pairs.replace_as(FeatureData, features=cosine_similarities)
The class we created is a child of Transformer. This tells LiR that it is a module that transforms data.
It has an apply() method that takes pairs of feature vectors and returns a similarity score.
The cosine similarity is calculated using the dot product of the two feature vectors, divided by the product of their
norms.
This module is now ready to run in an LR system, and can be referenced in a configuration file as cosine_similarity.CosineSimilarity.
output_path: ./output/${timestamp}_single_run_example # This is where generated output is saved.
experiments:
- name: my_experiment # Choose a descriptive name for the experiment.
strategy: single_run # single_run is the most basic strategy.
# The data section: which data to use and how to use it.
data:
setup: splits # Use a single dataset to be split into a training set and a test set
provider: # The data provider specifies which data to use.
method: parse_features_from_csv_url # We use the generic CSV parser to get glass data.
url: https://raw.githubusercontent.com/NetherlandsForensicInstitute/elemental_composition_glass/main/training.csv
source_id_column: Item # This column identifies the source.
feature_columns: # The features that are used to characterize the glass fragments.
- K39
- Ti49
- Mn55
- Rb85
- Sr88
- Zr90
- Ba137
- La139
- Ce140
- Pb208
splits: # The data splitter specifies how to split the data into training and test sets.
strategy: train_test_sources # Use a single train/test split, and split on the source IDs.
test_size: 0.5 # Split the data 50/50.
# The LR system section: this is where the action is.
lrsystem:
architecture: score_based
preprocessing: standard_scaler # The preprocessing is applied on the single measurements, before pairing.
pairing: # The pairing method governs the way the measurements are paired.
method: source_pairs # The source_pairing method generates one pair for each combination of sources.
ratio_limit: 1 # Subsample different-source pairs until their number is the same as the number of
# same-source pairs.
comparing: # The comparing module is applied on pairs.
method: pipeline # We need two modules, so we combine them in a pipeline.
steps:
score:
method: cosine_similarity.CosineSimilarity
to_llr: logistic_calibrator # Next, we turn the scores into LLRs.
# The output section: where results are aggregated.
output:
- method: metrics
columns:
- cllr
- cllr_min
Try running the above example in LiR. If it does not work, make sure the Python interpreter can access the
cosine_similarity.py file. It should work if the file is in the working directory or if it is in the
PYTHONPATH.
Step 3: add parameters
Our cosine similarity component works without any parameters. For the sake of it, we will add a parameter to control
whether the cosine similarity should be squared or not.
We extend the CosineSimilarity class by adding an __init__ method that takes a boolean parameter:
from pathlib import Path
import numpy as np
from numpy.linalg import norm
from lir import FeatureData, InstanceData, PairedFeatureData, Transformer
class CosineSimilarity(Transformer):
def __init__(self, square: bool = False):
self.square = square
def apply(self, pairs: InstanceData) -> FeatureData:
# make sure that we have pairs of feature vectors
pairs = check_type(PairedFeatureData, pairs)
# get the feature vectors for the trace and reference data
features_trace = pairs.features_trace[:, 0, :]
features_ref = pairs.features_ref[:, 0, :]
# calculate the similarities between the trace and the reference feature vectors
dot_products = np.sum(features_trace * features_ref, axis=1)
norms = norm(features_trace, axis=1) * norm(features_ref, axis=1)
cosine_similarities = dot_products / norms
if self.square:
cosine_similarities = np.square(cosine_similarities)
# return a FeatureData object with the same attributes as the input pairs, but with the calculated similarities
# as the features
return pairs.replace_as(FeatureData, features=cosine_similarities)
Any key/value-pair in the configuration section of score (except for method) will be passed to the component when it is instantiated.
output_path: ./output/${timestamp}_single_run_example # This is where generated output is saved.
experiments:
- name: my_experiment # Choose a descriptive name for the experiment.
strategy: single_run # single_run is the most basic strategy.
# The data section: which data to use and how to use it.
data:
setup: splits # Use a single dataset to be split into a training set and a test set
provider: # The data provider specifies which data to use.
method: parse_features_from_csv_url # We use the generic CSV parser to get glass data.
url: https://raw.githubusercontent.com/NetherlandsForensicInstitute/elemental_composition_glass/main/training.csv
source_id_column: Item # This column identifies the source.
feature_columns: # The features that are used to characterize the glass fragments.
- K39
- Ti49
- Mn55
- Rb85
- Sr88
- Zr90
- Ba137
- La139
- Ce140
- Pb208
splits: # The data splitter specifies how to split the data into training and test sets.
strategy: train_test_sources # Use a single train/test split, and split on the source IDs.
test_size: 0.5 # Split the data 50/50.
# The LR system section: this is where the action is.
lrsystem:
architecture: score_based
preprocessing: standard_scaler # The preprocessing is applied on the single measurements, before pairing.
pairing: # The pairing method governs the way the measurements are paired.
method: source_pairs # The source_pairing method generates one pair for each combination of sources.
ratio_limit: 1 # Subsample different-source pairs until their number is the same as the number of
# same-source pairs.
comparing: # The comparing module is applied on pairs.
method: pipeline # We need two modules, so we combine them in a pipeline.
steps:
score:
method: cosine_similarity.CosineSimilarity
square: True
to_llr: logistic_calibrator # Next, we turn the scores into LLRs.
# The output section: where results are aggregated.
output:
- method: metrics
columns:
- cllr
- cllr_min
Step 4: create a configuration parser (optional)
There is a good chance that this is all you need to do to create a new component. However, if you want more control over how the component is instantiated, you can create a custom configuration parser. Specifically, writing a configuration parser allows you to:
initialize the component with initialization parameters that cannot be specified in a YAML file (anything other than str, int, float, dict, list, None);
pass an output directory to the component to where it can write files to disk.
We create a configuration parser by defining a function that parses a configuration section and returns a CosineSimilarity object.
We take care that the function:
takes two arguments: a
ConfigValue, the configuration section in the YAML that is needed to initialize the module, and an output directory as aPathobject;returns an instance of the component (in our case,
CosineSimilarity);is marked as a configuration parser with the
@config_parserdecorator.
The output directory passed to the configuration parser may be affected by higher level components. For example, the configuration parser for an experiment receives a sub directory of the top level output directory for that specific experiment. If the experiment has multiple runs, the LR system modules receive an output directory for the run.
from pathlib import Path
import numpy as np
from numpy.linalg import norm
from lir import FeatureData, InstanceData, PairedFeatureData, Transformer
from lir.config import ConfigValue, config_parser
from lir.util import check_type
class CosineSimilarity(Transformer):
def __init__(self, square: bool = False):
self.square = square
def apply(self, pairs: InstanceData) -> FeatureData:
# make sure that we have pairs of feature vectors
pairs = check_type(PairedFeatureData, pairs)
# get the feature vectors for the trace and reference data
features_trace = pairs.features_trace[:, 0, :]
features_ref = pairs.features_ref[:, 0, :]
# calculate the similarities between the trace and the reference feature vectors
dot_products = np.sum(features_trace * features_ref, axis=1)
norms = norm(features_trace, axis=1) * norm(features_ref, axis=1)
cosine_similarities = dot_products / norms
if self.square:
cosine_similarities = np.square(cosine_similarities)
# return a FeatureData object with the same attributes as the input pairs, but with the calculated similarities
# as the features
return pairs.replace_as(FeatureData, features=cosine_similarities)
@config_parser
def parse_cosine_similarity_config(config: ConfigValue, output_dir: Path) -> CosineSimilarity:
print('CONTEXT:', config.context)
print('CONFIG:', config)
print('UNWRAPPED:', config.unwrap())
# the use of `with` is optional, and adds a check that all fields in `config` are consumed
with config:
# obtain the value of the "square" parameter, and remove it from the dictionary.
square = config.pop_field('square', default=False)
# instantiate the component with the parsed parameters and return it.
return CosineSimilarity(square=square)
The config parameter contains the relevant section in the configuration YAML.
Each ConfigValue object has a context attribute, which is the full path of the configuration value in the original YAML file, and a value attribute, which is the actual value.
If value is a container object such as a list or a dictionary, it is also wrapped inside a ConfigValue object.
Please refer to the API documentation for more information on dealing with ConfigValue objects.
lir run minimal-single-run-with-cosim-parser.yaml
CONTEXT: ['experiments', '0', 'lrsystem', 'comparing', 'steps', 'score']
CONFIG: ConfigValue(context=['experiments', '0', 'lrsystem', 'comparing', 'steps', 'score'], value={'square': ConfigValue(context=['experiments', '0', 'lrsystem', 'comparing', 'steps', 'score', 'square'], value=True)})
UNWRAPPED: {'square': True}
In our case, the config parameter holds the configuration section under score (line 31), which is a dictionary of two keys, namely method and square.
Since the method is already consumed to identify the configuration parser, this leaves a dictionary with just square as its single key.
The output_dir value is the path to the directory where the component may save its results, if applicable.
To use this configuration parser, simply replace CosineSimilarity in the configuration file in Step 3: add parameters with parse_cosine_similarity_config.
Step 5: register your component (optional)
Registering a component creates an alias. When registered, the component can be referenced by its alias (e.g.
cosim) instead of its full module path (i.e. cosine_similarity.CosineSimilarity or
cosine_similarity.parse_cosine_similarity_config).
To register a component, create a file named registry.yaml in the current directory.
See the documentation of confidence.load_name for the list of locations where registry files are searched.
The cosine similarity module can be registered by adding the following entry to the registry.yaml file:
modules:
cosine_similarity: cosine_similarity.CosineSimilarity
Or, if you want to use the configuration parser:
modules:
cosine_similarity: cosine_similarity.parse_cosine_similarity_config
You can also use this mechanism to override specific built-in registry entries, since user-defined registry entries take precedence over built-in registry entries.
Examples for other components
Other components can be added in a similar way, by creating a function with the @config_parser decorator, and returning the component instance.
A data provider to read from a database
We will create a data provider that obtains its data from a Sqlite database.
Before writing the component, we create and populate a database with dummy values.
import sqlite3
with sqlite3.connect('example.db') as db:
db.execute('CREATE TABLE feature_table (hypothesis INT, feature1 FLOAT, feature2 FLOAT)')
db.execute('INSERT INTO feature_table VALUES(1, 1.0, 1.1), (1, 1.1, 1.2), (0, 3.1, 3.3), (0, 3.0, 4.0)')
Now that we have the database, we create a data provider component to read from it.
The recommended way to do it, is to define a function that returns the data, and decorate it with @data_provider:
import sqlite3
import numpy as np
from lir import FeatureData
from lir.config.data import data_provider
@data_provider
def read_from_sqlite3(path: str) -> FeatureData:
with sqlite3.connect(path) as db:
hypotheses = []
features = []
result = db.execute('SELECT hypothesis, feature1, feature2 FROM feature_table')
for row in result:
hypotheses.append(row[0])
features.append([row[1], row[2]])
db.close()
return FeatureData(hypothesis=np.array(hypotheses), features=np.array(features))
Alternatively, we may define a DataProvider class. If its __init__ method requires no parameters or atomic parameters only, like here, it can be used directly.
Otherwise, we’ll have to use @config_parser:
from pathlib import Path
from lir import DataProvider, FeatureData
from lir.config import ConfigValue, config_parser
from .sqlite_reader import read_from_sqlite3
class SqliteDataProvider(DataProvider):
def __init__(self, path: str):
self.path = path
def get_instances(self) -> FeatureData:
return read_from_sqlite3(self.path)
@config_parser
def parse_sqlite_data_provider_config(config: ConfigValue, output_dir: Path) -> SqliteDataProvider:
# the use of `with` is optional, and adds a check that all fields in `config` are consumed
with config:
path = config.pop_field('path')
return SqliteDataProvider(path)
An experiment type to count the number of records in the dataset
This example shows how to create a new type of experiment. All it does is to count the number of instances in a dataset.
from pathlib import Path
from lir import DataProvider
from lir.config import ConfigValue, config_parser
from lir.config.data import parse_data_provider
from lir.experiments import Experiment
class DataCounterExperiment(Experiment):
def __init__(self, data_provider: DataProvider, output_dir: Path):
super().__init__(output_path=output_dir)
self.data_provider = data_provider
def run(self):
number_of_instances = len(self.data_provider.get_instances())
with open(self.output_path / 'counter.txt', 'w') as f:
f.write(f'{number_of_instances}\n')
@config_parser
def parse_data_counter_experiment_config(config: ConfigValue, output_dir: Path) -> Experiment:
# the use of `with` is optional, and adds a check that all fields in `config` are consumed
with config:
data_provider_config = config.pop_field('data_provider')
data_provider = parse_data_provider(data_provider_config, output_dir)
return DataCounterExperiment(data_provider, output_dir)
An output method to calculate the average LLR
The output section of the experiments lists methods to aggregate results.
This is done by Aggregation objects, which receive the results of each LR system run one by one.
In this example, we will create an output method that calculates the average LLR for each run, and writes it to a file. Finally, we will calculate the average of all runs.
from pathlib import Path
import numpy as np
from lir.aggregation import Aggregation, AggregationData
from lir.config import ConfigValue, config_parser
class AverageLLR(Aggregation):
def __init__(self, path: Path):
self.path = path
self._average_cumulative = 0
self._average_count = 0
def report(self, data: AggregationData):
average = np.average(data.llrdata.llrs)
with open(self.path, 'a') as f:
f.write(f'average LLR for run {data.run_name}: {average}\n')
self._average_cumulative += average
self._average_count += 1
def close(self):
with open(self.path, 'a') as f:
f.write(f'overall average LLR: {self._average_cumulative / self._average_count}\n')
@config_parser
def average_llr(config: ConfigValue, output_dir: Path) -> AverageLLR:
# the use of `with` is optional, and adds a check that all fields in `config` are consumed
with config:
filename = config.pop_field('filename')
return AverageLLR(output_dir / filename)
A metric to calculate the average LLR
A metric is a function that takes LLRData and returns a float.
In this example, we implement the average of LLRs as a metric.
import numpy as np
from lir import LLRData
def average_llr(llrdata: LLRData) -> float:
return np.average(llrdata.llrs)
A slightly more complicated example is the calculation of a weighted CLLR value, which involves the @config_parser decorator.
import functools
from collections.abc import Callable
from pathlib import Path
import numpy as np
from lir import LLRData
from lir.config import ConfigValue, config_parser
from lir.util import logodds_to_odds
def calculate_weighted_cllr(llrdata: LLRData, h0_weight: float, h1_weight: float) -> float:
lrs = logodds_to_odds(llrdata.llrs)
lrs0 = lrs[llrdata.hypothesis == 0]
lrs1 = lrs[llrdata.hypothesis == 1]
cllr0 = h0_weight * np.mean(np.log2(1 + lrs0))
cllr1 = h1_weight * np.mean(np.log2(1 + 1 / lrs1))
return (cllr0 + cllr1) / (h0_weight + h1_weight)
@config_parser
def weighted_cllr(config: ConfigValue, output_dir: Path) -> Callable[[LLRData], float]:
# the use of `with` is optional, and adds a check that all fields in `config` are consumed
with config:
h0_weight = config.pop_field('h0_weight', validate=float, default=1.0)
h1_weight = config.pop_field('h1_weight', validate=float, default=1.0)
return functools.partial(calculate_weighted_cllr, h0_weight=h0_weight, h1_weight=h1_weight)
A test-only data strategy
Some models do not require a training phase. In this example, we implement a data strategy that assumes we work with such models only, and offers the full dataset for testing.
from collections.abc import Iterator
from lir import DataStrategy, InstanceData
class AllTest(DataStrategy):
def apply[DataType: InstanceData](self, instances: DataType) -> Iterator[tuple[DataType, DataType]]:
yield None, instances