東大・京大のPython教科書から学ぶ実践的AI・機械学習入門

※ この記事はAIによって自動生成されています

目次

  1. はじめに
  2. Pythonによる機械学習の基礎セットアップ
  3. 実践的なデータ前処理テクニック
  4. scikit-learnを使った機械学習モデルの実装
  5. まとめ

はじめに

最近、東京大学と京都大学が公開した無料のPython教科書が話題となっています。この記事では、これらの教材を参考に、実際の開発現場で使える実践的なAI・機械学習の実装方法について解説します。

Pythonによる機械学習の基礎セットアップ

開発環境の構築

1
2
3
4
5
6
7
8
# 必要なライブラリのインストール
!pip install numpy pandas scikit-learn matplotlib

# 基本的なライブラリのインポート
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

仮想環境の設定

1
2
3
4
5
6
7
8
# 仮想環境の作成
python -m venv ml_env

# 仮想環境の有効化
# Windows
ml_env\Scripts\activate
# Mac/Linux
source ml_env/bin/activate

実践的なデータ前処理テクニック

データの読み込みと基本的な前処理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# CSVファイルの読み込み
df = pd.read_csv('data.csv')

# 欠損値の処理
df = df.fillna(df.mean())

# カテゴリ変数のエンコーディング
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['category'] = le.fit_transform(df['category'])

# データの正規化
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

データの分割とバリデーション

1
2
3
4
5
6
7
8
9
10
11
# トレーニングデータとテストデータの分割
X_train, X_test, y_train, y_test = train_test_split(
X_scaled,
y,
test_size=0.2,
random_state=42
)

# クロスバリデーションの実装
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=5)

scikit-learnを使った機械学習モデルの実装

回帰モデルの実装例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# モデルの初期化と学習
model = LinearRegression()
model.fit(X_train, y_train)

# 予測と評価
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f'Mean Squared Error: {mse}')
print(f'R2 Score: {r2}')

分類モデルの実装例

1
2
3
4
5
6
7
8
9
10
11
12
13
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

# ランダムフォレストモデルの構築
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)

# 予測と評価
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')
print('\nClassification Report:')
print(classification_report(y_test, y_pred))

まとめ

本記事では、東大・京大のPython教科書を参考に、実践的な機械学習の実装方法について解説しました。基本的なセットアップから、データ前処理、モデルの実装まで、実務で使える具体的なコード例を紹介しました。これらの基礎を押さえた上で、より高度な実装にチャレンジしていくことをお勧めします。

参考