STEP 8:確認演習

🎯 STEP 8: 確認演習

Scikit-learnの基礎と可視化を総まとめ。Irisデータセットで分類モデルを構築します

📋 このステップで学ぶこと

  • Scikit-learnのAPIの総復習
  • データの読み込みから評価までの一連の流れ
  • モデルの可視化テクニック
  • ミニプロジェクト:Irisデータセットで分類
  • 実践的な機械学習ワークフロー

演習問題: 6問

🎯 1. これまでの復習

STEP 6-7で学んだこと

📚 STEP 6: Scikit-learnの基礎
  • Estimatorの概念(fit、predict、score)
  • 一貫性のあるAPI設計
  • サンプルデータセットの使い方
📊 STEP 7: 機械学習の可視化
  • 決定境界の可視化
  • 学習曲線と検証曲線
  • 混同行列のヒートマップ
  • 特徴量の重要度グラフ

機械学習の基本ワークフロー

【標準的な流れ】 1. データの読み込み ↓ 2. データの分割(訓練データ・テストデータ) ↓ 3. モデルの作成 ↓ 4. モデルの訓練(fit) ↓ 5. 予測(predict) ↓ 6. 評価(score) ↓ 7. 可視化
💡 このステップの目標

これまで学んだ内容を実際のデータセットで実践します。コードを自分で書いて、手を動かしながら理解を深めましょう!

📊 2. 総合演習:Irisデータセットで分類

Irisデータセットとは?

🌸 アヤメの分類問題

Irisデータセットは、機械学習で最もよく使われる入門用データセットです。3種類のアヤメの花を、4つの特徴から分類します。

3つのクラス(分類先):
・Setosa(セトサ)
・Versicolor(バージカラー)
・Virginica(バージニカ)

4つの特徴量:
・がく片の長さ(sepal length)
・がく片の幅(sepal width)
・花びらの長さ(petal length)
・花びらの幅(petal width)

STEP 1: データの読み込みと確認

まずはIrisデータセットを読み込んで、データの概要を確認しましょう。

import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score, confusion_matrix, classification_report # Irisデータセットの読み込み iris = load_iris() # データの確認 print(“データの形状:”, iris.data.shape) print(“クラスの数:”, len(iris.target_names)) print(“クラス名:”, iris.target_names) print(“\n特徴量の名前:”) for i, name in enumerate(iris.feature_names): print(f” {i}: {name}”)
データの形状: (150, 4) クラスの数: 3 クラス名: [‘setosa’ ‘versicolor’ ‘virginica’] 特徴量の名前: 0: sepal length (cm) 1: sepal width (cm) 2: petal length (cm) 3: petal width (cm)

STEP 2: DataFrameで見やすく表示

pandasのDataFrameに変換すると、データが見やすくなります。

# DataFrameに変換 df = pd.DataFrame( data=iris.data, columns=iris.feature_names ) df[‘species’] = iris.target df[‘species_name’] = df[‘species’].map({ 0: ‘setosa’, 1: ‘versicolor’, 2: ‘virginica’ }) # 最初の5行を表示 print(df.head()) # 基本統計量 print(“\n=== 基本統計量 ===”) print(df.describe())
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) species species_name 0 5.1 3.5 1.4 0.2 0 setosa 1 4.9 3.0 1.4 0.2 0 setosa 2 4.7 3.2 1.3 0.2 0 setosa 3 4.6 3.1 1.5 0.2 0 setosa 4 5.0 3.6 1.4 0.2 0 setosa === 基本統計量 === sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) count 150.000000 150.000000 150.000000 150.000000 mean 5.843333 3.057333 3.758000 1.199333 std 0.828066 0.435866 1.765298 0.762238 min 4.300000 2.000000 1.000000 0.100000 max 7.900000 4.400000 6.900000 2.500000

STEP 3: データの可視化

データを可視化することで、クラス間の違いを視覚的に理解できます。

