0Pricing
R Academy · 강의

TF-IDF와 단어 빈도 분석

bind_tf_idf()로 문서 전체에서 단어의 중요도를 점수화합니다.

TF-IDF와 단어 빈도 분석은(는) CoddyKit의 무료 R Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 R Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

TF-IDF란?

TF-IDF(단어 빈도-역문서 빈도)는 말뭉치 안에서 특정 문서에 단어가 얼마나 특징적인지를 측정합니다. TF-IDF 점수가 높다는 것은 해당 문서에서는 자주 나타나지만 전체 문서에서는 드물다는 뜻이며, 문서의 주요 주제를 나타내는 좋은 지표입니다.

# TF-IDF formula
# TF(w, d)  = count of w in document d / total words in d
# IDF(w)    = log(N / number of docs containing w)
# TF-IDF(w, d) = TF(w, d) * IDF(w)

# Manual example
N <- 4  # total documents
docs_with_word <- 1  # 'neural' appears in only 1 doc
tf <- 5 / 100  # word appears 5 times in 100-word doc
idf <- log(N / docs_with_word)
tfidf <- tf * idf

cat('TF:     ', round(tf, 4), '\n')
cat('IDF:    ', round(idf, 4), '\n')
cat('TF-IDF: ', round(tfidf, 4), '\n')

단어 개수 준비하기

TF-IDF를 계산하기 전에 다음 열이 포함된 데이터 프레임이 필요합니다: document(문서 식별자), word(토큰), n(개수). unnest_tokens() 다음에 count(document, word)를 사용합니다.

library(tidytext)
library(dplyr)

# Simulate a 4-document corpus on tech topics
docs <- tibble::tibble(
  document = c(rep('ML', 3), rep('Stats', 3), rep('DB', 3), rep('Web', 3)),
  text = c(
    'machine learning neural networks training',
    'deep learning models gradient descent',
    'reinforcement learning reward policy agent',
    'probability distributions hypothesis testing',
    'bayesian inference regression analysis variance',
    'statistics sampling confidence intervals normal',
    'database sql joins indexes queries transactions',
    'relational tables primary keys foreign constraints',
    'nosql document store mongodb redis cassandra',
    'html css javascript frontend react components',
    'dom events browser api fetch requests',
    'responsive design flexbox grid layout'
  )
)

word_counts <- docs |>
  unnest_tokens(word, text) |>
  count(document, word, sort = TRUE)

cat('Document-word pairs:', nrow(word_counts), '\n')
print(head(word_counts, 8))

bind_tf_idf: TF-IDF 계산

bind_tf_idf(word, document, n)은 정돈된 개수 데이터 프레임을 받아 세 열을 추가합니다: tf(단어 빈도), idf(역문서 빈도), tf_idf(두 값의 곱). 데이터 프레임에 포함된 문서를 기준으로 IDF를 계산합니다.

library(tidytext)
library(dplyr)

docs <- tibble::tibble(
  document = c(rep('ML', 2), rep('Stats', 2), rep('DB', 2)),
  text = c(
    'machine learning neural gradient',
    'deep networks training epochs',
    'probability distributions variance covariance',
    'bayesian inference prior posterior',
    'sql database tables joins indexes',
    'queries transactions foreign primary'
  )
)

tfidf <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n)

cat('Columns added:', names(tfidf), '\n')
print(head(arrange(tfidf, desc(tf_idf)), 8))

arrange(desc(tf_idf)): 주요 단어

tf_idf를 내림차순으로 정렬하면 각 문서를 가장 잘 특징짓는 단어를 확인할 수 있습니다. 모든 문서에 나타나는 IDF가 0인 단어는 빈도와 관계없이 TF-IDF가 0이므로 문서를 구별할 수 없습니다.

library(tidytext)
library(dplyr)

docs <- tibble::tibble(
  document = c(rep('Python', 3), rep('R', 3), rep('Julia', 3)),
  text = c(
    'python pandas numpy scipy programming',
    'machine learning scikit tensorflow keras',
    'jupyter notebooks scripts debugging modules',
    'ggplot2 dplyr tidyverse statistics vectors',
    'shiny rmarkdown knitr cran bioconductor',
    'linear models factors dataframes packages',
    'julia multiple dispatch type system macros',
    'package ecosystem flux diffeq parallel',
    'scientific computing performance benchmarks'
  )
)

top_terms <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n) |>
  arrange(desc(tf_idf))

cat('Top distinctive terms per language:\n')
print(head(top_terms[, c('document', 'word', 'tf_idf')], 9))

문서별 주요 TF-IDF 단어

group_by(document) |> slice_max(tf_idf, n = 5)를 사용하면 문서별로 가장 특징적인 상위 N개 단어를 추출할 수 있습니다. 이는 말뭉치를 강력하게 요약하는 방법으로, 각 문서의 특징적인 어휘가 명확하게 드러납니다.

