Struct Sif

Source
pub struct Sif<'w, 'p, W, P> { /* private fields */ }
Expand description

An implementation of SIF.

SIF is Smooth Inverse Frequency and Common Component Removal, simple but pewerful techniques for sentence embeddings described in the paper: Sanjeev Arora, Yingyu Liang, and Tengyu Ma, A Simple but Tough-to-Beat Baseline for Sentence Embeddings, ICLR 2017.

§Brief description of API

The algorithm consists of two steps:

  1. Compute sentence embeddings with the SIF weighting.
  2. Remove the common components from the sentence embeddings.

The common components are computed from input sentences.

Our API is designed to allow reuse of common components once computed because it is not always possible to obtain a sufficient number of sentences as queries to compute.

Sif::fit computes the common components from input sentences and returns a fitted instance of Sif. Sif::embeddings computes sentence embeddings with the fitted components.

§Examples

use std::io::BufReader;

use finalfusion::compat::text::ReadText;
use finalfusion::embeddings::Embeddings;
use wordfreq::WordFreq;

use sif_embedding::{Sif, SentenceEmbedder};

// Loads word embeddings from a pretrained model.
let word_embeddings_text = "las 0.0 1.0 2.0\nvegas -3.0 -4.0 -5.0\n";
let mut reader = BufReader::new(word_embeddings_text.as_bytes());
let word_embeddings = Embeddings::read_text(&mut reader)?;

// Loads word probabilities from a pretrained model.
let word_probs = WordFreq::new([("las", 0.4), ("vegas", 0.6)]);

// Prepares input sentences.
let sentences = ["las vegas", "mega vegas"];

// Fits the model with input sentences.
let model = Sif::new(&word_embeddings, &word_probs);
let model = model.fit(&sentences)?;

// Computes sentence embeddings in shape (n, m),
// where n is the number of sentences and m is the number of dimensions.
let sent_embeddings = model.embeddings(sentences)?;
assert_eq!(sent_embeddings.shape(), &[2, 3]);

§Only SIF weighting

If you want to apply only the SIF weighting to avoid the computation of common components, use Sif::with_parameters and set n_components to 0. In this case, you can skip Sif::fit and directly perform Sif::embeddings because there is no parameter to fit (although the quality of the embeddings may be worse).

use std::io::BufReader;

use finalfusion::compat::text::ReadText;
use finalfusion::embeddings::Embeddings;
use wordfreq::WordFreq;

use sif_embedding::{Sif, SentenceEmbedder};

// Loads word embeddings from a pretrained model.
let word_embeddings_text = "las 0.0 1.0 2.0\nvegas -3.0 -4.0 -5.0\n";
let mut reader = BufReader::new(word_embeddings_text.as_bytes());
let word_embeddings = Embeddings::read_text(&mut reader)?;

// Loads word probabilities from a pretrained model.
let word_probs = WordFreq::new([("las", 0.4), ("vegas", 0.6)]);

// When setting `n_components` to `0`, no common components are removed, and
// the sentence embeddings can be computed without `fit`.
let model = Sif::with_parameters(&word_embeddings, &word_probs, 1e-3, 0)?;
let sent_embeddings = model.embeddings(["las vegas", "mega vegas"])?;
assert_eq!(sent_embeddings.shape(), &[2, 3]);

§Serialization of fitted parameters

If you want to serialize and deserialize the fitted parameters, use Sif::serialize and Sif::deserialize.

use std::io::BufReader;

use approx::assert_relative_eq;
use finalfusion::compat::text::ReadText;
use finalfusion::embeddings::Embeddings;
use wordfreq::WordFreq;

use sif_embedding::{Sif, SentenceEmbedder};

// Loads word embeddings from a pretrained model.
let word_embeddings_text = "las 0.0 1.0 2.0\nvegas -3.0 -4.0 -5.0\n";
let mut reader = BufReader::new(word_embeddings_text.as_bytes());
let word_embeddings = Embeddings::read_text(&mut reader)?;

// Loads word probabilities from a pretrained model.
let word_probs = WordFreq::new([("las", 0.4), ("vegas", 0.6)]);

// Prepares input sentences.
let sentences = ["las vegas", "mega vegas"];

// Fits the model and computes sentence embeddings.
let model = Sif::new(&word_embeddings, &word_probs);
let model = model.fit(&sentences)?;
let sent_embeddings = model.embeddings(&sentences)?;

