機械学習モデルには、主に二種類のパラメータが存在します。
- ハイパーパラメータ: モデルの訓練が始まる前に決定する必要がある設定値。
- モデルパラメータ: 訓練プロセスを通じてデータから学習される値。
例として、K近傍法(KNN)アルゴリズムは訓練により学習する内部パラメータを持たず、近傍数kは典型的なハイパーパラメータです。
KNNの主要なハイパーパラメータ
近傍数 (k)
予測時に考慮する最近傍データポイントの数。最適な値はデータに依存します。探索結果が決定境界付近にある場合は、探索範囲を広げて調整することが推奨されます。
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
digits = datasets.load_digits()
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
optimal_score = 0.0
optimal_k = -1
for neighbor_count in range(1, 100):
model = KNeighborsClassifier(n_neighbors=neighbor_count)
model.fit(X_train, y_train)
current_score = model.score(X_test, y_test)
if current_score > optimal_score:
optimal_k = neighbor_count
optimal_score = current_score
print(f"最適なk: {optimal_k}, スコア: {optimal_score}")
重み付け方式 (weights)
近傍点への距離の逆数を重みとして使用します。分類時に同票数(タイ)が発生する可能性を減らす効果があります。
'uniform': 距離に関係なく、すべての近傍点に均等な重みを付与。'distance': 近傍点への距離の逆数に比例した重みを付与(近い点ほど影響が大きい)。
best_accuracy = 0.0
best_neighbors = -1
best_weight_scheme = ""
for weight_type in ["uniform", "distance"]:
for neighbor_count in range(1, 20):
classifier = KNeighborsClassifier(n_neighbors=neighbor_count, weights=weight_type)
classifier.fit(X_train, y_train)
accuracy = classifier.score(X_test, y_test)
if accuracy > best_accuracy:
best_neighbors = neighbor_count
best_accuracy = accuracy
best_weight_scheme = weight_type
print(f"結果: k={best_neighbors}, 精度={best_accuracy}, 重み={best_weight_scheme}")
距離指標のパラメータ (p)
ミンコフスキー距離の次数パラメータで、距離計算方法を定義します。
\[ \left( \sum_{i=1}^{n} |x_i^{(a)} - x_i^{(b)}|^p \right)^{\frac{1}{p}} \]
p=1の場合はマンハッタン距離、p=2の場合はユークリッド距離に相当します。
top_score = 0.0
top_k = -1
top_weights = ""
top_p = -1
for weight_scheme in ["uniform", "distance"]:
for neighbor_count in range(1, 20):
for minkowski_p in range(1, 6):
knn_model = KNeighborsClassifier(n_neighbors=neighbor_count, weights=weight_scheme, p=minkowski_p)
knn_model.fit(X_train, y_train)
model_score = knn_model.score(X_test, y_test)
if model_score > top_score:
top_k = neighbor_count
top_score = model_score
top_weights = weight_scheme
top_p = minkowski_p
print(f"最適設定: k={top_k}, 精度={top_score}, 重み={top_weights}, p={top_p}")
グリッドサーチによる自動最適化
Scikit-learnのGridSearchCVを使用して、複数のハイパーパラメータの組み合わせを体系的に探索できます。
from sklearn.model_selection import GridSearchCV
search_grid = [
{
'weights': ['uniform'],
'n_neighbors': list(range(1, 11))
},
{
'weights': ['distance'],
'n_neighbors': list(range(1, 11)),
'p': list(range(1, 6))
}
]
base_classifier = KNeighborsClassifier()
grid_searcher = GridSearchCV(base_classifier, search_grid, n_jobs=-1, verbose=2)
grid_searcher.fit(X_train, y_train)
print(f"最高検証スコア: {grid_searcher.best_score_}")
print(f"最適パラメータ: {grid_searcher.best_params_}")
print(f"最適モデル: {grid_searcher.best_estimator_}")