crfpp_datasets_segmentation.ipynb (Source)

In [1]:
%matplotlib inline
In [2]:
import numpy as np
import pandas as pd
In [3]:
def read_sentences(filepath_or_buffer, sep='\t', header=None, 
                   skip_blank_lines=False):
    
    # Don't skip blanklines so they can be read as NaNs
    df_all = pd.read_csv(filepath_or_buffer, 
                         sep=sep, header=header, 
                         skip_blank_lines=skip_blank_lines)
    
    # Find the location of rows with all NaNs (i.e. blank lines)
    indices_linebreak, *tail = np.where(df_all.isna()
                                              .all(axis='columns'))

    # Split big dataframe into list of dataframes
    dfs = np.vsplit(df_all, indices_linebreak+1)
    
    # Recombine list of dataframes into single dataframe with MultiIndex
    return pd.concat(map(lambda df: df.reset_index(drop=True) \
                                      .dropna(axis='index', how='all'), dfs),
                     keys=range(len(dfs)), axis='index')
In [4]:
seg_sentences_train = read_sentences('../example/seg/train.data')

The number of sequences $N_{seq}$ is:

In [5]:
len(seg_sentences_train.index.levels[0])
Out[5]:
36

The total number of tokens (words) $N = \sum_{n=1}^{N_{seq}} T_n$ is:

In [6]:
len(seg_sentences_train)
Out[6]:
965

The length $T_1$ of sequence 1 is 38:

In [7]:
seg_sentences_train.loc[0].T
Out[7]:
0 1 2 3 4 5 6 7 8 9 ... 28 29 30 31 32 33 34 35 36 37
0 ...
1 k k k k k k k k k n ... k k k k y k k k k k
2 B I I I I B I B I B ... I B I B B B I B I B

3 rows × 38 columns

In [8]:
seg_sentences_train.loc[1].T
Out[8]:
0 1 2 3 4 5 6 7 8 9 ... 21 22 23 24 25 26 27 28 29 30
0 ...
1 y n k k h k k k k k ... k h k k h k h k h y
2 B B B B B B I I I I ... B B B I B B B B I B

3 rows × 31 columns

In [9]:
seg_sentences_train.loc[35].T
Out[9]:
0 1 2 3 4 5 6 7 8 9 ... 22 23 24 25 26 27 28 29 30 31
0 ... 調
1 y h h k k h k k k k ... k k k k h k h y k k
2 B B I B I B B I I B ... B I B I B B I B B I

3 rows × 32 columns

In [10]:
seg_sentences_train[0].nunique()
Out[10]:
333
In [11]:
seg_sentences_train[0].value_counts()
Out[11]:
。    33
の    26
、    23
」    18
年    18
「    18
に    16
を    16
大    12
は    11
る    11
     11
人    10
学    10
氏    10
ン    10
て    10
な     9
日     9
と     8
い     8
た     8
3     8
か     7
一     7
京     7
長     7
ど     7
ト     7
め     7
     ..
方     1
ん     1
館     1
害     1
博     1
復     1
抗     1
報     1
為     1
次     1
俳     1
観     1
月     1
尾     1
紋     1
宰     1
認     1
師     1
供     1
芥     1
影     1
野     1
検     1
世     1
も     1
射     1
析     1
引     1
七     1
件     1
Name: 0, Length: 333, dtype: int64