// Serializes and deserializes the fitted parameters.
let bytes = model.serialize()?;
let other = Sif::deserialize(&bytes, &word_embeddings, &word_probs)?;
let other_embeddings = other.embeddings(&sentences)?;
assert_relative_eq!(sent_embeddings, other_embeddings);

Implementations§

Source§

impl<'w, 'p, W, P> Sif<'w, 'p, W, P>

Source

pub const fn new(word_embeddings: &'w W, word_probs: &'p P) -> Self

Creates a new instance with default parameters defined by DEFAULT_PARAM_A and DEFAULT_N_COMPONENTS.

§Arguments
  • word_embeddings - Word embeddings.
  • word_probs - Word probabilities.
Source

pub fn with_parameters( word_embeddings: &'w W, word_probs: &'p P, param_a: Float, n_components: usize, ) -> Result<Self>

Creates a new instance with manually specified parameters.

§Arguments
  • word_embeddings - Word embeddings.
  • word_probs - Word probabilities.
  • param_a - A parameter a for SIF-weighting that should be positive.
  • n_components - The number of principal components to remove.

When setting n_components to 0, no principal components are removed.

§Errors

Returns an error if param_a is not positive.

Source

pub const fn separator(self, separator: char) -> Self

Sets a separator for sentence segmentation (default: DEFAULT_SEPARATOR).

Source

pub fn n_samples_to_fit(self, n_samples_to_fit: usize) -> Result<Self>

Sets the number of samples to fit the model (default: DEFAULT_N_SAMPLES_TO_FIT).

§Errors

Returns an error if n_samples_to_fit is 0.

Source

pub fn serialize(&self) -> Result<Vec<u8>>

Serializes the model.

Source

pub fn deserialize( bytes: &[u8], word_embeddings: &'w W, word_probs: &'p P, ) -> Result<Self>

Deserializes the model.

§Arguments
  • bytes - Byte sequence exported by Self::serialize.
  • word_embeddings - Word embeddings.
  • word_probs - Word probabilities.

word_embeddings and word_probs must be the same as those used in serialization.

Trait Implementations§

Source§

impl<'w, 'p, W: Clone, P: Clone> Clone for Sif<'w, 'p, W, P>

Source§

fn clone(&self) -> Sif<'w, 'p, W, P>

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<W, P> SentenceEmbedder for Sif<'_, '_, W, P>

Source§

fn embedding_size(&self) -> usize

Returns the number of dimensions for sentence embeddings, which is the same as the number of dimensions for word embeddings.

Source§

fn fit<S>(self, sentences: &[S]) -> Result<Self>
where S: AsRef<str>,

Fits the model with input sentences.

Sentences to fit are randomly sampled from sentences with Self::n_samples_to_fit.

If n_components is 0, does nothing and returns self.

§Errors

Returns an error if sentences is empty.

§Complexities
  • Time complexity: O(L*D*S + max(D,S)^3)
  • Space complexity: O(D*S + max(D,S)^2)

where

  • L is the average number of words in a sentence.
  • D is the number of dimensions for word embeddings (embedding_size).
  • S is the number of sentences used to fit (n_samples_to_fit).
Source§

fn embeddings<I, S>(&self, sentences: I) -> Result<Array2<Float>>
where I: IntoIterator<Item = S>, S: AsRef<str>,

Computes embeddings for input sentences using the fitted model.

If n_components is 0, the fitting is not required.

§Errors

Returns an error if the model is not fitted.

§Complexities
  • Time complexity: O(L*D*N + C*D*N)
  • Space complexity: O(D*N)

where

  • L is the average number of words in a sentence.
  • D is the number of dimensions for word embeddings (embedding_size).
  • N is the number of sentences (sentences.len()).
  • C is the number of components to remove (n_components).

Auto Trait Implementations§

§

impl<'w, 'p, W, P> Freeze for Sif<'w, 'p, W, P>

§

impl<'w, 'p, W, P> RefUnwindSafe for Sif<'w, 'p, W, P>

§

impl<'w, 'p, W, P> Send for Sif<'w, 'p, W, P>
where W: Sync, P: Sync,

§

impl<'w, 'p, W, P> Sync for Sif<'w, 'p, W, P>
where W: Sync, P: Sync,

§

impl<'w, 'p, W, P> Unpin for Sif<'w, 'p, W, P>

§

impl<'w, 'p, W, P> UnwindSafe for Sif<'w, 'p, W, P>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V