제2유형에서 시작전에 train.info() test.info()하잖아요. 이후에 타입유형(int / float /object) 을 확인 한 후에 어떤 부분을 바꿔줘야하는건가요? 어차피 원핫인코딩 pd.get_dummies와 train, test = train.align(test, join ='left', axis=1, fill_value=0) 해주면 어느정도 형식이 정리되는거 아닌가요? 별도로 처리해줘야 할 게있는지 문의드립니다.
import pandas as pd from statsmodels.formula.api import logit from sklearn.metrics import accuracy_score # 1. 로지스틱 회귀 모델 적합 (test로 직접 학습 — 실전에서는 train 사용 권장) model = logit('target ~ age + sex + cp + trestbps + chol + fbs + restecg + thalach + exang + oldpeak + slope + ca + thal', data=test).fit() # 2. 예측 수행 (test 그대로 사용) pred_probs = model.predict(test) pred = (pred_probs > 0.5).astype(int) # 3. 정확도 → 오류율 계산 error_rate = 1 - accuracy_score(test['target'], pred) print(f'오류율: {error_rate:.4f}') Optimization terminated successfully. Current function value: 0.310865 Iterations 8 오류율: 0.1034 # model = logit('target~age+sex+cp+trestbps+chol+fbs+restecg+thalach+exang+oldpeak+slope+ca+thal',test).fit() import statsmodels.api as sm X2 = test.drop(columns = ['target']) X2 = sm.add_constant(X2) pred = model.predict(X2) pred = (pred>0.5).astype(int) pred from sklearn.metrics import accuracy_score 1-accuracy_score(test['target'],pred) 0.1954022988505747 문제는 test데이터의 독립변수로 target 예측 후 오류율을 구하여라 입니다. 근데 로짓이랑 sm이랑 차이가 좀 심하게 나는데 원래 로지스틱 회귀분석할때 sm으로 해야하나요..?
아래와 같이 train과 test를 합해서 스케일링과 인코딩을 모두 진행할 경우, 각각 진행하는 것과 차이가 있나요? 그리고 스케일링과 인코딩에 추천하는 함수가 있으신가요? df= pd.concat([x_train, x_test], axis=0) num = df.select _dtypes(exclude='object').columns from sklearn.preprocessing import RobustScaler scaler = RobustScaler() df[num] = scaler.fit _transform(df[num]) objs = df.select _dtypes(include='object').columns from sklearn.preprocessing import LabelEncoder for obj in objs : encoder = LabelEncoder() df[obj] = encoder.fit _transform(df[obj]) x_train2 = df[:len(x_train)] x_test2 = df[len(x_train):]
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 아래처럼 코드 짜도 되는지? m = df.loc[2000] > df.loc[2000].mean() print(sum(m))
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 실기체험하는대서 아래처럼 쓰고 실행했더니 import pandas as pd df = pd.DataFrame({ '키': [150, 160, 170, 175, 165, 155, 172, 168, 174, 158, 162, 173, 156, 159, 167, 163, 171, 169, 176, 161], '몸무게': [74, 50, 70, 64, 56, 48, 68, 60, 65, 52, 54, 67, 49, 51, 58, 55, 69, 61, 66, 53] }) from statsmodels.formula.api import ols model = ols('키 ~ 몸무게', data=df).fit() print(model.summary()) 아래처럼 나오는데, 왜 그런건가요? Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 아래 예시로 적혀있는 코드들도 시험 때 주어지는지 아니면 암기해야하는지 문의드립니다. from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score # 정확도 print(accuracy_score(y_test, pred)) # 정밀도 print(precision_score(y_test, pred)) # 재현율 (민감도) print(recall_score(y_test, pred)) # F1 print(f1_score(y_test , pred)) # roc-auc print(roc_auc_score(y_test, pred_proba))
train_target=train.pop('TotalCharges') # 3. 분할 from sklearn.model_selection import train_test_split tr_x, val_x, tr_y, val_y =train_test_split(train,train_target, test_size=0.2, random_state=0) # 3. 분할 from sklearn.model_selection import train_test_split tr_x, val_x, tr_y, val_y =train_test_split(train,train['TotalCharges'], test_size=0.2, random_state=0) tr_x.head(), tr_y.head(), val_x.head(), val_y.head() 위 두가지 경우로 모델링 하여 MAE값을 산출했습니다. 아래꺼는 Linear Regression : 0.0000000000012394228 RandomForest Regressor : 1.9100924757282742306 XGB Regressor : 10.5623083675717790442 위에꺼는 Linear Regression : 914.6725879047844500747 RandomForest Regressor : 941.4584990860494144727 XGB Regressor : 1033.3863728784358499979 왜 이렇게 다른 결론이 나올까요? 해당 내용만 변경하고, 나머지 코드는 모두 동일한 상태에서 구동했습니다.