mcpField
M
machine-learning

machine-learning

github.com/pluginagentmarketplaceデータ・データベース737 回インストール42 週間前に更新
リポジトリ

machine-learning について

Scikit-Learnでモデルを構築するデータ実務者向けの機械学習スキルです。分類、回帰、クラスタリングに加え、評価、調整、特徴量処理、モデル選択、交差検証、パイプラインの例を扱います。

主な機能

  1. 01分類・回帰・クラスタリングモデルの構築
  2. 02複数の指標によるモデル評価
  3. 03交差検証による性能評価
  4. 04GridSearchCVによるハイパーパラメーター調整
  5. 05特徴量のスケーリングとエンコード
  6. 06Pipelineによる処理手順の組み合わせ

活用シーン

  1. 01分類モデルを学習し評価レポートを作成
  2. 02回帰モデルを適合させ誤差指標を確認
  3. 03データをクラスタリングしエルボー法の結果を確認
  4. 04交差検証と調整でモデルを比較

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/pluginagentmarketplace/custom-plugin-ai-data-scientist --skill machine-learning

インストール後、Claude Code で/machine-learningを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

assets/
model_config.yaml
README.md
references/
GUIDE.md
README.md
scripts/
README.md
train_model.py

詳細

Scikit-Learn による機械学習

分類、回帰、クラスタリング向けの ML モデルを構築、学習、評価します。

クイックスタート

分類
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

# Split data
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Predict
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)

# Evaluate
print(classification_report(y_test, predictions))
回帰
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score

model = GradientBoostingRegressor(n_estimators=100)
model.fit(X_train, y_train)

predictions = model.predict(X_test)

print(f"MAE: {mean_absolute_error(y_test, predictions):.2f}")
print(f"R²: {r2_score(y_test, predictions):.3f}")
クラスタリング
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

# Find optimal k (elbow method)
inertias = []
for k in range(1, 11):
    km = KMeans(n_clusters=k, random_state=42)
    km.fit(X)
    inertias.append(km.inertia_)

plt.plot(range(1, 11), inertias, marker='o')
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.show()

# Train with optimal k
kmeans = KMeans(n_clusters=5, random_state=42)
clusters = kmeans.fit_predict(X)

モデル選択ガイド

分類:

  • ロジスティック回帰:線形で解釈しやすく、ベースラインに適しています
  • ランダムフォレスト:非線形で、特徴量の重要度を把握でき、堅牢です
  • XGBoost:高い性能を発揮し、欠損データにも対応します
  • SVM:小規模なデータセットに適しており、カーネルトリックを利用します

回帰:

  • 線形回帰:線形関係を扱い、解釈しやすい手法です
  • Ridge/Lasso:正則化と特徴量選択に利用します
  • ランダムフォレスト:非線形で、外れ値に対して堅牢です
  • XGBoost:高い性能を発揮し、コンペティションで優勝することもよくあります

クラスタリング:

  • K-Means:高速で、球状のクラスタを形成します
  • DBSCAN:任意の形状に対応し、ノイズも処理できます
  • 階層的クラスタリング:デンドログラムを作成し、k の選択は不要です

評価指標

分類:

from sklearn.metrics import (
    accuracy_score, precision_score, recall_score,
    f1_score, roc_auc_score, confusion_matrix
)

accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred, average='weighted')
recall = recall_score(y_true, y_pred, average='weighted')
f1 = f1_score(y_true, y_pred, average='weighted')
roc_auc = roc_auc_score(y_true, y_pred_proba, multi_class='ovr')

回帰:

from sklearn.metrics import (
    mean_absolute_error, mean_squared_error, r2_score
)

mae = mean_absolute_error(y_true, y_pred)
mse = mean_squared_error(y_true, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_true, y_pred)

交差検証

from sklearn.model_selection import cross_val_score

scores = cross_val_score(model, X, y, cv=5, scoring='f1_weighted')
print(f"CV F1: {scores.mean():.3f} (+/- {scores.std() * 2:.3f})")

ハイパーパラメーターのチューニング

from sklearn.model_selection import GridSearchCV

param_grid = {
    'n_estimators': [100, 200, 300],
    'max_depth': [5, 10, 15],
    'min_samples_split': [2, 5, 10]
}

grid_search = GridSearchCV(
    RandomForestClassifier(),
    param_grid,
    cv=5,
    scoring='f1_weighted',
    n_jobs=-1
)

grid_search.fit(X_train, y_train)
print(f"Best params: {grid_search.best_params_}")
print(f"Best score: {grid_search.best_score_:.3f}")

# Use best model
best_model = grid_search.best_estimator_

特徴量エンジニアリング

from sklearn.preprocessing import StandardScaler, LabelEncoder

# Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Encoding
encoder = LabelEncoder()
y_encoded = encoder.fit_transform(y)

# Polynomial features
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)

パイプライン

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('classifier', RandomForestClassifier(n_estimators=100))
])

pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)

ベストプラクティス

  1. 前処理の前に必ずデータを分割します
  2. 信頼性の高い推定には交差検証を使用します
  3. 距離ベースのモデルでは特徴量をスケーリングします
  4. クラスの不均衡に対処します(SMOTE、クラス重み)
  5. 過学習を確認します(訓練データとテストデータの性能を比較)
  6. joblib または pickle でモデルを保存します

コメント