is_it_slop_preprocessing/pre_processor/vectorizer/params.rs
1//! Vectorizer configuration parameters.
2//!
3//! This module defines [`VectorizerParams`], which controls:
4//! - N-gram range (e.g., 2-4 for bigrams through 4-grams)
5//! - Vocabulary filtering (`min_df` and `max_df` thresholds)
6//! - Term frequency scaling (sublinear TF option)
7//!
8//! # Parameter Guidelines
9//!
10//! - **`min_df`**: Filter rare terms to reduce vocabulary size and noise
11//! - Proportion (0.0-1.0): Term must appear in at least X% of documents
12//! - Absolute (≥1.0): Term must appear in at least X documents
13//! - Default: 10.0 (10 documents minimum)
14//!
15//! - **`max_df`**: Filter common terms that appear in most documents
16//! - Proportion (0.0-1.0): Term must appear in at most X% of documents
17//! - Absolute (>1.0): Term must appear in at most X documents
18//! - Default: 1.0 (100% - no filtering)
19//!
20//! - **`sublinear_tf`**: Apply log scaling to term frequencies
21//! - `tf → log(tf + 1)`
22//! - Reduces impact of terms repeated many times
23//! - Default: false
24
25/// Default minimum n-gram size.
26pub const DEFAULT_MIN_NGRAM: usize = 2;
27
28/// Default maximum n-gram size.
29///
30/// **Important**: This value is also used to optimize storage for n-gram keys as they are stored in
31/// a fixed-size format (u128) that can hold up to 4 tokens (4 * 32 bits = 128 bits). If you need
32/// n-grams larger than 4, you will need to change the storage format and increase this constant
33/// accordingly, which may involve more complex logic for handling variable-length n-grams and could
34/// impact performance. If you frequently use n-gram ranges larger than this, consider increasing
35/// this constant and recompiling for better performance. If you frequently use n-gram ranges larger
36/// than this, consider increasing this constant and recompiling for better performance.
37pub const DEFAULT_MAX_NGRAM: usize = 4;
38
39/// Configuration parameters for text vectorization.
40///
41/// Controls n-gram extraction, vocabulary filtering, and term frequency scaling.
42#[cfg_attr(
43 feature = "rkyv",
44 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
45)]
46#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48#[derive(Clone, Debug)]
49pub struct VectorizerParams {
50 ngram_range: Vec<usize>,
51 /// Minimum document frequency for filtering vocabulary.
52 /// - If `min_df` is in (0.0, 1.0), it's a proportion of documents
53 /// - If `min_df` >= 1.0, it's an absolute document count
54 min_df: f32,
55 /// Maximum document frequency for filtering vocabulary.
56 /// - If `max_df` is in (0.0, 1.0], it's a proportion of documents
57 /// - If `max_df` > 1.0, it's an absolute document count
58 max_df: f32,
59 /// Apply sublinear tf scaling: replace term frequency `tf` with `1 + log(tf)`.
60 /// This reduces the impact of terms that occur many times in a document.
61 sublinear_tf: bool,
62}
63
64impl VectorizerParams {
65 /// Create new vectorizer parameters.
66 ///
67 /// # Arguments
68 /// * `ngram_range` - Range of n-gram sizes (e.g., `3..=5` for trigrams to 5-grams)
69 /// * `min_df` - Minimum document frequency (proportion or count)
70 /// * `max_df` - Maximum document frequency (proportion or count)
71 /// * `sublinear_tf` - Whether to apply log scaling to term frequencies
72 ///
73 /// # Panics
74 /// Panics if `min_df` or `max_df` are not positive, or if `ngram_range` is empty.
75 #[must_use]
76 pub fn new(
77 // ngram_range: impl Into<RangeInclusive<usize>>,
78 min_df: f32,
79 max_df: f32,
80 sublinear_tf: bool,
81 ) -> Self {
82 let ngram_range = DEFAULT_MIN_NGRAM..=DEFAULT_MAX_NGRAM;
83 let n_sizes = ngram_range.collect::<Vec<_>>();
84 assert!(
85 !n_sizes.is_empty(),
86 "ngram_range must contain at least one value"
87 );
88 assert!(
89 min_df > 0.0,
90 "min_df must be positive (proportion in (0.0, 1.0) or absolute count >= 1.0)"
91 );
92 assert!(
93 max_df > 0.0,
94 "max_df must be positive (proportion in (0.0, 1.0] or absolute count > 1.0)"
95 );
96 Self {
97 ngram_range: n_sizes,
98 min_df,
99 max_df,
100 sublinear_tf,
101 }
102 }
103
104 /// Get all n-gram sizes as a slice.
105 #[must_use]
106 pub fn ngram_counts(&self) -> &[usize] {
107 &self.ngram_range
108 }
109
110 /// Get the n-gram range as a tuple `(min, max)`.
111 #[must_use]
112 pub fn ngram_range(&self) -> (usize, usize) {
113 (
114 *self.ngram_range.first().expect("ngram_range is not empty"),
115 *self.ngram_range.last().expect("ngram_range is not empty"),
116 )
117 }
118
119 /// Get the minimum document frequency threshold.
120 #[must_use]
121 pub fn min_df(&self) -> f32 {
122 self.min_df
123 }
124
125 /// Get the maximum document frequency threshold.
126 #[must_use]
127 pub fn max_df(&self) -> f32 {
128 self.max_df
129 }
130
131 /// Get whether sublinear TF scaling is enabled.
132 #[must_use]
133 pub fn sublinear_tf(&self) -> bool {
134 self.sublinear_tf
135 }
136}
137impl Default for VectorizerParams {
138 fn default() -> Self {
139 Self {
140 ngram_range: (DEFAULT_MIN_NGRAM..=DEFAULT_MAX_NGRAM).collect(),
141 min_df: 10.0,
142 max_df: 1.0,
143 sublinear_tf: false,
144 }
145 }
146}
147
148// impl From<((usize, usize), f32, f32, bool)> for VectorizerParams {
149// fn from(value: ((usize, usize), f32, f32, bool)) -> Self {
150// Self::new(value.0.0..=value.0.1, value.1, value.2, value.3)
151// }
152// }
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 #[allow(clippy::float_cmp)]
160 fn test_default_params() {
161 let params = VectorizerParams::default();
162 assert_eq!(params.ngram_range(), (2, 4));
163 assert_eq!(params.min_df(), 10.0);
164 assert_eq!(params.max_df(), 1.0);
165 assert!(!params.sublinear_tf());
166 }
167
168 #[test]
169 #[should_panic(expected = "min_df must be positive")]
170 fn test_invalid_min_df() {
171 let _ = VectorizerParams::new(0.0, 1.0, false);
172 }
173
174 #[test]
175 fn test_ngram_counts() {
176 let params = VectorizerParams::default();
177 assert_eq!(params.ngram_counts(), &[2, 3, 4]);
178 }
179}