# クラスごとの分布を可視化 plt.figure(figsize=(12, 4)) # 花びらの長さと幅の散布図 plt.subplot(1, 2, 1) for species_id, species_name in enumerate(iris.target_names): mask = iris.target == species_id plt.scatter( iris.data[mask, 2], # petal length iris.data[mask, 3], # petal width label=species_name, alpha=0.7 ) plt.xlabel(‘Petal Length (cm)’) plt.ylabel(‘Petal Width (cm)’) plt.title(‘Iris Dataset – Petal Features’) plt.legend() plt.grid(True, alpha=0.3) # がく片の長さと幅の散布図 plt.subplot(1, 2, 2) for species_id, species_name in enumerate(iris.target_names): mask = iris.target == species_id plt.scatter( iris.data[mask, 0], # sepal length iris.data[mask, 1], # sepal width label=species_name, alpha=0.7 ) plt.xlabel(‘Sepal Length (cm)’) plt.ylabel(‘Sepal Width (cm)’) plt.title(‘Iris Dataset – Sepal Features’) plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.show()
🔍 観察ポイント
  • Setosa(青)は他の2つと明確に分かれている → 分類が簡単そう
  • Versicolor(オレンジ)Virginica(緑)は少し重なっている → 境界で間違えるかも
  • 花びらの特徴(左図)の方が、がく片の特徴(右図)よりもクラスがきれいに分かれている → 花びらの特徴が重要

🤖 3. モデルの訓練と評価

STEP 1: データの分割

データを訓練用とテスト用に分割します。stratifyを使ってクラスの比率を保ちます。

# 特徴量とターゲットを分離 X = iris.data y = iris.target # 訓練データとテストデータに分割(80:20) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, # 20%をテストデータに random_state=42, # 再現性のため stratify=y # クラスの比率を保つ ) print(“訓練データ:”, X_train.shape) print(“テストデータ:”, X_test.shape) print(“\n訓練データのクラス分布:”) print(pd.Series(y_train).value_counts().sort_index()) print(“\nテストデータのクラス分布:”) print(pd.Series(y_test).value_counts().sort_index())
訓練データ: (120, 4) テストデータ: (30, 4) 訓練データのクラス分布: 0 40 1 40 2 40 dtype: int64 テストデータのクラス分布: 0 10 1 10 2 10 dtype: int64

STEP 2: モデルの作成と訓練

決定木分類器を使ってモデルを作成・訓練します。

# 決定木モデルの作成 model = DecisionTreeClassifier( max_depth=3, # 木の深さを制限(過学習を防ぐ) random_state=42 ) # モデルの訓練 model.fit(X_train, y_train) print(“✅ モデルの訓練が完了しました”)

STEP 3: 予測と評価

訓練データとテストデータの両方で精度を確認します。

# 訓練データでの予測 y_train_pred = model.predict(X_train) train_accuracy = accuracy_score(y_train, y_train_pred) # テストデータでの予測 y_test_pred = model.predict(X_test) test_accuracy = accuracy_score(y_test, y_test_pred) print(“=== モデルの性能 ===”) print(f”訓練データの正解率: {train_accuracy:.4f} ({train_accuracy*100:.2f}%)”) print(f”テストデータの正解率: {test_accuracy:.4f} ({test_accuracy*100:.2f}%)”) # 詳細なレポート print(“\n=== 詳細レポート(テストデータ) ===”) print(classification_report( y_test, y_test_pred, target_names=iris.target_names ))
=== モデルの性能 === 訓練データの正解率: 0.9833 (98.33%) テストデータの正解率: 1.0000 (100.00%) === 詳細レポート(テストデータ) === precision recall f1-score support setosa 1.00 1.00 1.00 10 versicolor 1.00 1.00 1.00 10 virginica 1.00 1.00 1.00 10 accuracy 1.00 30 macro avg 1.00 1.00 1.00 30 weighted avg 1.00 1.00 1.00 30
💡 結果の解釈

