Shlukování dokumentů

Cluster Analysis in Python

Shaumik Daityari

Business Analyst

Shlukování dokumentů: koncepty

  1. Vyčistit data před zpracováním
  2. Určit důležitost termínů v dokumentu (matice TF-IDF)
  3. Shlukovat matici TF-IDF
  4. Najít nejčastější termíny a dokumenty v každém shluku
Cluster Analysis in Python

Čištění a tokenizace dat

  • Převod textu na tokeny a čištění dat pro zpracování
from nltk.tokenize import word_tokenize
import re

def remove_noise(text, stop_words = []):
    tokens = word_tokenize(text)

cleaned_tokens = [] for token in tokens: token = re.sub('[^A-Za-z0-9]+', '', token)
if len(token) > 1 and token.lower() not in stop_words: # Get lowercase cleaned_tokens.append(token.lower()) return cleaned_tokens
remove_noise("It is lovely weather we are having. I hope the weather continues.")
['lovely', 'weather', 'hope', 'weather', 'continues']
Cluster Analysis in Python

Matice dokumentů a řídké matice

  • Vznikne matice dokumentů a termínů
  • Většina prvků matice jsou nuly

Zdroj

  • Vznikne řídká matice

Zdroj

Cluster Analysis in Python

TF-IDF (Term Frequency – Inverse Document Frequency)

  • Vážená míra: hodnotí důležitost slova v dokumentu v rámci kolekce
from sklearn.feature_extraction.text import TfidfVectorizer

tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=50, min_df=0.2, tokenizer=remove_noise)
tfidf_matrix = tfidf_vectorizer.fit_transform(data)
Cluster Analysis in Python

Shlukování s řídkou maticí

  • kmeans() v SciPy nepodporuje řídké matice
  • Pro převod na matici použijte .todense()
cluster_centers, distortion = kmeans(tfidf_matrix.todense(), num_clusters)
Cluster Analysis in Python

Nejdůležitější termíny v každém shluku

  • Středy shluků: seznamy o velikosti rovné počtu termínů
  • Každá hodnota ve středu shluku vyjadřuje jeho důležitost
  • Vytvořte slovník a vytiskněte nejčastější termíny
terms = tfidf_vectorizer.get_feature_names_out()

for i in range(num_clusters):
    center_terms = dict(zip(terms, list(cluster_centers[i])))

sorted_terms = sorted(center_terms, key=center_terms.get, reverse=True)
print(sorted_terms[:3])
['room', 'hotel', 'staff']

['bad', 'location', 'breakfast']
Cluster Analysis in Python

Další úvahy

  • Práce s hypertextovými odkazy, emotikony apod.
  • Normalizace slov (run, ran, running → run)
  • .todense() nemusí fungovat u velkých datových sad
Cluster Analysis in Python

Čas na cvičení!

Cluster Analysis in Python

Preparing Video For Download...