ichou1のブログ

主に音声認識、時々、データ分析のことを書く

Kerasメモ(テキストデータ操作)

https://www.oreilly.co.jp/books/images/picture978-4-87311-857-4.gif
「RとKerasによるディープラーニング」より)


未加工のIMDBデータセットを学習用に準備する操作のメモ。

データセットは、ラベル(pos : 好意的/ neg : 否定的)ごとのフォルダにレビュー記事が格納されている。

aclImdb/train/pos : 12,500記事
aclImdb/train/neg : 12,500記事

aclImdb/test/neg : 12,500記事
aclImdb/test/neg : 12,500記事

データ例(aclImdb/train/pos/0_9.txt)
Bromwell High is a cartoon comedy. It ran at the same time as some other programs about school life, such as "Teachers". (snip)
データ例(aclImdb/train/pos/10000_8.txt)

HTMLタグが入っている。

Homelessness (or Houselessness as George Carlin stated) has been an issue for years but never a plan to help those on the street that were once considered human who did everything from going to school, work, or vote for the matter. (snip) if they'll be next to end up on the streets.<br /><br />But (snip)

今回は2ファイルだけを読み込むとする。

imdb_dir <- "~/Downloads/aclImdb"
train_dir <- file.path(imdb_dir, "train")

file_list_pos <- c("0_9.txt", "10000_8.txt")

labels <- c()
texts <- c()

for (label_type in c("pos")) {
    label <- switch(label_type, pos = 1)
    dir_name <- file.path(train_dir, label_type)
    for (fname in file_list_pos) {
        fname <- file.path(dir_name, fname)
        texts <- c(texts, readChar(fname, file.info(fname)$size))
        labels <- c(labels, label)
    }
}

読み込まれたデータを確認。
indexは1から始まる。

> length(texts)
[1] 2

> texts[0]
character(0)

> texts[1]
[1] "Bromwell High is a cartoon comedy. It ran at the same time ...."
> nchar(texts[1])
[1] 806

> texts[2]
[1] "Homelessness (or Houselessness as George Carlin stated) ..."
> nchar(texts[2])
[1] 2366

テキスト内の単語をベクトル化する。

# データセット内の最頻出50語だけ
tokenizer <- text_tokenizer(num_words=50) %>% 
    fit_text_tokenizer(texts)

word_index <- tokenizer$word_index
# cat("Found", length(word_index), "unique tokens.\n")
# Found 298 unique tokens.

テキストをシーケンスに変換する。

sequences <- texts_to_sequences(tokenizer, texts)

変換結果の確認。

> sequences[1]
[[1]]
 [1] 21 22 10  3 45 11 46  1  8 32 47 33 48 34  8 35 49 23  1  2 12 21 10  2 10
[26] 35  1  2  1  9 36 37 38  1  5  1  5  1 15 16 38 39 15  1 23  3  2  1 33 15
[51] 46 22  3  2  5 35  2 21 22 15 12  5 49 12 21 22 10 13  3 12 11

> length(sequences[[1]])
[1] 71

indexをwordに変換してみる。

# tokenizer$index_word[index]
# original : 
#  Bromwell High is a cartoon comedy. It ran at the same time as some ...
bromwell high is a comedy it at the ...

頻度上位num_wordsの単語以外は読み飛ばされる。
UNKOWNに置き換えてくれるわけではない。

# 記事の11語以降を切り捨て
# truncatingは"pre"がdefault
> data <- pad_sequences(sequences, maxlen=10, truncating="post")
> data[1,]
 [1] 21 22 10  3 45 11 46  1  8 32

これがトレーニング用のインプットになる。

# シャッフル
indices <- sample(1:2)
> indices
[1] 2 1

x_train <- data[indices,]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    6    8   17    3    2    4    1   12   24     9
[2,]   21   22   10    3   45   11   46    1    8    32

> dim(x_train)
[1]  2 10