인프런 Chris Song님 강의 정리
Section2: 코드 품질, 데이터 검증, 모델 분석
TFDV (TensorFlow Data Validation)
pip install tensorflow-data-validation
pip install apache-beam
설치 확인
데이터 준비 (시카고 택시 데이터)
import os
import tempfile, urllib, zipfile
# Set up some globals for our file paths
BASE_DIR = tempfile.mkdtemp()
DATA_DIR = os.path.join(BASE_DIR, 'data')
OUTPUT_DIR = os.path.join(BASE_DIR, 'chicago_taxi_output')
TRAIN_DATA = os.path.join(DATA_DIR, 'train', 'data.csv')
EVAL_DATA = os.path.join(DATA_DIR, 'eval', 'data.csv')
SERVING_DATA = os.path.join(DATA_DIR, 'serving', 'data.csv')
# Download the zip file from GCP and unzip it
zip, headers = urllib.request.urlretrieve('https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/chicago_data.zip')
zipfile.ZipFile(zip).extractall(BASE_DIR)
zipfile.ZipFile(zip).close()
print("Here's what we downloaded:")
!ls -R {os.path.join(BASE_DIR, 'data')}
Statistics 생성
train_stats = tfdv.generate_statistics_from_csv(data_location=TRAIN_DATA)
Facets를 사용하여 데이터의 간결한 시각화
tfdv.visualize_statistics(train_stats)
숫자 형상과 범주는 별도로 시각화되며 각 형상에 대한 분포를 보여주는 차트가 표시됨
결측값 또는 영(0) 값을 가진 형상은 해당 형상의 예에 문제가 있을 수 있다는 시각적 지표로 백분율을 빨간색으로 표시함. 백분율은 해당 기능에 대한 결측값이 있거나 값이 0인 예제의 백분율
pickup_census_tract 값이 있는 예는 없음 --> 제거 필요
차트 위에 있는 "expand" 버튼을 클릭하면 분포를 크게 볼 수 있음
"log" 버튼을 클릭하면 로그 스케일 처리를 한 데이터 분포를 볼 수 있음
"Chart to show"(차트 표시) 메뉴에서 "quantiles"(정량화)를 선택하고 마커 위로 마우스를 가져가면 정량화 백분율이 표시됨
원본
로그 스케일링
Quantiles 버튼 클릭
tfdv.infer_schema
로 스키마를 추론한 후, tfdv.display_shcema
로 출력schema = tfdv.infer_schema(statistics=train_stats)
tfdv.display_schema(schema=schema)
Schema
도메인에 대한 허용하능한 목록
# Compute stats for evaluation data
eval_stats = tfdv.generate_statistics_from_csv(data_location=EVAL_DATA)
# Compare evaluation data with training data
tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats,
lhs_name='EVAL_DATASET', rhs_name='TRAIN_DATASET')
tfdv.validate_statistics
# Relax the minimum fraction of values that must come from the domain for feature company.
company = tfdv.get_feature(schema, 'company')
company.distribution_constraints.min_domain_mass = 0.9
# Add new value to the domain of feature payment_type.
payment_type_domain = tfdv.get_domain(schema, 'payment_type')
payment_type_domain.value.append('Prcard')
# Validate eval stats after updating the schema
updated_anomalies = tfdv.validate_statistics(eval_stats, schema)
tfdv.display_anomalies(updated_anomalies)
serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA)
serving_anomalies = tfdv.validate_statistics(serving_stats, schema)
tfdv.display_anomalies(serving_anomalies)
options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)
serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA, stats_options=options)
serving_anomalies = tfdv.validate_statistics(serving_stats, schema)
tfdv.display_anomalies(serving_anomalies)
# All features are by default in both TRAINING and SERVING environments.
schema.default_environment.append('TRAINING')
schema.default_environment.append('SERVING')
# Specify that 'tips' feature is not in SERVING environment.
tfdv.get_feature(schema, 'tips').not_in_environment.append('SERVING')
serving_anomalies_with_env = tfdv.validate_statistics(
serving_stats, schema, environment='SERVING')
tfdv.display_anomalies(serving_anomalies_with_env)
# Add skew comparator for 'payment_type' feature.
payment_type = tfdv.get_feature(schema, 'payment_type')
payment_type.skew_comparator.infinity_norm.threshold = 0.01
# Add drift comparator for 'company' feature.
company=tfdv.get_feature(schema, 'company')
company.drift_comparator.infinity_norm.threshold = 0.001
skew_anomalies = tfdv.validate_statistics(train_stats, schema,
previous_statistics=eval_stats,
serving_statistics=serving_stats)
tfdv.display_anomalies(skew_anomalies)
from tensorflow.python.lib.io import file_io
from google.protobuf import text_format
file_io.recursive_create_dir(OUTPUT_DIR)
schema_file = os.path.join(OUTPUT_DIR, 'schema.pbtxt')
tfdv.write_schema_text(schema, schema_file)
!cat {schema_file}