library(tidytext)
library(dplyr)

docs <- tibble::tibble(
  document = c(rep('Cooking', 3), rep('Finance', 3), rep('Sports', 3)),
  text = c(
    'recipe ingredients oven bake flour butter',
    'cooking temperature boil simmer saute',
    'kitchen knife chopping herbs spices garnish',
    'investment portfolio returns dividends stocks bonds',
    'market equity risk hedge fund derivatives',
    'inflation interest rate treasury balance sheet',
    'goal tackle pass dribble goalkeeper penalty',
    'tournament league championship trophy season',
    'athlete training stamina sprint endurance'
  )
)

top5 <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n) |>
  group_by(document) |>
  slice_max(tf_idf, n = 3) |>
  ungroup()

print(top5[, c('document', 'word', 'tf_idf')])

문서별 TF-IDF 시각화

문서별로 패싯을 나눈 TF-IDF 점수 막대 차트를 사용하면 각 문서의 특징적인 어휘를 한눈에 확인할 수 있습니다. facet_wrap(~document, scales = 'free_y')를 사용하면 각 패널이 자체적인 주요 단어를 독립적으로 표시합니다.

library(tidytext)
library(dplyr)
library(ggplot2)

docs <- tibble::tibble(
  document = c(rep('AI', 3), rep('DB', 3), rep('Web', 3)),
  text = c(
    'neural networks gradient backpropagation',
    'deep learning transformer attention bert',
    'reinforcement policy reward exploration',
    'sql database indexes joins transactions',
    'relational schema normalization queries',
    'nosql mongodb redis cassandra document',
    'html css javascript react dom',
    'frontend api fetch async components',
    'responsive flexbox grid webpack bundle'
  )
)

plot_data <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n) |>
  group_by(document) |>
  slice_max(tf_idf, n = 4) |>
  ungroup()

ggplot(plot_data, aes(reorder(word, tf_idf), tf_idf, fill = document)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~document, scales = 'free_y') +
  coord_flip() +
  labs(x = NULL, y = 'TF-IDF', title = 'Top TF-IDF Terms per Topic') +
  theme_minimal()

IDF: 모든 문서에 나타나는 단어

모든 문서에 나타나는 단어는 IDF = log(N/N) = 0이므로 TF-IDF = 0입니다. 따라서 불용어 목록이 없어도 말뭉치 전체에서 흔한 단어의 가중치가 자동으로 낮아집니다. 다만 매우 작은 말뭉치에서는 불용어 제거가 여전히 유용합니다.

library(tidytext)
library(dplyr)

docs <- tibble::tibble(
  document = c('A', 'B', 'C'),
  text = c(
    'data analysis statistics regression probability',
    'data engineering pipelines etl transformation',
    'data visualisation ggplot2 charts dashboards'
  )
)

tfidf <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n)

# 'data' appears in all 3 docs: tf_idf should be 0
data_rows <- filter(tfidf, word == 'data')
cat('TF-IDF for "data" across documents:\n')
print(data_rows[, c('document', 'word', 'idf', 'tf_idf')])

두 문서 비교하기

TF-IDF를 사용하면 문서를 쉽게 비교할 수 있습니다. 한 문서에서는 TF-IDF가 높지만 다른 문서에서는 낮거나 0인 단어를 찾으면 각 문서를 고유하게 만드는 요소를 파악할 수 있습니다. TF-IDF 표를 word를 기준으로 내부 결합하고 점수를 비교합니다.

library(tidytext)
library(dplyr)

docs <- tibble::tibble(
  document = c(rep('Doc1', 3), rep('Doc2', 3)),
  text = c(
    'bayesian statistics prior posterior mcmc',
    'markov chain monte carlo sampling',
    'probability distributions conjugate inference',
    'convolutional neural network image classification',
    'pooling activation relu softmax batch',
    'convolution filter feature map stride padding'
  )
)

tfidf <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n)

# Top 3 unique terms per document
tfidf |>
  group_by(document) |>
  slice_max(tf_idf, n = 3) |>
  select(document, word, tf_idf) |>
  print()

Jane Austen 소설의 TF-IDF

janeaustenr 패키지는 Austen의 소설 6편 전체 텍스트를 제공합니다. 이는 전형적인 TF-IDF 기준 예제입니다. Austen 작품의 독자는 각 소설의 특징적인 어휘를 찾아낼 수 있으며, "wentworth"라는 단어는 Persuasion에 거의 유일하게 나타납니다.

library(tidytext)
library(dplyr)

# Requires janeaustenr package
# library(janeaustenr)
# austen_books() returns: book, text

