묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
람다 관련 질문이요 ㅠ
데이터마님에 전처리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' failedmake: *** [py3_run] Error 1Traceback (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 mapvalues 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.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
예시문제 작업형2(신버전) 풀이 질문입니다.
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)
-
미해결
T2-4 집값예측 말씀해주신대로,,
말씀해주신대로 원핫인코딩은 범주형 변주에만 적용하기 때문에 라벨인코딩은 진행하지 않고 원핫인코딩만 진행했습니다 코드는 다음과 같습니다 cols = X_train.select_dtypes(include='object').columns X_train = pd.get_dummies(X_train, columns=cols) X_test = pd.get_dummies(X_test, columns=cols) X_train.shape, X_test.shape ((1168, 284), (292, 253)) from sklearn.model_selection import train_test_split X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train['SalePrice'], test_size=0.2, random_state=0) X_tr.shape, X_val.shape, y_tr.shape, y_val.shape ((934, 284), (234, 284), (934,), (234,)) from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(random_state=0) rf.fit(X_tr, y_tr) pred = rf.predict(X_val) pred ValueError: Input contains NaN, infinity or a value too large for dtype('float32').원핫인코딩으로 전처리 후 검증데이터 분리하고 랜덤포레스트리그레서 사용했는데, 여기서 수치형이 너무 많다고 나오는데,, 어떻게 해야할까요?
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
IO Exception: "/Users/eulyoungjung/test.mv.db" [90028-224] 90028/90028 (Help)
test.mv.db 를 직접 생성 하여 했는데도 연결이 되지 않습니다 ... 빠른답변 부탁드려요 !!
-
미해결
빅분기 제1유형 하드코딩 질문
체험환경 링크에 들어가보면, 답안을 직접 타이핑해서 제출하도록 되어있습니다. Q1. 제1유형(풀이용)에서 하드코딩을 해도, 코드를 제출하는 것이 아니니, 감점은 따로 없을까요? Q2. 구버전에서는 제1유형도 코드를 제출하는 것으로 되어있던데, 이번에 바뀐건가요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
실행결과 복사 질문
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요!질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요먼저 유사한 질문이 있었는지 검색해보세요 다름이 아니라, 체험환경에 실행결과 창에서는 Ctrl+C가 안 되어서 마우스 오른쪽-복사로 진행했었는데, 영상을 시청하다, 실행결과 창에서 단축키를 사용해서 붙여넣기를 하시더라고요..! 혹시 수업 내용과 관련된 답은 아니지만, 알려주실 수 있을까요? 시간 단축에 도움을 받고 싶습니다 ㅠㅠ
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
예시문제 작업형2(신버전) 라벨인코딩 질문
트레인의 주구매지점 값이 42개, 테스트의 주구매지점 값이 41개로 값이 달라서, 어떤 값 때문에 차이가 나는지 확인해주셨습니다.트레인에는 있고, 테스트에는 없는 '소형가전' 때문이라고 찾아주시면서, 이 경우엔 전처리가 쉽고,트레인에는 없는데, 테스트에는 있으면, 전처리가 어렵다고 해주셨습니다. (인코딩 시 트레인 테스트를 합친 후 분리) Q1. 이전까지는 라벨인코딩 시 위와 같이 범주형 변수의 값들을 set함수를 통해 확인하지 않고 라벨인코딩을 진행했는데, 앞으로는 무조건 하는 것이 좋을까요? Q2. 원핫 인코딩 시에도 동일하게 위와 같은 확인절차가 필요할까요? Q3. train과 test를 합칠 땐, pd.concat(['train', 'test'], axis = 0) 함수를 쓰면 될 것 같은데, 합치고 인코딩을 마친 뒤, 분리할 때는 어떤 함수를 써야할까요?train과 test의 컬럼수를 통일한 뒤, pd.concat으로 합치려했으나 계속 오류가 뜨네요..ㅠㅠ 감사합니다.
-
해결됨
로지스틱 회귀모형 관련
로지스틱 회귀분석관련 캐글에 있는 문제 ( T3-2-example-py ) 풀이 질문입니다.Pclass, Gender, sibsp, parch를 독립변수로 사용하여 로지스틱 회귀모형을 실시하였을 때, parch변수의 계수값은?정답 풀이는 스탯츠모델 포뮬라로 다음과 같이 되어있는데요, import pandas as pd from statsmodels.formula.api import logit df = pd.read_csv("/kaggle/input/bigdatacertificationkr/Titanic.csv") formula = "Survived ~ C(Pclass) + Gender + SibSp + Parch" model = logit(formula, data=df).fit() Optimization terminated successfully. Current function value: 0.459565 Iterations 6 Intercept 2.491729 C(Pclass)[T.2] -0.848152 C(Pclass)[T.3] -1.866905 Gender[T.male] -2.760281 SibSp -0.232553 Parch -0.049847 dtype: float64사이킷런 LogisticRegression으로 해서 coefficient 를 찾아도 되지 않나 싶어 해보니, 이경우는 원핫인코딩을 해야해서, Gender 변수가 나누어지고, SibSP와 Parch 계수 값만 비교해봐도 결과가 약간 다르게 나오는데, 어떤게 맞는걸까요 ?(아래 사이킷런에서 Parch 계수는 -0.04398284, 위 스탯츠포뮬라에서 Parch계수는 -0.049847)from sklearn.linear_model import LogisticRegression df = pd.get_dummies(df, columns=['Gender']) cols = ['Pclass', 'Gender_female', 'Gender_male', 'SibSp', 'Parch'] model = LogisticRegression() model.fit(df[cols], df['Survived']) coefficients = model.coef_ intercept = model.intercept_ print("Coefficients:", coefficients) print("Intercept:", intercept)Coefficients: [[-0.92192738 1.35286636 -1.35285472 -0.2285361 -0.04398284]] Intercept: [2.02953505] 답변주시면, 감사하겠습니다
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
공유해주신 데이콘 문제
안녕하세요. 공유해주신 데이콘 문제 즁 분류문제를 풀어봤습니다. 이 문제에서 저는 Macro f1 평가점수가 0.37901이 나왔는데요...이게 빅분기 시험이었다면..40점 중 몇점 정도를 받았을까요?
-
미해결
T2-4 집값 예측 랜덤포레스트에서
집값예측에서 수치형은 원핫인코딩 진행하고 범주형은 라벨인코딩으로 전처리 하려고 하는 코드를 만들어보려고 해요 그런데 하다가 랜덤포레스트에서 막혔습니다,, cols1 = X_train.select_dtypes(exclude='object').columns X_train[cols1] = pd.get_dummies(X_train[cols1]) X_test[cols1] = pd.get_dummies(X_test[cols1]) X_train.shape, X_test.shape ((1168, 79), (292, 79)) cols2 = X_train.select_dtypes(include='object').columns X_train[cols] = X_train[cols].fillna('NotAvailable') X_test[cols] = X_test[cols].fillna('NotAvailable') X_train.head() from sklearn.preprocessing import LabelEncoder le = LabelEncoder() for col in cols: 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['SalePrice'], test_size=0.2, random_state=0) X_tr.shape, X_val.shape, y_tr.shape, y_val.shape ((934, 79), (234, 79), (934,), (234,)) from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(random_state=0) rf.fit(X_tr, y_tr) pred = rf.predict(X_val) pred You have categorical data, but your model needs something numerical. See our one hot encoding tutorial for a solution. --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_20/1040259155.py in <module> 1 from sklearn.ensemble import RandomForestRegressor 2 rf = RandomForestRegressor(random_state=0) ----> 3 rf.fit(X_tr, y_tr) 4 pred = rf.predict(X_val) 5 pred /opt/conda/lib/python3.7/site-packages/sklearn/ensemble/_forest.py in fit(self, X, y, sample_weight) 302 ) 303 X, y = self._validate_data(X, y, multi_output=True, --> 304 accept_sparse="csc", dtype=DTYPE) 305 if sample_weight is not None: 306 sample_weight = _check_sample_weight(sample_weight, X) /opt/conda/lib/python3.7/site-packages/sklearn/base.py in _validate_data(self, X, y, reset, validate_separately, **check_params) 430 y = check_array(y, **check_y_params) 431 else: --> 432 X, y = check_X_y(X, y, **check_params) 433 out = X, y 434 /opt/conda/lib/python3.7/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs) 70 FutureWarning) 71 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) ---> 72 return f(**kwargs) 73 return inner_f 74 /opt/conda/lib/python3.7/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator) 800 ensure_min_samples=ensure_min_samples, 801 ensure_min_features=ensure_min_features, --> 802 estimator=estimator) 803 if multi_output: 804 y = check_array(y, accept_sparse='csr', force_all_finite=True, /opt/conda/lib/python3.7/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs) 70 FutureWarning) 71 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) ---> 72 return f(**kwargs) 73 return inner_f 74 /opt/conda/lib/python3.7/site-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) 596 array = array.astype(dtype, casting="unsafe", copy=False) 597 else: --> 598 array = np.asarray(array, order=order, dtype=dtype) 599 except ComplexWarning: 600 raise ValueError("Complex data not supported\n" /opt/conda/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order) 81 82 """ ---> 83 return array(a, dtype, copy=False, order=order) 84 85 /opt/conda/lib/python3.7/site-packages/pandas/core/generic.py in __array__(self, dtype) 1991 1992 def __array__(self, dtype: NpDtype | None = None) -> np.ndarray: -> 1993 return np.asarray(self._values, dtype=dtype) 1994 1995 def __array_wrap__( /opt/conda/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order) 81 82 """ ---> 83 return array(a, dtype, copy=False, order=order) 84 85 ValueError: could not convert string to float: 'RL'
-
미해결BBC 인터랙티브 페이지 "코로나19가 바꿀 사무실의 미래" 클론
React에도 적용 가능한가요?
질문은 제목 그대로 입니다 선생님.다 배우면 이것을 React 프로젝트에도 적용이 가능한지 궁금합니다. 좋은 강의를 무료로 베풀어주셔서 감사합니다!
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
섹션6 모의고사 풀어보기 2 관련
안녕하세요! 모의고사2 관련 질문입니다. 수업에서 배운대로 pd.get_dummies로 원핫 인코딩을 했는데요.. 파일을 합쳐서 원핫인코딩을 하고나니 원래 있던 다른 수치형 컬럼들이 다 없어지고 원핫으로 만든 컬럼들만 남더라구요;;이렇게 되면 파일 다시 나누고 모델학습할떄 원핫으로 만든 컬럼들만 남아서 안될것같은데 제가 코드를 잘못친걸까요..? 전체 코드는 아래에 붙여놓았습니다. # 시험환경 세팅import pandas as pdfrom sklearn import datasetsdataset = datasets.load_breast_cancer()df = pd.DataFrame(dataset['data'], columns=dataset['feature_names'])df['target'] = dataset['target']df.to_csv("data2.csv", index=False) from sklearn.model_selection import train_test_splittrain, test = train_test_split(df, test_size=0.2, random_state=2022)y_test = test.pop('target')train.to_csv('train.csv', index=False)test.to_csv('test.csv', index=False) # 데이터 파일 읽기 예제import pandas as pdtrain = pd.read_csv("data/customer_train.csv")test = pd.read_csv("data/customer_test.csv") #EDA# print(train.shape, test.shape) (3500, 11) (2482, 10)# print(train['성별'].value_counts()) 0 2184 1 1316# print(train.info(), test.info()) object=주구매상품, 주구매지점# print(train.isnull().sum(), test.isnull().sum()) 결측치는 환불금액 2295 / 1611# print(train['환불금액'].describe())pd.set_option('display.max_columns',None)#결측치train['환불금액'] = train['환불금액'].fillna(0)test['환불금액'] = test['환불금액'].fillna(0)# print(train.isnull().sum(), test.isnull().sum()) #파일 나누기target = train.pop('성별')# print(train.shape, target.shape)train =train.drop('회원ID', axis=1)# print(train.shape)id = test.pop('회원ID')# print(test.shape, id.shape)# print(train.shape, test.shape) #피쳐 엔지니어링#1.베이스라인 #2. 인코딩# print(train.describe(include='O'),test.describe(include='O') )# TRAIN 주구매상품에 소형가전이 추가로 있음# a = set(train['주구매지점'].unique())# b = set(test['주구매지점'].unique())# print (a-b)# print (b-a) all_df=pd.concat([train,test])cols = ['주구매상품', '주구매지점']all_df=pd.get_dummies(all_df[cols])print(all_df.head()) -> 여기서 원핫인코딩 한 이후로 원래 있던 수치형 컬럼들이 다 사라졌습니다; # print(train.columns) # from sklearn.preprocessing import LabelEncoder# for col in cols :# le = LabelEncoder()# train[col] = le.fit_transform(train[col])# test[col] = le.transform(test[col]) # print(train.head(), test.head()) # cols = ['주구매상품', '주구매지점']# cols = ['총구매액', '최대구매액', '환불금액', '방문일수', '방문당구매건수', '주말방문비율', '구매주기']# print(train.select_dtypes(exclude='object').columns) #데이터 분할# 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 =2024)# print(x_tr.shape, x_val.shape, y_tr.shape, y_val.shape) # #학습# from sklearn.ensemble import RandomForestClassifier# model = RandomForestClassifier(random_state=0)# model.fit(x_tr,y_tr)# pred = model.predict(x_val)# # print(pred)# print(pred.shape) # # #평가 f1# from sklearn.metrics import f1_score# print(f1_score(y_val, pred)) # #베이스라인 0.4460093896713615# #라벨인코딩 0.42352941176470593# #원핫인코딩
-
미해결자바 코딩테스트 - it 대기업 유제
방향바꾸기 문제 질문드립니다.
import java.io.*; import java.util.*; class Node implements Comparable<Node>{ int x; int y; int c; Node(int x, int y, int c){ this.x=x; this.y=y; this.c=c; } @Override public int compareTo(Node o) { return this.c-o.c; } } class Main { public int solution(int[][] board) { int answer = 0; int n=board.length; int m=board[0].length; int[][] dist =new int[n][m]; int INF = (int)1e9; PriorityQueue<Node> q = new PriorityQueue<>(); q.add(new Node(0,0,0)); for(int i=0; i<n; i++) Arrays.fill(dist[i], INF); dist[0][0]=0; int[] dx = {0,0,1,-1}; int[] dy = {1,-1,0,0}; while(!q.isEmpty()) { Node tmp = q.poll(); int nowx = tmp.x; int nowy = tmp.y; int nowc=tmp.c; int dir = board[nowx][nowy]-1; if(nowc>dist[nowx][nowy]) continue; for(int i=0; i<4;i++) { int nx = nowx+dx[i]; int ny = nowy+dy[i]; if(i==dir && dist[nx][ny]>nowc) { dist[nx][ny] = nowc; if(q.add(new Node(nx,ny,dist[nx][ny]))); } else if(i!=dir && dist[nx][ny]>nowc+1) { dist[nx][ny] = nowc+1; q.add(new Node(nx,ny,dist[nx][ny])); } } } answer = dist[n-1][m-1]; return answer; } public static void main(String[] args){ Main T = new Main(); System.out.println(T.solution(new int[][]{{3, 1, 3}, {1, 4, 2}, {4, 2, 3}})); System.out.println(T.solution(new int[][]{{3, 2, 1, 3}, {1, 1, 4, 2}, {3, 4, 2, 1}, {1, 2, 2, 4}})); System.out.println(T.solution(new int[][]{{3, 2, 1, 3, 1, 2}, {2, 1, 1, 1, 4, 2}, {2, 2, 2, 1, 2, 2}, {1, 3, 3, 4, 4, 4}, {1, 2, 2, 3, 3, 4}})); System.out.println(T.solution(new int[][]{{3, 2, 1, 3, 1, 2, 2, 2}, {2, 1, 1, 1, 4, 2, 1, 1}, {2, 2, 2, 1, 2, 2, 3, 4}, {1, 3, 3, 4, 4, 4, 3, 1}, {1, 2, 2, 3, 3, 4, 3, 4}, {1, 2, 2, 3, 3, 1, 1, 1}})); System.out.println(T.solution(new int[][]{{1, 2, 3, 2, 1, 3, 1, 2, 2, 2}, {1, 2, 2, 1, 1, 1, 4, 2, 1, 1}, {3, 2, 2, 2, 2, 1, 2, 2, 3, 4}, {3, 3, 1, 3, 3, 4, 4, 4, 3, 1}, {1, 1, 1, 2, 2, 3, 3, 4, 3, 4}, {1, 1, 1, 2, 2, 3, 3, 1, 1, 1}})); } }이렇게 작성하니까 배열 길이가 맞지 않다고 뜹니다.어디가 잘 못된건가요???
-
미해결
피그마 아코디언 오류인가요?
한 페이지 안에서 탭 버튼을 누르면 내부의 프레임을 변경을 하려고 합니다.페이지 안에 프레임과 버튼과 내용을 묶어서 인스턴스화해서 버튼 클릭할 때 마다 다른 다른 인스턴스로 바뀌게 하였고, 내용을 클릭하면 아코디언 형식으로 펼쳐지게 만들었습니다.아코디언 형식은 페에지 프레임에 쓰면 정상 작동을 하는데, 내부 프레임 안에만 들어가면 눌렀을 때 영역이 고정 된 상태에서 펼쳐집니다. 해결할 방법이 있을까요?
-
미해결실습으로 배우는 프로메테우스 - {{ x86-64, arm64 }}
보강 강의 A.11.005 교육 영상 및 자료 문의
질문 답변을 제공하지만, 강의 비용에는 Q&A는 포함되어 있지 않습니다. 다만 실습이 안되거나, 잘못된 내용의 경우는 알려주시면 가능한 빠르게 조치하겠습니다![질문 전 답변]1. 강의에서 다룬 내용과 관련된 질문인가요? [예 | 아니요]2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? [예 | 아니요]3. 질문 잘하기 법을 읽어보셨나요? [예 | 아니요](https://www.inflearn.com/blogs/1719)4. 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.[질문 하기]안녕하세요A.11.005.프로메테우스에 미리 지정된 메트릭 이야기 강의를 수강하려고 하였지만, 수강자료나 영상이 따로 없는것인지 빈화면으로 출력됩니다. 해당 강의는 향후 업데이트 되는것일까요?그리고 공지사항에 따로 글이 없없어 같이 질문을 남깁니다.A.11.012. 공개된 프로메테우스 데모 사이트 강의 사이의 A.11.006~A.11.011은 따로 있는것인지 아니면 해당 숫자는 의미가 없는것인지 알 수 있을까요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형3 범주형 변수 관련 질문
선생님 안녕하세요!작업형3 로지스틱 회귀모형을 진행할 때범주형 데이터는 C()로 묶어서 하라고 말씀해주셨는데, 강의에서 만약 범주형 데이터인지 헷갈린다면 모두 C()로 묶어서 하라고 하셨던 것으로 기억하는데그렇게하면 에러가 뜨는데 왜일까요??# 2. # 로지스틱 회귀모형 from statsmodels.formula.api import logit # model = logit('Survived ~ C(Gender) + C(SibSp) + C(Parch) + C(Fare)', data=df).fit() --> error # print(df.head()) model = logit('Survived ~ C(Gender) + SibSp + Parch + Fare', data=df).fit() print(model.summary()) # print(model.params['Parch']) # 답 : -0.201Warning: Maximum number of iterations has been exceeded. Current function value: inf Iterations: 35 Makefile:6: recipe for target 'py3_run' failed make: *** [py3_run] Error 1 /usr/local/lib/python3.9/dist-packages/statsmodels/discrete/discrete_model.py:1819: RuntimeWarning: overflow encountered in exp return 1/(1+np.exp(-X)) /usr/local/lib/python3.9/dist-packages/statsmodels/discrete/discrete_model.py:1872: RuntimeWarning: divide by zero encountered in log return np.sum(np.log(self.cdf(q*np.dot(X,params)))) Traceback (most recent call last): File "/goorm/Main.out", line 26, in <module> model = logit('Survived ~ C(Gender) + C(SibSp) + C(Parch) + C(Fare)', data=df).fit() File "/usr/local/lib/python3.9/dist-packages/statsmodels/discrete/discrete_model.py", line 1983, in fit bnryfit = super().fit(start_params=start_params, File "/usr/local/lib/python3.9/dist-packages/statsmodels/discrete/discrete_model.py", line 230, in fit mlefit = super().fit(start_params=start_params, File "/usr/local/lib/python3.9/dist-packages/statsmodels/base/model.py", line 579, in fit Hinv = np.linalg.inv(-retvals['Hessian']) / nobs File "<__array_function__ internals>", line 5, in inv File "/usr/local/lib/python3.9/dist-packages/numpy/linalg/linalg.py", line 545, in inv ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj) File "/usr/local/lib/python3.9/dist-packages/numpy/linalg/linalg.py", line 88, in _raise_linalgerror_singular raise LinAlgError("Singular matrix") numpy.linalg.LinAlgError: Singular matrix
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
random_state 값에 따라서 값이 큰 차이가 나는 경우가 있나여 ?
안녕하세요 2유형을 공부하는 중에 train_test_split의 random_state 값에 따라서 값의 편차가 크게 차이 나는 것을 발견했습니다. # random_state = 1 : 0.8643817947300534 # random_state = 2023 : 0.7804496038326884이 정도로 차이가 나는데 테스트 값에는 크게 영항이 없는 것인가요 ? 다른 코드들은 모두 동일했습니다 ! import pandas as pd import warnings warnings.filterwarnings('ignore') train= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/stroke_/train.csv') test= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/stroke_/test.csv') train = train.drop('id',axis=1) test_id = test.pop('id') y_train = train.pop('stroke') # 결측치 채우기 train['bmi'] = train['bmi'].fillna(train['bmi'].mean()) test['bmi'] = test['bmi'].fillna(train['bmi'].mean()) train['age'] = train['age'].str.replace('*','').astype('int') # StandarScaler # print(train.info()) # train.nunique() cols = ['age','avg_glucose_level', 'bmi'] from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() train[cols] = scaler.fit_transform(train[cols]) test[cols] = scaler.transform(test[cols]) # LabelEncoder from sklearn.preprocessing import LabelEncoder le = LabelEncoder() train['gender'] = le.fit_transform(train[['gender']]) test['gender'] = le.fit_transform(test[['gender']]) # get_dummies train = pd.get_dummies(train) test = pd.get_dummies(test) cols = ['ever_married_No','work_type_Govt_job','Residence_type_Rural','smoking_status_Unknown'] train = train.drop(cols,axis=1) test = test.drop(cols,axis=1) from sklearn.model_selection import train_test_split X_tr,X_val,y_tr,y_val = train_test_split(train,y_train,test_size=0.2,random_state=2023,stratify = y_train) from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier(random_state=2023,n_estimators = 200) model.fit(X_tr,y_tr) pred_val = model.predict_proba(X_val) from sklearn.metrics import roc_auc_score roc_auc_score(y_val,pred_val[:,1]) # random_state = 1 : 0.8643817947300534 # random_state = 2023 : 0.7804496038326884
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형1, 작업형3 답안제출 문의드립니다
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요!질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요먼저 유사한 질문이 있었는지 검색해보세요안녕하세요 실기 답안 제출 방식이 6회->7회 변경된 것 같습니다.작업형1, 작업형3 답안 제출 방식이 혼동스러워서, 문의드립니다. 제6회 빅데이터분석기사 실기 자격검정 안내제7회 빅데이터분석기사 실기 자격검정 안내 6회에서는 별도의 (답안제출)공간이 없었기 때문에 코드 작성 구간에 print()문으로 답안을 기입했던 것으로 유추가 됩니다. 그렇다면 7회에서는 (풀이용)에 작성하는 코드는 채점에 미반영되며, 오로지 (답안제출)로만 채점반영 한다고 판단하면 될까요? 작업형1, 작업형3 코드 작성 화면에도 <제출> 버튼이 있기에, (풀이용)에 별도로 print()문 작성 및 제출해야 하는 것인지 의문이 들었습니다. 사소하지만, 정확하게 알고 넘어가지 않으면 0점 받을 수도 있는 사안이기에 질문 드립니다. 감사합니다.
-
미해결
groupby 질문
# city와 f4를 기준으로 f5의 평균값을 구한 다음, f5를 기준으로 상위 7개 값을 모두 더해 출력하시오 (소수점 둘째자리까지 출력) # - 데이터셋 : basic1.csv # - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작 # - File -> Editor Type -> Script import pandas as pd df = pd.read_csv("../input/bigdatacertificationkr/basic1.csv") df.head() # city와 f4별 f5의 평균 값 (멀티인덱스 출력) df = df.groupby(['city', 'f4'])[['f5']].mean() print(df) 여기서는 명확하게 그룹화 한 후에 평균값을 구하라고 명시되어 있어서 mean()을 썼지만 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' # 주어진 데이터에서 상위 10개 국가의 접종률 평균과 하위 10개 국가의 접종률 평균을 구하고, 그 차이를 구해보세요# (단, 100%가 넘는 접종률 제거, 소수 첫째자리까지 출력)# - 데이터셋 : ../input/covid-vaccination-vs-death/covid-vaccination-vs-death_ratio.csv# - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작# - File -> Editor Type -> Scriptimport pandas as pddf = pd.read_csv("../input/covid-vaccination-vs-death/covid-vaccination-vs-death_ratio.csv")# print(df.head())df2 = df.groupby('country').max() #시간에 따라 접종률이 점점 올라감df2 = df2.sort_values(by='ratio', ascending = False) 여기서는 왜 groupby 뒤에 max()를 썼는지 이해를 못하겠어요,,그리고 그 밑에 ratio 를 내림차순 정렬하는데 by= 의 의미를 모르겠어요,,보통 내림차순 정렬은 df.sort_values('ratio', ascending=False) 로 하는데,, 여기서는 왜 by 쓴건가요?
-
미해결Java TPC 실전프로젝트 (Java API 활용)
강의 들으면서 잘 안되는 부분이 있어서요~
moquitto 관련 부분 작동이 되는지 확인해봐주실수 있나요?WARNING: An illegal reflective access operation has occurredWARNING: Illegal reflective access by org.eclipse.paho.client.mqttv3.internal.FileLock (file:/C:/eGovFrame-4.0.0/maven/repository/org/eclipse/paho/org.eclipse.paho.client.mqttv3/1.2.5/org.eclipse.paho.client.mqttv3-1.2.5.jar) to method sun.nio.ch.FileLockImpl.release()WARNING: Please consider reporting this to the maintainers of org.eclipse.paho.client.mqttv3.internal.FileLockWARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operationsWARNING: All illegal access operations will be denied in a future releaseERR0[Ljava.lang.StackTraceElement;@6021afeb이런 에러가 뜨는데 왜그런지 모르겠네요... maven이 아니라 일반 자바프로젝트에서 jar파일로 해봐도 ERR0[Ljava.lang.StackTraceElement;@6021afeb 이 메세지가 계속 뜨네요