Syeonny의 블로그

[빅데이터분석기사] 2, 3 유형 정리본 본문

이것저것

[빅데이터분석기사] 2, 3 유형 정리본

syeonny 2024. 11. 29. 16:15

 
빅데이터분석기사 실기 
 
2유형

 
회귀 또는 분류문제로 무조건 랜덤포레스트 모델링 <<< 중요 
 

분류
import pandas as pd
import numpy as np 
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score

train.info()
train.isnull().sum()
train.describe()

# 전처리 
y = train['y']
x = train.drop({'변수1','y'}, axis=1) # 아이디 값이나 너무 많은 nunique값 
test = test.drop({'변수1','y'}, axis=1)

x = pd.get_dummies(x)
test = pd.get_dummies(test)
test = test.reindex(columns=x.columns, fill_value=0) # train 에 열 맞추기 

# x y 분리
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
x_train.shape, x_test.shape

# 모델링 
rf = RandomForestClassifier(random_state=42)
rf.fit(x_train, y_train)

y_pred = rf.predict(x_test)
print(classification_report(y_test, y_pred))
print(roc_auc_score(y_test, y_pred))

test_pred = rf.predict(test)

pd.DataFrame({'pred':test_pred}).to_csv('수험번호.csv', index=False)
new = pd.read_csv('수험번호.csv')
new.head()

 
 

회귀
import pandas as pd
import numpy as np 
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score

train.info()
train.isnull().sum()
train.describe()

# 전처리 
y = train['y']
x = train.drop({'변수1','y'}, axis=1) # 아이디 값이나 너무 많은 nunique값 
test = test.drop({'변수1','y'}, axis=1)

x = pd.get_dummies(x)
test = pd.get_dummies(test)
test = test.reindex(columns=x.columns, fill_value=0) # train 에 열 맞추기 

# x y 분리
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
x_train.shape, x_test.shape

# 모델링 
rf = RandomForestRegressor(random_state=42)
rf.fit(x_train, y_train)

y_pred = rf.predict(x_test)
print('rmse: ', np.sqrt(mean_squared_error(y_test, y_pred)))
print('r2 score: ', r2_score(y_test, y_pred))

test_pred = rf.predict(test)

pd.DataFrame({'pred':test_pred}).to_csv('수험번호.csv', index=False)
new = pd.read_csv('수험번호.csv')
new.head()

 
 


하이퍼파라미터튜닝 안해도 된다고 통용된듯 ..? 
코드 돌리는 시간이 1분으로 정해져 있어서 그런듯하다. 
진짜 그냥 베이스라인! 
 
 
 

3유형 
 

나올 수 있는 부분은 크게 
선형회귀 / 로지스틱회귀 / t test / chi2
 

선형회귀 
import statsmodel.api as sm

# x y 지정 
x
y 
x = x.add_constant(x) # 상수항 지정 필수

# modeling 
model = sm.OLS(y, x).fit()
model.summary() 

model.params 
model.pvalues
model.tvalues
model.conf_int()
model.mse_reid
model.fittedvalues
model.resid 

model.predict([1, 숫자, 숫자]) # 예측값 반환
new_data = np.array([1, 숫자, 숫자]).reshape(-1, 1)
pred = model.get_prediction(new_data) 
pred.summary_frame(alpha=0.05) # 신뢰구간

 
 

로지스틱회귀
import statsmodels.api as sm

# x y
x 
y 
x = x.add_constant(x)

# modeling
model = sm.Logit(y, x).fit()
model.summary()

# 오즈비
odds = np.exp(model.params['변수'])

# 편차 = 잔차이탈도 
model = sm.GLM(y, x, family=sm.families.Binomial()).fit()
model.summary()

deviance 잔차 이탈도 
residual 잔차 자유도
model 모델 자유도

 
 

t
from scipy.stats import t
import pandas as pd 
import numpy as np 

mean = df.mean()
std = df.std()
n = df-1 # 자유도, 변수 갯수 -1 값으로 정수 지정 

t_value = t.ppf(1-alpha/2, n)

# 신뢰구간
lower = mean - (t_value * std / np.sqrt(n))
upper = mean + (t_value * std / np.sqrt(n))

 
 

카이제곱검정 - 독립성
from scipy.stats import chi2_contigency

crosstab = pd.crosstab(df[], df[])
chi, p, dof, exp = chi2_contigency(crosstab)

# dof 자유도 
# exp 예측

 
 

카이제곱검정 - 적합도 
from scipy.stats import chisquare
chi2, p = chisquare(df[], df[])

 
 

anova
from scipy.stats import f_oneway
f, p = f_oneway(df[], df[], df[])

'이것저것' 카테고리의 다른 글

jupyter notebook 번외  (0) 2024.09.05
하반기 마음가짐  (1) 2024.08.19
[빅데이터분석기사] 필기  (0) 2024.05.04
[정보처리기사 필기] 정보처리기사 필기  (1) 2024.03.26
[사조사 2급] 실기 후기  (0) 2023.11.28