창의설계

14장 14주차 · 통합 코드 워크스루

안내 예제 · 전체 파이프라인 미리보기

안내 예제 · 5단계 파이프라인 미리보기
import numpy as np

# ===== Step 1: 데이터 생성 =====
rng = np.random.default_rng(42)
n = 24
raw_time = np.arange(n)
raw_temp = 22.0 + rng.normal(scale=1.5, size=n)

# 불량 데이터 주입: 정상 범위를 벗어나므로 제거 대상
raw_temp[3]  = -5.0   # 음수 오류
raw_temp[17] = 80.0   # 극단값 오류

# 유효하지만 낮거나 높은 값: 분류 결과를 보기 위한 정상 범위 데이터
raw_temp[8] = 17.5
raw_temp[12] = 27.2

print(f"원본 데이터 (n={n}):")
print("  처음 6개:", np.round(raw_temp[:6], 2))
print(f"  불량 포함: index 3={raw_temp[3]}, index 17={raw_temp[17]}")
print(f"  유효한 낮음/높음: index 8={raw_temp[8]}, index 12={raw_temp[12]}")

# ===== Step 2: 처리 함수 =====
def make_valid_mask(data, low=0.0, high=50.0):
    return (data >= low) & (data <= high)

def filter_valid(data, valid_mask):
    return data[valid_mask]

def compute_stats(data):
    return {
        "mean": round(float(data.mean()), 2),
        "std":  round(float(data.std()),  2),
        "min":  round(float(data.min()),  2),
        "max":  round(float(data.max()),  2),
    }

def classify_temp(temp_c):
    if temp_c < 18:
        return "cold"
    elif temp_c <= 26:
        return "normal"
    else:
        return "hot"

# ===== Step 3: 검증 =====
def checked_mean(data):
    if len(data) == 0:
        print("경고: 정상 범위 데이터가 없습니다")
        return None
    return float(data.mean())

valid_mask = make_valid_mask(raw_temp)
clean_temp = filter_valid(raw_temp, valid_mask)
clean_time = raw_time[valid_mask]

assert len(clean_temp) > 0
assert len(clean_time) == len(clean_temp)
print(f"\n정제 후: {len(raw_temp)}개 → {len(clean_temp)}개 (제거: {len(raw_temp)-len(clean_temp)}개)")
print("남은 측정 인덱스:", clean_time.tolist())

# ===== Step 4: 출력 =====
stats = compute_stats(clean_temp)
print("\n요약 통계:")
print(f"  {'항목':<6} {'값':>7}")
print("  " + "-" * 14)
for k, v in stats.items():
    print(f"  {k:<6} {v:>7.2f}")

# 각 측정값 분류
labels = [classify_temp(v) for v in clean_temp]
label_counts = {}
for lb in labels:
    label_counts[lb] = label_counts.get(lb, 0) + 1
print("\n분류 결과:", label_counts)

m = checked_mean(clean_temp)
print(f"\n해석: 정제된 {len(clean_temp)}개 측정값의 평균 온도는 {m:.2f}°C이다.")

# ===== Step 5: 시각화 설계안 =====
plot_spec = {
    "title": "Sensor Temperature over 24 Readings",
    "x_label": "Measurement Index (-)",
    "y_label": "Temperature (°C)",
    "chart_type": "line+markers",
    "x": clean_time.tolist(),
    "y": [round(float(v), 2) for v in clean_temp],
}
print("\n시각화 설계안 self-check:")
print("  labels_ready:", all([plot_spec["title"], plot_spec["x_label"], plot_spec["y_label"]]))
print("  same_length:", len(plot_spec["x"]) == len(plot_spec["y"]))
print("  point_count:", len(plot_spec["x"]))
print("\n전체 파이프라인 흐름 확인")