Share
Embed
2024年度 CA 1day Youth Boot Camp ~ MLOps ~
2024年度 CA 1day Youth Boot Camp MLOps 編で使用したスライドです。
ハンズオンで使用したGitHub Repository: https://github.com/hosimesi/mlops-introduction
Keita Hoshii
September 26, 2024
Transcript
111 slides
-
7/111 自己紹介 干飯 啓太(ほしい けいた) 職種: ML Engineer/Data Scientist 所属:
AI Shift AI Messenger Summary 責任者 @hosimesi11_ @hosimesi -
なぜMLOpsが必要なのか? 大前提: • DevOpsで必要なことはMLOpsでも必要 ML特有の課題 • 機械学習モデルは入力に対して確率的な振る舞いをする • 最新のデータで再学習しないとモデルが劣化する可能性がある •
モデルにはいくつかのハイパーパラメータがある • コードのライフサイクルとモデルのライフサイクルが違う可能性がある 14/111 -
17/20 MLOpsを構成する要素 実験基盤 学習パイプライン 推論サーバ モデルのバージョン管理 データのバージョン管理 CI/CD 監視 継続的な学習
データ基盤 https://speakerdeck.com/nsakki55/mlops-basic?slide=34 実験基盤 学習パイプライン -
20/20 今日扱うもの 実験基盤 学習パイプライン 推論サーバ モデルのバージョン管理 データのバージョン管理 CI/CD 監視 継続的な学習
データ基盤 https://speakerdeck.com/nsakki55/mlops-basic?slide=34 実験基盤 -
Docker Desktopのインストール homebrewが入っている方 $ brew install --cask docker 直接ダウンロードする方(Mac) こちらに沿ってインストール
直接ダウンロードする方(Windows) こちらに沿ってインストール 24/111 -
レポジトリのClone $ git clone https://github.com/hosimesi/mlops-introduction $ cd mlops-introduction https://github.com/CyberAgentAI/dsc-onboarding-mlops-2024 レポジトリのClone
ディレクトリ移動 27/111 ※ macでgitが使えない場合、 xcodeのアップデートをしてください -
ディレクトリの外観 https://github.com/CyberAgentAI/dsc-onboarding-mlops-2024 . ├── 1-notebook-in-docker │ ├── README.md │ ├──
poetry.lock │ ├── pyproject.toml │ └── train.ipynb ├── 2-docker-mlflow │ ├── Dockerfile │ ├── README.md │ ├── poetry.lock │ ├── pyproject.toml │ └── train.ipynb ├── README.md └── train_data.zip $ tree 本章: Docker入門で使用 次章: 実験管理で使用 28/111 -
データとコードの前準備 $ unzip train_data.zip $ cp train_data 1-notebook-in-docker/train_data データの解凍 ファイルのコピー
$ cp train_data 2-docker-mlflow/train_data 29/111 -
Docker Docker is an open platform for developing, shipping, and
running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly. With Docker, you can manage your infrastructure in the same ways you manage your applications. By taking advantage of Docker's methodologies for shipping, testing, and deploying code, you can significantly reduce the delay between writing code and running it in production. https://docs.docker.com/get-started/docker-overview/ 35/111 -
Why Docker? • コードを動かすために必要なパッケージはDockerに全て含む ◦ Dockerさえ入っていればどの環境でも動く状態に ▪ pipやpyenvではダメ?? • コード共有時や引き継ぎはどうする?
• OSへの直インストールなどはどう対応? • 実験コードを動かすための手順をDockerで隠蔽 ◦ Docker Commandの実行のみで完結 • クラウドのコンテナサービスに機械学習アプリケーションをそのままデプロイ可能 ◦ 2024年現在だとMLに限らず、アプリケーション運用の業界標準 https://speakerdeck.com/chck/container-for-mlops?slide=12 36/111 -
より良い研究開発環境を作る いきなり全部変更するのはハードルが高いと思うので段階的に導入 してみましょう pythonを直インストールしている方 → uvやpyenv + poetry 直接環境構築している方 →
Docker コード管理していない方 → Git Linter・Formatterを設定していない方 → Ruff + mypyやpysen 39/111 -
余談: 最近のPython事情 Rust製ツールが人気 uv: • https://astral.sh/blog/uv • package manager rye:
• https://rye-up.com/ • package manager ruff: • https://github.com/astral-sh/ruff • linter & formatter 40/111 -
余談: 最近のPython事情 • pytest • mypy • black • flake8
• isort • pytest • mypy • ruff Pythonプロジェクトの開始時に入れるべきライブラリ群がアップデート 41/111 -
PythonのNotebookをDocker化する 1. 既にあるPythonのNotebookをDocker化する ※ ライブラリのインストールはpoetryで行なっているとします ステップ 1. 既存のPython環境の依存を含んだDocker Imageの作成 2.
Jupyter NotebookをDockerコンテナ内で実行 42/111 -
Notebookで行っていること オンライン広告のクリックスルー率 (CTR)を予測するモデルの作成 やっていること • データの読み込み • データの前処理 • モデルの学習
◦ SGD Classifier • 評価 https://github.com/nsakki55/aws-mlops-handson/blob/main/analyse.ipynb 43/111 -
どのイメージを使うか? おすすめはSlimイメージ python:3.12 python:3.12-slim python:3.12-alpine フルパッケージ(サイズが大きい) 軽量版(ちょうど良い) 最軽量版(必要なものが入っていないこともあり) $ docker
pull python:tag $ docker images | grep python python 3.12-slim cec3038ab647 6 days ago 254MB python 3.12-alpine aeff64320ffb 6 days ago 86.2MB python 3.12 3c085580c5f2 6 days ago 1.46GB 48/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 50/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 ベースイメージの指定 51/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 環境構築の依存コマンドの実行 52/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 Image内での実行ディレクトリ指定 53/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 環境変数の指定 54/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 Image内へのファイルのコピー local://{pwd}/file_name docker://app/file_name 55/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 コンテナ実行時の実行コマンド 56/111 -
Dockerfileを書く FROM python:3.12-slim AS base RUN apt-get update && apt-get
install -y --no-install-recommends \ && apt-get clean && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV PYTHONPATH=/app COPY pyproject.toml poetry.lock ./ RUN pip install --upgrade pip \ && pip install poetry=="1.8.3" \ && poetry export --with app --without-hashes -f requirements.txt -o requirements.txt \ && pip install -r requirements.txt COPY train.ipynb /app ENTRYPOINT ["jupyter", "lab", "--port", "8080", "--ip=0.0.0.0", "--no-browser", "--allow-root", "--NotebookApp.token=''"] EXPOSE 8080 コンテナのポートを公開 57/111 -
Docker Imageの作成 $ docker build . -t notebook-in-docker:1.0 ビルドコンテキスト: COPYの起点になる部分で基本的にDockerfileのある位置
イメージ名 タグ: 運用時はcommit hashをつけるのが一般的 59/111 -
Docker Imageの作成 $ docker images | grep notebook-in-docker notebook-in-docker 1.0
b37964265132 56 seconds ago 380MB 60/111 -
Docker Containerの実行 $ docker run -p 8080:8080 --rm notebook-in-docker:1.0 実行コマンド
コンテナポートをホストマシン側に ポートフォワード 起動後コンテナは破棄 イメージ名 [I 2024-09-07 14:44:20.730 ServerApp] jupyter_lsp | extension was successfully linked. [I 2024-09-07 14:44:20.731 ServerApp] jupyter_server_terminals | extension was successfully linked. [W 2024-09-07 14:44:20.732 LabApp] 'token' has moved from NotebookApp to ServerApp. This config will be passed to ServerApp. Be sure to update your config before our next release : :. 62/111 ※ -–rm: 不要なコンテナがシステムのリソースを占有するのを防ぐ -
Tips: Docker Containerの中に入るには? 63/111 $ docker exec -it {container_id} bash
コンテナ内に入ってデバッグしたい時 実行コマンドは上書き可能 コンテナの中に入る $ docker ps コンテナ一覧確認 -
Tips: Docker Imageの調査 脆弱性の調査 $ docker scout ~~ local://notebook-in-docker:1.0 $
docker scout recommendations local://notebook-in-docker:1.0 脆弱性の減少やイメージ サイズの縮小の調査 Docker Imageの調査 $ docker scout cves local://notebook-in-docker:1.0 例 64/111 ※ docker scoutはinstallが必要(https://docs.docker.com/scout/install/) -
Tips: コンテナ内での編集を元ファイルに反映したい 今のままだとcontainer内でnotebookを編集したとしても、containerを落とした場合に元々のファイルは変更されていない local コンテナ内 コピー 同期されない $ docker run
-p 8080:8080 -v $PWD/train.ipynb:/app/train.ipynb --rm notebook-in-docker:1.0 Volumeを使ってマウントする 65/111 -
Tips: モデルなど大きなファイルを扱いたい時 機械学習で使うデータをそのままコンテナ内に入れるとイメージサイズが大きくなる $ docker run -p 8080:8080 -v $PWD/train_data:/app/train_data
--rm notebook-in-docker:1.0 Volumeを使う volumeでsyncすることでイメージサイズを小さくする 66/111 -
Jupyterの実行 http://localhost:8080/ にアクセス train.ipynbをopen Run All Cells Grid Search| alpha:
1e-05, score: 0.3974486898518637 Grid Search| alpha: 0.0001, score: 0.3933346694988594 Grid Search| alpha: 0.001, score: 0.4020087564820292 Grid Search| alpha: 100.0, score: 0.6864819640382058 Grid Search| alpha: 0.1, score: 0.43974074906133426 test logloss: 0.40316918447397815 AUC: 0.721722629994545 Accuracy: 0.8375670929283435 70/111 終わったらコンテナを終了 -
実験管理とは Experiment management in the context of machine learning is
a process of tracking experiment metadata like: • code versions, • data versions, • hyperparameters, • environment, • metrics, organizing them in a meaningful way and making them available to access and collaborate on within your organization . In the next sections, you will see exactly what that means with examples and implementations. https://neptune.ai/blog/experiment-management 72/111 -
実験の何を管理するのか • インフラ ◦ 実験に使用したマシン・ソフトウェアバージョン • コードのバージョン ◦ どのような実験コードを使用したか •
データの設定 ◦ データをどのような設定で行ったか • モデルのパラメータ ◦ ハイパーパラメータの実験設定 • メトリクス ◦ モデルの評価 76/111 -
MLflowとは A Tool for Managing the Machine Learning Lifecycle MLflow
is an open-source platform , purpose-built to assist machine learning practitioners and teams in handling the complexities of the machine learning process. MLflow focuses on the full lifecycle for machine learning projects , ensuring that each phase is manageable , traceable , and reproducible . https://mlflow.org/docs/latest/index.html 77/111 -
Docker Compose Docker Compose is a tool for defining and
running multi-container applications . It is the key to unlocking a streamlined and efficient development and deployment experience. Compose simplifies the control of your entire application stack, making it easy to manage services, networks, and volumes in a single , comprehensible YAML configuration file. Then, with a single command, you create and start all the services from your configuration file. https://docs.docker.com/compose/ 78/111 -
Why Docker Compose? 複数のContainer(application, DB, etc..)を立てる時、一つずつdocker runするのは大変 docker composeを使うと 単一のYAMLで複数のコンテナアプリケーションの定義と管理が可能
Docker: $ docker run ~~ Docker Compose:(compose.yamlがあるディレクトリで) $ docker compose up 79/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo $ $EDITOR compose.yaml 80/111 $ cd path/to/2-docker-mlflow ディレクトリ移動 compose.yaml -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo コンテナごとの定義 81/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo コンテナ名 82/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo ビルド設定 83/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo volumeのsync 84/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo コンテナの立ち上げ順序の依存の設定 85/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo ポートフォワード 86/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo コンテナの実行コマンド もし、Dockerfileにもコマンド書かれている時は compose.yamlのコマンドで上書きされる 87/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo リスタート設定と標準出力設定 88/111 -
compose.yamlの作成 services: jupyter: container_name: jupyter_container build: context: . dockerfile: Dockerfile
volumes: - ./:/app ports: - 8080:8080 command: jupyter lab --port 8080 --ip=0.0.0.0 --no-browser --allow-root --NotebookApp.token='' restart: always tty: true environment: - TZ=Asia/Tokyo mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile volumes: - ./mlflow:/app/.mlflow depends_on: - jupyter ports: - 5000:5000 command: mlflow server --backend-store-uri /app/.mlflow --host 0.0.0.0 --port 5000 restart: always tty: true environment: - TZ=Asia/Tokyo 環境変数 89/111 -
MLflowの立ち上げ 90/111 $ docker compose up --build http://localhost:5000/ にアクセス 強制的にbuild
※ もし、portが被って立ち上がらない場合 ポート: 5000 -> 5001 -
実装の追加 import pandas as pd from sklearn.linear_model import SGDClassifier from
sklearn.feature_extraction import FeatureHasher from sklearn.model_selection import train_test_split import warnings from sklearn import metrics warnings.filterwarnings('ignore') ### 追加 ### import mlflow import mlflow.sklearn from mlflow.models.signature import infer_signature mlflow.set_tracking_uri("http://mlflow_container:5000") mlflow.set_experiment("ca24-mlops-introduction") 92/111 train.ipynb(1の実装とほぼ同じ)への追加 -
実装の追加 train.ipynb(1の実装とほぼ同じ)への追加 import pandas as pd from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction import FeatureHasher from sklearn.model_selection import train_test_split import warnings from sklearn import metrics warnings.filterwarnings('ignore') ### 追加 ### import mlflow import mlflow.sklearn from mlflow.models.signature import infer_signature mlflow.set_tracking_uri("http://mlflow_container:5000") mlflow.set_experiment("ca24-mlops-introduction") MLflowライブラリのインポート 93/111 -
実装の追加 train.ipynb(1の実装とほぼ同じ)への追加 import pandas as pd from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction import FeatureHasher from sklearn.model_selection import train_test_split import warnings from sklearn import metrics warnings.filterwarnings('ignore') ### 追加 ### import mlflow import mlflow.sklearn from mlflow.models.signature import infer_signature mlflow.set_tracking_uri("http://mlflow_container:5000") mlflow.set_experiment("ca24-mlops-introduction") 実験名をつける(なんでもOK) MLflowのURIを指定 Docker Composeで同じネットワークにたてた場合、 http://{container_name}:{port}でアクセス可能 mlflow: container_name: mlflow_container build: context: . dockerfile: Dockerfile : ports: - 5000:5000 : 94/111 -
ハイパラチューニング def grid_search(X_train, y_train, X_valid, y_valid): best_score = 1e10 best_alpha
= 100 for alpha in [1e-5, 1e-4, 1e-3, 1e-2, 1e-1]: : : if best_score > valid_score: best_score = valid_score best_alpha = alpha ### 追加 ### # Log parameter and metrics with mlflow.start_run(run_name=f"Grid Search alpha={alpha}"): mlflow.log_param("alpha", alpha) mlflow.log_metric("train_score", train_score) mlflow.log_metric("valid_score", valid_score) mlflow.log_param("train_size", X_train.shape[0]) mlflow.log_param("valid_size", X_valid.shape[0]) return best_alpha ハイパラチューニングのメトリクスを送信 95/111 -
ハイパラチューニング def grid_search(X_train, y_train, X_valid, y_valid): best_score = 1e10 best_alpha
= 100 for alpha in [1e-5, 1e-4, 1e-3, 1e-2, 1e-1]: : : if best_score > valid_score: best_score = valid_score best_alpha = alpha ### 追加 ### # Log parameter and metrics with mlflow.start_run(run_name=f"Grid Search alpha={alpha}"): mlflow.log_param("alpha", alpha) mlflow.log_metric("train_score", train_score) mlflow.log_metric("valid_score", valid_score) mlflow.log_param("train_size", X_train.shape[0]) mlflow.log_param("valid_size", X_valid.shape[0]) return best_alpha ハイパラチューニングのメトリクスを送信 新たな実行の開始 この中で送られるメトリクスは全て同一runとして 紐づけられる 96/111 -
ハイパラチューニング def grid_search(X_train, y_train, X_valid, y_valid): best_score = 1e10 best_alpha
= 100 for alpha in [1e-5, 1e-4, 1e-3, 1e-2, 1e-1]: : : if best_score > valid_score: best_score = valid_score best_alpha = alpha ### 追加 ### # Log parameter and metrics with mlflow.start_run(run_name=f"Grid Search alpha={alpha}"): mlflow.log_param("alpha", alpha) mlflow.log_metric("train_score", train_score) mlflow.log_metric("valid_score", valid_score) mlflow.log_param("train_size", X_train.shape[0]) mlflow.log_param("valid_size", X_valid.shape[0]) return best_alpha ハイパラチューニングのメトリクスを送信 メトリクスの送信 パラメータはパラメータとして、 メトリクスはメトリクスとして送信 • alpha • trainのlogloss • validのlogloss • trainデータのサイズ • validデータのサイズ 97/111 -
最終結果の送信 best_alpha = grid_search(X_train_preprocessed, y_train, X_valid_preprocessed, y_valid) : : print("test
logloss: {}".format(logloss)) print("AUC: {}".format(auc)) print("Accuracy: {}".format(accuracy)) ### 追加 ### with mlflow.start_run(run_name="Model Evaluation") as run: mlflow.log_metric("test_logloss", logloss) mlflow.log_metric("AUC", auc) mlflow.log_metric("Accuracy", accuracy) mlflow.log_param("best_alpha", best_alpha) run_id = run.info.run_id sig = infer_signature(X_train_preprocessed, best_model.predict(X_train_preprocessed)) mlflow.sklearn.log_model(best_model, "sgd_classifier", signature=sig, input_example=X_test_preprocessed[0]) mlflow.register_model(f"runs:/{run_id}/sgd_classifier", "sgd_classifier") 最終結果のメトリクスを送信 98/111 -
最終結果の送信 best_alpha = grid_search(X_train_preprocessed, y_train, X_valid_preprocessed, y_valid) : : print("test
logloss: {}".format(logloss)) print("AUC: {}".format(auc)) print("Accuracy: {}".format(accuracy)) ### 追加 ### with mlflow.start_run(run_name="Model Evaluation") as run: mlflow.log_metric("test_logloss", logloss) mlflow.log_metric("AUC", auc) mlflow.log_metric("Accuracy", accuracy) mlflow.log_param("best_alpha", best_alpha) run_id = run.info.run_id sig = infer_signature(X_train_preprocessed, best_model.predict(X_train_preprocessed)) mlflow.sklearn.log_model(best_model, "sgd_classifier", signature=sig, input_example=X_test_preprocessed[0]) mlflow.register_model(f"runs:/{run_id}/sgd_classifier", "sgd_classifier") 最終結果のメトリクスを送信 新たな実行の開始 99/111 -
最終結果の送信 best_alpha = grid_search(X_train_preprocessed, y_train, X_valid_preprocessed, y_valid) : : print("test
logloss: {}".format(logloss)) print("AUC: {}".format(auc)) print("Accuracy: {}".format(accuracy)) ### 追加 ### with mlflow.start_run(run_name="Model Evaluation") as run: mlflow.log_metric("test_logloss", logloss) mlflow.log_metric("AUC", auc) mlflow.log_metric("Accuracy", accuracy) mlflow.log_param("best_alpha", best_alpha) run_id = run.info.run_id sig = infer_signature(X_train_preprocessed, best_model.predict(X_train_preprocessed)) mlflow.sklearn.log_model(best_model, "sgd_classifier", signature=sig, input_example=X_test_preprocessed[0]) mlflow.register_model(f"runs:/{run_id}/sgd_classifier", "sgd_classifier") 最終結果のメトリクスを送信 メトリクスの送信 パラメータはパラメータとして、 メトリクスはメトリクスとして送信 • best_alpha • testのlogloss • AUC • Accuracy 100/111 -
最終結果の送信 best_alpha = grid_search(X_train_preprocessed, y_train, X_valid_preprocessed, y_valid) : : print("test
logloss: {}".format(logloss)) print("AUC: {}".format(auc)) print("Accuracy: {}".format(accuracy)) ### 追加 ### with mlflow.start_run(run_name="Model Evaluation") as run: mlflow.log_metric("test_logloss", logloss) mlflow.log_metric("AUC", auc) mlflow.log_metric("Accuracy", accuracy) mlflow.log_param("best_alpha", best_alpha) run_id = run.info.run_id sig = infer_signature(X_train_preprocessed, best_model.predict(X_train_preprocessed)) mlflow.sklearn.log_model(best_model, "sgd_classifier", signature=sig, input_example=X_test_preprocessed[0]) mlflow.register_model(f"runs:/{run_id}/sgd_classifier", "sgd_classifier") 最終結果のメトリクスを送信 モデルの登録 学習済みモデルをインターフェイスとともに保存 101/111