빅분기 실기시험 3유형 파이썬 풀이 가이드
| topics | 900-자격증 100-데이터분석 & AI |
| 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
# <span id="데이터-로드-예-당뇨병-예측"></span>데이터 로드 (예: 당뇨병 예측)
# <span id="df-pdread_csvdiabetescsv"></span>df = pd.read_csv('diabetes.csv')
# <span id="x-dfa-hrefpagesage2c-bmi2c-glucosehtml-classwiki-linkage-bmi-glucosea-독립변수"></span>X = df<a href="/pages/'age'%2C-'bmi'%2C-'glucose'.html" class="wiki-link">'age', 'bmi', 'glucose'</a> # 독립변수
# <span id="y-dfdiabetes-종속변수-0-비당뇨-1-당뇨"></span>y = df['diabetes'] # 종속변수 (0: 비당뇨, 1: 당뇨)
# <span id="샘플-데이터"></span>샘플 데이터
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])
# <span id="모델-학습"></span>모델 학습
model = LogisticRegression()
model.fit(X, y)
주요 출제 포인트별 해결법
1) p-value와 유의성 검정^1
# <span id="statsmodels로-p-value-확인"></span>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
# <span id="회귀계수에서-odds-ratio-계산-오즈비-승산비라캄"></span>회귀계수에서 odds ratio 계산 오즈비 승산비라캄
coefficients = result.params[1:] # 상수항 제외
odds_ratios = np.exp(coefficients)
print("Odds Ratios:", odds_ratios)
# <span id="해석-odds-ratio가-1보다-크면-해당-변수-증가-시-발생-확률-증가"></span>해석: odds ratio가 1보다 크면 해당 변수 증가 시 발생 확률 증가
3) 특정 임계값 초과 데이터 수
# <span id="예측-확률-계산"></span>예측 확률 계산
probabilities = model.predict_proba(X)[:, 1] # 클래스 1의 확률
print("예측 확률:", probabilities)
# <span id="임계값-03-초과-데이터-수"></span>임계값 0.3 초과 데이터 수
threshold = 0.3
count_above_threshold = sum(probabilities > threshold)
print(f"임계값 {threshold} 초과 데이터 수: {count_above_threshold}")
4) 개별 데이터 예측값 계산
# <span id="새로운-데이터-예측"></span>새로운 데이터 예측
new_data = np.array(<a href="/pages/52%2C-27.5%2C-125.html" class="wiki-link">52, 27.5, 125</a>)
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
# <span id="샘플-데이터-자동차-연비-예측"></span>샘플 데이터 (자동차 연비 예측)
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]) # 연비
# <span id="모델-학습"></span>모델 학습
model = LinearRegression()
model.fit(X, y)
주요 출제 포인트별 해결법
1) 회귀계수와 p-value^4
# <span id="statsmodels로-상세-통계-확인"></span>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
# <span id="r-계산"></span>R² 계산
y_pred = model.predict(X)
r2 = r2_score(y, y_pred)
print(f"R² (결정계수): {r2:.4f}")
# <span id="조정된-r-계산"></span>조정된 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) 상관계수 계산
# <span id="독립변수-간-상관계수"></span>독립변수 간 상관계수
correlation_matrix = np.corrcoef(X.T)
print("독립변수 간 상관계수:")
print(correlation_matrix)
# <span id="종속변수와-독립변수-간-상관계수"></span>종속변수와 독립변수 간 상관계수
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
# <span id="새로운-데이터로-예측"></span>새로운 데이터로 예측
new_data = np.array(<a href="/pages/2300%2C-165%2C-4.html" class="wiki-link">2300, 165, 4</a>)
prediction = model.predict(new_data)
print(f"예측값: {prediction[^0]:.2f}")
# <span id="회귀식-출력"></span>회귀식 출력
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
# <span id="교차표-데이터-성별-vs-선호도"></span>교차표 데이터 (성별 vs 선호도)
contingency_table = np.array([[30, 20], [10, 40]]) # [[남성_A, 남성_B], [여성_A, 여성_B]]
print("교차표:")
print(contingency_table)
주요 출제 포인트별 해결법
1) 기대빈도 계산^6
# <span id="카이제곱-검정-실행"></span>카이제곱 검정 실행
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}")
# <span id="유의수준-005에서-가설-검정"></span>유의수준 0.05에서 가설 검정
alpha = 0.05
if p_value < alpha:
print("귀무가설 기각 - 두 변수는 독립적이지 않음")
else:
print("귀무가설 채택 - 두 변수는 독립적임")
3) 임계값을 이용한 검정^7
# <span id="임계값-계산"></span>임계값 계산
critical_value = chi2.ppf(1-alpha, dof)
print(f"임계값 (α=0.05): {critical_value:.4f}")
if chi2_stat > critical_value:
print("카이제곱 통계량 > 임계값 → 귀무가설 기각")
else:
print("카이제곱 통계량 ≤ 임계값 → 귀무가설 채택")
4) 적합성 검정
# <span id="적합성-검정-예시-주사위가-공정한지-검정"></span>적합성 검정 예시 (주사위가 공정한지 검정)
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}")
실전 문제 해결 패턴
전체 과정 통합 코드
# <span id="1단계-데이터-준비-및-eda"></span>1단계: 데이터 준비 및 EDA
df = pd.read_csv('data.csv')
print(df.describe())
print(df.isnull().sum())
# <span id="2단계-모델-학습"></span>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)
# <span id="3단계-결과-해석-및-답안-도출"></span>3단계: 결과 해석 및 답안 도출
# <span id="--p-value-확인-유의성-판단"></span>- p-value 확인 → 유의성 판단
# <span id="--회귀계수odds-ratio-변수-영향력"></span>- 회귀계수/odds ratio → 변수 영향력
# <span id="--예측값-계산-개별-케이스-답안"></span>- 예측값 계산 → 개별 케이스 답안
# <span id="--성능-지표-모델-평가"></span>- 성능 지표 → 모델 평가
이러한 패턴으로 빅분기 실기시험의 3유형 문제들을 체계적으로 해결할 수 있습니다. 각 단계별로 필요한 통계량과 해석 방법을 숙지하는 것이 핵심입니다.
⁂