パハットノート

主にUnity(C#)を中心としたプログラムの備忘録

python 機械学習関連の備忘録(随時更新)





前処理

pandas_profilingで分析結果をHTMLで出力

#pandas_profilingで分析
import pandas_profiling as pdp

pdp.ProfileReport(df).to_file("df.html")



ピボットテーブル

aggfuncを調整することで、最大値や最小値など表示する物を変更できる(例は平均)

pd.pivot_table(train, index=['a', 'b', …], columns=['c', 'd', …], values='target', aggfunc=np.mean)



groupby

df2.groupby('feature')['target'].mean()





データ分類

訓練データと評価データに分割

# 訓練データとテストデータに分類
from sklearn.model_selection import train_test_split
train_X, val_X, train_y, val_y = train_test_split(X, y, test_size=0.2, random_state=1)


Kfoldでの分割

from sklearn.model_selection import KFold

# KFoldのインスタンスを作成
kf = KFold(n_splits=3, shuffle=True)

# K-fold交差検証を行い、学習モデルを作成
for train_index, test_index in kf.split(X):
    train_X, train_y = X.loc[train_index], y.loc[train_index]
    val_X, val_y = X.loc[val_index], y.loc[val_index]


アンダーサンプリング

  • sampling_stragegyで目的変数の値の割合を辞書型で調整
  • 不均衡データにおいて、多数派クラスのデータ数を減らして少数派の数に合わせる。
  • コードでは、クラス0のクラスをnに、1のクラスをm個にしている。ただし、nとmはデータ数を超えるとエラー。
from imblearn.under_sampling import RandomUnderSampler
sampler = RandomUnderSampler(sampling_strategy={0: n,  1:  m}, random_state=4)
train_X_resampled, train_y_resampled = sampler.fit_resample(train_X, train_y)


オーバーサンプリング

  • アンダーサンプリングとは逆に、少数派のデータ数を増やして多数派のデータ数に合わせる。
  • 例では、SMOTEを利用しているが他にもアルゴリズムはあるらしい。
from imblearn.over_sampling import SMOTE
sm = SMOTE()
train_X_resampled, train_y_resampled = sm.fit_resample(train_X, train_y)





モデル作成

sklearn準拠クラスの継承

  • 自分でモデルを作成したいとき。
  • 継承することで、GridSearchとかが楽に適用できるらしい。
  • 以下のクラスはRandomForestClassifierとほぼ同じ動作をする。
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.ensemble import RandomForestClassifier

class MyModel(BaseEstimator, ClassifierMixin):
    # 初期化
    def __init__(self, random_state = 0):
        self.rf = RandomForestClassifier(random_state = random_state)
    
    # 学習
    def fit(self, X, y):
        self.rf.fit(X, y)
        return self

    # 予測
    def predict(self ,X, y=None):
        pred = self.rf.predict(X)

        return pred


保存と読込

#保存
import pickle
with open('model.pkl', mode='wb') as f:
    pickle.dump(model, f)

#読込
with open('model.pkl', 'rb') as f:
    model = pickle.load(f)





評価

混合行列

#評価
from sklearn.metrics import confusion_matrix

#予測
y_pred = rf.predict(val_X)

#混合行列の作成
confusion_matrix(val_y, y_pred)