※ この記事はAIによって自動生成されています
目次
- はじめに
- Matplotlibの基本セットアップ
- 機械学習で頻出のグラフパターン
- パフォーマンス最適化とベストプラクティス
- まとめ
はじめに
機械学習プロジェクトにおいて、データの可視化は非常に重要な役割を果たします。ITmediaの記事でも紹介されているように、Matplotlibは Python で最も広く使われている可視化ライブラリの一つです。本記事では、特に機械学習プロジェクトで使用される実践的な実装方法に焦点を当てて解説します。
Matplotlibの基本セットアップ
1 2 3 4 5 6 7 8
| import matplotlib.pyplot as plt import numpy as np import seaborn as sns
plt.style.use('seaborn') plt.rcParams['figure.figsize'] = (10, 6) plt.rcParams['font.size'] = 12
|
機械学習で頻出のグラフパターン
1. 学習曲線の描画
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| def plot_learning_curve(history): plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.plot(history['loss'], label='Training Loss') plt.plot(history['val_loss'], label='Validation Loss') plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.subplot(1, 2, 2) plt.plot(history['accuracy'], label='Training Accuracy') plt.plot(history['val_accuracy'], label='Validation Accuracy') plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend() plt.tight_layout() plt.show()
|
2. 混同行列の可視化
1 2 3 4 5 6 7 8 9
| def plot_confusion_matrix(cm, classes): plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=classes, yticklabels=classes) plt.title('Confusion Matrix') plt.ylabel('True Label') plt.xlabel('Predicted Label') plt.tight_layout() plt.show()
|
3. 特徴量の重要度可視化
1 2 3 4 5 6 7 8 9
| def plot_feature_importance(importance, features): idx = np.argsort(importance) plt.figure(figsize=(10, 6)) plt.barh(range(len(idx)), importance[idx]) plt.yticks(range(len(idx)), features[idx]) plt.xlabel('Feature Importance') plt.title('Feature Importance Ranking') plt.tight_layout() plt.show()
|
パフォーマンス最適化とベストプラクティス
1. メモリ使用量の最適化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg
def memory_efficient_plot(data): fig = Figure(figsize=(10, 6)) canvas = FigureCanvasAgg(fig) ax = fig.add_subplot(111) chunk_size = 1000 for i in range(0, len(data), chunk_size): chunk = data[i:i+chunk_size] ax.plot(chunk) canvas.draw() return fig
|
2. スタイル設定のベストプラクティス
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| def set_plot_style(): plt.style.use('seaborn-whitegrid') plt.rcParams.update({ 'figure.figsize': (10, 6), 'axes.grid': True, 'grid.alpha': 0.3, 'lines.linewidth': 2, 'font.size': 12, 'axes.labelsize': 14, 'axes.titlesize': 16, 'xtick.labelsize': 12, 'ytick.labelsize': 12, 'legend.fontsize': 12, })
|
3. インタラクティブモードの活用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| %matplotlib inline
plt.ion()
def real_time_plot(data_generator): fig, ax = plt.subplots() line, = ax.plot([], []) for data in data_generator: line.set_data(range(len(data)), data) ax.relim() ax.autoscale_view() plt.pause(0.1)
|
まとめ
Matplotlibは機械学習プロジェクトにおいて必須のツールです。本記事では、学習曲線、混同行列、特徴量重要度など、機械学習で頻繁に使用される可視化パターンの実装方法を紹介しました。また、大規模データセットでの使用を想定したパフォーマンス最適化やベストプラクティスについても解説しました。
参考