묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
작업형1 하드코딩 관련
체험환경 링크에 들어가보면, 답안을 직접 타이핑해서 제출하도록 되어있습니다. Q1. 제1유형(풀이용)에서 하드코딩을 해도, 코드를 제출하는 것이 아니니, 감점은 따로 없을까요? Q2. 구버전에서는 제1유형도 코드를 제출하는 것으로 되어있던데, 이번에 바뀐건가요?
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
2회 작업형 2번 pred 질문 입니다.
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] 로 할지는 어떤 것을 보고 정할 수 있는지 여쭈어볼 수 있을까요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스
styles.js 자동완성이 안되요
styles.js 자동완성이 안되는데 익스텐션 뭐 설치해야되나요?
-
해결됨실무에서 바로 쓰는 영어 이메일
강의자료 요청
안녕하세요! 좋은 강의 정말 잘 듣고 있습니다~ 강의 자료 요청드립니다 :)chincrst@gmail.com 입니다~!
-
미해결
T2-4. House Prices (Regression)
# 시험환경 세팅 (코드 변경 X) import pandas as pd import numpy as np from sklearn.model_selection import train_test_split def exam_data_load(df, target, id_name="", null_name=""): if id_name == "": df = df.reset_index().rename(columns={"index": "id"}) id_name = 'id' else: id_name = id_name if null_name != "": df[df == null_name] = np.nan X_train, X_test = train_test_split(df, test_size=0.2, shuffle=True, random_state=2021) y_train = X_train[[id_name, target]] X_train = X_train.drop(columns=[id_name, target]) y_test = X_test[[id_name, target]] X_test = X_test.drop(columns=[id_name, target]) return X_train, X_test, y_train, y_test df = pd.read_csv("../input/house-prices-advanced-regression-techniques/train.csv") X_train, X_test, y_train, y_test = exam_data_load(df, target='SalePrice', id_name='Id') X_train.shape, X_test.shape, y_train.shape, y_test.shape ((1168, 79), (292, 79), (1168, 2), (292, 2))# 집 값 예측# 예측할 변수 ['SalePrice']# 평가: rmse, r2# rmse는 낮을 수록 좋은 성능# r2는 높을 수록 좋은 성능 죄송한데 이걸 레이블인코딩 후 랜덤포레스트로 핏 하고 RMSE와 r2_score로 평가하는 전체 코드좀 알 수 있을까요? 하나하나 질문하려니 계속 오류나거나 막힙니다,,
-
해결됨풀스택 리액트 라이브코딩 - 간단한 쇼핑몰 만들기
graphqlFetcher 관련 에러와 , data 객체 정의 되지 않는 오류 질문 드립니다
안녕하세요. msw 강의를 듣는 중에 해결되지 않는 문제가 있어서 질문 남깁니다.pages > products > [id].tsx이 호출과 일치하는 오버로드가 없습니다.오버로드 1/3('(queryKey: QueryKey, options?: Omit<UseQueryOptions<Product, unknown, Product, QueryKey>, "queryKey"> | undefined): UseQueryResult<...>')에서 다음 오류가 발생했습니다.'() => Promise<unknown>' 유형에 'Omit<UseQueryOptions<Product, unknown, Product, QueryKey>, "queryKey">' 유형과 공통적인 속성이 없습니다.오버로드 2/3('(queryKey: QueryKey, queryFn: QueryFunction<Product, QueryKey>, options?: Omit<UseQueryOptions<Product, unknown, Product, QueryKey>, "queryKey" | "queryFn"> | undefined): UseQueryResult<...>')에서 다음 오류가 발생했습니다.'Promise<unknown>' 형식은 'Product | Promise<Product>' 형식에 할당할 수 없습니다.'Promise<unknown>' 형식은 'Promise<Product>' 형식에 할당할 수 없습니다.'unknown' 형식은 'Product' 형식에 할당할 수 없습니다.ts(2769)types.d.ts(9, 89): 필요한 형식은 이 시그니처의 반환 형식에서 가져옵니다ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ'{}' 형식에 'Product' 형식의 id, imageUrl, price, title 외 2개 속성이 없습니다.ts(2740)detail.tsx(3, 77): 필요한 형식은 여기에서 'IntrinsicAttributes & { item: Product; }' 형식에 선언된 'item' 속성에서 가져옵니다.import { Product } from '../../graphql/products' const ProductDetail = ({ item: { title, imageUrl, description, price } }: { item: Product }) => ( <div className="product-detail"> <p className="product-detail__title">{title}</p> <img className="product-detail__image" src={imageUrl} /> <p className="product-detail__description">{description}</p> <span className="product-detail__price">${price}</span> </div> ) export default ProductDetailcomponents > products > detail.tsxpages > products > index.tsx이 호출과 일치하는 오버로드가 없습니다. ... 필요한 형식은 이 시그니처의 반환 형식에서 가져옵니다(위와 동일)'NonNullable<TQueryFnData>' 형식에 'products' 속성이 없습니다'product' 매개 변수에는 암시적으로 'any' 형식이 포함됩니다 해당 에러는 앞서 다른 수강생들도 질문한 부분이라 찾아봤는데const { data } = useQuery<Products>(QueryKeys.PRODUCTS, () => graphqlFetcher<Products>(GET_PRODUCTS) ) 알려주신 방식대로 리액트쿼리 버전 변경에 따라 타입스크립트 정의 방식이 바뀐 형태로 수정해주었는데도 같은 에러가 발생합니다.handlers.ts이 상태에서 실행을 하니 data객체가 정의되지 않는다고 나오며 localhost 500 Request Handler Error가 뜹니다import { gql } from 'graphql-tag' export type Product = { id: string imageUrl: string price: number title: string description: string createdAt: string } // export type MutableProduct = Omit<Product, 'id' | 'createdAt'> export type Products = { products: Product[] } const GET_PRODUCTS = gql` query GET_PRODUCTS { id imageUrl price title description createdAt } ` export const GET_PRODUCT = gql` query GET_PRODUCT($id: string) { id imageUrl price title description createdAt } `graphql > products.ts며칠째 계속 잡고 하다가 안되서 그냥 두고 다음 강의 듣고 있는 중인데 오류 때문에 자꾸 신경이 쓰이네요별거 아닌 에러였으면 좋겠네요
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형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}})); } }이렇게 작성하니까 배열 길이가 맞지 않다고 뜹니다.어디가 잘 못된건가요???
-
미해결
피그마 아코디언 오류인가요?
한 페이지 안에서 탭 버튼을 누르면 내부의 프레임을 변경을 하려고 합니다.페이지 안에 프레임과 버튼과 내용을 묶어서 인스턴스화해서 버튼 클릭할 때 마다 다른 다른 인스턴스로 바뀌게 하였고, 내용을 클릭하면 아코디언 형식으로 펼쳐지게 만들었습니다.아코디언 형식은 페에지 프레임에 쓰면 정상 작동을 하는데, 내부 프레임 안에만 들어가면 눌렀을 때 영역이 고정 된 상태에서 펼쳐집니다. 해결할 방법이 있을까요?