※ この記事はAIによって自動生成されています
目次
はじめに
AI・機械学習の基礎環境構築
機械学習モデルの実装例
モデルの評価とチューニング
本番環境への展開とベストプラクティス
まとめ
はじめに 最近、PR Timesで公開された「AI(人工知能)と機械学習パーフェクトガイド」の無料公開のニュースを受け、本記事では特に実装面に焦点を当てて、エンジニアの皆様に実践的なガイドを提供します。
AI・機械学習の基礎環境構築 必要な環境設定 1 2 3 4 5 6 7 8 !pip install numpy pandas scikit-learn tensorflowimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler
開発環境の推奨スペック
CPU: 4コア以上
RAM: 16GB以上
GPU: NVIDIA GPU(CUDA対応)推奨
ストレージ: SSD 256GB以上
機械学習モデルの実装例 シンプルな分類モデルの実装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=100 ) X = pd.DataFrame(...) y = pd.Series(...) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2 , random_state=42 ) clf.fit(X_train, y_train) predictions = clf.predict(X_test)
ディープラーニングモデルの実装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense model = Sequential([ Dense(64 , activation='relu' , input_shape=(input_dim,)), Dense(32 , activation='relu' ), Dense(1 , activation='sigmoid' ) ]) model.compile (optimizer='adam' , loss='binary_crossentropy' , metrics=['accuracy' ]) history = model.fit(X_train, y_train, epochs=10 , batch_size=32 , validation_split=0.2 )
モデルの評価とチューニング 評価指標の実装 1 2 3 4 5 6 7 8 9 10 from sklearn.metrics import accuracy_score, precision_score, recall_scoredef evaluate_model (y_true, y_pred ): accuracy = accuracy_score(y_true, y_pred) precision = precision_score(y_true, y_pred) recall = recall_score(y_true, y_pred) print (f'Accuracy: {accuracy:.4 f} ' ) print (f'Precision: {precision:.4 f} ' ) print (f'Recall: {recall:.4 f} ' )
ハイパーパラメータチューニング 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from sklearn.model_selection import GridSearchCV param_grid = { 'n_estimators' : [100 , 200 , 300 ], 'max_depth' : [10 , 20 , 30 , None ], 'min_samples_split' : [2 , 5 , 10 ] } grid_search = GridSearchCV( RandomForestClassifier(), param_grid, cv=5 , n_jobs=-1 ) grid_search.fit(X_train, y_train)
本番環境への展開とベストプラクティス モデルの保存と読み込み 1 2 3 4 5 6 7 import joblib joblib.dump(model, 'model.joblib' ) loaded_model = joblib.load('model.joblib' )
APIエンドポイントの実装例(Flask) 1 2 3 4 5 6 7 8 9 10 11 12 13 from flask import Flask, request, jsonify app = Flask(__name__)@app.route('/predict' , methods=['POST' ] ) def predict (): data = request.json features = pd.DataFrame(data['features' ]) prediction = loaded_model.predict(features) return jsonify({'prediction' : prediction.tolist()})if __name__ == '__main__' : app.run(host='0.0.0.0' , port=5000 )
まとめ 本記事では、AI・機械学習の実装面に焦点を当て、環境構築から本番環境への展開まで、実践的なコード例を交えて解説しました。これらの実装例をベースに、各自のプロジェクトに合わせてカスタマイズしていくことをお勧めします。
参考