Vector Database

Tf-Idf Vectorizer

Term frequency

$$tf(t,d)=\frac{f_{t,d}}{\sum_{t'\in d}{f_{t',d}}}$$

ft,d là tần suất xuất hiện của một từ (term) trong 1 tài liệu (document)

Mẫu số là tổng số từ (term) trong 1 tài liệu

Inverse document frequency

$$idf(t, D) = 1 + ln\frac{N}{df(t)}$$

N: là tổng số tài liệu document trong corpus

df(t): số tài liệu chứa từ (term)

Smooth Inverse document frequency

$$idf(t, D) = 1 + ln\frac{N + 1}{df(t) + 1}$$

Example

d1: the cats are in the house
d2: the dogs are in the house and outside
d3: the cats and dogs are friends
tf - idf
andarecatsdogsfriendshouseinoutsidethe
d1011001102
d2110101112
d3111110001
df(t)232212213
$$idf(t, D) = 1 + ln\frac{N}{df(t)}$$$$1+ln\frac{3}{2}=1.4055$$$$1+ln\frac{3}{3}=1$$$$1+ln\frac{3}{2}=1.4055$$$$1+ln\frac{3}{2}=1.4055$$$$1+ln\frac{3}{1}=2.0986$$$$1+ln\frac{3}{2}=1.4055$$$$1+ln\frac{3}{2}=1.4055$$$$1+ln\frac{3}{1}=2.0986$$$$1+ln\frac{3}{3}=1$$
tf - idf Non Normal
andarecatsdogsfriendshouseinoutsidethe
0.01.01.40550.00.01.40551.40550.02.0
1.40551.00.01.40550.01.40551.40552.09862.0
1.40551.01.40551.40552.09860.00.00.01.0
tf - idf l1-norm
andarecatsdogsfriendshouseinoutsidethe
0.00.13860.19480.00.00.19480.19480.00.2771
0.13110.09330.00.13110.00.13110.13110.19580.1866
0.1690.12030.1690.1690.25240.00.00.00.1203
tf - idf l2-norm
andarecatsdogsfriendshouseinoutsidethe
0.00.30250.42520.00.00.42520.42520.00.6051
0.33790.24040.00.33790.00.33790.33790.50450.4808
0.40030.28480.40030.40030.59770.00.00.00.2848

Python Code

Prepare
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = [
    "the cats are in the house",
    "the dogs are in the house and outside",
    "the cats and dogs are friends",
]
Non Normalize
vectorizer = TfidfVectorizer(use_idf=True, norm=None, smooth_idf=False)
vectorizer.fit_transform(corpus)
vectorizer.get_feature_names_out()
l1-norm
vectorizer = TfidfVectorizer(use_idf=True, norm='l1', smooth_idf=False)
l2-norm
vectorizer = TfidfVectorizer(use_idf=True, norm='l2', smooth_idf=False)
l2-norm smooth-idf
vectorizer = TfidfVectorizer(use_idf=True, norm='l2', smooth_idf=True)