빅분기 실기시험 3유형 파이썬 풀이 가이드

topics
types
contexts 자격증
tags
#빅분기 #파이썬 #실기시험 #가이드

빅분기 실기시험 3유형 파이썬 풀이 가이드

  • 실제 시험에서는 모델링 후 주어진 개별 데이터에 대해 예측값을 구하는 문제가 자주 출제됨

  • glm

    • 잔차 이탈도, deviance 등 GLM에서만 제공되는 지표를 물을 때
    • 시험 문제에서 "일반화 선형모형" 또는 "GLM"이라는 단어가 직접적으로 언급될 때

빅분기 실기시험 3유형 파이썬 풀이 가이드

빅분기 실기시험에서 자주 출제되는 회귀분석과 가설검정 문제들을 파이썬으로 해결하는 방법을 상세히 설명하겠습니다.


1. 로지스틱 회귀분석

기본 모델링

import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
import scipy.stats as stats

# 데이터 로드 (예: 당뇨병 예측)
# df = pd.read_csv('diabetes.csv')
# X = df<span class="dead-link" title="페이지 없음">&#039;age&#039;, &#039;bmi&#039;, &#039;glucose&#039;</span>  # 독립변수
# y = df['diabetes']  # 종속변수 (0: 비당뇨, 1: 당뇨)

# 샘플 데이터
X = np.array([[45, 25.3, 120], [60, 30.1, 140], [35, 22.5, 100], 
              [50, 28.7, 135], [55, 32.1, 150], [40, 24.8, 110]])
y = np.array([0, 1, 0, 1, 1, 0])

# 모델 학습
model = LogisticRegression()
model.fit(X, y)

주요 출제 포인트별 해결법

1) p-value와 유의성 검정^1

# statsmodels로 p-value 확인
import statsmodels.api as sm

X_with_const = sm.add_constant(X)  # 상수항 추가
logit_model = sm.Logit(y, X_with_const)
result = logit_model.fit()

print("회귀계수 p-value:")
print(result.pvalues)
print("\n유의하지 않은 변수 (p>0.05):")
print(result.pvalues[result.pvalues > 0.05])

2) Odds Ratio 계산^1

# 회귀계수에서 odds ratio 계산 오즈비 승산비라캄
coefficients = result.params[1:]  # 상수항 제외
odds_ratios = np.exp(coefficients)
print("Odds Ratios:", odds_ratios)

# 해석: odds ratio가 1보다 크면 해당 변수 증가 시 발생 확률 증가

3) 특정 임계값 초과 데이터 수

# 예측 확률 계산
probabilities = model.predict_proba(X)[:, 1]  # 클래스 1의 확률
print("예측 확률:", probabilities)

# 임계값 0.3 초과 데이터 수
threshold = 0.3
count_above_threshold = sum(probabilities > threshold)
print(f"임계값 {threshold} 초과 데이터 수: {count_above_threshold}")

4) 개별 데이터 예측값 계산

# 새로운 데이터 예측
new_data = np.array(<span class="dead-link" title="페이지 없음">52, 27.5, 125</span>)
prediction_prob = model.predict_proba(new_data)[0, 1]
prediction_class = model.predict(new_data)[^0]

print(f"예측 확률: {prediction_prob:.4f}")
print(f"예측 클래스: {prediction_class}")

2. 다중선형회귀분석

기본 모델링

from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
import seaborn as sns

# 샘플 데이터 (자동차 연비 예측)
X = np.array([[2000, 150, 4], [2500, 180, 6], [1800, 130, 4], 
              [3000, 200, 8], [2200, 160, 4], [2800, 190, 6]])
y = np.array([25, 20, 28, 15, 24, 18])  # 연비

# 모델 학습
model = LinearRegression()
model.fit(X, y)

주요 출제 포인트별 해결법

1) 회귀계수와 p-value^4

# statsmodels로 상세 통계 확인
X_with_const = sm.add_constant(X)
ols_model = sm.OLS(y, X_with_const)
result = ols_model.fit()

print("회귀분석 결과:")
print(result.summary())
print("\n회귀계수:", result.params)
print("p-values:", result.pvalues)

2) R² (결정계수) 계산^4

# R² 계산
y_pred = model.predict(X)
r2 = r2_score(y, y_pred)
print(f"R² (결정계수): {r2:.4f}")

