### Install DeepMatcher with pip Source: https://github.com/anhaidgroup/deepmatcher/blob/master/README.rst Installs the DeepMatcher package using pip. Recommended installation method. ```bash pip install deepmatcher ``` -------------------------------- ### Install py_entitymatching if not present Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/end_to_end_em.ipynb Attempts to import py_entitymatching and installs it via pip if the import fails. This is the recommended way to install Magellan. ```python try: import py_entitymatching as em except: !pip install py_entitymatching ``` -------------------------------- ### MatchingModel Initialization Logic Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/core.html Handles the setup of attribute summarizers, condensors, comparators, and the classifier. It also performs an initial forward pass to finalize model state. ```python if self._initialized: return # Copy over training info from train set for persistent state. But remove actual # data examples. self.meta = Bunch(**train_dataset.__dict__) if hasattr(self.meta, 'fields'): del self.meta.fields del self.meta.examples self._register_train_buffer('state_meta', Bunch(**self.meta.__dict__)) del self.state_meta.metadata # we only need `self.meta.orig_metadata` for state. self.attr_summarizers = dm.modules.ModuleMap() if isinstance(self.attr_summarizer, Mapping): for name, summarizer in self.attr_summarizer.items(): self.attr_summarizers[name] = AttrSummarizer._create( summarizer, hidden_size=self.hidden_size) assert len( set(self.attr_summarizers.keys()) ^ set(self.meta.canonical_text_fields) ) == 0 else: self.attr_summarizer = AttrSummarizer._create( self.attr_summarizer, hidden_size=self.hidden_size) for name in self.meta.canonical_text_fields: self.attr_summarizers[name] = copy.deepcopy(self.attr_summarizer) if self.attr_condense_factor == 'auto': self.attr_condense_factor = min(len(self.meta.canonical_text_fields), 6) if self.attr_condense_factor == 1: self.attr_condense_factor = None if not self.attr_condense_factor: self.attr_condensors = None else: self.attr_condensors = dm.modules.ModuleMap() for name in self.meta.canonical_text_fields: self.attr_condensors[name] = dm.modules.Transform( '1-layer-highway', non_linearity=None, output_size=self.hidden_size // self.attr_condense_factor) self.attr_comparators = dm.modules.ModuleMap() if isinstance(self.attr_comparator, Mapping): for name, comparator in self.attr_comparator.items(): self.attr_comparators[name] = _create_attr_comparator(comparator) assert len( set(self.attr_comparators.keys()) ^ set(self.meta.canonical_text_fields) ) == 0 else: if isinstance(self.attr_summarizer, AttrSummarizer): self.attr_comparator = self._get_attr_comparator( self.attr_comparator, self.attr_summarizer) else: if self.attr_comparator is None: raise ValueError('"attr_comparator" must be specified if ' '"attr_summarizer" is custom.') self.attr_comparator = _create_attr_comparator(self.attr_comparator) for name in self.meta.canonical_text_fields: self.attr_comparators[name] = copy.deepcopy(self.attr_comparator) self.attr_merge = dm.modules._merge_module(self.attr_merge) self.classifier = _utils.get_module( Classifier, self.classifier, hidden_size=self.hidden_size) self._reset_embeddings(train_dataset.vocabs) # Instantiate all components using a small batch from training set. if not init_batch: run_iter = MatchingIterator( train_dataset, train_dataset, train=False, batch_size=4, device=-1, sort_in_buckets=False) init_batch = next(run_iter.__iter__()) self.forward(init_batch) # Keep this init_batch for future initializations. self.state_meta.init_batch = init_batch self._initialized = True logger.info('Successfully initialized MatchingModel with {:d} trainable ' 'parameters.'.format(tally_parameters(self))) ``` -------------------------------- ### Training output - initial and epoch summaries Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/getting_started.ipynb Sample console output from run_train showing the number of trainable parameters, progress bars, and per-epoch training/evaluation metrics (F1, precision, recall, examples per second). The output includes best F1 scores and model saving messages. ```text Output: * Number of trainable parameters: 17757810 ===> TRAIN Epoch 1 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 1 || Run Time: 4.1 | Load Time: 0.5 || F1: 46.15 | Prec: 35.42 | Rec: 66.23 || Ex/s: 70.08 ===> EVAL Epoch 1 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 Finished Epoch 1 || Run Time: 0.6 | Load Time: 0.2 || F1: 66.67 | Prec: 60.00 | Rec: 75.00 || Ex/s: 141.47 * Best F1: 66.66666666666667 Saving best model... Done. --------------------- ===> TRAIN Epoch 2 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 2 || Run Time: 3.8 | Load Time: 0.5 || F1: 65.64 | Prec: 54.24 | Rec: 83.12 || Ex/s: 75.19 ===> EVAL Epoch 2 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 Finished Epoch 2 || Run Time: 0.6 | Load Time: 0.2 || F1: 60.32 | Prec: 48.72 | Rec: 79.17 || Ex/s: 143.34 --------------------- ===> TRAIN Epoch 3 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 3 || Run Time: 3.9 | Load Time: 0.5 || F1: 80.23 | Prec: 71.00 | Rec: 92.21 || Ex/s: 73.89 ===> EVAL Epoch 3 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 Finished Epoch 3 || Run Time: 0.6 | Load Time: 0.2 || F1: 75.47 | Prec: 68.97 | Rec: 83.33 || Ex/s: 143.36 * Best F1: 75.47169811320755 Saving best model... Done. --------------------- ===> TRAIN Epoch 4 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 4 || Run Time: 3.8 | Load Time: 0.5 || F1: 93.25 | Prec: 88.37 | Rec: 98.70 || Ex/s: 74.89 ===> EVAL Epoch 4 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 Finished Epoch 4 || Run Time: 0.6 | Load Time: 0.2 || F1: 84.00 | Prec: 80.77 | Rec: 87.50 || Ex/s: 143.36 * Best F1: 84.0 Saving best model... Done. --------------------- ===> TRAIN Epoch 5 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 5 || Run Time: 3.9 | Load Time: 0.5 || F1: 95.00 | Prec: 91.57 | Rec: 98.70 || Ex/s: 73.68 ===> EVAL Epoch 5 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 Finished Epoch 5 || Run Time: 0.6 | Load Time: 0.2 || F1: 86.27 | Prec: 81.48 | Rec: 91.67 || Ex/s: 142.36 * Best F1: 86.27450980392157 Saving best model... Done. --------------------- ===> TRAIN Epoch 6 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 6 || Run Time: 3.8 | Load Time: 0.5 || F1: 98.06 | Prec: 97.44 | Rec: 98.70 || Ex/s: 74.76 ===> EVAL Epoch 6 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 Finished Epoch 6 || Run Time: 0.6 | Load Time: 0.2 || F1: 82.14 | Prec: 71.88 | Rec: 95.83 || Ex/s: 142.86 --------------------- ===> TRAIN Epoch 7 0% [████] 100% | ETA: 00:00:00 Total time elapsed: 00:00:04 Finished Epoch 7 || Run Time: 3.9 | Load Time: 0.5 || F1: 99.35 | Prec: 98.72 | Rec: 100.00 || Ex/s: 74.46 ===> EVAL Epoch 7 0% [█] 100% | ETA: 00:00:00 Total time elapsed: 00:00:00 ``` -------------------------------- ### process(path, train=None, validation=None, test=None, unlabeled=None, cache='cacheddata.pth', check_cached_data=True, auto_rebuild_cache=True, tokenize='nltk', lowercase=True, embeddings='fasttext.en.bin', embeddings_cache_path='~/.vector_cache', ignore_columns=(), include_lengths=True, id_attr='id', label_attr='label', left_prefix='left_', right_prefix='right_', use_magellan_convention=False, pca=True) Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/data/process.html Creates dataset objects for multiple splits of a dataset. It reads CSV files, verifies headers, creates fields, loads and preprocesses examples, computes metadata, builds vocabulary, downloads word embeddings, and caches the processed data. ```APIDOC ## process(path, train=None, validation=None, test=None, unlabeled=None, cache='cacheddata.pth', check_cached_data=True, auto_rebuild_cache=True, tokenize='nltk', lowercase=True, embeddings='fasttext.en.bin', embeddings_cache_path='~/.vector_cache', ignore_columns=(), include_lengths=True, id_attr='id', label_attr='label', left_prefix='left_', right_prefix='right_', use_magellan_convention=False, pca=True) ### Description Creates dataset objects for multiple splits of a dataset. This involves reading CSV headers, creating fields, loading and preprocessing examples, computing metadata, building vocabulary, downloading word embeddings, and caching the processed data. ### Parameters - **path** (str) - Required - Path to the directory containing the data files. - **train** (str) - Optional - Filename of the training data file. - **validation** (str) - Optional - Filename of the validation data file. - **test** (str) - Optional - Filename of the test data file. - **unlabeled** (str) - Optional - Filename of the unlabeled data file. - **cache** (str) - Optional - Path to the cache file. Default: 'cacheddata.pth'. - **check_cached_data** (bool) - Optional - Whether to check cached data. Default: True. - **auto_rebuild_cache** (bool) - Optional - Whether to automatically rebuild cache if invalid. Default: True. - **tokenize** (str or callable) - Optional - Tokenization method. Default: 'nltk'. - **lowercase** (bool) - Optional - Whether to lowercase text. Default: True. - **embeddings** (str) - Optional - Embeddings to use. Default: 'fasttext.en.bin'. - **embeddings_cache_path** (str) - Optional - Path to cache embeddings. Default: '~/.vector_cache'. - **ignore_columns** (tuple) - Optional - Columns to ignore. Default: (). - **include_lengths** (bool) - Optional - Whether to include lengths. Default: True. - **id_attr** (str) - Optional - Name of the ID column. Default: 'id'. - **label_attr** (str) - Optional - Name of the label column. Default: 'label'. - **left_prefix** (str) - Optional - Prefix for left table attributes. Default: 'left_'. - **right_prefix** (str) - Optional - Prefix for right table attributes. Default: 'right_'. - **use_magellan_convention** (bool) - Optional - Whether to use Magellan convention. Default: False. - **pca** (bool) - Optional - Whether to use PCA. Default: True. ### Returns - Dataset objects for the specified splits (train, validation, test, unlabeled) as created by the process. ``` -------------------------------- ### Initialize Attribute Summarizer Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/core.html The _init method sets up the word contextualizer, comparator, and aggregator modules using the provided configuration or defaults. ```python def _init(self, word_contextualizer, word_comparator, word_aggregator, hidden_size=None): self.word_contextualizer = WordContextualizer._create( word_contextualizer, hidden_size=hidden_size) self.word_comparator = WordComparator._create( word_comparator, hidden_size=hidden_size) self.word_aggregator = WordAggregator._create( word_aggregator, hidden_size=hidden_size) ``` -------------------------------- ### Run prediction on validation data with run_prediction Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/getting_started.ipynb Call run_prediction on a trained DeepMatcher model with validation data and output_attributes=True to get predictions. The method prints an epoch progress line with F1, precision, recall, and examples per second. The returned DataFrame includes match_score, label, and the original attributes. ```python valid_predictions = model.run_prediction(validation, output_attributes=True) valid_predictions.head() ``` ```text Output: ===> PREDICT Epoch 8 Finished Epoch 8 || Run Time: 0.4 | Load Time: 0.2 || F1: 88.46 | Prec: 82.14 | Rec: 95.83 || Ex/s: 192.18 ``` ```text Result: match_score label left_Song_Name \ id 299 0.210376 0 Blame ( feat . John Newman ) [ BURNS Remix ] 48 0.991802 1 Afire Love 34 0.187756 0 Lifted ( feat . Emeli Sand ' © & Professor Gre... 215 0.986806 1 Jack Daniels and Jesus 376 0.172195 0 Turn Around ( 5,4,3,2,1 ) [ AK Remix ] left_Artist_Name left_Album_Name \ id 299 Calvin Harris Blame ( Remixes ) [ feat . John Newman ] - EP 48 Ed Sheeran x 34 Naughty Boy Hotel Cabana ( Deluxe Version ) 215 Chase Rice Ignite the Night 376 Flo Rida Turn Around ( 5,4,3,2,1 ) [ Remixes ] left_Genre left_Price \ id 299 Dance , Music $ 1.29 48 Singer/Songwriter , Music , Pop , Rock , Conte... $ 1.29 34 Pop , Music , Rock , R&B / Soul , Contemporary... $ 1.29 215 Country , Music , Urban Cowboy , Contemporary ... $ 1.29 376 Dance,Music,Hip-Hop / Rap , Dirty South , Rap ... $ 1.29 left_CopyRight left_Time \ id 299 2014 Sony Music Entertainment UK Limited 4:17 48 2014 Asylum Records UK , a Warner Music UK Com... 5:14 34 2013 Naughty Boy Recordings Ltd under exclusiv... 4:15 215 2014 Dack Janiels Records 3:55 376 2011 Atlantic Recording Corporation for the Un... 5:09 left_Released right_Song_Name \ id 299 10-Nov-14 Pray to God ( R3hab Remix ) 48 20-Jun-14 Afire Love 34 6-May-14 Never Been The Same [ feat . Thabo ] 215 19-Aug-14 Jack Daniels and Jesus 376 19-Apr-11 Good Feeling ( Jaywalker Remix ) right_Artist_Name \ id 299 Calvin Harris feat . HAIM 48 Ed Sheeran 34 Naughty Boy 215 Chase Rice 376 Flo Rida right_Album_Name right_Genre \ id 299 Pray to God ( Remixes ) Dance & Electronic 48 x Pop 34 Hotel Cabana ( Deluxe Version ) [ Explicit ] Pop 215 Ignite the Night ( Party Edition ) [ Explicit ] Country 376 Good Feeling ( Remixes ) Dance & Electronic right_Price right_CopyRight right_Time \ id 299 $ 1.29 ( C ) 2015 Third Pardee Records , LLC under ex... 4:31 48 $ 1.29 ( C ) 2014 mau5trap Recordings Ltd 5:14 34 $ 1.29 ( C ) 2014 Naughty Boy Recordings Ltd under ex... 3:29 215 $ 0.89 ( C ) 2014 Dack Janiels Records , under exclus... 3:55 376 $ 1.29 ( C ) 2009 MPL Tours Inc. under exclusive lice... 4:51 right_Released id 299 September 25 , 2015 48 June 20 , 2014 34 May 6 , 2014 215 August 19 , 2014 376 November 15 , 2011 ``` -------------------------------- ### Initialize MatchingModel with sample data Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/matching_models.ipynb Initializes a MatchingModel and processes the itunes-amazon sample data. The output shows the expected log message after successful initialization. ```python import deepmatcher as dm import logging import torch logging.getLogger('deepmatcher.core').setLevel(logging.INFO) # Download sample data. !mkdir -p sample_data/itunes-amazon !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/sidharthms/deepmatcher/master/examples/sample_data/itunes-amazon/train.csv !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/sidharthms/deepmatcher/master/examples/sample_data/itunes-amazon/validation.csv !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/sidharthms/deepmatcher/master/examples/sample_data/itunes-amazon/test.csv train_dataset, validation_dataset, test_dataset = dm.data.process( path='sample_data/itunes-amazon', train='train.csv', validation='validation.csv', test='test.csv', ignore_columns=('left_id', 'right_id')) model = dm.MatchingModel() model.initialize(train_dataset) # Explicitly initialize model. ``` ```text Output: INFO:deepmatcher.core:Successfully initialized MatchingModel with 17757810 trainable parameters. ``` -------------------------------- ### Download sample data for entity matching Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/getting_started.ipynb Downloads four CSV datasets (training, validation, test, and unlabeled) into the sample_data/itunes-amazon directory using shell commands. ```bash !mkdir -p sample_data/itunes-amazon !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/anhaidgroup/deepmatcher/master/examples/sample_data/itunes-amazon/train.csv !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/anhaidgroup/deepmatcher/master/examples/sample_data/itunes-amazon/validation.csv !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/anhaidgroup/deepmatcher/master/examples/sample_data/itunes-amazon/test.csv !wget -qnc -P sample_data/itunes-amazon https://raw.githubusercontent.com/anhaidgroup/deepmatcher/master/examples/sample_data/itunes-amazon/unlabeled.csv ``` -------------------------------- ### Install DeepMatcher in Colab Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/question_answering.ipynb Installs the deepmatcher package if it is not already available. This is intended for use in Google Colab notebooks. ```python try: import deepmatcher except: !pip install -qqq deepmatcher ``` -------------------------------- ### RNN Module Initialization and Support Check Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/modules.html Methods for checking supported RNN styles and initializing the multi-layered RNN with dropout and bypass network configurations. ```python @classmethod def supports_style(cls, style): return style.lower() in cls._supported_styles def _init(self, unit_type='gru', hidden_size=None, layers=1, bidirectional=True, dropout=0, input_dropout=0, last_layer_dropout=0, bypass_network=None, connect_num_layers=1, input_size=None, **kwargs): hidden_size = input_size if hidden_size is None else hidden_size last_layer_dropout = dropout if last_layer_dropout is None else last_layer_dropout if bidirectional: hidden_size //= 2 ``` -------------------------------- ### Classifier Output Example Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/end_to_end_em.ipynb An example of the raw output table generated by the deepmatcher classifier, showing match scores and associated data. ```text Result: match_score ltable_id rtable_id ltable_Song_Name \ _id 1472466 0.995653 2462 30798 It 's Never Easy to Say Goodbye 1472465 0.995653 2453 30798 It 's Never Easy to Say Goodbye 1472464 0.995653 2438 30798 It 's Never Easy to Say Goodbye 1472463 0.995653 2435 30798 It 's Never Easy to Say Goodbye 1472462 0.995653 2430 30798 It 's Never Easy to Say Goodbye ltable_Artist_Name ltable_Album_Name \ _id 1472466 Kenny Chesney Me and You 1472465 Kenny Chesney Me and You 1472464 Kenny Chesney Me and You 1472463 Kenny Chesney Me and You 1472462 Kenny Chesney Me and You ltable_Genre ltable_Price \ _id 1472466 Country , Music , Urban Cowboy , Contemporary Country $ 0.99 1472465 Country , Music , Urban Cowboy , Contemporary Country $ 0.99 1472464 Country , Music , Urban Cowboy , Contemporary Country $ 0.99 1472463 Country , Music , Urban Cowboy , Contemporary Country $ 0.99 1472462 Country , Music , Urban Cowboy , Contemporary Country $ 0.99 ltable_CopyRight ltable_Time ltable_Released \ _id 1472466 1996 BMG Entertainment 4:44 1-Jan-90 1472465 1996 BMG Entertainment 4:44 1-Jan-90 1472464 1996 BMG Entertainment 4:44 1-Jan-90 1472463 1996 BMG Entertainment 4:44 1-Jan-90 1472462 1996 BMG Entertainment 4:44 1-Jan-90 rtable_Song_Name rtable_Artist_Name rtable_Album_Name \ _id 1472466 It 's Never Easy To Say Goodbye Kenny Chesney Me And You 1472465 It 's Never Easy To Say Goodbye Kenny Chesney Me And You 1472464 It 's Never Easy To Say Goodbye Kenny Chesney Me And You 1472463 It 's Never Easy To Say Goodbye Kenny Chesney Me And You 1472462 It 's Never Easy To Say Goodbye Kenny Chesney Me And You rtable_Genre rtable_Price \ _id 1472466 Country $ 0.99 1472465 Country $ 0.99 1472464 Country $ 0.99 1472463 Country $ 0.99 1472462 Country $ 0.99 rtable_CopyRight \ _id 1472466 ( C ) 2011 MPL Communications Ltd/Inc under exclusive license to StarCon LLC 1472465 ( C ) 2011 MPL Communications Ltd/Inc under exclusive license to StarCon LLC 1472464 ( C ) 2011 MPL Communications Ltd/Inc under exclusive license to StarCon LLC 1472463 ( C ) 2011 MPL Communications Ltd/Inc under exclusive license to StarCon LLC 1472462 ( C ) 2011 MPL Communications Ltd/Inc under exclusive license to StarCon LLC rtable_Time rtable_Released _id 1472466 4:44 January 1 , 1990 1472465 4:44 January 1 , 1990 1472464 4:44 January 1 , 1990 1472463 4:44 January 1 , 1990 1472462 4:44 January 1 , 1990 ``` -------------------------------- ### Get Attribute Comparator Method Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/core.html Retrieves the attribute comparator module. ```python def _get_attr_comparator(self, arg, attr_summarizer): r"""Get the attribute comparator. ``` -------------------------------- ### Import packages and download WikiQA dataset Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/question_answering.ipynb Imports deepmatcher, pandas, and os, then downloads and unzips the WikiQA corpus from Microsoft. The wget and unzip commands are shell commands run in a notebook environment. ```python import deepmatcher as dm import pandas as pd import os !wget -qnc https://download.microsoft.com/download/E/5/F/E5FCFCEE-7005-4814-853D-DAA7C66507E0/WikiQACorpus.zip !unzip -qn WikiQACorpus.zip ``` -------------------------------- ### deepmatcher.modules.ModuleMap Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/modules.html Holds submodules in a map, similar to torch.nn.ModuleList but for maps. Provides an example usage. ```APIDOC ## deepmatcher.modules.ModuleMap ### Description Holds submodules in a map. Similar to torch.nn.ModuleList, but for maps. ### Class `deepmatcher.modules.ModuleMap` ### Example ```python import torch.nn as nn import deepmatcher as dm class MyModule(nn.Module): def __init__(self): super(MyModule, self).__init__() linears = dm.ModuleMap() linears['type'] = nn.Linear(10, 10) linears['color'] = nn.Linear(10, 10) self.linears = linears def forward(self, x1, x2): y1, y2 = self.linears['type'], self.linears['color'] return y1, y2 ``` ``` -------------------------------- ### Module _init and _forward methods Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/modules.html Initializes a sequence of linear transforms with optional bypass networks and nonlinearities, then applies them in the forward pass. The style string can specify the number of layers (e.g., '2-layer') and the nonlinearity (e.g., 'leaky_relu'). ```python @classmethod def supports_nonlinearity(cls, nonlin): return nonlin.lower() in cls._supported_nonlinearities def _init(self, style, layers=1, bypass_network=None, non_linearity='leaky_relu', hidden_size=None, output_size=None, input_size=None): hidden_size = hidden_size or input_size output_size = output_size or hidden_size parts = style.split('-') if 'layer' in parts: layers = int(parts[parts.index('layer') - 1]) for part in parts: if Bypass.supports_style(part): bypass_network = part if Transform.supports_nonlinearity(part): non_linearity = part self.transforms = nn.ModuleList() self.bypass_networks = nn.ModuleList() assert (non_linearity is None or self.supports_nonlinearity(non_linearity)) self.non_linearity = non_linearity.lower() if non_linearity else None transform_in_size = input_size transform_out_size = hidden_size for layer in range(layers): if layer == layers - 1: transform_out_size = output_size self.transforms.append(nn.Linear(transform_in_size, transform_out_size)) self.bypass_networks.append(_bypass_module(bypass_network)) transform_in_size = transform_out_size def _forward(self, input): output = input for transform, bypass in zip(self.transforms, self.bypass_networks): new_output = transform(output) if self.non_linearity: new_output = getattr(F, self.non_linearity)(new_output) if bypass: new_output = bypass(new_output, output) output = new_output return output ``` -------------------------------- ### ModuleMap usage example Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/modules.html ModuleMap provides a dictionary-like interface for managing submodules within a PyTorch module. ```python import torch.nn as nn import deepmatcher as dm class MyModule(nn.Module): def __init__(self): super(MyModule, self).__init__() linears = dm.ModuleMap() linears['type'] = nn.Linear(10, 10) linears['color'] = nn.Linear(10, 10) self.linears = linears def forward(self, x1, x2): y1, y2 = self.linears['type'], self.linears['color'] return y1, y2 ``` -------------------------------- ### Prediction Result Structure Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/getting_started.ipynb An example of the output format for predictions, showing match scores and associated data attributes. ```text Result: match_score left_Song_Name \ id 141999 0.165365 Erase ( Samantha Ronson Remix ) [ feat . Priya... 302034 0.349144 True Colors ( feat . Nicki Minaj ) 126354 0.698185 Biggest Man in Los Angeles 714676 0.186895 Good for You ( feat . A$ AP Rocky ) [ KASBO Re... 659997 0.770332 Rewind ( feat . Monty ) left_Artist_Name left_Album_Name \ id 141999 The Chainsmokers Erase ( Samantha Ronson Remix ) [ feat . Priya... 302034 Wiz Khalifa Blacc Hollywood 126354 Andy Grammer Andy Grammer 714676 Selena Gomez Good for You ( feat . A$ AP Rocky ) [ Remixes ... 659997 Fetty Wap Fetty Wap left_Genre left_Price \ id 141999 Pop , Music $ 1.29 302034 Hip-Hop/Rap , Music , Rap , East Coast Rap , H... $ 1.29 126354 Pop , Music , Rock , Adult Alternative $ 1.29 714676 Pop , Music $ 1.29 659997 Hip-Hop/Rap , Music , Rap Album Only left_CopyRight left_Time \ id 141999 2012 Interscope Records 4:09 302034 2014 Atlantic Recording Corporation for the Un... 4:15 126354 ‰ ãÑ 2011 S-Curve Records 3:55 714676 2015 Interscope Records 3:41 659997 2015 300 Entertainment/RGF Productions 5:36 left_Released right_Song_Name \ id 141999 4-Dec-12 Auuh Remix ( feat . Pacho , Cirilo & Angel Doze ) 302034 19-Aug-14 House In The Hills ( feat . Curren $ y ) [ Cle... 126354 14-Jun-11 Biggest Man In Los Angeles 714676 4-Sep-15 Forget Forever ( STå # FAN Remix ) 659997 NaN Rewind ( feat . Monty ) [ Clean ] right_Artist_Name right_Album_Name \ id 141999 Javy the Flow Auuh Remix ( feat . Pacho , Cirilo & Angel Doze ) 302034 Wiz Khalifa Blacc Hollywood [ Clean ] 126354 Andy Grammer Andy Grammer [ + Video ] [ + Digital Booklet ] 714676 Selena Gomez For You 659997 Fetty Wap Fetty Wap ( Deluxe ) [ Clean ] right_Genre right_Price \ id 141999 R&B , Dance & Electronic , Rap & Hip-Hop , Con... $ 0.99 302034 Rap & Hip-Hop $ 0.99 126354 Pop $ 0.99 714676 Pop $ 1.29 659997 Rap & Hip-Hop $ 1.29 right_CopyRight right_Time \ id 141999 2015 Javy the Flow 5:05 302034 2014 Atlantic Recording Corporation for the Un... 4:52 126354 ( C ) 2011 S-Curve Records 3:54 714676 ( C ) 2014 Hollywood Records , Inc. 3:46 659997 ( C ) 2000 Mute Records Ltd. , a BMG Company ,... 5:36 right_Released id 141999 June 13 , 2015 302034 August 19 , 2014 126354 June 14 , 2011 714676 November 24 , 2014 659997 September 25 , 2015 ``` -------------------------------- ### MatchingBatch attribute access example Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/batch.html Shows how to access the AttrTensor for each attribute (e.g., name and category) from a MatchingBatch object. ```python name_attr = mbatch.name category_attr = mbatch.category ``` -------------------------------- ### MatchingModel.initialize Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/deepmatcher.html Initializes the matching model given the actual training data, instantiating all sub-components and trainable parameters. ```APIDOC ## MatchingModel.initialize ### Description Initialize (not lazily) the matching model given the actual training data. Instantiates all sub-components and their trainable parameters. ### Method initialize ### Signature initialize(train_dataset, init_batch=None) ### Parameters - **train_dataset** (MatchingDataset) - Required - The training dataset obtained using deepmatcher.data.process(). - **init_batch** (MatchingBatch) - Optional - A batch of data to forward propagate through the model. If None, a batch is drawn from the training dataset. ### Returns None ``` -------------------------------- ### Bypass Module Style Support and Initialization Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/modules.html Methods for checking supported styles and initializing the bypass module with specific configurations like residual scaling or highway bias. ```python @classmethod def supports_style(cls, style): return style.lower() in cls._supported_styles def _init(self, style, residual_scale=True, highway_bias=-2, input_size=None): assert self.supports_style(style) self.style = style.lower() self.residual_scale = residual_scale self.highway_bias = highway_bias self.highway_gate = nn.Linear(input_size[1], input_size[0]) ``` -------------------------------- ### MatchingBatch Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_sources/batch.rst.txt The MatchingBatch class represents a batch of matching examples in deepmatcher. It provides methods for accessing and manipulating batch data. ```APIDOC ## MatchingBatch ### Description The MatchingBatch class represents a batch of matching examples in deepmatcher. It provides methods for accessing and manipulating batch data. ### Methods - (Members are documented in the source but not listed here.) ``` -------------------------------- ### MatchingModel.__init__ Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/core.html Initializes a MatchingModel instance with configurable components for attribute summarization, comparison, and classification. The network is constructed lazily before training based on training set metadata. ```APIDOC ## MatchingModel.__init__ ### Description Initializes a MatchingModel instance. The network is not constructed immediately; it is built just before training based on metadata from the training set. The model consists of attribute summarizers, attribute comparators, and a classifier. ### Method Constructor ### Signature ```python MatchingModel(attr_summarizer='hybrid', attr_condense_factor='auto', attr_comparator=None, attr_merge='concat', classifier='2-layer-highway', hidden_size=300) ``` ### Parameters - **attr_summarizer** (string or AttrSummarizer or callable) - Optional - The attribute summarizer. Takes two word embedding sequences and produces two summary vectors. Defaults to 'hybrid'. - **attr_condense_factor** (string or int) - Optional - Factor by which to condense each attribute similarity vector. Can be a number or 'auto'. Defaults to 'auto'. - **attr_comparator** (string or Merge or callable) - Optional - The attribute comparator. Applies a comparison function over the summary vectors. Default is selected based on attr_summarizer choice. - **attr_merge** (string or Merge or callable) - Optional - Operation to merge attribute similarity vectors. Defaults to 'concat'. - **classifier** (string or Classifier or callable) - Optional - Neural network for match/mismatch classification. Defaults to '2-layer-highway'. - **hidden_size** (int) - Optional - Hidden size for attr_summarizer and classifier if they are string arguments. Defaults to 300. ### Returns None ### Notes - The network is constructed just before training based on training set metadata. - For each attribute, an Attribute Summarizer and Attribute Comparator are constructed using the specified templates. - A Classifier is constructed based on the specified classifier template. ``` -------------------------------- ### Add deepmatcher to Python path Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/end_to_end_em.ipynb Adds the deepmatcher package directory to the Python path so that it can be imported. This is a development setup step. ```python sys.path.append('/Users/pradap/Documents/Research/Python-Package/anhaid/deepmatcher') ``` -------------------------------- ### Inspect table A Source: https://github.com/anhaidgroup/deepmatcher/blob/master/examples/end_to_end_em.ipynb Display the first few rows of table A. ```python # The first few tuples in table A. A.head() ``` -------------------------------- ### AttrTensor usage example Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/batch.html Shows how to create an AttrTensor and access its fields (data, lengths, word_probs, pc). The class is a namedtuple, so fields are accessible as attributes. ```python name_attr = AttrTensor(data, lengths, word_probs, pc) assert(name_attr.data == data) assert(name_attr.lengths == lengths) assert(name_attr.word_probs == word_probs) assert(name_attr.pc == pc) ``` -------------------------------- ### AlignmentNetwork _init method Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/modules.html Initializes the alignment network with a specific style and transform network configuration. ```python def _init(self, style='decomposable', hidden_size=None, transform_network='2-layer-highway', input_size=None): if style in ['general', 'decomposable']: if style == 'general': assert hidden_size is None or hidden_size == input_size self.transform = _transform_module(transform_network, hidden_size) # elif style in ['concat', 'concat_dot']: # self.input_transform = nn.ModuleList() # self.input_transform.append(_transform_module(transform_network, hidden_size)) # if style == 'concat': # self.input_transform.append(Transform('1-layer', output_size=1)) # self.context_transform = _transform_module(transform_network, hidden_size, # output_size) # if style == 'concat_dot': # self.output_transform = Transform( # '1-layer', non_linearity=None, output_size=1) elif style != 'dot': raise ValueError('Unknown AlignmentNetwork style') self.style = style ``` -------------------------------- ### Word comparator initialization and forward pass Source: https://github.com/anhaidgroup/deepmatcher/blob/master/docs/html/_modules/deepmatcher/models/word_comparators.html The _init method configures the word comparator module with alignment networks, transform networks, merge modules, and dropout layers. It sets up multi-head attention with optional raw alignment and scaling. The _forward method applies dropout, computes alignment scores, masks them based on sequence lengths, and produces a comparison output using the configured networks. ```python def _init(self, heads=1, hidden_size=None, raw_alignment=False, input_dropout=0, alignment_network='decomposable', scale=False, score_dropout=0, value_transform_network=None, input_transform_network=None, value_merge='concat', transform_dropout=0, comparison_merge='concat', comparison_network='2-layer-highway', input_size=None): hidden_size = hidden_size if hidden_size is not None else input_size[0] self.alignment_networks = nn.ModuleList() for head in range(heads): self.alignment_networks.append( dm.modules._alignment_module(alignment_network, hidden_size)) if value_transform_network is None and heads > 1: value_transform_network = dm.modules.Transform( '1-layer-highway', non_linearity=None, hidden_size=hidden_size // heads) self.value_transform_network = dm.modules._transform_module( value_transform_network, hidden_size // heads) if input_transform_network is None: self.input_transform_network = self.value_transform_network else: self.input_transform_network = dm.modules._transform_module( input_transform_network, hidden_size // heads) self.value_merge = dm.modules._merge_module(value_merge) self.comparison_merge = dm.modules._merge_module(comparison_merge) self.comparison_network = dm.modules._transform_module(comparison_network, hidden_size) self.input_dropout = nn.Dropout(input_dropout) self.transform_dropout = nn.Dropout(transform_dropout) self.score_dropout = nn.Dropout(score_dropout) self.softmax = nn.Softmax(dim=2) self.raw_alignment = raw_alignment self.heads = heads self.scale = scale ``` ```python def _forward(self, input_with_meta, context_with_meta, raw_input_with_meta=None, raw_context_with_meta=None): input = self.input_dropout(input_with_meta.data) context = self.input_dropout(context_with_meta.data) raw_input = self.input_dropout(raw_input_with_meta.data) raw_context = self.input_dropout(raw_context_with_meta.data) queries = input keys = context values = context if self.raw_alignment: queries = raw_input keys = raw_context inputs_transformed = [] values_aligned = [] for head in range(self.heads): # Dims: batch x len1 x len2 alignment_scores = self.score_dropout(self.alignment_networks[head](queries, keys)) if self.scale: alignment_scores = alignment_scores / torch.sqrt(hidden_size) if context_with_meta.lengths is not None: mask = _utils.sequence_mask(context_with_meta.lengths) mask = mask.unsqueeze(1) # Make it broadcastable. alignment_scores.data.masked_fill_(1 - mask, -float('inf')) # Make values along dim 2 sum to 1. normalized_scores = self.softmax(alignment_scores) if self.input_transform_network is not None: inputs_transformed.append( self.transform_dropout(self.input_transform_network(input))) if self.value_transform_network is not None: values_transformed = self.transform_dropout( self.value_transform_network(values)) else: values_transformed = values # Dims: batch x len1 x channels values_aligned.append(torch.bmm(normalized_scores, values_transformed)) inputs_merged = input if inputs_transformed: inputs_merged = self.value_merge(*inputs_transformed) values_merged = self.value_merge(*values_aligned) comparison_merged = self.comparison_merge(inputs_merged, values_merged) comparison = self.comparison_network(comparison_merged) return AttrTensor.from_old_metadata(comparison, input_with_meta) ```