トークン化とストップワードの除去
テキストをトークンに分割し、anti_join() で情報量の少ない単語を除外します。
「トークン化とストップワードの除去」はCoddyKit上の無料R Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはR Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 R Academyコースには全4レッスンが含まれています。
テキストマイニングとは
テキストマイニング(テキスト分析ともいいます)は、構造化されていないテキストを、統計的に分析できる構造化データへ変換します。tidytextパッケージでは、tidyな方法で扱えます。各行を1つのトークン(単語、バイグラム、文など)として表すため、dplyrやggplot2と互換性があります。
library(tidytext)
library(dplyr)
# A simple text corpus
text_df <- tibble::tibble(
doc_id = 1:3,
text = c(
'The quick brown fox jumps over the lazy dog.',
'Text mining with R is powerful and fun.',
'Natural language processing enables many applications.'
)
)
cat('Input: ', nrow(text_df), 'documents\n')
cat('Columns:', names(text_df), '\n')unnest_tokens: 単語のトークン化
unnest_tokens(output, input)は、テキストを1行1トークンの形式に分割します。デフォルトでは単語単位でトークン化し、小文字に変換して句読点を除去します。token引数では、'words'、'ngrams'、'sentences'などを指定できます。
library(tidytext)
library(dplyr)
text_df <- tibble::tibble(
doc_id = 1:2,
text = c(
'R is a great language for data analysis.',
'Text mining reveals hidden patterns in documents.'
)
)
# Tokenise into words
tokens <- text_df |>
unnest_tokens(word, text)
cat('Tokens extracted:', nrow(tokens), '\n')
print(tokens)stop_wordsデータセット
tidytextには、SMART、Snowball、onixという3つの辞書に由来する、1,149個の一般的な英語のストップワードを含むstop_wordsティブルが組み込まれています。これらの単語("the"、"is"、"and"など)は意味情報が少ないため、通常は分析前に除去します。
library(tidytext)
library(dplyr)
# Inspect the stop_words dataset
cat('Total stop words:', nrow(stop_words), '\n')
cat('Lexicons:', paste(unique(stop_words$lexicon), collapse = ', '), '\n')
# First few stop words from each lexicon
stop_words |>
group_by(lexicon) |>
slice_head(n = 3) |>
print()anti_join: ストップワードの除去
anti_join(tokens, stop_words, by = 'word')は、wordがstop_words内のいずれかの項目と一致するすべての行を除去します。これは、ストップワードを除去するためのtidytextの標準的なパターンです。簡潔で読みやすく、容易に拡張できます。
library(tidytext)
library(dplyr)
text_df <- tibble::tibble(
doc_id = 1:3,
text = c(
'The quick brown fox jumps over the lazy dog',
'A stitch in time saves nine important words',
'To be or not to be that is the question'
)
)
tokens <- text_df |>
unnest_tokens(word, text)
cat('Before removing stop words:', nrow(tokens), '\n')
tokens_clean <- tokens |>
anti_join(stop_words, by = 'word')
cat('After removing stop words:', nrow(tokens_clean), '\n')
print(tokens_clean)count: 頻度の計算
トークン化してストップワードを除去した後、count(word, sort = TRUE)を使用して用語頻度を計算します。これは多くのテキストマイニング分析の基礎であり、頻度の高い意味のある単語から文書のトピックを把握できます。
library(tidytext)
library(dplyr)
# Use Jane Austen's novels from janeaustenr package
# For demo: simulate a small corpus
corpus <- tibble::tibble(
text = c(
'data science involves statistics programming analysis',
'machine learning algorithms data patterns training',
'statistics probability distributions random variables data',
'programming languages python r julia statistics',
'analysis patterns distributions algorithms science'
)
)
word_counts <- corpus |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE)
cat('Top 8 words:\n')
print(head(word_counts, 8))カスタムストップワード
特定分野のコーパスには、頻出するものの分析には不要な単語が含まれることがあります(例: 医療記録の「patient」や「doctor」)。カスタムのストップワードティブルを作成し、bind_rows()を使って組み込みの辞書に結合します。
library(tidytext)
library(dplyr)
# Domain-specific words to remove
custom_stops <- tibble::tibble(
word = c('data', 'analysis', 'r', 'using', 'also'),
lexicon = 'custom'
)
# Combine with built-in stop words
all_stops <- bind_rows(stop_words, custom_stops)
cat('Total stop words after custom:', nrow(all_stops), '\n')
corpus <- tibble::tibble(
text = c(
'Using R for data analysis and machine learning models',
'Statistical data analysis also involves data visualisation'
)
)
clean_tokens <- corpus |>
unnest_tokens(word, text) |>
anti_join(all_stops, by = 'word') |>
count(word, sort = TRUE)
print(clean_tokens)バイグラムのトークン化
token = 'ngrams', n = 2を指定すると、連続する2つの単語の組(バイグラム)にトークン化できます。バイグラムを使うと、単語単体では捉えられない「machine learning」や「data science」のようなフレーズを捉えられるため、より豊かな文脈を得られます。
library(tidytext)
library(dplyr)
corpus <- tibble::tibble(
doc_id = 1:2,
text = c(
'machine learning and deep learning are powerful techniques',
'natural language processing uses machine learning methods'
)
)
bigrams <- corpus |>
unnest_tokens(bigram, text, token = 'ngrams', n = 2)
cat('Bigrams extracted:', nrow(bigrams), '\n')
print(bigrams)
# Count most common bigrams
bigram_counts <- bigrams |> count(bigram, sort = TRUE)
cat('\nTop bigrams:\n')
print(head(bigram_counts, 5))バイグラムの品質向上のためのフィルタリング
頻度の高いバイグラムには、「of the」のようなストップワード同士の組が多く含まれます。tidyr::separate()でバイグラムを2列に分け、どちらか一方の単語がストップワードである行を除去してから、再び結合して意味のあるフレーズの組に戻します。
library(tidytext)
library(dplyr)
library(tidyr)
corpus <- tibble::tibble(
text = c(
'the field of machine learning and deep learning is growing',
'natural language processing is a subfield of artificial intelligence'
)
)
bigrams_filtered <- corpus |>
unnest_tokens(bigram, text, token = 'ngrams', n = 2) |>
separate(bigram, into = c('word1', 'word2'), sep = ' ') |>
filter(
!word1 %in% stop_words$word,
!word2 %in% stop_words$word
) |>
unite(bigram, word1, word2, sep = ' ') |>
count(bigram, sort = TRUE)
print(bigrams_filtered)単語頻度の可視化
ggplot2を使い、単語頻度を棒グラフとして表示します。reorder(word, n)で棒を並べ替え、coord_flip()でラベルを横向きにします。これはテキストマイニングで特に分かりやすい出力の1つです。
library(tidytext)
library(dplyr)
library(ggplot2)
corpus <- tibble::tibble(
text = c(
'statistics probability machine learning algorithms patterns',
'data science programming analysis visualisation models',
'machine learning deep learning neural networks patterns',
'probability statistics hypothesis testing distributions',
'algorithms optimisation gradient descent models training'
)
)
top_words <- corpus |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE) |>
slice_head(n = 10)
ggplot(top_words, aes(reorder(word, n), n)) +
geom_col(fill = 'steelblue') +
coord_flip() +
labs(x = 'Word', y = 'Count', title = 'Top 10 Terms') +
theme_minimal()文書ごとの単語数
コーパスに複数の文書がある場合は、文書識別子の列を追加し、doc_id, wordでグループ化して文書ごとの用語頻度を計算します。この結果は、TF-IDFやトピックモデルの分析にそのまま利用できます。
library(tidytext)
library(dplyr)
docs <- tibble::tibble(
doc_id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
text = c(
'machine learning models training',
'neural networks deep learning',
'algorithms gradient descent optimisation',
'statistical analysis probability distributions',
'hypothesis testing confidence intervals regression',
'bayesian inference prior posterior likelihood',
'data visualisation plots charts dashboards',
'ggplot2 ggvis plotly interactive graphics',
'colour scales aesthetics themes layers'
)
)
word_counts <- docs |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(doc_id, word, sort = TRUE)
cat('Word-doc pairs:', nrow(word_counts), '\n')
print(head(word_counts, 10))文のトークン化
token = 'sentences'を指定すると、文の境界でテキストを分割できます。文単位のトークンは、感情分析(各文をスコア化)、要約(代表的な文を選択)、質問応答タスクなどに役立ちます。
library(tidytext)
library(dplyr)
doc <- tibble::tibble(
id = 1L,
text = paste(
'R is a statistical programming language.',
'It is widely used in data science and machine learning.',
'The tidyverse makes data manipulation easy.',
'Text mining with tidytext is elegant and powerful.'
)
)
sentences <- doc |>
unnest_tokens(sentence, text, token = 'sentences')
cat('Sentences found:', nrow(sentences), '\n')
print(sentences$sentence)確認問題
unnest_tokens()を使ってコーパスを単語にトークン化し、一般的な英単語を除去したいとします。組み込みのstop_wordsデータセットを使うには、どの操作を実行すればよいでしょうか。
まとめ: トークン化とストップワード
主なポイント:
unnest_tokens(word, text)で、生テキストを1行1単語のtidy形式に変換できます- デフォルトでは小文字化と句読点の除去を行い、
'words'、'ngrams'、'sentences'に対応しています stop_wordsは、3つの辞書に由来する1,149個の一般的な英単語を含む組み込みのティブルですanti_join(tokens, stop_words, by = 'word')でストップワードを除去しますbind_rows()と組み合わせると、分野固有のカスタムストップワードを追加できますcount(word, sort = TRUE)でtidy形式のトークンから用語頻度を計算します- バイグラムには
unnest_tokens(bigram, text, token = 'ngrams', n = 2)を使用します
library(tidytext)
library(dplyr)
tibble::tibble(text = 'The quick brown fox jumps over the lazy dog') |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE) |>
print()AI チューターと学ぶ R — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 43
- レッスン
- 159
よくある質問
「トークン化とストップワードの除去」レッスンは無料ですか?
はい。「トークン化とストップワードの除去」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、R Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 R Academyコースには全4レッスンが含まれています。
「トークン化とストップワードの除去」で何を学びますか?
テキストをトークンに分割し、anti_join() で情報量の少ない単語を除外します。 ブラウザで直接実行するハンズオンコードでR Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
R Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのR Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「トークン化とストップワードの除去」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このR Academyレッスンでコードを書いて実行できますか?
はい。すべてのR Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- トークン化とストップワードの除去
- TF-IDF と単語頻度分析
- R での感情分析
- LDA によるトピックモデリング