adp 실기/기출문제
[Python] 데이터 에듀 ADP 실기 모의고사 3회 1번 파이썬 ver. (통계 분석)
ㅅ ㅜ ㅔ ㅇ
2022. 9. 5. 21:36
728x90
사용 데이터 : Carseat.csv
Carseats 데이터는 자동차 좌석에 대한 판매정보이며, 변수의 설명은 아래와 같다.
변수 | 데이터 형태 | 설명 |
Sales | 수치형 | 각 지역의 천 달러 단위 매출 |
ComPrice | 수치형 | 각 위치에서 경쟁업체가 부과하는 가격 |
Income | 수치형 | 지역 소득 수준 |
Advertising | 수치형 | 각 지역의 광고 예산 |
Population | 수치형 | 지역의 인구(단위 : 1000) |
Price | 수치형 | 자동차 좌석의 가격 |
ShelveLoc | 범주형 | 보관 장소의 품질 |
Age | 수치형 | 인구의 연령대 |
Education | 수치형 | 지역의 교육 수준 |
Urban | 범주형 | 도시인지 혹은 아닌지의 여부 |
US | 범주형 | 미국인지 혹은 아닌 지의 여부 |
1. Urban 변수에 따른 Sales의 차이가 있는지를 통계적으로 검증하기 위한 통계분석을 수행하고, 결과를 해석하시오. (데이터는 정규성을 만족한다고 가정하고 유의수준 0.05하에서 검정)
import pandas as pd
import numpy as np
df = pd.read_csv('../data/Carseats.csv')
df.head()
- 귀무가설 : Urban 변수에 따른 Sales의 평균에는 차이가 없다.
- 대립가설 : 차이가 존재한다.
df.Urban.value_counts()
import scipy.stats as stats
y_data = df[df['Urban'] == 'Yes']['Sales']
n_data = df[df['Urban'] == 'No']['Sales']
stats.f_oneway(y_data, n_data)
# F_onewayResult(statistic=0.09465065557659712, pvalue=0.7585069603942085)
p-value가 0.05보다 크기 때문에 귀무가설을 채택하여 두 집단의 평균의 차이는 없다고 할 수 있다.
2. Sales변수와 Comprice, Income, Advertising, Population, Price, Age, Education 변수들 간에 피어슨 상관계수를 이용한 상관관계 분석을 수행하고 이를 해석하시오.
import seaborn as sns
df_corr = df.corr(method='pearson')
sns.heatmap(df_corr, cmap='RdBu_r', annot=True)
Sales 변수와 유의한 상관관계를 가진 변수는 없는 것으로 판단함
3. 종속변수를 Sales, 독립변수를 Comprice, Income, Adgertising, Population, Price, Age, Education으로 설정하고, 후진제거법을 활용하여 회귀분석을 실시하고 추정된 회귀식을 작성하시오.
import statsmodels.formula.api as smf
# 모든 변수 선택
indi_var_list = ["CompPrice", "Income", "Advertising", "Population", "Price", "Age", "Education"]
indi_var_formula = "+".join(indi_var_list)
model = smf.ols("Sales ~ "+indi_var_formula, df)
model.fit().summary()
수정된 R-squared값은 0.533, p-value값이 0.05보다 작아 유의하다고 판단
#후진제거법
def backward_elimination(df, dep_var, ind_vars, select_criteria = "AIC", return_case = "s"):
alpha = 0.05
selected_vars = ind_vars.copy()
eliminated_vars = []
done = False
while done is False:
#step1 : 변수 하나씩을 제외한 n개의 모델을 만들어낸다. (n : 변수 갯수)
model_result_list = []
for var in selected_vars:
var_list = ind_vars.copy()
if len(eliminated_vars)>0:
for el_var in eliminated_vars:
var_list.remove(el_var)
var_list.remove(var)
this_ind_vars_str = " + ".join(var_list)
this_model_fit = smf.ols(dep_var+" ~ "+this_ind_vars_str, data=df).fit()
this_result = {
"selected var" : this_ind_vars_str,
"eliminated var" : var,
"AIC" : this_model_fit.aic,
"rsquared_adj" : this_model_fit.rsquared_adj
}
model_result_list.append(this_result)
result = pd.DataFrame(model_result_list)
#step2 : n개 모델들 중 가장 좋은 결과를 보인 모델을 선택하고, 제외 후보 변수를 찾는다.
ascending = True
if select_criteria == "rsquared_adj":
ascending = False
result.sort_values(by=select_criteria, ascending=ascending, inplace=True)
candidate_var = result.iloc[0, [1]].values[0]
#step3 : 제외 후보 변수로 fitting하여 p-value를 알아보고 유의하다면 종료한다.
candidate_model_fit = smf.ols(dep_var+" ~ "+candidate_var, data=df).fit()
if candidate_model_fit.pvalues[candidate_var] > alpha: #유의하지 않다면
eliminated_vars.append(candidate_var) #제거확정
selected_vars.remove(candidate_var)
print("{} 변수를 제거합니다.".format(candidate_var))
else: #유의하다면 종료한다
done = True
if return_case == "s":
print("후보 독립변수들 : {}".format(ind_vars))
print("후진제거법에 의해 선택된 최종 변수들 : {}".format(selected_vars))
return selected_vars
elif return_case == "e":
return eliminated_vars
indi_var_list = ["CompPrice", "Income", "Advertising", "Population", "Price", "Age", "Education"]
selected_vars = backward_elimination(df, "Sales", indi_var_list, "AIC")
#후진 제거법에 의해 선택된 변수만으로 회귀분석을 해본다.
indi_var_formula = "+".join(selected_vars)
model = smf.ols("Sales ~ "+indi_var_formula, df)
model.fit().summary()
4. 앞서 생성한 회귀모델에 대해 해석하시오.
최종 선택된 변수는 Comprice, Income, Advertising, Price, Age
Sales = 7.1092 + 0.0939 * Comprice + 0.0131 * Income + 0.1306 * Advertising - 0.0925 * Price - 0.0450 * Age
R-sqaured값은 0.54로 모든 변수를 선택했을 때와 큰 차이점은 없음
728x90