DVC(資料版本控制) 是做什麼的?
安裝
pip install dvc[s3]
pip install dvc[gs]
pip install dvc[azure]
pip install dvc[all]
cd my-ml-project
git init
dvc init
追蹤資料檔案
dvc add data/training_images/
dvc add data/dataset.csv
git add data/training_images.dvc data/dataset.csv.dvc .gitignore
git commit -m "使用 DVC 追蹤訓練資料"
設定遠端儲存
dvc remote add -d myremote s3://my-bucket/dvc-storage
dvc remote add -d myremote gs://my-bucket/dvc-storage
dvc remote add -d myremote /mnt/shared/dvc-storage
dvc push
dvc pull
建置可重現的管線
stages:
prepare:
cmd: python src/prepare.py
deps:
- src/prepare.py
- data/raw/
outs:
- data/processed/
train:
cmd: python src/train.py
deps:
- src/train.py
- data/processed/
params:
- train.epochs
- train.learning_rate
- train.batch_size
outs:
- models/model.pkl
metrics:
- metrics/train.json:
cache: false
evaluate:
cmd: python src/evaluate.py
deps:
- src/evaluate.py
- models/model.pkl
- data/processed/
metrics:
- metrics/eval.json:
cache: false
plots:
- metrics/confusion_matrix.csv:
x: predicted
y: actual
train:
epochs: 50
learning_rate: 0.001
batch_size: 32
dvc repro
dvc repro train
實驗追蹤
dvc exp run --set-param train.learning_rate=0.01
dvc exp run --set-param train.learning_rate=0.001 --queue
dvc exp run --set-param train.learning_rate=0.01 --queue
dvc exp run --set-param train.learning_rate=0.1 --queue
dvc queue start --jobs 3
dvc exp show
dvc exp diff
dvc exp apply exp-abc123
dvc exp push origin exp-abc123
指標與圖表
import json
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score
import yaml
import pickle
with open("params.yaml") as f:
params = yaml.safe_load(f)["train"]
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=params["epochs"])
model.fit(X_train, y_train)
preds = model.predict(X_test)
metrics = {
"accuracy": accuracy_score(y_test, preds),
"f1_score": f1_score(y_test, preds, average="weighted"),
}
with open("metrics/train.json", "w") as f:
json.dump(metrics, f, indent=2)
with open("models/model.pkl", "wb") as f:
pickle.dump(model, f)
dvc metrics show
dvc metrics diff
dvc plots show metrics/confusion_matrix.csv
dvc plots diff
無須複製即可存取資料
dvc get https://github.com/org/ml-repo data/processed/dataset.csv
dvc import https://github.com/org/ml-repo models/model.pkl
import dvc.api
with dvc.api.open("data/dataset.csv", repo="https://github.com/org/ml-repo") as f:
import pandas as pd
df = pd.read_csv(f)
url = dvc.api.get_url("models/model.pkl", repo="https://github.com/org/ml-repo")
關鍵概念
.dvc 檔案:提交到 Git 的小型指標檔,用於參照遠端儲存中的大型資料
dvc repro:重現管線 — 僅重新執行相依性有變更的階段
- 實驗:無分支的實驗追蹤 — 執行、比較並套用結果
- 參數:由 DVC 追蹤的 YAML 參數檔,用於可重現的組態設定
- 指標:JSON/YAML 格式的指標檔,內建比較工具
- 遠端儲存:S3、GCS、Azure、SSH、HDFS — 資料存放在您想要的位置