# 조정된 R² 계산
n = len(y)  # 샘플 수
p = X.shape[^1]  # 독립변수 개수
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
print(f"조정된 R²: {adjusted_r2:.4f}")

3) 상관계수 계산

# 독립변수 간 상관계수
correlation_matrix = np.corrcoef(X.T)
print("독립변수 간 상관계수:")
print(correlation_matrix)

# 종속변수와 독립변수 간 상관계수
for i in range(X.shape[^1]):
    corr = np.corrcoef(X[:, i], y)[0, 1]
    print(f"X{i+1}과 Y의 상관계수: {corr:.4f}")

4) 예측값 계산^4

# 새로운 데이터로 예측
new_data = np.array(<span class="dead-link" title="페이지 없음">2300, 165, 4</span>)
prediction = model.predict(new_data)
print(f"예측값: {prediction[^0]:.2f}")

# 회귀식 출력
intercept = model.intercept_
coefficients = model.coef_
print(f"회귀식: Y = {intercept:.2f} + {coefficients[^0]:.4f}*X1 + {coefficients[^1]:.4f}*X2 + {coefficients[^2]:.4f}*X3")

3. 카이제곱 검정

기본 검정

from scipy.stats import chi2_contingency, chi2

# 교차표 데이터 (성별 vs 선호도)
contingency_table = np.array([[30, 20], [10, 40]])  # [[남성_A, 남성_B], [여성_A, 여성_B]]
print("교차표:")
print(contingency_table)

주요 출제 포인트별 해결법

1) 기대빈도 계산^6

# 카이제곱 검정 실행
chi2_stat, p_value, dof, expected = chi2_contingency(contingency_table)

print("기대빈도:")
print(expected)

2) 카이제곱 통계량과 p-value^6

print(f"카이제곱 통계량: {chi2_stat:.4f}")
print(f"자유도: {dof}")
print(f"p-value: {p_value:.4f}")

# 유의수준 0.05에서 가설 검정
alpha = 0.05
if p_value < alpha:
    print("귀무가설 기각 - 두 변수는 독립적이지 않음")
else:
    print("귀무가설 채택 - 두 변수는 독립적임")

3) 임계값을 이용한 검정^7

# 임계값 계산
critical_value = chi2.ppf(1-alpha, dof)
print(f"임계값 (α=0.05): {critical_value:.4f}")

if chi2_stat > critical_value:
    print("카이제곱 통계량 > 임계값 → 귀무가설 기각")
else:
    print("카이제곱 통계량 ≤ 임계값 → 귀무가설 채택")

4) 적합성 검정

# 적합성 검정 예시 (주사위가 공정한지 검정)
observed = [18, 22, 16, 25, 12, 17]  # 관측빈도
expected_uniform = [20, 20, 20, 20, 20, 20]  # 기대빈도 (균등분포)

chi2_stat_fit = sum((obs - exp)**2 / exp for obs, exp in zip(observed, expected_uniform))
dof_fit = len(observed) - 1
p_value_fit = 1 - chi2.cdf(chi2_stat_fit, dof_fit)

print(f"적합성 검정 - 카이제곱 통계량: {chi2_stat_fit:.4f}")
print(f"적합성 검정 - p-value: {p_value_fit:.4f}")

실전 문제 해결 패턴

전체 과정 통합 코드

# 1단계: 데이터 준비 및 EDA
df = pd.read_csv('data.csv')
print(df.describe())
print(df.isnull().sum())

# 2단계: 모델 학습
if problem_type == 'logistic':
    model = LogisticRegression()
    model.fit(X, y)
    
elif problem_type == 'linear':
    model = LinearRegression()
    model.fit(X, y)
    
elif problem_type == 'chi_square':
    chi2_stat, p_value, dof, expected = chi2_contingency(contingency_table)

# 3단계: 결과 해석 및 답안 도출
# - p-value 확인 → 유의성 판단
# - 회귀계수/odds ratio → 변수 영향력
# - 예측값 계산 → 개별 케이스 답안
# - 성능 지표 → 모델 평가

이러한 패턴으로 빅분기 실기시험의 3유형 문제들을 체계적으로 해결할 수 있습니다. 각 단계별로 필요한 통계량과 해석 방법을 숙지하는 것이 핵심입니다.