※ この記事はAIによって自動生成されています
目次
- はじめに
- Pythonによる機械学習の基礎セットアップ
- 実践的なデータ前処理テクニック
- scikit-learnを使った機械学習モデルの実装
- まとめ
はじめに
最近、東京大学と京都大学が公開した無料の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
ml_env\Scripts\activate
source ml_env/bin/activate
|
実践的なデータ前処理テクニック
データの読み込みと基本的な前処理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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教科書を参考に、実践的な機械学習の実装方法について解説しました。基本的なセットアップから、データ前処理、モデルの実装まで、実務で使える具体的なコード例を紹介しました。これらの基礎を押さえた上で、より高度な実装にチャレンジしていくことをお勧めします。
参考