Transformers(8) - テキスト分類①学習データと検証データの生成

テキスト分類を2回に分けて説明していきます。

今回は、データセットをダウンロードし、そのデータから学習データと検証データを生成します。

データセットのダウンロード

まずlivedoor ニュースコーパスからニュース記事のデータセットをダウンロードします。

[Google Colaboratory]

1
!wget https://www.rondhuit.com/download/ldcc-20140209.tar.gz

[実行結果]

1
2
3
4
5
6
7
8
9
10
--2021-10-01 20:42:32--  https://www.rondhuit.com/download/ldcc-20140209.tar.gz
Resolving www.rondhuit.com (www.rondhuit.com)... 59.106.19.174
Connecting to www.rondhuit.com (www.rondhuit.com)|59.106.19.174|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 8855190 (8.4M) [application/x-gzip]
Saving to: ‘ldcc-20140209.tar.gz’

ldcc-20140209.tar.g 100%[===================>] 8.44M 2.99MB/s in 2.8s

2021-10-01 20:42:37 (2.99 MB/s) - ‘ldcc-20140209.tar.gz’ saved [8855190/8855190]

データセットの解凍

ダウンロードした圧縮ファイル(ldcc-20140209.tar.gz)を解凍します。

[Google Colaboratory]

1
!tar xzvf ldcc-20140209.tar.gz

textディレクトリが作成され、その中に各ジャンル別にニュース記事のテキストファイルがたくさん解凍されます。

学習データと検証データの生成

解凍したデータセットから、学習データ(dev.csv)検証データ(train.csv)を生成します。

[Google Colaboratory]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import os
import pandas as pd

# タイトルリストの取得
def get_title_list(path):
title_list = []
filenames = os.listdir(path)
for filename in filenames:
# ファイルの読み込み
with open(path+filename) as f:
title = f.readlines()[2].strip()
title_list.append(title)
return title_list

# データフレームの作成
df = pd.DataFrame(columns=['label', 'sentence'])
title_list = get_title_list('text/it-life-hack/')
for title in title_list:
df = df.append({'label':0 , 'sentence':title}, ignore_index=True)
title_list = get_title_list('text/sports-watch/')
for title in title_list:
df = df.append({'label':1 , 'sentence':title}, ignore_index=True)
title_list = get_title_list('text/movie-enter/')
for title in title_list:
df = df.append({'label':2 , 'sentence':title}, ignore_index=True)

# シャッフル
df = df.sample(frac=1)

# CSVファイルの保存
num = len(df)
df[:int(num*0.8)].to_csv('train.csv', sep=',', index=False)
df[int(num*0.8):].to_csv('dev.csv', sep=',', index=False)

正常に処理が実行されると、学習データ(dev.csv)検証データ(train.csv)が作成されます。

次回は、この学習データと検証データを使ってテキスト分類の学習と推論を行います。