-
Notifications
You must be signed in to change notification settings - Fork 0
feat(corpus): refuse TF-IDF and BM25 as inferential weights #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
seonghobae
wants to merge
4
commits into
main
Choose a base branch
from
agent/corpus-refuse-inferential-tfidf
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b0a9565
feat(corpus): refuse TF-IDF and BM25 as inferential weights
seonghobae aa7949e
test: exercise normalized corpus masses
seonghobae 907f4a8
Merge remote-tracking branch 'origin/main' into review/pr63-refresh
seonghobae 4b64edc
fix(corpus): ground inferential weight evidence
seonghobae File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| //! Retrieval scores and stopword deletion are not inferential split weights. | ||
|
|
||
| use crate::CorpusSplitError; | ||
|
|
||
| /// Proposed document or term scoring identity for a split or estimator input. | ||
| #[derive(Clone, Copy, Debug, Eq, PartialEq)] | ||
| #[non_exhaustive] | ||
| pub enum WeightingScheme { | ||
| /// Kish / group-normalized observation weights. | ||
| GroupNormalizedEss, | ||
| /// Uniform observation weights. | ||
| Uniform, | ||
| /// TF-IDF retrieval ranking score. | ||
| TfIdf, | ||
| /// BM25 retrieval ranking score. | ||
| Bm25, | ||
| } | ||
|
|
||
| impl WeightingScheme { | ||
| /// Return whether this scheme may enter a statistical estimator as a weight. | ||
| #[must_use] | ||
| pub const fn is_inferential_weight(self) -> bool { | ||
| matches!(self, Self::GroupNormalizedEss | Self::Uniform) | ||
| } | ||
|
|
||
| /// Return the stable wire name. | ||
| #[must_use] | ||
| pub const fn wire_name(self) -> &'static str { | ||
| match self { | ||
| Self::GroupNormalizedEss => "group_normalized_ess", | ||
| Self::Uniform => "uniform", | ||
| Self::TfIdf => "tf_idf", | ||
| Self::Bm25 => "bm25", | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Proposed token-deletion rule applied before estimation. | ||
| #[derive(Clone, Copy, Debug, Eq, PartialEq)] | ||
| #[non_exhaustive] | ||
| pub enum TokenDeletionRule { | ||
| /// Keep tokens and model template, section, copied, and style as method structure. | ||
| PreserveAndModelBackground, | ||
| /// Delete tokens that appear on a global stopword list. | ||
| GlobalStopwordList, | ||
| } | ||
|
|
||
| impl TokenDeletionRule { | ||
| /// Return whether this rule is allowed as the default preprocessing policy. | ||
| #[must_use] | ||
| pub const fn is_default_allowed(self) -> bool { | ||
| matches!(self, Self::PreserveAndModelBackground) | ||
| } | ||
|
|
||
| /// Return the stable wire name. | ||
| #[must_use] | ||
| pub const fn wire_name(self) -> &'static str { | ||
| match self { | ||
| Self::PreserveAndModelBackground => "preserve_and_model_background", | ||
| Self::GlobalStopwordList => "global_stopword_list", | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Refuse TF-IDF and BM25 as inferential estimator weights. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns [`CorpusSplitError::InferentialRetrievalWeight`] unless `scheme` is | ||
| /// [`WeightingScheme::GroupNormalizedEss`] or [`WeightingScheme::Uniform`]. | ||
| pub fn refuse_inferential_retrieval_weight( | ||
| scheme: WeightingScheme, | ||
| ) -> Result<(), CorpusSplitError> { | ||
| if scheme.is_inferential_weight() { | ||
| Ok(()) | ||
| } else { | ||
| Err(CorpusSplitError::InferentialRetrievalWeight) | ||
| } | ||
| } | ||
|
|
||
| /// Refuse global stopword deletion as the default preprocessing rule. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns [`CorpusSplitError::DefaultStopwordDeletion`] unless `rule` is | ||
| /// [`TokenDeletionRule::PreserveAndModelBackground`]. | ||
| pub fn refuse_default_stopword_deletion(rule: TokenDeletionRule) -> Result<(), CorpusSplitError> { | ||
| if rule.is_default_allowed() { | ||
| Ok(()) | ||
| } else { | ||
| Err(CorpusSplitError::DefaultStopwordDeletion) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::{ | ||
| TokenDeletionRule, WeightingScheme, refuse_default_stopword_deletion, | ||
| refuse_inferential_retrieval_weight, | ||
| }; | ||
| use crate::CorpusSplitError; | ||
|
|
||
| #[test] | ||
| fn predicates_export_stable_wire_names_and_gates() { | ||
| assert!(WeightingScheme::GroupNormalizedEss.is_inferential_weight()); | ||
| assert!(WeightingScheme::Uniform.is_inferential_weight()); | ||
| assert!(!WeightingScheme::TfIdf.is_inferential_weight()); | ||
| assert!(!WeightingScheme::Bm25.is_inferential_weight()); | ||
| assert_eq!( | ||
| WeightingScheme::GroupNormalizedEss.wire_name(), | ||
| "group_normalized_ess" | ||
| ); | ||
| assert_eq!(WeightingScheme::Uniform.wire_name(), "uniform"); | ||
| assert_eq!(WeightingScheme::TfIdf.wire_name(), "tf_idf"); | ||
| assert_eq!(WeightingScheme::Bm25.wire_name(), "bm25"); | ||
| refuse_inferential_retrieval_weight(WeightingScheme::GroupNormalizedEss).expect("ess"); | ||
| refuse_inferential_retrieval_weight(WeightingScheme::Uniform).expect("uniform"); | ||
| assert_eq!( | ||
| refuse_inferential_retrieval_weight(WeightingScheme::TfIdf), | ||
| Err(CorpusSplitError::InferentialRetrievalWeight) | ||
| ); | ||
| assert_eq!( | ||
| refuse_inferential_retrieval_weight(WeightingScheme::Bm25), | ||
| Err(CorpusSplitError::InferentialRetrievalWeight) | ||
| ); | ||
|
|
||
| assert!(TokenDeletionRule::PreserveAndModelBackground.is_default_allowed()); | ||
| assert!(!TokenDeletionRule::GlobalStopwordList.is_default_allowed()); | ||
| assert_eq!( | ||
| TokenDeletionRule::PreserveAndModelBackground.wire_name(), | ||
| "preserve_and_model_background" | ||
| ); | ||
| assert_eq!( | ||
| TokenDeletionRule::GlobalStopwordList.wire_name(), | ||
| "global_stopword_list" | ||
| ); | ||
| refuse_default_stopword_deletion(TokenDeletionRule::PreserveAndModelBackground) | ||
| .expect("preserve"); | ||
| assert_eq!( | ||
| refuse_default_stopword_deletion(TokenDeletionRule::GlobalStopwordList), | ||
| Err(CorpusSplitError::DefaultStopwordDeletion) | ||
| ); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 155 additions & 0 deletions
155
crates/corpus_split/tests/inferential_weight_contract.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| //! TF-IDF, BM25, and global stopword deletion are not inferential inputs. | ||
|
|
||
| use corpus_split::{ | ||
| CorpusSplitError, LeakageLink, LeakageLinkKind, TokenDeletionRule, WeightingScheme, | ||
| build_connected_groups, group_normalized_weights, refuse_default_stopword_deletion, | ||
| refuse_inferential_retrieval_weight, | ||
| }; | ||
| use std::collections::BTreeMap; | ||
| use uuid::Uuid; | ||
|
|
||
| fn computed_rmse(truth: &[f64], recovered: &[f64]) -> f64 { | ||
| assert_eq!(truth.len(), recovered.len()); | ||
| let n = f64::from(u32::try_from(truth.len()).expect("tiny fixture")); | ||
| let sse: f64 = truth | ||
| .iter() | ||
| .zip(recovered) | ||
| .map(|(truth_value, recovered_value)| { | ||
| let residual = truth_value - recovered_value; | ||
| residual * residual | ||
| }) | ||
| .sum(); | ||
| (sse / n).sqrt() | ||
| } | ||
|
|
||
| fn l1_normalize(values: &[f64]) -> Vec<f64> { | ||
| let total: f64 = values.iter().sum(); | ||
| assert!(total > 0.0); | ||
| values.iter().map(|value| value / total).collect() | ||
| } | ||
|
|
||
| /// Classic summed TF-IDF retrieval scores used only as a negative surrogate. | ||
| fn tf_idf_document_scores(documents: &[&[&str]]) -> Vec<f64> { | ||
| let document_count = f64::from(u32::try_from(documents.len()).expect("tiny fixture")); | ||
| let mut document_frequency = BTreeMap::<&str, f64>::new(); | ||
| for document in documents { | ||
| let mut seen = std::collections::BTreeSet::new(); | ||
| for token in *document { | ||
| if seen.insert(*token) { | ||
| *document_frequency.entry(*token).or_insert(0.0) += 1.0; | ||
| } | ||
| } | ||
| } | ||
| documents | ||
| .iter() | ||
| .map(|document| { | ||
| let mut term_frequency = BTreeMap::<&str, f64>::new(); | ||
| for token in *document { | ||
| *term_frequency.entry(*token).or_insert(0.0) += 1.0; | ||
| } | ||
| term_frequency | ||
| .into_iter() | ||
| .map(|(token, frequency)| { | ||
| let df = document_frequency.get(token).copied().unwrap_or(0.0); | ||
| frequency * (document_count / df).ln() | ||
| }) | ||
| .sum() | ||
| }) | ||
| .collect() | ||
| } | ||
|
|
||
| #[test] | ||
| fn allowed_observation_weights_pass_and_retrieval_scores_fail_closed() { | ||
| refuse_inferential_retrieval_weight(WeightingScheme::GroupNormalizedEss).expect("ess"); | ||
| refuse_inferential_retrieval_weight(WeightingScheme::Uniform).expect("uniform"); | ||
| assert_eq!( | ||
| refuse_inferential_retrieval_weight(WeightingScheme::TfIdf), | ||
| Err(CorpusSplitError::InferentialRetrievalWeight) | ||
| ); | ||
| assert_eq!( | ||
| refuse_inferential_retrieval_weight(WeightingScheme::Bm25), | ||
| Err(CorpusSplitError::InferentialRetrievalWeight) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn global_stopword_deletion_is_not_the_default_rule() { | ||
| refuse_default_stopword_deletion(TokenDeletionRule::PreserveAndModelBackground) | ||
| .expect("preserve"); | ||
| assert_eq!( | ||
| refuse_default_stopword_deletion(TokenDeletionRule::GlobalStopwordList), | ||
| Err(CorpusSplitError::DefaultStopwordDeletion) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn group_normalized_mass_recovers_true_shares_with_lower_rmse_than_tfidf() { | ||
| let truth = [0.40_f64, 0.10, 0.30, 0.20]; | ||
| let observation_mass = [4.0_f64, 1.0, 3.0, 2.0]; | ||
| let documents: [&[&str]; 4] = [ | ||
| &["report", "report", "report", "event"], | ||
| &["report", "unique"], | ||
| &["report", "event", "event"], | ||
| &["report", "report", "unique", "event"], | ||
| ]; | ||
| let document_ids: Vec<Uuid> = (0..truth.len()).map(|_| Uuid::now_v7()).collect(); | ||
| let links: Vec<LeakageLink> = document_ids | ||
| .windows(2) | ||
| .map(|pair| LeakageLink { | ||
| left: pair[0], | ||
| right: pair[1], | ||
| kind: LeakageLinkKind::SameEpisode, | ||
| }) | ||
| .collect(); | ||
| let groups = build_connected_groups(&document_ids, &links); | ||
| let normalized_by_id: BTreeMap<Uuid, f64> = group_normalized_weights( | ||
| &groups, | ||
| &document_ids | ||
| .iter() | ||
| .copied() | ||
| .zip(observation_mass) | ||
| .collect::<Vec<_>>(), | ||
| ) | ||
| .into_iter() | ||
| .collect(); | ||
| let ess_recovered: Vec<f64> = document_ids | ||
| .iter() | ||
| .map(|document_id| *normalized_by_id.get(document_id).expect("normalized mass")) | ||
| .collect(); | ||
| let tfidf_recovered = l1_normalize(&tf_idf_document_scores(&documents)); | ||
| let ess_rmse = computed_rmse(&truth, &ess_recovered); | ||
| let tfidf_rmse = computed_rmse(&truth, &tfidf_recovered); | ||
| assert!( | ||
| ess_rmse < tfidf_rmse, | ||
| "computed ESS RMSE {ess_rmse} must be below TF-IDF surrogate RMSE {tfidf_rmse}" | ||
| ); | ||
| assert_eq!( | ||
| refuse_inferential_retrieval_weight(WeightingScheme::TfIdf), | ||
| Err(CorpusSplitError::InferentialRetrievalWeight) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn wire_names_and_predicates_are_stable() { | ||
| assert_eq!( | ||
| WeightingScheme::GroupNormalizedEss.wire_name(), | ||
| "group_normalized_ess" | ||
| ); | ||
| assert_eq!(WeightingScheme::Uniform.wire_name(), "uniform"); | ||
| assert_eq!(WeightingScheme::TfIdf.wire_name(), "tf_idf"); | ||
| assert_eq!(WeightingScheme::Bm25.wire_name(), "bm25"); | ||
| assert!(WeightingScheme::GroupNormalizedEss.is_inferential_weight()); | ||
| assert!(WeightingScheme::Uniform.is_inferential_weight()); | ||
| assert!(!WeightingScheme::TfIdf.is_inferential_weight()); | ||
| assert!(!WeightingScheme::Bm25.is_inferential_weight()); | ||
| assert_eq!( | ||
| TokenDeletionRule::PreserveAndModelBackground.wire_name(), | ||
| "preserve_and_model_background" | ||
| ); | ||
| assert_eq!( | ||
| TokenDeletionRule::GlobalStopwordList.wire_name(), | ||
| "global_stopword_list" | ||
| ); | ||
| assert!(TokenDeletionRule::PreserveAndModelBackground.is_default_allowed()); | ||
| assert!(!TokenDeletionRule::GlobalStopwordList.is_default_allowed()); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.