正解率100%を達成しました!Irisデータセットは比較的簡単な分類問題なので、決定木でも高い精度が出ます。

⚠️ 注意:実際のビジネス問題では、こんなに高い精度が出ることは稀です。過学習していないか、必ず訓練データとテストデータの両方の精度を確認しましょう。

📊 4. 結果の可視化

混同行列(Confusion Matrix)の作成

混同行列を使って、どのクラスをどのクラスと間違えたかを確認します。

# 混同行列を計算 cm = confusion_matrix(y_test, y_test_pred) # ヒートマップで可視化 plt.figure(figsize=(8, 6)) sns.heatmap( cm, annot=True, # 数値を表示 fmt=’d’, # 整数で表示 cmap=’Blues’, # 色 xticklabels=iris.target_names, yticklabels=iris.target_names ) plt.title(‘Confusion Matrix – Iris Classification’) plt.ylabel(‘True Label’) plt.xlabel(‘Predicted Label’) plt.show() print(“\n=== 混同行列の読み方 ===”) print(“対角線上の数字:正しく分類された数”) print(“対角線以外の数字:間違って分類された数”) print(“\nこのケースでは全て対角線上にあるので、完璧な分類!”)

特徴量の重要度を可視化

どの特徴量が分類に最も貢献しているかを確認します。

# 特徴量の重要度を取得 feature_importance = model.feature_importances_ # グラフで表示 plt.figure(figsize=(10, 6)) plt.barh(iris.feature_names, feature_importance, color=’steelblue’) plt.xlabel(‘Importance’) plt.title(‘Feature Importance in Iris Classification’) plt.grid(True, alpha=0.3, axis=’x’) # 数値も表示 for i, v in enumerate(feature_importance): plt.text(v + 0.01, i, f'{v:.3f}’, va=’center’) plt.tight_layout() plt.show() print(“\n=== 特徴量の重要度 ===”) for name, importance in zip(iris.feature_names, feature_importance): print(f”{name:20s}: {importance:.4f}”)
=== 特徴量の重要度 === sepal length (cm) : 0.0000 sepal width (cm) : 0.0000 petal length (cm) : 0.0357 petal width (cm) : 0.9643
🔍 重要度の解釈

花びらの幅(petal width)が最も重要な特徴量です(96.43%)。次に花びらの長さ(petal length)(3.57%)。

がく片の特徴はほとんど使われていません。これは、花びらの特徴だけで十分に分類できることを示しています。

決定木の構造を可視化

from sklearn.tree import plot_tree # 決定木を可視化 plt.figure(figsize=(15, 10)) plot_tree( model, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, # ノードに色を付ける rounded=True, # 角を丸くする fontsize=10 ) plt.title(‘Decision Tree Structure’) plt.show()
🌳 決定木の読み方
  • 各ノード(四角)に分岐条件が書かれている(例:petal width <= 0.8)
  • は予測されるクラスを表す(濃いほど確信度が高い)
  • samplesはそのノードを通るデータ数
  • valueは各クラスのデータ数([setosa, versicolor, virginica])
  • 上から下に条件分岐していき、最終的に葉ノードで予測が決まる

🎓 5. 実践演習問題

演習問題 1 基礎

異なるモデルで比較

DecisionTreeClassifierの代わりに、以下のモデルを試して、性能を比較してください。

  • LogisticRegression(ロジスティック回帰)
  • KNeighborsClassifier(k近傍法)
  • SVC(サポートベクターマシン)

どのモデルが最も高い精度を達成しましたか?

