use ahash::HashMap;
use sprs::CsMat;
use tracing::debug;
use super::{count_vectorizer::CountVectorizer, params::VectorizerParams};
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub struct TfidfVectorizer {
count_vectorizer: CountVectorizer,
idf: Vec<f32>,
}
impl TfidfVectorizer {
pub fn fit<T: AsRef<str> + Sync>(
texts: &[T],
count_vectorizer_params: VectorizerParams,
) -> Self {
debug!(num_texts = texts.len(), "Fitting TfidfVectorizer");
let (count_vectorizer, tf_matrix) =
CountVectorizer::fit_transform(texts, count_vectorizer_params);
Self::fit_from_tf_matrix(count_vectorizer, &tf_matrix, texts.len())
}
fn fit_from_tf_matrix(
count_vectorizer: CountVectorizer,
tf_matrix: &CsMat<f32>,
n_docs: usize,
) -> Self {
debug!("Calculating IDF values from TF matrix");
let n_docs = n_docs as f32;
let num_features = count_vectorizer.num_features();
let mut df = vec![0usize; num_features];
for row_vec in tf_matrix.outer_iterator() {
for (col_idx, _val) in row_vec.iter() {
df[col_idx] += 1;
}
}
let idf = df
.iter()
.map(|&doc_freq| ((n_docs + 1.0) / (doc_freq as f32 + 1.0)).ln() + 1.0)
.collect();
debug!("IDF calculation complete");
Self {
count_vectorizer,
idf,
}
}
pub fn transform<T: AsRef<str> + Sync>(&self, texts: &[T]) -> CsMat<f32> {
debug!(
num_texts = texts.len(),
"Transforming texts using TfidfVectorizer"
);
let tf_matrix = self.count_vectorizer.transform(texts);
self.apply_tfidf_transform(tf_matrix)
}
fn apply_tfidf_transform(&self, mut tf_matrix: CsMat<f32>) -> CsMat<f32> {
debug!("Applying TF-IDF transformation");
let use_sublinear_tf = self.count_vectorizer.params().sublinear_tf();
for mut row_vec in tf_matrix.outer_iterator_mut() {
let mut norm_squared = 0.0;
for (col_idx, val) in row_vec.iter_mut() {
if use_sublinear_tf && *val > 0.0 {
*val = 1.0 + val.ln();
}
*val *= self.idf[col_idx];
norm_squared += *val * *val;
}
if norm_squared > 0.0 {
let norm = norm_squared.sqrt();
for (_, val) in row_vec.iter_mut() {
*val /= norm;
}
}
}
tf_matrix
}
pub fn fit_transform<T: AsRef<str> + Sync>(
texts: &[T],
count_vectorizer_params: VectorizerParams,
) -> (Self, CsMat<f32>) {
debug!(
num_texts = texts.len(),
"Fitting and transforming texts using TfidfVectorizer"
);
let (count_vectorizer, tf_matrix) =
CountVectorizer::fit_transform(texts, count_vectorizer_params);
let vectorizer = Self::fit_from_tf_matrix(count_vectorizer, &tf_matrix, texts.len());
let tfidf_matrix = vectorizer.apply_tfidf_transform(tf_matrix);
debug!("fit_transform complete with single tokenization pass");
(vectorizer, tfidf_matrix)
}
#[must_use]
pub fn num_features(&self) -> usize {
self.count_vectorizer.num_features()
}
#[must_use]
pub fn vocabulary(&self) -> HashMap<String, usize> {
self.count_vectorizer.vocabulary()
}
#[must_use]
pub fn params(&self) -> &VectorizerParams {
self.count_vectorizer.params()
}
}
#[cfg(feature = "bincode")]
impl TfidfVectorizer {
pub fn to_bytes(&self) -> Result<Vec<u8>, bincode::error::EncodeError> {
bincode::encode_to_vec(self, bincode::config::standard())
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, bincode::error::DecodeError> {
let (vectorizer, _): (Self, usize) =
bincode::decode_from_slice(bytes, bincode::config::standard())?;
Ok(vectorizer)
}
}
#[cfg(feature = "serde")]
impl TfidfVectorizer {
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
pub fn from_json(json_str: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json_str)
}
}