0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

欠損値の処理について

Posted at

kaggleのData Preparation & Explorationからの気づき

特徴量の扱い

Pandasを使って特徴量をあらかじめそれぞれ定義している。
訓練データをtrainとしているとき、すべてのデータを以下のように処理することで、それぞれに固有の特徴を可視化することができる。


data = [] #データの入れ子
for f in train.columns: #特徴量の名前をfに入れている
    # Defining the role
    if f == 'target': #特徴量の名前がtargetなら、役割(role)をtargetにする
        role = 'target'
    elif f == 'id':  #idならidにする
        role = 'id'
    else:
        role = 'input' #上記以外なら、すべて訓練するべきデータ(input)
         
    # Defining the level #roleごとに数値に意味を与えている。二値、カテゴリデータ、離散値、連続値。
    if 'bin' in f or f == 'target':
        level = 'binary'
    elif 'cat' in f or f == 'id':
        level = 'nominal'
    elif train[f].dtype == float:
        level = 'interval'
    elif train[f].dtype == int:
        level = 'ordinal'
        
    # Initialize keep to True for all variables except for id
  #keep がTrueの特徴量をいじる。
  #data[(data.role == "id") & (data.keep)]とすれば、data.keepがTrueなら操作できるし、Falseなら操作を免れることができる。
    keep = True
    if f == 'id':
        keep = False
    
    # Defining the data type 
    dtype = train[f].dtype
    
    # Creating a Dict that contains all the metadata for the variable
    f_dict = {
        'varname': f,
        'role': role,
        'level': level,
        'keep': keep,
        'dtype': dtype
    }
    data.append(f_dict)
    
meta = pd.DataFrame(data, columns=['varname', 'role', 'level', 'keep', 'dtype'])
meta.set_index('varname', inplace=True)

欠損値の処理

欠損値の処理は基本的に除去するか、補完するか(たぶん他にもあるけど)。
欠損を除去するのはpd.drop()を使えばいい。欠損値がやたら含まれている特徴量があれば、まるごと除去すればいい。
データを完全なものとして扱おうとしてすべての欠損値を除去してしまうと、使えるデータがなくなってしまう。多すぎる欠損値はさっさと列ごと(pd.drop(axis=1))で削除する。

補完の場合は二択。
1.平均値(特徴量が連続値の場合)
2.最頻値(特徴量が離散値の場合)

これを実行するのに便利なのが、


from sklearn.preprocessing import Imputer

# missing_valueを変更すること。Nanなど。
# 平均値
mean_imp = Imputer(missing_values=-1, strategy='mean', axis=0)

# 最頻値
mode_imp = Imputer(missing_values=-1, strategy='most_frequent', axis=0)

# 適用する
# ravel()を使うと、配列を一元化する。元のデータを破壊するので、pamdasのデータも変更されている?
data["columns_name"] = mean_imp.fit_transform(data[["columns_name"]]).ravel()
data["columns_name"] = mode_imp.fit_transform(data[["columns_name"]]).ravel()

Imputerは欠損値を処理する。これを使うと簡単に色々な処理が実行できる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?