解答例
from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC # モデルのリスト models = { ‘DecisionTree’: DecisionTreeClassifier(max_depth=3, random_state=42), ‘LogisticRegression’: LogisticRegression(max_iter=200, random_state=42), ‘KNN’: KNeighborsClassifier(n_neighbors=5), ‘SVM’: SVC(kernel=’rbf’, random_state=42) } # 各モデルを訓練・評価 results = {} for name, model in models.items(): # 訓練 model.fit(X_train, y_train) # 評価 train_score = model.score(X_train, y_train) test_score = model.score(X_test, y_test) results[name] = { ‘train’: train_score, ‘test’: test_score } print(f”{name:20s} – Train: {train_score:.4f}, Test: {test_score:.4f}”) # 結果を可視化 import pandas as pd df_results = pd.DataFrame(results).T df_results.plot(kind=’bar’, figsize=(10, 6)) plt.title(‘Model Comparison’) plt.ylabel(‘Accuracy’) plt.xlabel(‘Model’) plt.ylim(0.9, 1.01) plt.legend([‘Train’, ‘Test’]) plt.grid(True, alpha=0.3, axis=’y’) plt.tight_layout() plt.show()
期待される結果:

Irisデータセットでは、どのモデルも90%以上の精度を達成するはずです。特にSVM(サポートベクターマシン)が最も高い精度を出すことが多いです。

演習問題 2 標準

2つの特徴量だけで分類

花びらの長さ(petal length)と花びらの幅(petal width)の2つの特徴量だけを使って分類してみましょう。また、決定境界を可視化してください。

解答例
import numpy as np # 花びらの特徴量だけを使用(列2と3) X_2d = iris.data[:, [2, 3]] # petal length, petal width y = iris.target # データ分割 X_train_2d, X_test_2d, y_train, y_test = train_test_split( X_2d, y, test_size=0.2, random_state=42, stratify=y ) # モデル訓練 model_2d = DecisionTreeClassifier(max_depth=3, random_state=42) model_2d.fit(X_train_2d, y_train) # 評価 print(f”訓練精度: {model_2d.score(X_train_2d, y_train):.4f}”) print(f”テスト精度: {model_2d.score(X_test_2d, y_test):.4f}”) # 決定境界の可視化 def plot_decision_boundary(model, X, y): # メッシュグリッドの作成 x_min, x_max = X[:, 0].min() – 0.5, X[:, 0].max() + 0.5 y_min, y_max = X[:, 1].min() – 0.5, X[:, 1].max() + 0.5 xx, yy = np.meshgrid( np.linspace(x_min, x_max, 200), np.linspace(y_min, y_max, 200) ) # 予測 Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # プロット plt.figure(figsize=(10, 8)) plt.contourf(xx, yy, Z, alpha=0.3, cmap=’viridis’) # データポイント for i, species in enumerate(iris.target_names): mask = y == i plt.scatter( X[mask, 0], X[mask, 1], label=species, s=50, edgecolors=’black’, linewidth=1 ) plt.xlabel(‘Petal Length (cm)’) plt.ylabel(‘Petal Width (cm)’) plt.title(‘Decision Boundary – 2D Features’) plt.legend() plt.grid(True, alpha=0.3) plt.show() # 可視化 plot_decision_boundary(model_2d, X_2d, y)
観察ポイント:

2つの特徴量だけでも、ほぼ完璧に分類できることがわかります。決定境界は階段状になり、決定木の特徴が視覚的に理解できます。

演習問題 3 標準

交差検証で評価

train_test_splitではなく、交差検証(Cross Validation)を使って、より信頼性の高い評価をしてください。ヒント:cross_val_scoreを使います。

