import pandas as pd train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") y_test = pd.read_csv("y_test.csv") from sklearn.preprocessing import LabelEncoder cols = train.select_dtypes(include = 'object').columns for col in cols: le = LabelEncoder() train[col] = le.fit_transform(train[col]) test[col] = le.transform(test[col]) train = train.drop('CLIENTNUM',axis=1) test_id = test.pop('CLIENTNUM') from sklearn.model_selection import train_test_split X_tr,X_val,y_tr,y_val = train_test_split(train, train['Attrition_Flag'], test_size = 0.2, random_state = 2022) from xgboost import XGBClassifier from sklearn.metrics import roc_auc_score,accuracy_score,f1_score,precision_score, recall_score model = XGBClassifier(random_state=2022) model.fit(X_tr,y_tr) pred = model.predict(X_val) pred print(accuracy_score(y_val,pred)) print(f1_score(y_val,pred)) print(precision_score(y_val,pred)) print(recall_score(y_val,pred)) pred = model.predict(X_val) pred pred = model.predict_proba(test) pred (여기 과정에서 오류가 생깁니다 ㅠ) ValueError: Feature shape mismatch, expected: 20, got 19 이렇게 오류가 생기는데 뭐가 잘못된걸까요?ㅠㅠ
ttest_rel의 alternative 부분 scipy 공식문서를 보면 Defines the alternative hypothesis. The following options are available (default is ‘two-sided’): ‘two-sided’: the means of the distributions underlying the samples are unequal. ‘less’: the mean of the distribution underlying the first sample is less than the mean of the distribution underlying the second sample. ‘greater’: the mean of the distribution underlying the first sample is greater than the mean of the distribution underlying the second sample. 이렇게 되어 있는데요. a와 b에 넣는 위치에 따라 달라진다고 이해하면 될까요? 이게 무조건 고정은 아닌 것 같아서요.. 예를 들어 a에 before, b에 after을 넣게 되면 a에 있는 before 혈압이 더 크니까 'greater'를 써주고 a에 after, b에 before을 넣게 되면 a에 있는 after 혈압이 더 작으니까 'less'를 써주는 게 맞는건가요? 강의에서는 대립가설을 기준으로 뭐 하라고 설명 해주셨는데 잘 이해가 안 가서요.. 자세하게 설명해주실 수 있을까요?
안녕하세요! 강의 잘 듣고 있습니다! i. 3회 기출유형(작업형2)의 <데이터 전처리 및 피처엔지니어링 - 스케일링> 부분에서 ii. 2회 기출 강의에서는 for col in cols: i_train[cols] = scaler.fit_transform(i_train[cols]) i_test[cols] = scaler.transform(i_test[cols]) i_train.head() 요렇게 for문을 쓰셔서 transform을 하셨는데요 iii. 3회 기출에서는 i_train[cols] = scaler.fit_transform(i_train[cols]) i_test[cols] = scaler.transform(i_test[cols]) i_train.head() 요렇게 for문을 안쓰셨더라구요. iiii. 혹시 for문을 써야하는 조건과 쓰지 않아도 되는 조건이 따로 있는건가요?
import pandas as pd train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") #print(train.shape) cols = ['name','host_name', 'last_review', 'host_id'] for col in cols: train = train.drop(col, axis =1) test = test.drop(col, axis = 1) #print(train.shape) train = train.drop('id', axis = 1) test_id = test.pop('id') train['reviews_per_month'] = train['reviews_per_month'].fillna(0) test['reviews_per_month'] = test['reviews_per_month'].fillna(0) from sklearn.preprocessing import LabelEncoder le = LabelEncoder() cols = ['neighbourhood_group', 'neighbourhood','room_type'] for col in cols: le = LabelEncoder() train[col] = le.fit_transform(train[col]) test[col] = le.transform(test[col]) from sklearn.model_selection import train_test_split X_tr, X_val, y_tr, y_val = train_test_split( train.drop('price', axis =1), train['price'], test_size = 0.15, random_state = 2022 ) import numpy as np from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor(random_state = 2023) model.fit(X_tr, y_tr) pred = model.predict(X_val) print("r2 :", r2_score(y_val,pred)) print("MAE :",mean_absolute_error(y_val, pred)) print("MSE :", mean_squared_error(y_val, pred)) pred = model.predict(test) print(pred) submit = pd.DataFrame({ 'id': test_id, 'price': pred }) submit.to_csv("0000.csv", index = False) pd.read_csv("0000.csv") y_test = pd.read_csv("y_test.csv") print(r2_score(y_test, pred)) 위와 같이 직접 코딩하였는데 정상적으로 코드실행은 되나 값이 아래와 같이 나옵니다. 맨아래 평가 부분에서 r2-score가 너무 낮게 나와 하이퍼파라미터 튜닝 등의 작업을 진행해도 값이 눈에띄게 높아지지 않습니다. 만약 시험장에서 저정도의 값이 나오게 되어도 문제가 없는지...만약 문제가 있다면 randomforest 모델 사용시 어떻게 코드를 수정해야 좋을까요? 항상 좋은 강의와 질의응답 감사합니다. 덕분에 많이 배우고 있습니다. r2 : 0.24135176879686082 MAE : 66.06702993637809 MSE : 37136.57052394958 [434.45 145.45 165.35 ... 138.18 162.28 205.64] 0.05889849774689748
le = LabelEncoder() for col in cols: X_train[col] = le.fit _transform(X_train[col]) X_test[col] = le.transform(X_test[col]) 이렇게 해주어도 결과는 동일한게 아닌가 해서요. 매 컬럼마다 새로 LabelEncoder() 해줘야 하는 이유가 있는지 궁금합니다
안녕하세요?, 선생님 4회 기출 유형(작업형2) 관련한 강의에서는 다른 강의와 다르게 교차검증을 이용하는 방법으로 진행하셨는데, 기존에 강의하신 대로 검증 데이터를 분리하고 모델링 및 평가를 하려고 하였는데, 평가방법이 macro_f1 이어서 어떻게 평가를 하여야 할지 모르겠습니다. macro_f1 이 f1_score를 평균으로 나타내는 방법을 사용하려고 하였지만 f1_score 가 에러가 발생합니다. macro_f1 평가는 어떻게 해야 하는가요?
안녕하세요 data_atype을 가지고 0또는 1일 확률을 구하는 문제에서 범주형 데이터를 원핫인코딩하면 마지막 pred=rf.predict_proba(test) 과정에서 다음과 같은 에러메세지가 발생합니다. 저 4개의 컬럼이 원핫인코딩 과정에서 사라졌다는건가요..? 원핫인코딩 후 c_x.info()했을 때 저 컬럼들이 있는 걸 확인할 수 있는데요ㅠ // 그리고 원핫인코딩 말고 라벨인코딩을 하면 정상실행 되는데 어떤 차이가 있는건지 궁금합니다!! 감사합니다!!! --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-185-ae1d02bf50a7> in <cell line: 1>() ----> 1 pred=rf.predict_proba(test) 3 frames /usr/local/lib/python3.10/dist-packages/sklearn/base.py in _check_feature_names(self, X, reset) 479 ) 480 --> 481 raise ValueError(message) 482 483 def _validate_data( ValueError: The feature names should match those that were passed during fit. Feature names seen at fit time, yet now missing: - native.country_Holand-Netherlands - native.country_Honduras - native.country_Hungary - native.country_Scotland
안녕하세요, 좋은 강의 잘 듣고 있습니다! 다름이 아니라 3회 기출 작업형 1번(문제2) 강의 - 2000년 데이터 중 2000년 평균보다 큰 값의 데이터 수 구하기에서 선생님이께서 cond = df.loc[2000].mean() print(sum(df.loc[2000,:]>cond)) 으로 'sum'을 쓰신 부분(결과값 100)을 저는 print(len(df.loc[2000,:]>cond)) 로 쓰니, 저는 전체 행의 개수가 계속 출력(결과값 200)이 나오더라구요. 이유가 뭔지 생각해봐도 제 얄팍한 지식으로는 도무지 생각이 안나서 선생님의 답변을 듣고싶어 질문드립니다!
안녕하세요. 동영상대로 따라하다가 에러가 났는데 잘못된 부분을 찾지 못해 질문드립니다 ㅠㅠ [고/저소득을 0또는 1로 분류할 때] 저는 x,y,test로 3개 데이터를 불러온 후->전처리->피처엔지니어링까지 했고 inty=(y['income']=='>50K').astype(int) from sklearn.model_selection import train_test_split x_tr, x_val, y_tr, y_val= train_test_split(x, inty, test_size=0.1, random_state=100) x_tr.shape, x_val.shape, y_tr.shape, y_val.shape 여기서 값이 ((26373, 15), (2931, 15), (26373,), (2931,)) 이렇게 나오면서 정상 실행 됐는데요.. from sklearn.ensemble import RandomForestClassifier rf=RandomForestClassifier() rf.fit(x_tr,y_tr) pred=rf.predict(x_val) **여기에서 아래와 같은 오류가 납니다.ㅠㅠ 왜 그런 걸까요ㅠㅠㅠ <ipython-input-112-e7142a22ea96> in <cell line: 3>() 1 from sklearn.ensemble import RandomForestClassifier 2 rf=RandomForestClassifier() ----> 3 rf.fit(x_tr,y_tr) 4 pred=rf.predict(x_val) /usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in _assert_all_finite(X, allow_nan, msg_dtype, estimator_name, input_name) 159 "#estimators-that-handle-nan-values" 160 ) --> 161 raise ValueError(msg_err) 162 163 ValueError: Input X contains NaN.
안녕하십니까 수업 잘 수강하고 있습니다! 수업을 수강하며 pyspark를 통해 예전에 했던 프로젝트의 데이터를 전처리부터 머신러닝까지 적용해보는 중인데, 전처리 과정에서 데이터를 수정해야 하는 경우에 대하여 질문이 있습니다. spark의 경우 pandas처럼 바꾸고 싶은 컬럼의 값만 바꿀 수 있지가 않고, withColumn을 통해 새로운 컬럼을 만들어내는 형식으로 대체가 가능한걸로 알고 있습니다. 단순히 컬럼별로 기준을 정해서 바꾸는 거면 withColumn으로도 가능하지만, 만약 개별 줄마다 값을 변경해야 할 경우 for문을 써서 바꿔야 하는 경우가 있는데, 이렇게 할 경우 제 현재 작업 환경(로컬)이 노드가 하나여서 그런지 Java.lang.OutOfMemoryError이 뜨더군요. 그래서 기존에 하던 pandas에서 하던 것 처럼 하려면, toPandas로 바꿔서 해도 되긴 합니다만.. 그러면 pyspark를 이 단계에서는 굳이 사용해봐야 의미가 없고, 또한 나중에 in-memory에서는 처리를 하기 힘든 큰 데이터의 경우에서는 pandas를 사용하지 못하니 방법이 아예 사라지게 됩니다. 그래서 질문은, 만약 이 경우처럼 세세하게 한줄한줄마다 값을 수정할 필요가 있을 경우, 어떻게 하는 것이 좋을지 궁금합니다. 또, spark dataframe을 toPandas로 변환할 경우 그냥 Pandas dataframe으로 불러오는 것과 차이점이 있는지도 여쭤보고 싶습니다.
선생님 안녕하세요 ~ 항상 강의 잘 듣고있습니다! 공부를 하다 궁금한 점이 생겨 작업형2 3회 기출문제 관련 질문드립니다. 1. 다른 피처엔지니어링은 따로 for문을 사용하지 않아도 여러 컬럼에 대해 스케일링이 적용되던데 왜 Label Encoding만 for문을 사용하는지 궁금합니다. 2. unamed:0은 삭제해도 되고, 삭제하지 않아도 되는걸까요? 3. 복습을 하며 아래와 같이 풀었는데 이렇게 해도 되는걸까요? 제출할 때 선생님께서 사용하신 'index':test.index 대신 기존에 있던 Unnamed: 0을 인덱스처럼 사용하였습니다. #데이터 전처리 train = train.drop('Unnamed: 0',axis=1) index = test.pop('Unnamed: 0') #제출 submit = pd.DataFrame({'index':index, 'pred':pred[:,1]}) submit.to_csv('2014.csv', index = False) 4. 그리고 pred의 범위 설정할 때, pred 변수를 만들 때 하는게 좋은지 제출할 때 하는게 좋은지 궁금합니다. (pred[:,1]이런식으로 범위 설정) #pred 변수 설정시 pred = model.predict_proba(test)[:,1] #제출시 submit = pd.DataFrame({'index':index, 'pred':pred[:,1]}) 5. 수치형 /범주형 데이터 분리 없이 원핫인코딩하는 코드를 알고싶습니다. cols = 범주형 데이터 train[cols] = pd.get_dummies(train[cols]) >> 이렇게 했을 때는 길이가 안 맞아서 오류가 났고 train = pd.get_dummies(train[cols]) >> 이렇게 했을 때는 train에 원핫인코딩된 범주형 데이터만 저장이 됐습니다. 감사합니다.
빅데이터분석기사 실기시험 hist 사용이 가능한가요 ? 사용을 못하는 상황에서는 로그적용해볼만한 데이터 분포 확인 쉽게 하는 방법이 무엇이 있을지 궁금합니다 3-6 Regression노트북에서 insurance 데이터셋의 charges 값에 로그를 취하실 때 왼편으로 치우친 것을 확인하신 것 관련 질문입니다 LinearRegression은 모델에 random_state를 안 줘도 계속 5888 이라는 RMSE 값이 나오는 반면에, RandomForestRegressor의 경우, (아마도 모델에 random_state적용이 없어서) 결과가 계속 달라집니다. 혹시 LinearRegression은 원래 그런 특징이 있는 모델인가요??