묻고 답해요
160만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
3회 기출유형(작업형2) 강의 관련 질문 있습니다!
안녕하세요! 강의 잘 듣고 있습니다!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문을 써야하는 조건과 쓰지 않아도 되는 조건이 따로 있는건가요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형2 모의문제2
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.24135176879686082MAE : 66.06702993637809MSE : 37136.57052394958[434.45 145.45 165.35 ... 138.18 162.28 205.64]0.05889849774689748
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
4회 기출 유형(작업형2)의 xgb 에러 관련
선생님!! 4회 기출 유형(작업형2)에서 랜덤포레스트와 lgb 는 이상이 없는데, xgb 로 모델링 할 경우에만 에러가 발생하는데, 무슨 문제인가요?[코딩]import pandas as pdtrain = pd.read_csv('train.csv')test = pd.read_csv('test.csv')# print(train.shape, test.shape)# print(train.head(3))# print(test.head(3))# print(train.info())# print(train.describe())# print(train.describe(include='object'))# print(test.describe(include='object'))# print(train['Segmentation'].value_counts())# print(train.isnull().sum())# print(test.isnull().sum())train = train.drop('ID', axis=1)test_id = test.pop('ID')test.head(3)cols = train.select_dtypes(include='object').columnsprint(cols)from sklearn.preprocessing import LabelEncoderfor col in cols : le = LabelEncoder() train[col] = le.fit_transform(train[col]) test[col] = le.transform(test[col])train.head(3)from sklearn.model_selection import train_test_splitX_tr, X_val, y_tr, y_val = train_test_split(train.drop('Segmentation', axis=1), train['Segmentation'], test_size=0.1, random_state=2022)print(X_tr.shape, X_val.shape, y_tr.shape, y_val.shape)from sklearn.metrics import f1_scorefrom sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(random_state=2022, max_depth=7, n_estimators=100)rf.fit(X_tr, y_tr)pred = rf.predict(X_val)pred[:10]f1_score(y_val, pred, average='macro')from sklearn.metrics import f1_score# import lightgbm as lgb# model = lgb.LGBMClassifier(random_state=2022, max_depth=5, n_estimators=800, learning_rate=0.01 )# model.fit(X_tr, y_tr)# pred = model.predict(X_val)# pred[:10]# f1_score(y_val, pred, average='macro')from sklearn.metrics import f1_scorefrom xgboost import XGBClassifierxgb = XGBClassifier(random_state=2022)xgb.fit(X_tr, y_tr)pred = xgb.predict(X_val)pred[:10][에러내용]ValueError Traceback (most recent call last)<ipython-input-57-d656863c7bc3> in <cell line: 4>() 2 from xgboost import XGBClassifier 3 xgb = XGBClassifier(random_state=2022)----> 4 xgb.fit(X_tr, y_tr) 5 pred = xgb.predict(X_val) 6 pred[:10]1 frames/usr/local/lib/python3.10/dist-packages/xgboost/sklearn.py in fit(self, X, y, sample_weight, base_margin, eval_set, eval_metric, early_stopping_rounds, verbose, xgb_model, sample_weight_eval_set, base_margin_eval_set, feature_weights, callbacks) 1438 or not (self.classes_ == expected_classes).all() 1439 ):-> 1440 raise ValueError( 1441 f"Invalid classes inferred from unique values of y. " 1442 f"Expected: {expected_classes}, got {self.classes_}"ValueError: Invalid classes inferred from unique values of y. Expected: [0 1 2 3], got [1 2 3 4]
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
반복문 안에서 LabelEncoder() 해주는 이유가 궁금합니다
le = LabelEncoder()for col in cols: X_train[col] = le.fit_transform(X_train[col]) X_test[col] = le.transform(X_test[col])이렇게 해주어도 결과는 동일한게 아닌가 해서요. 매 컬럼마다 새로 LabelEncoder() 해줘야 하는 이유가 있는지 궁금합니다
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
4회 기출 유형(작업형2) 관련 질문
안녕하세요?, 선생님4회 기출 유형(작업형2) 관련한 강의에서는 다른 강의와 다르게 교차검증을 이용하는 방법으로 진행하셨는데, 기존에 강의하신 대로 검증 데이터를 분리하고 모델링 및 평가를 하려고 하였는데, 평가방법이 macro_f1 이어서 어떻게 평가를 하여야 할지 모르겠습니다.macro_f1 이 f1_score를 평균으로 나타내는 방법을 사용하려고 하였지만 f1_score 가 에러가 발생합니다.macro_f1 평가는 어떻게 해야 하는가요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
모델링 및 평가(분류)/원핫인코딩-라벨인코딩 오류 질문드립니다!
안녕하세요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
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
안녕하세요! sum 함수를 쓸 곳에 len을 썼다가 의문이 생겨서 질문드립니다!
안녕하세요, 좋은 강의 잘 듣고 있습니다!다름이 아니라 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)이 나오더라구요. 이유가 뭔지 생각해봐도 제 얄팍한 지식으로는 도무지 생각이 안나서 선생님의 답변을 듣고싶어 질문드립니다!
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
머신러닝 실행 오류(ValueError: Input X contains NaN.) 질문드립니다
안녕하세요. 동영상대로 따라하다가 에러가 났는데 잘못된 부분을 찾지 못해 질문드립니다 ㅠㅠ[고/저소득을 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.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형2 빅데이터 분석기사 2회 실기 질문
df = pd.concat([X_train,y_train['Reached.on.Time_Y.N']], axis=1) n_train = df.select_dtypes(exclude = object).copy() c_train = df.select_dtypes(include = object).copy() n_test = df.select_dtypes(exclude = object).copy() c_test = df.select_dtypes(include = object).copy() from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() cols = ['Customer_care_calls','Customer_rating', 'Cost_of_the_Product', 'Prior_purchases', 'Discount_offered', 'Weight_in_gms'] n_train[cols] = scaler.fit_transform(n_train[cols]) n_test[cols] = scaler.transform(n_test[cols]) c_train = pd.get_dummies(c_train) c_test = pd.get_dummies(c_test) train = pd.concat([n_train, c_train], axis =1) test = pd.concat([n_test, c_test], axis =1) train = train.drop('ID', axis =1) test_id = test.pop('ID') from sklearn.model_selection import train_test_split X_tr, X_val, y_tr, y_val = train_test_split( train.drop('Reached.on.Time_Y.N', axis =1), train['Reached.on.Time_Y.N'], test_size = 0.2, random_state = 2023) from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score model = RandomForestClassifier(random_state = 2023) model.fit(X_tr, y_tr) pred = model.predict_proba(X_val)[:,1] print(roc_auc_score(y_val, pred)) pred = model.predict_proba(test)[:,1] submit = pd.DataFrame({ 'ID': test_id, 'Reached.on.Time_Y.N': pred }) submit.to_csv("0000.csv", index = False)작업형2를 n_train, n_test, c_train, c_test로 나누어서 풀어보는 연습을 하고있는데요위와 같이 코딩을 했는데 roc_auc_score는 잘 출력이 되지만 아래와 같은 워닝이 뜹니다. 이유를 알 수 있을까요? 0.7289745856473446 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-81-0b0c32327ea7> in <cell line: 38>() 36 print(roc_auc_score(y_val, pred)) 37 ---> 38 pred = model.predict_proba(test)[:,1] 39 submit = pd.DataFrame({ 40 'ID': test_id, 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 unseen at fit time: - Reached.on.Time_Y.N
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
3회 기출유형(작업형2) 수업 관련 질문
선생님 안녕하세요 ~ 항상 강의 잘 듣고있습니다!공부를 하다 궁금한 점이 생겨 작업형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에 원핫인코딩된 범주형 데이터만 저장이 됐습니다. 감사합니다.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
예시문제 작업형2 test 데이터 예측시 발생하는 오류
안녕하세요! 복습하는 도중에 이런 에러가 발생되어 질문드립니다 ㅠㅠimport pandas as pd X_train = pd.read_csv('X_train.csv',encoding="euc-kr") y_train = pd.read_csv('y_train.csv') X_test = pd.read_csv('X_test.csv',encoding="euc-kr") print(X_train.shape,y_train.shape) # X_train.head() # y_train.head() # X_train.info() #X_train 환불금액 결측치, 오브젝트 두개 # y_train.info() X_train = X_train.fillna(0) X_train.isnull().sum() X_train = X_train.drop(['cust_id'],axis=1) cust_id = X_test.pop('cust_id') #라벨인코딩 from sklearn.preprocessing import LabelEncoder cols = X_train.select_dtypes( include = 'object').columns cols for col in cols : le = LabelEncoder() X_train[col] = le.fit_transform(X_train[col]) X_test[col] = le.transform(X_test[col]) X_train.head() #검증데이터 분리 from sklearn.model_selection import train_test_split X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train['gender'], test_size = 0.2, random_state = 2022) X_tr.shape, X_val.shape, y_tr.shape, y_val.shape #모델링 - 랜덤포레스트 from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score model = RandomForestClassifier(random_state=2022) model.fit(X_tr,y_tr) pred = model.predict_proba(X_val) roc_auc_score(y_val,pred[:,1]) pred = model.predict_proba(X_test) <------------------이 과정에서 발생되는 오류입니다 pred ValueError: Input X contains NaN. RandomForestClassifier does not accept missing values encoded as NaN natively. 라는 에러가 발생합니다 ㅠㅠ코드를 검토해봐도 이상은 없는거같은데.. 뭐가문제일까요? ㅠㅠ
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
빅데이터분석기사 실기시험 hist 사용 못하면 분포 확인을 쉽게 하는 방법 궁금합니다
빅데이터분석기사 실기시험 hist 사용이 가능한가요 ? 사용을 못하는 상황에서는 로그적용해볼만한 데이터 분포 확인 쉽게 하는 방법이 무엇이 있을지 궁금합니다3-6 Regression노트북에서 insurance 데이터셋의 charges 값에 로그를 취하실 때 왼편으로 치우친 것을 확인하신 것 관련 질문입니다LinearRegression은 모델에 random_state를 안 줘도 계속 5888 이라는 RMSE 값이 나오는 반면에, RandomForestRegressor의 경우, (아마도 모델에 random_state적용이 없어서) 결과가 계속 달라집니다. 혹시 LinearRegression은 원래 그런 특징이 있는 모델인가요??
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형1 모의문제3 : 9번 문제 문의
작업형1 모의문제3 의 9번 문제를 풀었는데 답에 '대구'만 나오지 않고 밑에 다른 설명이 나오는데, 무슨 의미이고 왜 나오는지 궁금합니다.[코딩 내용]import pandas as pddf = pd.read_csv('members.csv')# print(df.shape)# print(df.head(10))df = df.fillna(method = 'bfill')df.head()df = df.groupby(['city', 'f2']).sum().reset_index()df.head()df = df.sort_values('views', ascending=False)df.head()print(df.iloc[2,0])[답안내용]대구<ipython-input-102-fa90dbbb01dd>:7: FutureWarning: The default value of numeric_only in DataFrameGroupBy.sum is deprecated. In a future version, numeric_only will default to False. Either specify numeric_only or select only columns which should be valid for the function. df = df.groupby(['city', 'f2']).sum().reset_index()
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형1 모의문제3 : 7번 문제 질문
선생님!!!작업형1 모의문제3 의 7번에서 행의 평균을 loc 를 사용하여 구하셨는데, 혹시 axis=1 을 사용하여 행별로 평균을 못 구하는지요/즉, df[2001].mean(axis = 1) 로 할때 에러가 발생다던데 loc만 사용해야 하는가요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형 2 실전 환경 연습 pd.dataframe 시 에러 해석 부탁드립니다
pd.DataFrame({'cust_id': X_test['cust_id'], 'gender': pred})기재하였는데요, 아래 에러 화면이 뜨는데 해석이 불가하여 문의드립니다. > Makefile:6: recipe for target 'py3_run' failedmake: *** [py3_run] Error 1Traceback (most recent call last): File "/goorm/Main.out", line 37, in <module> pd.DataFrame({'cust_id': X_test['cust_id'], 'gender': pred}) File "/usr/local/lib/python3.9/dist-packages/pandas/core/frame.py", line 636, in init mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager) File "/usr/local/lib/python3.9/dist-packages/pandas/core/internals/construction.py", line 502, in dict_to_mgr return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy) File "/usr/local/lib/python3.9/dist-packages/pandas/core/internals/construction.py", line 120, in arrays_to_mgr
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
5회 기출유형(작업형2)
안녕하세요. 강의 잘 듣고 있습니다.보통 작업형2 실행시 train 데이터 id drop하고, test 데이터 id pop처리 했는데(작업형2 모의문제1 에서는 CLIENTNUM 드롭 및 팝처리 함)5회 작업형 2에서는 실시 안 하셨길래... 다른 이유라도 있으신지 궁금합니다.submit으로 내보내기해야하는 값에 price만 있어서 그런가요? 언제 해야하고.. .언제 안 해야하는지.. 넘 헷갈려서요.model을 없애고 돌린게.. rmse가 더 높긴 하더라구요.... ^^;;train = train.drop('model', axis = 1) test_model = test.pop('model')
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형3 예시문제 ttest_rel
ttest_rel 파라미터 중에 a,b가 있는데요강의에서 설명주신 건치료 후 혈압 - 치료 전 혈압이렇게 표시되어 있으니 순서대로 넣어야 한다고 했는데요. 치료 전 혈압 - 치료 후 혈압 이라면stats.ttest_rel(df['bp_before'] - df['bp_after'])위와 같이 작성해야 하는 것으로 이해했습니다. 여기서, ttest_rel 유형은 예시문제 처럼 무조건 두 집단(혹은 조치 전 집단과 조치 후 집단)이 있고, 두 집단 사이의 차이를 이용하는 게 맞을까요?! a와 b를 그냥 설명주신대로만 이해하면 되는지 문의드립니다.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형2 모의문제 1 질문2
import pandas as pd train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score train n_train = train.select_dtypes(exclude = object).copy() c_train = train.select_dtypes(include = object).copy() n_test = test.select_dtypes(exclude = object).copy() c_test = test.select_dtypes(include = object).copy() from sklearn.preprocessing import MinMaxScaler cols = ['Customer_Age','Dependent_count', 'Months_on_book', 'Total_Relationship_Count', 'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct', 'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio'] scaler = MinMaxScaler() n_train[cols] = scaler.fit_transform(n_train[cols]) n_test[cols] = scaler.transform(n_test[cols]) c_train = pd.get_dummies(c_train) c_test = pd.get_dummies(c_test) train = pd.concat([n_train, c_train], axis =1) test = pd.concat([n_test, c_test], axis =1) train = train.drop('CLIENTNUM', axis =1) test = 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 = 2023 ) from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score model = RandomForestClassifier(random_state = 2023) model.fit(X_tr, y_tr) pred = model.predict(X_val) print(pred) # 정확도 print(accuracy_score(y_val, pred)) # 정밀도 print(precision_score(y_val, pred)) # 재현율 (민감도) print(recall_score(y_val, pred)) # F1 print(f1_score(y_val , pred))위와 같이 코드를 진행시[0 1 0 ... 1 0 1]1.01.01.01.0 이 나옵니다. pred 자체가 1차원으로만 나오고 정확도 정밀도 재현율 F1도 1.0으로만 나오는데 무엇이 잘못된건지 모르겠습니다ㅠㅠ
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형2 모의문제1 질문
작업형2 문제마다 어떤문제들은 n_train, c_train, n_test, c_test로 나누는 문제들이 있고 그렇지 않은 문제들이 있어서 헷갈리는데요. 수치형변수를 스케일링하는 과정을 거치려면 n_train, c_train, n_test, c_test로 나눠야 하고,스케일링 과정을 생략하고 범주형 변수 인코딩 과정만을 진행할때는 나눌필요가 없는게 맞나요? 작업형 모의문제 1을 혼자 풀어보는 와중 MinMaxScaler로 스케일링을 해보는중인데 from sklearn.preprocessing import MinMaxScaler cols = ['CLIENTNUM', 'Customer_Age','Dependent_count', 'Months_on_book', 'Total_Relationship_Count', 'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct', 'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio'] scaler = MinMaxScaler() for col in cols: n_train[col] = scaler.fit_transform(n_train[col]) n_test[col] = scaler.transform(n_test[col])ValueError Traceback (most recent call last)<ipython-input-38-b70edfd82bf0> in <cell line: 5>() 4 scaler = MinMaxScaler() 5 for col in cols: ----> 6 n_train[col] = scaler.fit_transform(n_train[col]) 7 n_test[col] = scaler.transform(n_test[col]) 85 frames/usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name) 900 # If input is 1D raise error 901 if array.ndim == 1: --> 902 raise ValueError( 903 "Expected 2D array, got 1D array instead:\narray={}.\n" 904 "Reshape your data either using array.reshape(-1, 1) if "ValueError: Expected 2D array, got 1D array instead: array=[0.58522152 0.08465774 0.60121236 ... 0.06531669 0.06194963 0.52375209]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. 위와 같은 오류가 발생합니다. 혹시 어떤 부분이 잘못된걸까요?반면에 아래와 같이 실행할 경우 오류가 발생하지않습니다. 강의에서는 cols안에 컬럼값이 여러개이므로 반복문을 써야한다고 배웠는데 제가 잘못알고있는걸까요?from sklearn.preprocessing import MinMaxScaler cols = ['CLIENTNUM', 'Customer_Age','Dependent_count', 'Months_on_book', 'Total_Relationship_Count', 'Months_Inactive_12_mon', 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal', 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt', 'Total_Trans_Ct', 'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio'] scaler = MinMaxScaler() n_train[cols] = scaler.fit_transform(n_train[cols]) n_test[cols] = scaler.transform(n_test[cols])
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
회귀문제에서 이런 오류 났을 때 어떻게 해결해야 하나요?
pred1 = pred1.astype(int) y_val = y_val.astype(int) pred1 = np.log1p(pred1) y_val = np.log1p(y_val) rmse(np.exp(y_val),np.exp(pred1)) MSE loss가 기하급수적으로 증가해서 NaN값이 발생하는 것 같은데어떻게 해결해야할지 모르겠어요! ㅠㅠ 에러는 아래에 있습니다. <ipython-input-35-aacfc97a4692>:3: RuntimeWarning: invalid value encountered in log1p pred1 = np.log1p(pred1) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-35-aacfc97a4692> in <cell line: 6>() 4 y_val = np.log1p(y_val) 5 ----> 6 rmse(np.exp(y_val),np.exp(pred1)) 4 frames/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 contains NaN.