Tensorflow 모델 분석 모델 검증

개요

TFMA는 지원 되는 측정항목을 기반으로 값 임계값 및 변경 임계값을 설정하여 모델 검증을 지원합니다.

구성

일반값임계값

값 임계값은 해당 메트릭이 하한보다 크거나 상한보다 작은지 여부를 확인하여 후보 모델을 게이트하는 데 유용합니다. 사용자는 lower_bound 및 upper_bound 값 중 하나 또는 둘 다를 설정할 수 있습니다. lower_bound는 설정되지 않은 경우 기본값은 음의 무한대로 설정되고, upper_bound는 설정되지 않은 경우 기본값은 무한대로 설정됩니다.

import tensorflow_model_analysis as tfma

lower_bound = tfma.GenericValueThreshold(lower_bound={'value':0})
upper_bound = tfma.GenericValueThreshold(upper_bound={'value':1})
lower_upper_bound = tfma.GenericValueThreshold(lower_bound={'value':0},
                                               upper_bound={'value':1))

일반변경임계값

변경 임계값은 해당 측정항목이 기본 모델의 측정항목보다 크거나 작은지 여부를 확인하여 후보 모델을 게이트하는 데 유용합니다. 변화를 측정하는 방법에는 절대적 변화와 상대적 변화라는 두 가지 방법이 있습니다. 절대적 변화는 후보 모델과 기준 모델의 메트릭 사이의 값 차이, 즉 v_c - v_b 로 계산됩니다. 여기서 v_c는 후보 메트릭 값을 나타내고 v_b는 기준 값을 나타냅니다. 상대값은 후보의 측정항목과 기준선의 상대적인 차이, 즉 v_c/v_b 입니다. 절대 임계값과 상대 임계값은 두 기준에 따라 게이트 모델에 공존할 수 있습니다. 임계값 설정 외에도 사용자는 MetricDirection을 구성해야 합니다. 유리하게 더 높은 값(예: AUC)을 갖는 지표의 경우 방향을 HIGHER_IS_BETTER로 설정하고, 유리하게 더 낮은 값(예: 손실)을 갖는 지표의 경우 방향을 LOWER_IS_BETTER로 설정합니다. 변경 임계값을 사용하려면 후보 모델과 함께 평가할 기준 모델이 필요합니다. 예를 보려면 시작하기 가이드를 참조하세요.

import tensorflow_model_analysis as tfma

absolute_higher_is_better = tfma.GenericChangeThreshold(absolute={'value':1},
                                                        direction=tfma.MetricDirection.HIGHER_IS_BETTER)
absolute_lower_is_better = tfma.GenericChangeThreshold(absolute={'value':1},
                                                       direction=tfma.MetricDirection.LOWER_IS_BETTER)
relative_higher_is_better = tfma.GenericChangeThreshold(relative={'value':1},
                                                        direction=tfma.MetricDirection.HIGHER_IS_BETTER)
relative_lower_is_better = tfma.GenericChangeThreshold(relative={'value':1},
                                                       direction=tfma.MetricDirection.LOWER_IS_BETTER)
absolute_and_relative = tfma.GenericChangeThreshold(relative={'value':1},
                                                    absolute={'value':0.2},
                                                    direction=tfma.MetricDirection.LOWER_IS_BETTER)

물건을 하나로 모으기

다음 예에서는 값과 변경 임계값을 결합합니다.

import tensorflow_model_analysis as tfma

lower_bound = tfma.GenericValueThreshold(lower_bound={'value':0.7})
relative_higher_is_better =
    tfma.GenericChangeThreshold(relative={'value':1.01},
                                direction=tfma.MetricDirection.HIGHER_IS_BETTER)
auc_threshold = tfma.MetricThreshold(value_threshold=lower_bound,
                                     change_threshold=relative_higher_is_better)

proto 형식으로 구성을 기록하는 것이 더 읽기 쉽습니다.

from google.protobuf import text_format

auc_threshold = text_format.Parse("""
  value_threshold { lower_bound { value: 0.6 } }
  change_threshold { relative { value: 1.01 } }
""", tfma.MetricThreshold())

MetricThreshold는 모델 훈련 시간 지표(EvalSavedModel 또는 Keras 저장 모델)와 훈련 후 지표(TFMA 구성에 정의됨) 모두에 대해 게이트로 설정될 수 있습니다. 훈련 시간 지표의 경우 임계값은 tfma.MetricsSpec에 지정됩니다.

metrics_spec = tfma.MetricSpec(thresholds={'auc': auc_threshold})

훈련 후 지표의 경우 임계값은 tfma.MetricConfig에서 직접 정의됩니다.

metric_config = tfma.MetricConfig(class_name='TotalWeightedExample',
                                  threshold=lower_bound)

다음은 EvalConfig의 다른 설정과 함께 예입니다.

# Run in a Jupyter Notebook.
from google.protobuf import text_format

eval_config = text_format.Parse("""
  model_specs {
    # This assumes a serving model with a "serving_default" signature.
    label_key: "label"
    example_weight_key: "weight"
  }
  metrics_spec {
    # Training Time metric thresholds
    thresholds {
      key: "auc"
      value: {
        value_threshold {
          lower_bound { value: 0.7 }
        }
        change_threshold {
          direction: HIGHER_IS_BETTER
          absolute { value: -1e-10 }
        }
      }
    }
    # Post Training metrics and their thesholds.
    metrics {
      # This assumes a binary classification model.
      class_name: "AUC"
      threshold {
        value_threshold {
          lower_bound { value: 0 }
        }
      }
    }
  }
  slicing_specs {}
  slicing_specs {
    feature_keys: ["age"]
  }
""", tfma.EvalConfig())

eval_shared_models = [
  tfma.default_eval_shared_model(
      model_name=tfma.CANDIDATE_KEY,
      eval_saved_model_path='/path/to/saved/candiate/model',
      eval_config=eval_config),
  tfma.default_eval_shared_model(
      model_name=tfma.BASELINE_KEY,
      eval_saved_model_path='/path/to/saved/baseline/model',
      eval_config=eval_config),
]

eval_result = tfma.run_model_analysis(
    eval_shared_models,
    eval_config=eval_config,
    # This assumes your data is a TFRecords file containing records in the
    # tf.train.Example format.
    data_location="/path/to/file/containing/tfrecords",
    output_path="/path/for/output")

tfma.view.render_slicing_metrics(eval_result)
tfma.load_validation_result(output_path)

산출

평가자의 메트릭 파일 출력 외에도 유효성 검사를 사용하면 추가 "검증" 파일도 출력됩니다. 페이로드 형식은 ValidationResult 입니다. 오류가 없으면 출력에서 ​​"validation_ok"가 True로 설정됩니다. 오류가 있는 경우 관련 지표, 임계값 및 관찰된 지표 값에 대한 정보가 제공됩니다. 다음은 "weighted_examle_count"가 임계값을 초과하는 예입니다(1.5가 1.0보다 작지 않으므로 실패).

  validation_ok: False
  metric_validations_per_slice {
    failures {
      metric_key {
        name: "weighted_example_count"
        model_name: "candidate"
      }
      metric_threshold {
        value_threshold {
          upper_bound { value: 1.0 }
        }
      }
      metric_value {
        double_value { value: 1.5 }
      }
    }
  }