ML 튜닝
ML 튜닝 (ML Tuning)
이 섹션에서는 ML 알고리즘과 파이프라인을 튜닝하는 MLlib 도구를 어떻게 쓰는지 설명해요. 내장된 교차 검증(Cross-Validation)과 기타 도구를 이용하면 알고리즘과 파이프라인의 하이퍼파라미터를 최적화할 수 있어요.
출처: ML Tuning
본문
- 모델 선택(일명 하이퍼파라미터 튜닝)
- 교차 검증(Cross-Validation)
- Train-Validation Split
모델 선택(일명 하이퍼파라미터 튜닝)
ML에서 중요한 작업은 모델 선택(model selection), 즉 주어진 작업에 가장 좋은 모델이나 파라미터를 데이터를 사용해 찾는 일이에요. 이걸 *튜닝(tuning)*이라고도 불러요. 튜닝은 LogisticRegression 같은 개별 Estimator에 대해서도 할 수 있고, 여러 알고리즘, 피처 변환, 기타 단계를 포함하는 전체 Pipeline에 대해서도 할 수 있어요. 사용자는 Pipeline의 각 요소를 따로 튜닝하는 대신 전체 Pipeline을 한 번에 튜닝할 수 있어요.
MLlib은 CrossValidator와 TrainValidationSplit 같은 도구로 모델 선택을 지원해요. 이 도구들은 다음 항목을 필요로 해요.
Estimator: 튜닝할 알고리즘 또는PipelineParamMap집합: 선택할 파라미터들. 검색할 "파라미터 그리드"라고도 불러요.Evaluator: 피팅된Model이 남겨둔(held-out) 테스트 데이터에서 얼마나 잘 하는지 측정할 지표
높은 수준에서 이 모델 선택 도구들은 다음과 같이 동작해요.
- 입력 데이터를 별도의 훈련 데이터셋과 테스트 데이터셋으로 나눠요.
- 각 (훈련, 테스트) 쌍에 대해
ParamMap집합을 반복해요. - 각
ParamMap에 대해 그 파라미터로Estimator를 피팅하고, 피팅된Model을 얻은 뒤,Evaluator로Model의 성능을 평가해요. - 가장 좋은 성능을 낸 파라미터 집합이 만든
Model을 선택해요.
Evaluator는 회귀 문제에는 RegressionEvaluator, 이진 데이터에는 BinaryClassificationEvaluator, 다중 클래스 문제에는 MulticlassClassificationEvaluator, 다중 레이블 분류에는 MultilabelClassificationEvaluator, 랭킹 문제에는 RankingEvaluator일 수 있어요. 최적 ParamMap을 고르는 데 쓰는 기본 지표는 이 평가자 각각의 setMetricName 메서드로 바꿀 수 있어요.
파라미터 그리드 구성을 돕기 위해 사용자는 ParamGridBuilder 유틸리티를 쓸 수 있어요. 기본적으로 파라미터 그리드의 파라미터 집합들은 직렬로 평가돼요. CrossValidator나 TrainValidationSplit로 모델 선택을 실행하기 전에 parallelism을 2 이상으로 설정하면 파라미터 평가를 병렬로 수행할 수 있어요(값이 1이면 직렬). parallelism 값은 클러스터 자원을 초과하지 않으면서 병렬성을 최대화하도록 신중히 골라야 해요. 값이 커도 항상 성능이 좋아지지는 않아요. 일반적으로 대부분 클러스터에서는 10 이하가 충분해요.
교차 검증(Cross-Validation)
CrossValidator는 데이터셋을 별도의 훈련·테스트 데이터셋으로 쓰이는 폴드(folds) 집합으로 나누는 것에서 시작해요. 예를 들어 폴드 $k=3$개라면 CrossValidator는 3개의 (훈련, 테스트) 데이터셋 쌍을 생성하는데, 각 쌍은 데이터의 2/3을 훈련에, 1/3을 테스트에 사용해요. 특정 ParamMap을 평가하기 위해 CrossValidator는 3개의 서로 다른 (훈련, 테스트) 데이터셋 쌍에서 Estimator를 피팅해 만든 3개의 Model에 대한 평균 평가 지표를 계산해요.
최적 ParamMap을 식별한 뒤 CrossValidator는 마지막으로 최적 ParamMap과 전체 데이터셋을 사용해 Estimator를 다시 피팅해요.
예제: 교차 검증을 통한 모델 선택
다음 예제는 CrossValidator를 사용해 파라미터 그리드에서 선택하는 방법을 보여줘요.
파라미터 그리드에 대한 교차 검증은 비싸다는 점에 유의하세요. 예를 들어 아래 예제에서 파라미터 그리드는 hashingTF.numFeatures 값 3개와 lr.regParam 값 2개를 가지며, CrossValidator는 폴드 2개를 사용해요. 이는 $(3 \times 2) \times 2 = 12$개의 서로 다른 모델이 훈련되는 셈이에요. 실제 상황에서는 훨씬 더 많은 파라미터를 시도하고 더 많은 폴드($k=3$이나 $k=10$이 흔해요)를 쓰는 게 일반적이에요. 즉 CrossValidator를 쓰는 건 매우 비쌀 수 있어요. 하지만 이는 파라미터를 고르는 검증된 방법이기도 하고, 경험에 의한 수동 튜닝보다 통계적으로 더 타당해요.
API에 대한 자세한 내용은 CrossValidator Python 문서를 참고하세요.
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.feature import HashingTF, Tokenizer
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
# Prepare training documents, which are labeled.
training = spark.createDataFrame([
(0, "a b c d e spark", 1.0),
(1, "b d", 0.0),
(2, "spark f g h", 1.0),
(3, "hadoop mapreduce", 0.0),
(4, "b spark who", 1.0),
(5, "g d a y", 0.0),
(6, "spark fly", 1.0),
(7, "was mapreduce", 0.0),
(8, "e spark program", 1.0),
(9, "a e c l", 0.0),
(10, "spark compile", 1.0),
(11, "hadoop software", 0.0)
], ["id", "text", "label"])
# Configure an ML pipeline, which consists of tree stages: tokenizer, hashingTF, and lr.
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression(maxIter=10)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])
# We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
# This will allow us to jointly choose parameters for all Pipeline stages.
# A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
# We use a ParamGridBuilder to construct a grid of parameters to search over.
# With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
# this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
paramGrid = ParamGridBuilder() \
.addGrid(hashingTF.numFeatures, [10, 100, 1000]) \
.addGrid(lr.regParam, [0.1, 0.01]) \
.build()
crossval = CrossValidator(estimator=pipeline,
estimatorParamMaps=paramGrid,
evaluator=BinaryClassificationEvaluator(),
numFolds=2) # use 3+ folds in practice
# Run cross-validation, and choose the best set of parameters.
cvModel = crossval.fit(training)
# Prepare test documents, which are unlabeled.
test = spark.createDataFrame([
(4, "spark i j k"),
(5, "l m n"),
(6, "mapreduce spark"),
(7, "apache hadoop")
], ["id", "text"])
# Make predictions on test documents. cvModel uses the best model found (lrModel).
prediction = cvModel.transform(test)
selected = prediction.select("id", "text", "probability", "prediction")
for row in selected.collect():
print(row)
전체 예제 코드는 Spark 저장소의 "examples/src/main/python/ml/cross_validator.py"에서 찾을 수 있어요.
API에 대한 자세한 내용은 CrossValidator Scala 문서를 참고하세요.
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.classification.LogisticRegression
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
import org.apache.spark.ml.feature.{HashingTF, Tokenizer}
import org.apache.spark.ml.linalg.Vector
import org.apache.spark.ml.tuning.{CrossValidator, ParamGridBuilder}
import org.apache.spark.sql.Row
// Prepare training data from a list of (id, text, label) tuples.
val training = spark.createDataFrame(Seq(
(0L, "a b c d e spark", 1.0),
(1L, "b d", 0.0),
(2L, "spark f g h", 1.0),
(3L, "hadoop mapreduce", 0.0),
(4L, "b spark who", 1.0),
(5L, "g d a y", 0.0),
(6L, "spark fly", 1.0),
(7L, "was mapreduce", 0.0),
(8L, "e spark program", 1.0),
(9L, "a e c l", 0.0),
(10L, "spark compile", 1.0),
(11L, "hadoop software", 0.0)
)).toDF("id", "text", "label")
// Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
val tokenizer = new Tokenizer()
.setInputCol("text")
.setOutputCol("words")
val hashingTF = new HashingTF()
.setInputCol(tokenizer.getOutputCol)
.setOutputCol("features")
val lr = new LogisticRegression()
.setMaxIter(10)
val pipeline = new Pipeline()
.setStages(Array(tokenizer, hashingTF, lr))
// We use a ParamGridBuilder to construct a grid of parameters to search over.
// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
val paramGrid = new ParamGridBuilder()
.addGrid(hashingTF.numFeatures, Array(10, 100, 1000))
.addGrid(lr.regParam, Array(0.1, 0.01))
.build()
// We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
// This will allow us to jointly choose parameters for all Pipeline stages.
// A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
// Note that the evaluator here is a BinaryClassificationEvaluator and its default metric
// is areaUnderROC.
val cv = new CrossValidator()
.setEstimator(pipeline)
.setEvaluator(new BinaryClassificationEvaluator)
.setEstimatorParamMaps(paramGrid)
.setNumFolds(2) // Use 3+ in practice
.setParallelism(2) // Evaluate up to 2 parameter settings in parallel
// Run cross-validation, and choose the best set of parameters.
val cvModel = cv.fit(training)
// Prepare test documents, which are unlabeled (id, text) tuples.
val test = spark.createDataFrame(Seq(
(4L, "spark i j k"),
(5L, "l m n"),
(6L, "mapreduce spark"),
(7L, "apache hadoop")
)).toDF("id", "text")
// Make predictions on test documents. cvModel uses the best model found (lrModel).
cvModel.transform(test)
.select("id", "text", "probability", "prediction")
.collect()
.foreach { case Row(id: Long, text: String, prob: Vector, prediction: Double) =>
println(s"($id, $text) --> prob=$prob, prediction=$prediction")
}
전체 예제 코드는 Spark 저장소의 "examples/src/main/scala/org/apache/spark/examples/ml/ModelSelectionViaCrossValidationExample.scala"에서 찾을 수 있어요.
API에 대한 자세한 내용은 CrossValidator Java 문서를 참고하세요.
import java.util.Arrays;
import org.apache.spark.ml.Pipeline;
import org.apache.spark.ml.PipelineStage;
import org.apache.spark.ml.classification.LogisticRegression;
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator;
import org.apache.spark.ml.feature.HashingTF;
import org.apache.spark.ml.feature.Tokenizer;
import org.apache.spark.ml.param.ParamMap;
import org.apache.spark.ml.tuning.CrossValidator;
import org.apache.spark.ml.tuning.CrossValidatorModel;
import org.apache.spark.ml.tuning.ParamGridBuilder;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
// Prepare training documents, which are labeled.
Dataset<Row> training = spark.createDataFrame(Arrays.asList(
new JavaLabeledDocument(0L, "a b c d e spark", 1.0),
new JavaLabeledDocument(1L, "b d", 0.0),
new JavaLabeledDocument(2L,"spark f g h", 1.0),
new JavaLabeledDocument(3L, "hadoop mapreduce", 0.0),
new JavaLabeledDocument(4L, "b spark who", 1.0),
new JavaLabeledDocument(5L, "g d a y", 0.0),
new JavaLabeledDocument(6L, "spark fly", 1.0),
new JavaLabeledDocument(7L, "was mapreduce", 0.0),
new JavaLabeledDocument(8L, "e spark program", 1.0),
new JavaLabeledDocument(9L, "a e c l", 0.0),
new JavaLabeledDocument(10L, "spark compile", 1.0),
new JavaLabeledDocument(11L, "hadoop software", 0.0)
), JavaLabeledDocument.class);
// Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
Tokenizer tokenizer = new Tokenizer()
.setInputCol("text")
.setOutputCol("words");
HashingTF hashingTF = new HashingTF()
.setNumFeatures(1000)
.setInputCol(tokenizer.getOutputCol())
.setOutputCol("features");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.01);
Pipeline pipeline = new Pipeline()
.setStages(new PipelineStage[] {tokenizer, hashingTF, lr});
// We use a ParamGridBuilder to construct a grid of parameters to search over.
// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
ParamMap[] paramGrid = new ParamGridBuilder()
.addGrid(hashingTF.numFeatures(), new int[] {10, 100, 1000})
.addGrid(lr.regParam(), new double[] {0.1, 0.01})
.build();
// We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
// This will allow us to jointly choose parameters for all Pipeline stages.
// A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
// Note that the evaluator here is a BinaryClassificationEvaluator and its default metric
// is areaUnderROC.
CrossValidator cv = new CrossValidator()
.setEstimator(pipeline)
.setEvaluator(new BinaryClassificationEvaluator())
.setEstimatorParamMaps(paramGrid)
.setNumFolds(2) // Use 3+ in practice
.setParallelism(2); // Evaluate up to 2 parameter settings in parallel
// Run cross-validation, and choose the best set of parameters.
CrossValidatorModel cvModel = cv.fit(training);
// Prepare test documents, which are unlabeled.
Dataset<Row> test = spark.createDataFrame(Arrays.asList(
new JavaDocument(4L, "spark i j k"),
new JavaDocument(5L, "l m n"),
new JavaDocument(6L, "mapreduce spark"),
new JavaDocument(7L, "apache hadoop")
), JavaDocument.class);
// Make predictions on test documents. cvModel uses the best model found (lrModel).
Dataset<Row> predictions = cvModel.transform(test);
for (Row r : predictions.select("id", "text", "probability", "prediction").collectAsList()) {
System.out.println("(" + r.get(0) + ", " + r.get(1) + ") --> prob=" + r.get(2)
+ ", prediction=" + r.get(3));
}
전체 예제 코드는 Spark 저장소의 "examples/src/main/java/org/apache/spark/examples/ml/JavaModelSelectionViaCrossValidationExample.java"에서 찾을 수 있어요.
Train-Validation Split
CrossValidator 외에도 Spark는 하이퍼파라미터 튜닝을 위한 TrainValidationSplit을 제공해요. TrainValidationSplit은 CrossValidator처럼 k번 대신 각 파라미터 조합을 한 번만 평가해요. 따라서 비용이 덜 들지만, 훈련 데이터셋이 충분히 크지 않으면 그만큼 신뢰할 만한 결과를 내지 못해요.
CrossValidator와 달리 TrainValidationSplit은 단일 (훈련, 테스트) 데이터셋 쌍을 만들어요. trainRatio 파라미터로 데이터셋을 두 부분으로 나눠요. 예를 들어 $trainRatio=0.75$라면 TrainValidationSplit은 데이터의 75%를 훈련에, 25%를 검증에 쓰는 훈련·테스트 데이터셋 쌍을 만들어요.
CrossValidator처럼 TrainValidationSplit도 마지막에 최적 ParamMap과 전체 데이터셋으로 Estimator를 피팅해요.
예제: train validation split을 통한 모델 선택
API에 대한 자세한 내용은 TrainValidationSplit Python 문서를 참고하세요.
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.regression import LinearRegression
from pyspark.ml.tuning import ParamGridBuilder, TrainValidationSplit
# Prepare training and test data.
data = spark.read.format("libsvm")\
.load("data/mllib/sample_linear_regression_data.txt")
train, test = data.randomSplit([0.9, 0.1], seed=12345)
lr = LinearRegression(maxIter=10)
# We use a ParamGridBuilder to construct a grid of parameters to search over.
# TrainValidationSplit will try all combinations of values and determine best model using
# the evaluator.
paramGrid = ParamGridBuilder()\
.addGrid(lr.regParam, [0.1, 0.01]) \
.addGrid(lr.fitIntercept, [False, True])\
.addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0])\
.build()
# In this case the estimator is simply the linear regression.
# A TrainValidationSplit requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
tvs = TrainValidationSplit(estimator=lr,
estimatorParamMaps=paramGrid,
evaluator=RegressionEvaluator(),
# 80% of the data will be used for training, 20% for validation.
trainRatio=0.8)
# Run TrainValidationSplit, and choose the best set of parameters.
model = tvs.fit(train)
# Make predictions on test data. model is the model with combination of parameters
# that performed best.
model.transform(test)\
.select("features", "label", "prediction")\
.show()
전체 예제 코드는 Spark 저장소의 "examples/src/main/python/ml/train_validation_split.py"에서 찾을 수 있어요.
API에 대한 자세한 내용은 TrainValidationSplit Scala 문서를 참고하세요.
import org.apache.spark.ml.evaluation.RegressionEvaluator
import org.apache.spark.ml.regression.LinearRegression
import org.apache.spark.ml.tuning.{ParamGridBuilder, TrainValidationSplit}
// Prepare training and test data.
val data = spark.read.format("libsvm").load("data/mllib/sample_linear_regression_data.txt")
val Array(training, test) = data.randomSplit(Array(0.9, 0.1), seed = 12345)
val lr = new LinearRegression()
.setMaxIter(10)
// We use a ParamGridBuilder to construct a grid of parameters to search over.
// TrainValidationSplit will try all combinations of values and determine best model using
// the evaluator.
val paramGrid = new ParamGridBuilder()
.addGrid(lr.regParam, Array(0.1, 0.01))
.addGrid(lr.fitIntercept)
.addGrid(lr.elasticNetParam, Array(0.0, 0.5, 1.0))
.build()
// In this case the estimator is simply the linear regression.
// A TrainValidationSplit requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
val trainValidationSplit = new TrainValidationSplit()
.setEstimator(lr)
.setEvaluator(new RegressionEvaluator)
.setEstimatorParamMaps(paramGrid)
// 80% of the data will be used for training and the remaining 20% for validation.
.setTrainRatio(0.8)
// Evaluate up to 2 parameter settings in parallel
.setParallelism(2)
// Run train validation split, and choose the best set of parameters.
val model = trainValidationSplit.fit(training)
// Make predictions on test data. model is the model with combination of parameters
// that performed best.
model.transform(test)
.select("features", "label", "prediction")
.show()
전체 예제 코드는 Spark 저장소의 "examples/src/main/scala/org/apache/spark/examples/ml/ModelSelectionViaTrainValidationSplitExample.scala"에서 찾을 수 있어요.
API에 대한 자세한 내용은 TrainValidationSplit Java 문서를 참고하세요.
import org.apache.spark.ml.evaluation.RegressionEvaluator;
import org.apache.spark.ml.param.ParamMap;
import org.apache.spark.ml.regression.LinearRegression;
import org.apache.spark.ml.tuning.ParamGridBuilder;
import org.apache.spark.ml.tuning.TrainValidationSplit;
import org.apache.spark.ml.tuning.TrainValidationSplitModel;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
Dataset<Row> data = spark.read().format("libsvm")
.load("data/mllib/sample_linear_regression_data.txt");
// Prepare training and test data.
Dataset<Row>[] splits = data.randomSplit(new double[] {0.9, 0.1}, 12345);
Dataset<Row> training = splits[0];
Dataset<Row> test = splits[1];
LinearRegression lr = new LinearRegression();
// We use a ParamGridBuilder to construct a grid of parameters to search over.
// TrainValidationSplit will try all combinations of values and determine best model using
// the evaluator.
ParamMap[] paramGrid = new ParamGridBuilder()
.addGrid(lr.regParam(), new double[] {0.1, 0.01})
.addGrid(lr.fitIntercept())
.addGrid(lr.elasticNetParam(), new double[] {0.0, 0.5, 1.0})
.build();
// In this case the estimator is simply the linear regression.
// A TrainValidationSplit requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
TrainValidationSplit trainValidationSplit = new TrainValidationSplit()
.setEstimator(lr)
.setEvaluator(new RegressionEvaluator())
.setEstimatorParamMaps(paramGrid)
.setTrainRatio(0.8) // 80% for training and the remaining 20% for validation
.setParallelism(2); // Evaluate up to 2 parameter settings in parallel
// Run train validation split, and choose the best set of parameters.
TrainValidationSplitModel model = trainValidationSplit.fit(training);
// Make predictions on test data. model is the model with combination of parameters
// that performed best.
model.transform(test)
.select("features", "label", "prediction")
.show();
전체 예제 코드는 Spark 저장소의 "examples/src/main/java/org/apache/spark/examples/ml/JavaModelSelectionViaTrainValidationSplitExample.java"에서 찾을 수 있어요.
더 알아보기 (Learn more)
- ML 파이프라인 — 튜닝의 대상이 되는 파이프라인 개념.
- MLlib Main Guide — MLlib의 전반적인 내용.