기출 6 작업형 2 import pandas as pd train = pd.rea d_csv( "energy_train.csv" ) test = pd.rea d_csv( "energy_test.csv" ) # train.shape,test.shape # print(train.head()) # print(test.head()) # print(train.isnull().sum()) # print(test.isnull().sum()) target = train.pop( 'Heat_Load' ) # print(train.describe(include='object')) train = pd.get_dummies(train) test = pd.get_dummies(test) # train.head() 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.ensemble import RandomForestClassifier model = RandomForestClassifier(random_state= 2023 ) model.fi t(X_tr,y_tr) pred = model.predict(X_val) # pred from sklearn.metrics import f1_score print (f1_score(y_val,pred,average= 'macro' )) pred = model.predict(test) pd.DataFrame({ 'pred' :pred}).to_csv( "result.csv" ,index= False ) pd.rea d_csv( "result.csv" ) 최근 인코딩 영상을 봤는데 범주형 인코딩 과정에서 train과 test unique 값이 같은지 다 비교해본 후에 진행해야 되나요? 지금은 nunique 값이 동일하면 바로 원핫인코딩이나 라벨인코딩 사용하고 있습니다. 만약 다른 값이 들어가 있으면 인코딩 할 때 오류가 발생하나요? randomforest만 이용해서 분류일 때랑 회귀일 때 나눠서 풀고 있는데 위의 코드처럼 작성하면 문제되는 점은 없을까요? randomforest에서 분류든 회귀든 max_depth와 n_estimators를 추가해서 검증 값이 높게 나오는 정도만 하면 될까요?
민맥스에서는 문제없이 돌아가는데 표준화와 로버스트 스케일링 에서는 T ransformerMixin.fit_ transform() missing 1 required positional argument: 'X' 라는 오류가 나옵니다! n_train[cols] = scaler.fit _transform(n_train[cols]) 이부분에서 에러가 나는 거 같은데 어떤 문제일까요? copy() 부분은 계속 실행하고 돌리고 있습니다
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 질문 : test에서 결측치가 발생할 경우엔 행을 삭제 못하나요? test 파일의 경우 저희가 시험장에서 볼 수 있는 것은 X_test 파일이고, y_test는 저희가 볼 수 없는 파일이잖아요. 그럼 X_test의 행을 삭제하면 오류가 뜨나요? 예를 들어 X_test에서 행이 50개인데 행을 3개 삭제하면, y_test는 50개이니까 평가가 불가능하지 않을까 싶습니다. 즉, test에는 결측치가 발생하면 X_test.fillna()를 통해 대체를 할 수 있지, X_test.dropna()처럼 행을 삭제할 수 없나요? 강의 때 올려주신 예시문제나 기출문제 해설을 봐도 작업형2에는 모두 결측치가 없어서, 이렇게 질문으로 올립니다. 시험이 다가오니 사소해 보이는 질문도 확인을 받고 싶네요 ㅠㅠ 항상 감사합니다
from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier(random_state = 2023) model.fit(X_tr, y_tr) pred = model.predict_proba(X_val) roc_auc_score(y_val, pred[:,1]) 안녕하세요? 마지막 pred 에서 슬라이싱할때.. 조금 헷갈리는데요..! pred[:,1]로 하는 이유가 예측(시간에 맞춰 도착하지 않을 확률) 때문인거 같은데..! 혹시 pred[:,0]을 할지 pred[:,1] 로 할지는 어떤 것을 보고 정할 수 있는지 여쭈어볼 수 있을까요?
데이터마님에 전처리100문제 훑어보고 있어요 람다식이 있어서 시험환경 문제1의 데이터로 응용해서 해보려니 안되네요 ㅠㅠ 그냥 딕셔너리 형태를 넣으면 되구요... help에서는 딕셔너리 아니면 시리즈를 넣으라고 되어있는데 그래서 안되는건지... a.cyl = a.cyl.astype('object') dic = { '4' : 'N', '6' : 'a', '8' : 'b' } a['newcyl'] =a.cyl.map(dic) print(a.cyl) a['newcyl'] = a.cyl.map (lambda x: dic[x]) > Makefile:6: recipe for target 'py3_run' failed make: *** [py3_run] Error 1 Traceback (most recent call last): File "/goorm/Main.out", line 18, in <module> a['newcyl'] =a.cyl.map(lambda x: dic[x]) File "/usr/local/lib/python3.9/dist-packages/pandas/core/series.py", line 4237, in map new_values = self._map_values(arg, na_action=na_action) File "/usr/local/lib/python3.9/dist-packages/pandas/core/base.py", line 880, in map values new_values = map_f(values, mapper) File "pandas/_libs/lib.pyx", line 2870, in pandas._libs.lib.map_infer File "/goorm/Main.out", line 18, in <lambda> a['newcyl'] =a.cyl.map(lambda x: dic[x]) KeyError: 6 help map(arg, na_action=None) -> 'Series' method of pandas.core.series.Series instance Map values of Series according to an input mapping or function. Used for substituting each value in a Series with another value, that may be derived from a function, a ``dict`` or a :class:`Series`. Parameters ---------- arg : function, collections.abc.Mapping subclass or Series Mapping correspondence. na_action : {None, 'ignore'}, default None If 'ignore', propagate NaN values, without passing them to the mapping correspondence.
train_test_split한 다음에 랜덤포레스트 모델학습에서 아래와 같이 코드 설명해주셨는데요. model.fit(X_tr[cols], y_tr) pred = model.predict_proba(X_val[cols]) train_test_split에서 이미 train[cols]로 train 범위가 한정되었는데 모델학습에서 X_tr과 X_val를 [cols]로 또 한정해줘야 할까요? 저는 아래와 같이 모델학습에서 [cols]를 빼고 코드를 작성했는데 오류는 나지 않지만 강의와 결과값이 조금 다릅니다. from sklearn.model_selection import train_test_split X_tr, X_val, y_tr, y_val = train_test_split(train[cols], target, test_size=0.2, random_state=0) # 모델학습 from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier(random_state=2023) model.fit(X_tr, y_tr) pred = model.predict_proba(X_val)
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 다름이 아니라, 체험환경에 실행결과 창에서는 Ctrl+C가 안 되어서 마우스 오른쪽-복사로 진행했었는데, 영상을 시청하다, 실행결과 창에서 단축키를 사용해서 붙여넣기를 하시더라고요..! 혹시 수업 내용과 관련된 답은 아니지만, 알려주실 수 있을까요? 시간 단축에 도움을 받고 싶습니다 ㅠㅠ
트레인의 주구매지점 값이 42개, 테스트의 주구매지점 값이 41개로 값이 달라서, 어떤 값 때문에 차이가 나는지 확인해주셨습니다. 트레인에는 있고, 테스트에는 없는 '소형가전' 때문이라고 찾아주시면서, 이 경우엔 전처리가 쉽고, 트레인에는 없는데, 테스트에는 있으면, 전처리가 어렵다고 해주셨습니다. (인코딩 시 트레인 테스트를 합친 후 분리) Q1. 이전까지는 라벨인코딩 시 위와 같이 범주형 변수의 값들을 set함수를 통해 확인하지 않고 라벨인코딩을 진행했는데, 앞으로는 무조건 하는 것이 좋을까요? Q2. 원핫 인코딩 시에도 동일하게 위와 같은 확인절차가 필요할까요? Q3. train과 test를 합칠 땐, pd.concat(['train', 'test'], axis = 0) 함수를 쓰면 될 것 같은데, 합치고 인코딩을 마친 뒤, 분리할 때는 어떤 함수를 써야할까요? train과 test의 컬럼수를 통일한 뒤, pd.concat으로 합치려했으나 계속 오류가 뜨네요..ㅠㅠ 감사합니다.