はじめに
この実験では、scikit-learn に用意されている前処理手法を調べます。前処理は、機械学習のワークフローにおいて欠かせないステップであり、学習アルゴリズムに適した形式に生データを変換するのに役立ちます。標準化、スケーリング、正規化、カテゴリカル特徴量のエンコード、欠損値の補完、多項式特徴量の生成、カスタムトランスフォーマの作成など、様々な前処理手法を扱います。
VM のヒント
VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使って練習しましょう。
Jupyter Notebook の読み込みには数秒かかる場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題があった場合は、Labby にお問い合わせください。セッション終了後にフィードバックを提供してください。すぐに問題を解決いたします。
標準化
標準化は、多くの機械学習アルゴリズムに共通する前処理ステップです。これは、特徴量を平均 0、分散 1 に変換します。scikit-learn の StandardScaler を使って標準化を行うことができます。
from sklearn.preprocessing import StandardScaler
import numpy as np
## Create a sample dataset
X = np.array([[1., -1., 2.],
[2., 0., 0.],
[0., 1., -1.]])
## Initialize the StandardScaler
scaler = StandardScaler()
## Fit the scaler on the training data
scaler.fit(X)
## Transform the training data
X_scaled = scaler.transform(X)
## Print the transformed data
print(X_scaled)
スケーリング
特徴量を特定の範囲にスケーリングすることは、もう一つの一般的な前処理手法です。特徴量が異なるスケールを持っており、同じ範囲にする必要がある場合に便利です。MinMaxScaler と MaxAbsScaler を使ってスケーリングを行うことができます。
from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler
import numpy as np
## Create a sample dataset
X = np.array([[1., -1., 2.],
[2., 0., 0.],
[0., 1., -1.]])
## Initialize the MinMaxScaler
min_max_scaler = MinMaxScaler()
## Fit and transform the training data
X_minmax = min_max_scaler.fit_transform(X)
## Print the transformed data
print(X_minmax)
## Initialize the MaxAbsScaler
max_abs_scaler = MaxAbsScaler()
## Fit and transform the training data
X_maxabs = max_abs_scaler.fit_transform(X)
## Print the transformed data
print(X_maxabs)
正規化
正規化は、個々のサンプルを単位ノルムにスケーリングするプロセスです。データの大きさが重要でなく、データの方向(または角度)のみに興味がある場合に一般的に使用されます。scikit-learn の Normalizer を使って正規化を行うことができます。
from sklearn.preprocessing import Normalizer
import numpy as np
## Create a sample dataset
X = np.array([[1., -1., 2.],
[2., 0., 0.],
[0., 1., -1.]])
## Initialize the Normalizer
normalizer = Normalizer()
## Fit and transform the training data
X_normalized = normalizer.fit_transform(X)
## Print the transformed data
print(X_normalized)
カテゴリカル特徴量のエンコード
カテゴリカル特徴量は、機械学習アルゴリズムで使用する前に数値にエンコードする必要があります。scikit-learn の OrdinalEncoder と OneHotEncoder を使ってカテゴリカル特徴量をエンコードすることができます。
from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder
import numpy as np
## Create a sample dataset
X = [['male', 'from US', 'uses Safari'],
['female', 'from Europe', 'uses Firefox']]
## Initialize the OrdinalEncoder
ordinal_encoder = OrdinalEncoder()
## Fit and transform the training data
X_encoded = ordinal_encoder.fit_transform(X)
## Print the transformed data
print(X_encoded)
## Initialize the OneHotEncoder
onehot_encoder = OneHotEncoder()
## Fit and transform the training data
X_onehot = onehot_encoder.fit_transform(X)
## Print the transformed data
print(X_onehot.toarray())
欠損値の補完
データセットにおける欠損値は、機械学習アルゴリズムに問題を引き起こす可能性があります。scikit-learn の impute モジュールに提供されているメソッドを使って欠損値を処理することができます。ここでは、欠損値を補完するために SimpleImputer を使用します。
from sklearn.impute import SimpleImputer
import numpy as np
## Create a sample dataset with missing values
X = np.array([[1., 2., np.nan],
[3., np.nan, 5.],
[np.nan, 4., 6.]])
## Initialize the SimpleImputer
imputer = SimpleImputer()
## Fit and transform the training data
X_imputed = imputer.fit_transform(X)
## Print the transformed data
print(X_imputed)
多項式特徴量の生成
時には、入力データの非線形特徴量を考慮することでモデルに複雑さを追加することが有益です。scikit-learn の PolynomialFeatures を使って多項式特徴量を生成することができます。
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
## Create a sample dataset
X = np.array([[0, 1],
[2, 3],
[4, 5]])
## Initialize the PolynomialFeatures
poly = PolynomialFeatures(2)
## Fit and transform the training data
X_poly = poly.fit_transform(X)
## Print the transformed data
print(X_poly)
カスタムトランスフォーマーの作成
場合によっては、既存の Python 関数をトランスフォーマーに変換して、データのクリーニングや処理を支援したい場合があります。これは、scikit-learn の FunctionTransformer を使用して達成できます。
from sklearn.preprocessing import FunctionTransformer
import numpy as np
## Create a custom function
def custom_function(X):
return np.log1p(X)
## Initialize the FunctionTransformer
transformer = FunctionTransformer(custom_function)
## Create a sample dataset
X = np.array([[0, 1],
[2, 3]])
## Transform the data using the custom function
X_transformed = transformer.transform(X)
## Print the transformed data
print
まとめ
おめでとうございます!あなたは「前処理データ実験」を完了しました。あなたのスキルを向上させるために、LabEx でさらに多くの実験を行って練習することができます。