묻고 답해요
160만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
[섹션6] 작업형2 모의문제2 mape 평가 관련 질문입니다.
안녕하세요~ 계속 반복한 끝에 미숙하게나마 직접 데이터를 가공해서 모델을 만들어서 돌려보는 데까지 성공했습니다. 정말 좋은 강의 감사합니다. 저 같은 경우에는 name, host_id, host_name, last_review, reviews_per_month 이런 결측치가 많거나 object인 컬럼들은 모두 날려줬고LabelEncoer, MinMaxScaler를 사용해서 피처엔지니어링을 해줬습니다.그렇게 해서 평가에 사용한 모델은 RandomForestRegressor 고요.다른 결과치들은 선생님께서 방송 중에 만들어주신 모델에 비해서 살짝 살짝 낮지만… 그래도 결과값이 나오긴 나와서 다행이라고 생각하고 있는데요.(정말 고맙습니다!) 딱 하나 아래 mape 요 놈은 결과값이 inf로 나옵니다.MAPE(Mean Absolute Percent Error)요건 Inf - 아마 무한대겠죠?분모에 해당하는 수가 0에 가까워서 그런 게 아닐까 싶기도 한데요. 이 평가지표를 쓰라고 한다면 MinMaxScaler는 쓰면 안 되는 걸까요? 요게 영향을 주지 않았을까 싶어서요. 출근을 해야해서 일단 생각을 여기까지 해보고 퇴근하고 다시 올려보겠습니다.랜덤포레스트 모델하고 LightBGM 요렇게 두 가지만 쓰려고 작정하고 준비하고 있습니다.그럼~
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형2 모의문제 2 질문있습니다!
안녕하세요!작업형 2 모의문제 2의 마지막에 csv파일을 제출할 때 에러가 발생하는데, 어떤 이유인지 찾아봐도 안보여 질문드립니다. 그리고 작업형 2유형의 train과 test데이터 파일만 주어진 경우, 어떤 문제는 n_train, c_train, n_test, c_test로 나누는 문제가 있고 그렇지 않은 문제들이 있어서 헷갈립니다ㅠ 그래서 문제를 읽고 데이터를 분리해야하는 상황이 궁금합니다!import pandas as pd train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') # print(train.head()) # print(test.head()) # print(train.info()) 1. 불필요한 컬럼제거 2. 결측치 대치 3. 인코딩 4. 스케일링 # print(test.info()) train = train.drop(columns ='id') test_id = test.pop('id') # print(test_id) cols = ['host_id','neighbourhood_group','neighbourhood','name', 'host_name', 'last_review'] # print(train.shape) train = train.drop(cols, axis =1) test = test.drop(cols, axis =1) # print(train.shape) # train = train.drop(columns ='host_id') # test = test.drop(columns ='host_id') # train = train.drop(columns ='neighbourhood_group') # test = test.drop(columns ='neighbourhood_group') # train = train.drop(columns ='neighbourhood') # test = test.drop(columns ='neighbourhood') # train = train.drop(columns ='name') # test = test.drop(columns ='name') # train = train.drop(columns ='host_name') # test = test.drop(columns ='host_name') # train = train.drop(columns ='last_review') # test = test.drop(columns ='last_review') # print(train.info()) # print(test.info()) # print(train.isnull().sum()) # print(test.isnull().sum()) train['reviews_per_month'] = train['reviews_per_month'].fillna(0) test['reviews_per_month'] = test['reviews_per_month'].fillna(0) # print(train.isnull().sum()) # print(test.isnull().sum()) #라벨 인코딩 from sklearn.preprocessing import LabelEncoder cols =train.select_dtypes(include = 'object').columns for col in cols: encoder = LabelEncoder() train[col] = encoder.fit_transform(train[col]) test[col] = encoder.transform(test[col]) # print(train.info()) # print(test.info()) # print(train.describe()) # print(test.describe()) # 스케일링 from sklearn.preprocessing import minmax_scale cols2 = train.select_dtypes(exclude = 'object').columns for col in cols2: train[col] = minmax_scale(train[col]) cols2 = test.select_dtypes(exclude = 'object').columns for col in cols2: test[col] = minmax_scale(test[col]) # print(train.describe()) # print(test.describe()) from sklearn.model_selection import train_test_split X_train, X_val, y_train, y_val = train_test_split(train.drop('price', axis=1), train['price'], test_size=0.2, random_state=20) # print(X_train.head()) from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor() rf.fit(X_train, y_train) pred = rf.predict(X_val) # print(pred) #id,price sumit = pd.DataFrame({'id': test_id, 'price' : pred}) submit.to_csv('10004.csv', index=False)
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
3회 기출유형(작업형2) 코드 인코딩 방법 관련 질문
안녕하세요. 우선 좋은 강의 너무 감사드립니다.3회 기출유형(작업형2) 코드 인코딩 방법 관련 질문드립니다.풀이 영상에서 원핫인코딩 방법을 선택해주셨던데 시험 문제를 풀때 1)원핫인코딩을 할지 2)라벨인코딩을 할지는 어떤 정보를 보고 선택하나요?저는 라벨 인코딩이 익숙해서 아래 처럼 작성했는데 인코딩 방식이 무관하다면, 아래처럼 라벨인코딩으로 진행해도 될지 문의드립니다.# 수치형 데이터와 범주형 데이터 분리 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()cols = c_train.columns for col in cols: le = LabelEncoder() c_train[col] = le.fit_transform(c_train[col]) c_test[col] = le.transform(c_test[col]) c_train.head()
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
하이퍼파라미터 질문입니다.
안녕하세요 강사님교차검증을 통해 하이퍼파라미터를 사용할 때, 분류모델인 랜덤포레스트 외에도 의사결정나무, XGBOOST, 회귀모델인 로지스틱 등 전 모델에 동일하게 사용이 가능한가요?random_state의 값을 다른 값을 찾을 필요없이 0으로 고정해도 괜찮을까요?기존방식대로 검증 데이터를 분리하여 하이퍼파라미터 최적 값을 찾는 방법은 없을까요? 하이퍼파라미터를 사용하지 않고 기존방식으로 검증 데이터를 분리 후 성능지표가 가장 좋은 모델을 사용하는 방식으로 해도 점수감점이 없을까요?4가지 질문에 대한 답변을 해주시면 감사합니다.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
df.sum() 과 sum(df) 차이가 뭔가요?
df.sum() 과 sum(df) 차이가 무엇인지 질문드립니다.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
캐글 폰트 크기 설정
캐글 글자가 너무 작아서 안보이는데 크기 설정 어떻게 하나요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
삭제예정콘텐츠 강의
'(삭제 예정 콘텐츠) 회귀모형'라는 강의가 있는데 빅데이터분석기사 실기 시험에 필요한 내용일까요? 수강해야 되는지 몰라서 질문드립니다.
-
해결됨비전공자를 위한 진짜 입문 올인원 개발 부트캠프
로그 이미지 주소 중 절대 경로 원리에 관한 질문
본 강의 중 로그가 나오지 않는 이슈에 관하여경로 설정에 문제가 있다고 하셨고, grab_market_web/src/App.js의 내용 중 로그 src의 경로를"./imgages/icons/log.png"에서 -> "/imgages/icons/log.png"으로 변경하라고 하였습니다. 작동은 잘 되는데, 작동 원리가 궁금합니다./ 절대값 root경로의 시작은 어디로 설정되어 있나요?이전에는 메인 화면에서는 ./ 상대 경로 중, 현재 경로로 설정되어 있었는데 잘 작동했던 이유도 궁금합니다.App.js파일의 내용이니까 App.js가 존재하는 grab_market_web/src 디렉토리가 현재 경로라고 이해되는데,그보다 상위 디렉토리에 존재하는 grab_market_web/public이 ./ 현재 경로로 인식되어grab_market_web/public/images가 호출 되는 것도 이해가 잘 되지 않으며/ 절대 경로로 설정시에도grab_market_web/public/images가 호출되는 것이 잘 이해가 되지 않습니다.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
Lightgbm 관련 질문
Ligthgbm을 쓰면 결측치 처리가 필요없고, 범주형 데이터 인코딩도 필요없다고 하셨는데트리 관련 모델이라 수치형 변수 스케일링도 딱히 필요가 없고,이상치 처리에 대해서도 딱히 필요가 없나요??
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형2 모의문제2 lightGBM 적용 질문
import pandas as pd train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') pd.set_option('display.max_columns', None) # print(train.shape, test.shape) # print(train.head()) # print(test.head()) # print(train.info()) # print(test.info()) cols = train.select_dtypes(include='object') for col in cols : train[col] = train[col].astype('category') test[col] = test[col].astype('category') # 이걸 안 하면 lgb.predict(test) 구문에서 에러남 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.2, random_state=2023) import lightgbm lgb = lightgbm.LGBMRegressor(random_state = 2023) lgb.fit(X_tr, y_tr) pred = lgb.predict(X_val) from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error # print("r2 : ", r2_score(y_val, pred)) #0.2392705394376351 # print("mae : ", mean_absolute_error(y_val, pred)) #71.81171796246842 # print("mse : ", mean_squared_error(y_val, pred)) #63344.209788490516 pred_res = lgb.predict(test) pd.DataFrame({'price': pred_res}).to_csv('result.csv', index=False) print(pd.read_csv('result.csv')) y_test = pd.read_csv("y_test.csv") print(r2_score(y_test, pred_res)) #0.22012967580409581안녕하세요, 딴짓님lightGBM 모델 설명 주셔서 적용해보았는데요.이렇게 하는 게 맞을까요?for col in cols : train[col] = train[col].astype('category') test[col] = test[col].astype('category')이 부분을 하지 않으면 에러가 나긴 하더라구요. train[col]을 하지 않으면 아래와 같은 에러메시지가 나옵니다.'DataFrame.dtypes for data must be int, float or bool.Did not expect the data types in the following fields: name, host_name, neighbourhood_group, neighbourhood, room_type, last_review' test[col]을 하지 않으면 아래와 같은 에러메시지가 나옵니다.'train and valid dataset categorical_feature do not match.' lightGBM모델은 데이터 타입이 int, float, bool 이 세가지만 허용하게 되어 object 타입을 category 타입으로 변경train만 변경해주면 test[col]을 하지 않았을 때와 같은 에러메시지가 출력되니 test도 category로 변경이게 맞을까요? 평가지표 같은 것도 주석으로 작성했는데, lightGBM을 이렇게 사용하는 것이 맞는지 확인 한 번 부탁드립니다!
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
preprocessing MinMaxScaler와 minmax_scale의 차이가 궁금합니다.
작업형2 수치형데이터 인코딩 MinMaxScaler로 열심히하다가,작업형1 min-max scale 문제에 위 수치형데이터 인코딩을 하면서 순간 혼돈이 왔었는데요,MinMaxScaler와 min-max scale의 preprocessing 차이가 궁금합니다..!
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
모의문제3 작업형1 출력오류 질문입니다.
안녕하세요 강사님 모의문제3 작업형1 7번 출력 시 발생한 오류를 해결하지 못해 질문드립니다.강사님의 코드와 비교했을 때 iloc/loc만 다를뿐 나머지는 동일한 코드인데 출력값이 202로 다릅니다...어떤 문제가 있어서 그럴까요? 그리고 이외의 2가지 질문 더 있습니다..! 실제 시험에서 평가지표(R-Squared, MAE, MSE, RMSE, RMSLE, MAPE)의 수치를 나타내어야 하는가요? 만일 그렇다면, 다음과 같이 함수로 만들 수 있도록 모두 외워야하나요? 아니면 시험환경에서 주어지나요?작업형2에서 csv파일은 만들어서 제출 후 오류가 있음을 발견해 다시 csv파일을 만들어서 제출해도 상관이 없을까요?시험칠 때 코드에서 주석다는 것은 큰 문제 없을까요? 긴 질문이지만 답변해주시면 감사합니다...ㅜ
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형 2 시험에서 제출 시 평가를 꼭 해야하나요 ?
회귀는 rmse, 분류는 roc 등으로 평가가 있는데,실제 시험에서 평가 없이 바로 제출해도 무방한가요 ?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형 2유형 제출 관련
안녕하세요. 큰 도움 받고 있습니다. 감사합니다!!다름이 아니라 유형별로 답안 제출할 때,작업형1: print()작업형3: 별도의 답안 입력창에 답 입력하여 제출하는 것으로 알고 있는데,2유형은 제출 전 마지막 행을 어떤 내용으로 끝내야 하는지 헷갈려서요.pd.DataFrame().to_csv() 식의 파일 저장으로 제출하면 될까요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
섹션 6 작업형 2 정확도 오류 원인 질문드립니다! Classification metrics can't handle a mix of binary and continuous targets
from sklearn.model_selection import train_test_split X_tr,X_val,y_tr,y_val=train_test_split(train.drop('Attrition_Flag',axis=1),train['Attrition_Flag'],test_size=0.2,random_state=2023) from sklearn.ensemble import RandomForestClassifier rf=RandomForestClassifier(random_state=2023) rf.fit(X_tr,y_tr) pred=rf.predict_proba(X_val) from sklearn.metrics import accuracy_score # 정확도 print(accuracy_score(y_val, pred[:,1])) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-63-aa6b6ce781f8> in <cell line: 10>() 8 9 # 정확도 ---> 10 print(accuracy_score(y_val, pred[:,1])) 2 frames /usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py in _check_targets(y_true, y_pred) 93 94 if len(y_type) > 1: ---> 95 raise ValueError( 96 "Classification metrics can't handle a mix of {0} and {1} targets".format( 97 type_true, type_pred ValueError: Classification metrics can't handle a mix of binary and continuous targets 혹은 print(accuracy_score(y_val, pred)) 실행 시, 오류2번 Classification metrics can't handle a mix of binary and continuous-multioutput targets해당 코드로 제출까지는 잘 되고 있습니다. 그러나 정확도 측정 시 오류가 발생하여, 제출에 문제가 있는 것인가 불안하여 오류 현상 문의드립니다..!
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
맥북 터미널에서 node-v 입력시 나오는 오류
안녕하세요 그랩님!혹시 영상 4:56쯤 단계부터 오류가 떠 다른 분들의 질문과 그랩님 답변도 보고 이것저것 시도해 보았으나 해결이 안되어 질문드립니다ㅜㅜ 혹시 아래의 오류가 제가 지금 사용하는 맥북이 2017년 버전(10.13.1)으로 시스템 업그레이드를 한지 오래되었기 때문에 뜨는걸까요..? 맥에서 지원하는 최신 시스템 업그레이드를 하려면외장하드 구입 후 컴퓨터 내 백업을 준비 후에 OS 삭제>재설치>백업복원 까지 진행해야 하기에 하기 오류가 컴퓨터 백업과 OS 재설치 없이도 해결이 가능할지 혹시 아실까 하여 문의드립니다ㅜㅜ
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
과대적합 발생 시 처리 방법에 대해 궁금합니다!
평가 지표를 이용해 점수 확인 시, train점수가 높지만 test 점수가 낮을 때 과대적합이 발생했다고 판단하고, max_depth와 n_estimators를 조금씩 조절해야한다고 알고 있습니다!그런데, 조절 시 점수 판단 기준이 궁금합니다. 예를 들어 accuracy 사용 시, train - 1.0 , test - 0.9xxx 정도로 점수가 나오면 train점수를 낮춰가면서라도 test와 비슷해지도록 맞춰나가야 하는 것인가요?!아니면 train과 test가 현저히 차이날 때만 조절하면 될까요? ㅠㅠ이론적인 지식이 부족해서 어떻게 처리해야하는지 감이 잡히질 않아 질문드립니다. 항상 감사드립니다 : )
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
섹션7. 모의고사 풀어보기 2 질문있습니다.
goorm을 써서 코드를 실행해보는데데이터 분석하는 과정에서 랜덤 포레스트를 쓸 때는 warning 메시지가 하나도 안 나왔는데 한번 XGBoost를 사용하니까 바로 WARNING: ../src/learner.cc:1095: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.0.9724770642201834/usr/local/lib/python3.9/dist-packages/xgboost/compat.py:31: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead. from pandas import MultiIndex, Int64Index/usr/local/lib/python3.9/dist-packages/xgboost/sklearn.py:1146: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1]. warnings.warn(label_encoder_deprecation_msg, UserWarning)/usr/local/lib/python3.9/dist-packages/xgboost/data.py:208: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead. from pandas import MultiIndex, Int64Index이런 워닝 코드가 뜹니다. 어떤 것이 문제일까요?코드는 아래에 있습니다.import pandas as pd pd.set_option('display.max_columns',None) train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") # 사용자 코딩 # print(train.head()) # print(train.describe()) from sklearn.model_selection import train_test_split X_tr,X_val,y_tr,y_val = train_test_split(train.drop('target',axis=1), train['target'], test_size=0.2, random_state=2022) from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(random_state=2022, max_depth=5, n_estimators=400) rf.fit(X_tr,y_tr) pred = rf.predict(X_val) from xgboost import XGBClassifier xgb = XGBClassifier(random_state=2022, max_depth=5, n_estimators=400, learning_rate=0.01) xgb.fit(X_tr,y_tr) pred = xgb.predict(X_val) from sklearn.metrics import f1_score print(f1_score(y_val,pred))
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
기출유형 4회 작업형2 f1_score 평가
안녕하세요, 매 강의마다 좋은 수업해주셔서 감사드립니다. lightgmb 뽀너스 영상도 정말 감사합니다~~f1_score로 평가를 진행하고 싶었으나, 해당 오류가 발생하여 질문드리게 되었습니다. 제시된 데이터 set에 적합한 평가 모델을 문제에서 제시를 해주는 것인지, 제가 잘못된 코딩을 한 것 인지 확인해주시면 너무 감사드릴 것같습니다.Please choose another average setting, one of [None, 'micro', 'macro', 'weighted'].에러 메시지를 확인하고 임의로 micro를 추가하여 옵션값을 주니까 에러 메시지 없이 평가값이 나오는점 확인하였습니다. 혹시 average setting이라는걸 세팅하는 경우는 어떤 경우인지 알려주실 수 있으신가요??발생 오류 : Target is multiclass but average='binary'--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-22-dbd4046600d4> in <cell line: 34>() 32 pred = model.predict(X_val) 33 ---> 34 print(f1_score(y_val,pred)) 35 36 # submit = pd.DataFrame({ 3 frames /usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py in _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) 1389 if y_type == "multiclass": 1390 average_options.remove("samples") -> 1391 raise ValueError( 1392 "Target is %s but average='binary'. Please " 1393 "choose another average setting, one of %r." % (y_type, average_options) ValueError: Target is multiclass but average='binary'. Please choose another average setting, one of [None, 'micro', 'macro', 'weighted'].*작성코드# 라이브러리 불러오기 import pandas as pd # 데이터 불러오기 train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") target = train.pop('Segmentation') train = train.drop('ID',axis = 1) test_id = test.pop('ID') # 데이터 인코딩 train = pd.get_dummies(train) test = pd.get_dummies(test) # print(train.shape,test.shape) # 검증데이터 생성 from sklearn.model_selection import train_test_split X_tr,X_val,y_tr,y_val = train_test_split( train,target,test_size=0.2,random_state=2023 ) # 모델 생성 및 평가 from sklearn.metrics import f1_score from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier(random_state = 2023,max_depth = 5,n_estimators = 200) model.fit(X_tr,y_tr) pred = model.predict(X_val) print(f1_score(y_val,pred))
-
해결됨딥러닝 CNN 완벽 가이드 - TFKeras 버전
안녕하세요 교수님 코드 부분 질문있습니다.
show_pixel_histogram(images_array[0])값이 실행할때마다 항상 다른 히스토그램을 보여주고있습니다.실행할때마다 batch_size만큼 다음 batch로 넘어가기 때문에 히스토그램 값이 달라지는것이 맞는지 여쭤보고 싶습니다.