# Simulated mini-Austen corpus
mini_austen <- tibble::tibble(
  book = c(rep('Sense', 3), rep('Pride', 3), rep('Emma', 3)),
  text = c(
    'elinor marianne dashwood willoughby colonel',
    'edward ferrars barton cottage sister sense',
    'brandon feelings attachment sensibility heart',
    'darcy bennet bingley netherfield wickham',
    'jane lizzy lydia longbourn pemberley',
    'pride prejudice proposal marriage happiness',
    'emma woodhouse knightley harriet weston',
    'highbury match social governess niece',
    'frank jane fairfax box hill picnic'
  )
)

top <- mini_austen |>
  unnest_tokens(word, text) |>
  count(book, word) |>
  bind_tf_idf(word, book, n) |>
  group_by(book) |>
  slice_max(tf_idf, n = 3) |>
  select(book, word, tf_idf)

print(top)

특성 공학을 위한 TF-IDF

TF-IDF 점수는 기계 학습 분류기의 특성으로 사용할 수 있습니다. 정돈된 TF-IDF 결과를 cast_dtm() 또는 cast_sparse()를 사용해 문서-단어 행렬로 변환한 다음 glmnet, xgboost 또는 다른 분류기에 전달합니다.

library(tidytext)
library(dplyr)

docs <- tibble::tibble(
  document = c(rep('Positive', 4), rep('Negative', 4)),
  text = c(
    'excellent product love recommend quality',
    'amazing fast delivery five star perfect',
    'great value money satisfied happy return',
    'wonderful experience purchase outstanding best',
    'terrible waste money broken arrived damaged',
    'horrible quality slow delivery disappointed awful',
    'poor value cheap plastic flimsy broken',
    'worst experience refund needed useless junk'
  )
)

# TF-IDF as features
tfidf_wide <- docs |>
  unnest_tokens(word, text) |>
  count(document, word) |>
  bind_tf_idf(word, document, n) |>
  cast_dtm(document, word, tf_idf)

cat('DTM dimensions:', dim(tfidf_wide), '\n')
cat('(rows=documents, cols=unique words)\n')

한계와 대안

TF-IDF에는 한계가 있습니다. 단어를 서로 독립적으로 취급하고, 단어 순서와 맥락을 무시하며, 드문 오탈음에 좌우될 수 있습니다. 현대적인 대안으로는 단어 임베딩(word2vec, GloVe)과 문맥 임베딩(BERT)이 있지만, TF-IDF는 문서 검색과 분류의 기준선으로 여전히 매우 뛰어납니다.

# TF-IDF strengths and weaknesses summary
criteria <- data.frame(
  Criterion = c('Speed', 'Interpretability', 'Context', 'Word order',
                'Rare words', 'Scalability'),
  TF_IDF    = c('Fast', 'High', 'None', 'Ignored',
                'High IDF (inflated)', 'Excellent'),
  BERT      = c('Slow', 'Low', 'Rich', 'Captured',
                'Handled', 'Moderate')
)

print(criteria, row.names = FALSE)

빠른 확인

말뭉치의 모든 문서에 한 단어가 나타납니다. 이 단어의 TF-IDF 점수는 얼마일까요?

복습: TF-IDF 분석

핵심 내용:

  • TF-IDF = 단어 빈도 × 역문서 빈도이며, 점수가 높을수록 특징적인 단어입니다
  • 작업 흐름: unnest_tokens() → count(document, word) → bind_tf_idf(word, document, n)
  • bind_tf_idf()는 tf, idf, tf_idf 열을 추가합니다
  • arrange(desc(tf_idf)) / slice_max(tf_idf, n = 5)는 문서별 주요 단어를 보여 줍니다
  • 모든 문서에 있는 단어는 자동으로 IDF = 0 및 TF-IDF = 0이 됩니다
  • cast_dtm(document, word, tf_idf)는 기계 학습을 위한 문서-단어 행렬로 변환합니다
  • 패싯을 적용한 막대 차트는 TF-IDF 결과를 시각화하는 표준 방법입니다
library(tidytext)
library(dplyr)

# Minimal TF-IDF pipeline
tibble::tibble(
  doc = c('A', 'A', 'B', 'B'),
  text = c('neural networks deep', 'learning training', 'sql database query', 'joins indexes')
) |>
  unnest_tokens(word, text) |>
  count(doc, word) |>
  bind_tf_idf(word, doc, n) |>
  arrange(desc(tf_idf)) |>
  print()

자주 묻는 질문

“TF-IDF와 단어 빈도 분석” 강의는 무료인가요?

네 — “TF-IDF와 단어 빈도 분석” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 R Academy 강의 전체를 잠금 해제할 수 있습니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“TF-IDF와 단어 빈도 분석”에서 뭘 배우나요?

bind_tf_idf()로 문서 전체에서 단어의 중요도를 점수화합니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

R Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 R Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“TF-IDF와 단어 빈도 분석” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 R Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 R Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 토큰화와 불용어 제거
  2. TF-IDF와 단어 빈도 분석
  3. R에서 감성 분석
  4. LDA를 활용한 토픽 모델링
← R Academy(으)로 돌아가기