解答例
from sklearn.model_selection import cross_val_score # モデルの作成 model = DecisionTreeClassifier(max_depth=3, random_state=42) # 5分割交差検証 cv_scores = cross_val_score( model, iris.data, iris.target, cv=5, # 5分割 scoring=’accuracy’ ) print(“=== 交差検証の結果 ===”) print(f”各分割の精度: {cv_scores}”) print(f”平均精度: {cv_scores.mean():.4f}”) print(f”標準偏差: {cv_scores.std():.4f}”) print(f”95%信頼区間: {cv_scores.mean():.4f} ± {1.96 * cv_scores.std():.4f}”) # 可視化 plt.figure(figsize=(10, 6)) plt.bar(range(1, 6), cv_scores, color=’steelblue’, alpha=0.7) plt.axhline(y=cv_scores.mean(), color=’red’, linestyle=’–‘, label=f’Mean: {cv_scores.mean():.4f}’) plt.xlabel(‘Fold’) plt.ylabel(‘Accuracy’) plt.title(‘Cross-Validation Scores’) plt.ylim(0.8, 1.0) plt.legend() plt.grid(True, alpha=0.3, axis=’y’) plt.show()
交差検証の利点:

1回の分割だけでなく、複数回に分けて評価することで、より信頼性の高い性能評価ができます。データの分割の仕方に依存しない、公平な評価が可能になります。

演習問題 4 標準

ハイパーパラメータの調整

DecisionTreeClassifierのmax_depth(木の深さ)を1〜10まで変えて、訓練精度とテスト精度がどう変化するかを可視化してください。過学習が起きているかを確認しましょう。

解答例
# データ分割(共通) X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.2, random_state=42, stratify=iris.target ) # max_depthを変えて評価 max_depths = range(1, 11) train_scores = [] test_scores = [] for depth in max_depths: # モデル作成 model = DecisionTreeClassifier(max_depth=depth, random_state=42) # 訓練 model.fit(X_train, y_train) # 評価 train_scores.append(model.score(X_train, y_train)) test_scores.append(model.score(X_test, y_test)) # 可視化 plt.figure(figsize=(10, 6)) plt.plot(max_depths, train_scores, ‘o-‘, label=’Training Score’, linewidth=2) plt.plot(max_depths, test_scores, ‘s-‘, label=’Test Score’, linewidth=2) plt.xlabel(‘Max Depth’) plt.ylabel(‘Accuracy’) plt.title(‘Training vs Test Accuracy by Max Depth’) plt.legend() plt.grid(True, alpha=0.3) plt.xticks(max_depths) plt.ylim(0.8, 1.05) plt.show() # 最適なmax_depthを見つける best_depth = max_depths[np.argmax(test_scores)] best_test_score = max(test_scores) print(f”\n最適なmax_depth: {best_depth}”) print(f”そのときのテスト精度: {best_test_score:.4f}”)
⚠️ 過学習のサイン:

max_depthが大きくなると、訓練精度は上がりますが、テスト精度は下がることがあります。これが過学習(Overfitting)です。

良いモデル:訓練精度とテスト精度が両方とも高く、差が小さい
過学習:訓練精度は高いが、テスト精度が低い(差が大きい)

演習問題 5 応用

完全なミニプロジェクト

これまで学んだことを全て使って、以下の流れで完全なプロジェクトを完成させてください。

  1. データの読み込みと基本統計量の確認
  2. データの可視化(散布図、相関行列など)
  3. データの分割
  4. 複数のモデルを試して比較
  5. 最良のモデルを選択
  6. ハイパーパラメータチューニング
  7. 最終評価(混同行列、分類レポート)
  8. 結果の可視化とレポート作成
解答例(完全版)
# === 1. データ準備 === import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.metrics import accuracy_score, confusion_matrix, classification_report # データ読み込み iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df[‘species’] = iris.target print(“=== データの基本情報 ===”) print(df.info()) print(“\n=== 基本統計量 ===”) print(df.describe()) # === 2. データ可視化 === # ペアプロット sns.pairplot(df, hue=’species’, palette=’Set2′) plt.suptitle(‘Iris Dataset – Pairplot’, y=1.02) plt.show() # 相関行列 plt.figure(figsize=(8, 6)) sns.heatmap(df.iloc[:, :-1].corr(), annot=True, cmap=’coolwarm’, center=0) plt.title(‘Feature Correlation Matrix’) plt.show() # === 3. データ分割 === X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) # === 4. 複数モデルの比較 === models = { ‘DecisionTree’: DecisionTreeClassifier(random_state=42), ‘LogisticRegression’: LogisticRegression(max_iter=200, random_state=42), ‘KNN’: KNeighborsClassifier(), ‘SVM’: SVC(random_state=42) } print(“\n=== モデル比較(交差検証) ===”) cv_results = {} for name, model in models.items(): scores = cross_val_score(model, X, y, cv=5, scoring=’accuracy’) cv_results[name] = scores print(f”{name:20s}: {scores.mean():.4f} (±{scores.std():.4f})”) # === 5. 最良モデルの選択とチューニング === print(“\n=== ハイパーパラメータチューニング(DecisionTree) ===”) param_grid = { ‘max_depth’: [2, 3, 4, 5, 6, 7, 8], ‘min_samples_split’: [2, 5, 10], ‘min_samples_leaf’: [1, 2, 4] } grid_search = GridSearchCV( DecisionTreeClassifier(random_state=42), param_grid, cv=5, scoring=’accuracy’, n_jobs=-1 ) grid_search.fit(X_train, y_train) print(f”最良パラメータ: {grid_search.best_params_}”) print(f”最良スコア: {grid_search.best_score_:.4f}”) # === 6. 最終評価 === best_model = grid_search.best_estimator_ y_pred = best_model.predict(X_test) print(“\n=== 最終評価 ===”) print(f”テスト精度: {accuracy_score(y_test, y_pred):.4f}”) print(“\n分類レポート:”) print(classification_report(y_test, y_pred, target_names=iris.target_names)) # === 7. 結果の可視化 === # 混同行列 plt.figure(figsize=(8, 6)) cm = confusion_matrix(y_test, y_pred) sns.heatmap(cm, annot=True, fmt=’d’, cmap=’Blues’, xticklabels=iris.target_names, yticklabels=iris.target_names) plt.title(‘Confusion Matrix’) plt.ylabel(‘True Label’) plt.xlabel(‘Predicted Label’) plt.show() print(“\n✅ プロジェクト完了!”)
🎯 このプロジェクトで学んだこと:
  • データ分析の全体フロー
  • 複数モデルの比較方法
  • ハイパーパラメータチューニング
  • 適切な評価と可視化

この流れは、実際の機械学習プロジェクトでも使える基本パターンです!

演習問題 6 応用

独自の予測関数を作る

訓練済みモデルを使って、新しい花のデータから品種を予測する関数を作成してください。
入力:4つの特徴量(がく片の長さ・幅、花びらの長さ・幅)
出力:予測される品種名と確率

解答例
# モデルの訓練(全データで) final_model = DecisionTreeClassifier(max_depth=3, random_state=42) final_model.fit(iris.data, iris.target) def predict_iris_species(sepal_length, sepal_width, petal_length, petal_width): “”” アヤメの品種を予測する関数 Parameters: ———– sepal_length : float – がく片の長さ (cm) sepal_width : float – がく片の幅 (cm) petal_length : float – 花びらの長さ (cm) petal_width : float – 花びらの幅 (cm) Returns: ——– dict : 予測結果(品種名と確率) “”” # 入力データを配列に変換 X_new = np.array([[sepal_length, sepal_width, petal_length, petal_width]]) # 予測 prediction = final_model.predict(X_new)[0] species_name = iris.target_names[prediction] # 確率(決定木は predict_proba をサポート) probabilities = final_model.predict_proba(X_new)[0] # 結果を辞書で返す result = { ‘species’: species_name, ‘class_id’: int(prediction), ‘probabilities’: { iris.target_names[i]: float(prob) for i, prob in enumerate(probabilities) } } return result # === テスト === print(“=== テスト 1: Setosaっぽい花 ===”) result1 = predict_iris_species(5.1, 3.5, 1.4, 0.2) print(f”予測品種: {result1[‘species’]}”) print(“確率:”) for species, prob in result1[‘probabilities’].items(): print(f” {species:12s}: {prob:.4f} ({prob*100:.2f}%)”) print(“\n=== テスト 2: Virginicaっぽい花 ===”) result2 = predict_iris_species(6.5, 3.0, 5.5, 2.0) print(f”予測品種: {result2[‘species’]}”) print(“確率:”) for species, prob in result2[‘probabilities’].items(): print(f” {species:12s}: {prob:.4f} ({prob*100:.2f}%)”)
💡 実用的な関数の作り方:
  • 入力パラメータを明確に
  • 返り値を構造化(辞書形式)
  • ドキュメント文字列(docstring)を書く
  • エラーハンドリングを含める

この関数は、Webアプリやモバイルアプリに組み込むこともできます!

📝 STEP 8 のまとめ

✅ このステップで学んだこと
  • Scikit-learnの基本ワークフローを実践
  • データの読み込みから評価までの一連の流れ
  • 複数モデルの比較方法
  • 可視化による結果の解釈
  • ハイパーパラメータチューニングの基礎
  • 交差検証による信頼性の高い評価
  • 実用的な予測関数の作成
🎯 機械学習の実践で大切なこと
  1. データを理解する – 可視化と統計量の確認
  2. 適切に評価する – 訓練データとテストデータを分ける
  3. 過学習に注意 – 訓練精度だけでなくテスト精度も見る
  4. 複数モデルを試す – 1つのモデルに固執しない
  5. 結果を可視化する – 数値だけでなくグラフで確認
🚀 次のステップへ

Part 2の基礎編が完了しました!次のPart 3では、回帰分析を学びます。

回帰とは:連続値(数値)を予測する問題
例:住宅価格の予測、売上の予測、気温の予測など

実際のビジネスでも頻繁に使われる重要な手法です。線形回帰から始めて、より高度な回帰手法まで段階的に学んでいきましょう!

❓ よくある質問

Q1. なぜIrisデータセットはこんなに高い精度が出るのですか?
Irisデータセットは比較的簡単な問題だからです。データがきれいで、特徴量が明確に分かれています。実際のビジネス問題では、ノイズが多く、もっと難しいことが多いです。Irisは学習用の入門データセットと考えてください。
Q2. 訓練精度とテスト精度の差が大きい場合、どうすればいいですか?
これは過学習のサインです。対策としては、モデルを単純にする(例:決定木の深さを制限)、正則化を使う、訓練データを増やす、特徴量を減らす、交差検証で評価する、などがあります。
Q3. どのモデルを選べばいいかわかりません
まずは複数試してみるのが鉄則です。まずシンプルなモデル(決定木、ロジスティック回帰)を試し、うまくいかなければ複雑なモデル(SVM、アンサンブル)を試します。交差検証で比較して、最良のモデルを選びましょう。「このデータには絶対このモデル」というルールはありません。
Q4. 特徴量の重要度が0のものがあるのはなぜですか?
そのモデルではその特徴量が使われていないということです。他の特徴量だけで十分に分類できる、その特徴量が予測に役立たない、または他の特徴量と相関が高い(重複している)などの理由が考えられます。重要度0の特徴量は削除しても性能は変わりませんが、慎重に判断しましょう。
Q5. random_stateは必ず指定すべきですか?
Yes!必ず指定してください。random_stateを指定しないと、実行するたびに結果が変わります。指定することで、結果が再現可能になり、デバッグしやすくなり、他の人が同じ結果を得られます。開発中は固定値(42がよく使われる)を使い、本番では複数の乱数で試すのが良い実践方法です。
📝

学習メモ

機械学習入門 - Step 8

📋 過去のメモ一覧
#artnasekai #学習メモ
LINE