프로그래밍 시작하기 : 도전! 45가지 파이썬 기초 문법 실습 (Inflearn Original)
1. 질문하시기 전 유사한 질문 이 있는지 검색을 먼저 부탁드려요! 전체 소스코드 를 올려주시면 답변을 빠르게 드릴 수 있어요!(글보다 빨라요) 기초적인 질문은 이미 검색해보시면 사례가 많이 있어요! 문법적인 궁금증은 먼저 구글 검색을 통해서 레퍼런스(메뉴얼)을 읽어보시고 해결하시면 실력 향상 100% 너무 잦은 질문이나 강의와 관련 없는 질문 은 가급적 자제 부탁드려요 ㅠ.ㅠ 2. 답변이 다소 늦을 수도 있어요! 일반적인 근무시간(9 TO 6) 안에는 답변을 드리도록 노력하고 있어요! 문법적인 질문은 먼저 검색을 통해 해결해 보세요! 정확하게 질문해주시면 정확한 답변을 받으실 수 있어요! 늦더라도 꼭 응답은 드리고 있으니, 먼저 검색을 통해 해결해 보세요! random. sample ( population , k , * , counts=None ) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. random. choices ( population , weights=None , * , cum_weights=None , k=1 ) Return a k sized list of elements chosen from the population with replacement. python 공식 문서에는 sample 함수가 중복 없이 생성한다고 적혀 있는 것 같은데, 강의 자료나 강의 내에서는 choices 함수가 중복 없이 생성한다고 적혀 있어서 문의 드립니다
아래의 코드를 입력하면 다음과 같은 에러가 발생합니다 KeyError : "['name', 'host_name', 'last_review', 'host_id'] not found in axis" 왜 이런 건가요?ㅠㅠ cols = ['name','host_name','last_review','host_id'] print(train.shape) train = train.drop(cols, axis=1) test = test.drop(cols, axis=1) print(train.shape)
레이블 인코딩 시 le = LabelEncoder() for col in cols: le = LabelEncoder() c_train[col = le.fit_transform(..) c_test .... for 문 전에 레이블 인코더를 호출하여 선언하고 for문 내에서 또 하는 이유는 무엇인가요? for문 시작 전 한번만 해 줘도 되는 게 아닌가해서 질문드려 봅니다.
$ npm start > MatzipApp@0.0.1 start > react-native start ▒▒▓▓▓▓▒▒ ▒▓▓▓▒▒░░▒▒▓▓▓▒ ▒▓▓▓▓░░░▒▒▒▒░░░▓▓▓▓▒ ▓▓▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▓▓ ▓▓░░░░░▒▓▓▓▓▓▓▒░░░░░▓▓ ▓▓░░▓▓▒░░░▒▒░░░▒▓▒░░▓▓ ▓▓░░▓▓▓▓▓▒▒▒▒▓▓▓▓▒░░▓▓ ▓▓░░▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░▓▓ ▓▓▒░░▒▒▓▓▓▓▓▓▓▓▒░░░▒▓▓ ▒▓▓▓▒░░░▒▓▓▒░░░▒▓▓▓▒ ▒▓▓▓▒░░░░▒▓▓▓▒ ▒▒▓▓▓▓▒▒ Welcome to Metro v0.76.8 Fast - Scalable - Integrated r - reload the app d - open developer menu i - run on iOS a - run on Android info Opening the app on Android... info JS server already running. info Launching emulator... info Installing the app... > Task :gradle-plugin:compileKotlin UP-TO-DATE > Task :gradle-plugin:compileJava NO-SOURCE > Task :gradle-plugin:pluginDescriptors UP-TO-DATE > Task :gradle-plugin:processResources UP-TO-DATE > Task :gradle-plugin:classes UP-TO-DATE > Task :gradle-plugin:jar UP-TO-DATE > Task :gradle-plugin:inspectClassesForKotlinIC UP-TO-DATE > Task :app:buildCodegenCLI SKIPPED > Task :app:generateCodegenSchemaFromJavaScript SKIPPED > Task :app:generateCodegenArtifactsFromSchema SKIPPED > Task :app:generatePackageList > Task :app:preBuild > Task :app:preDebugBuild > Task :app:compileDebugAidl NO-SOURCE > Task :app:compileDebugRenderscript NO-SOURCE > Task :app:generateDebugBuildConfig UP-TO-DATE > Task :app:javaPreCompileDebug UP-TO-DATE > Task :app:checkDebugAarMetadata UP-TO-DATE > Task :app:generateDebugResValues UP-TO-DATE > Task :app:mapDebugSourceSetPaths UP-TO-DATE > Task :app:generateDebugResources UP-TO-DATE > Task :app:mergeDebugResources UP-TO-DATE > Task :app:createDebugCompatibleScreenManifests UP-TO-DATE > Task :app:extractDeepLinksDebug UP-TO-DATE > Task :app:processDebugMainManifest UP-TO-DATE > Task :app:processDebugManifest UP-TO-DATE > Task :app:processDebugManifestForPackage UP-TO-DATE > Task :app:processDebugResources UP-TO-DATE > Task :app:compileDebugJavaWithJavac UP-TO-DATE > Task :app:mergeDebugShaders UP-TO-DATE > Task :app:compileDebugShaders NO-SOURCE > Task :app:generateDebugAssets UP-TO-DATE > Task :app:mergeDebugAssets UP-TO-DATE > Task :app:compressDebugAssets UP-TO-DATE > Task :app:processDebugJavaRes NO-SOURCE > Task :app:mergeDebugJavaResource UP-TO-DATE > Task :app:checkDebugDuplicateClasses UP-TO-DATE > Task :app:desugarDebugFileDependencies UP-TO-DATE > Task :app:mergeExtDexDebug UP-TO-DATE > Task :app:mergeLibDexDebug UP-TO-DATE > Task :app:dexBuilderDebug UP-TO-DATE > Task :app:mergeProjectDexDebug UP-TO-DATE > Task :app:mergeDebugJniLibFolders UP-TO-DATE > Task :app:mergeDebugNativeLibs UP-TO-DATE > Task :app:stripDebugDebugSymbols UP-TO-DATE > Task :app:validateSigningDebug UP-TO-DATE > Task :app:writeDebugAppMetadata UP-TO-DATE > Task :app:writeDebugSigningConfigVersions UP-TO-DATE > Task :app:packageDebug UP-TO-DATE > Task :app:createDebugApkListingFileRedirect UP-TO-DATE > Task :app:installDebug FAILED 38 actionable tasks: 2 executed, 36 up-to-date info 💡 Tip: Make sure that you have set up your development environment correctly, by running react-native doctor. To read more about doctor command visit: https://github.com/react-native-community/cli/blob/main/packages/cli-doctor/README.md#doctor Warning: SDK processing. This version only understands SDK XML versions up to 3 but an SDK XML file of version 4 was encountered. This can happen if you use versions of Android Studio and the command-line tools that were released at different times. FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:installDebug'. > com.android.builder.testing.api.DeviceException: No connected devices! * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 15s info Run CLI with --verbose flag for more details. 프로젝트 버전을 0.72.6로 했던 것 같은데, 아니네욤 $ npx react-native doctor Common ✓ Node.js - Required to execute JavaScript code ✓ npm - Required to install NPM dependencies Android ✖ Adb - No devices and/or emulators connected. Please create emulator with Android Studio or connect Android device. ✓ JDK - Required to compile Java code ✓ Android Studio - Required for building and installing your app on Android ✖ Android SDK - Required for building and installing your app on Android - Versions found: N/A - Version supported: 33.0.0 ✓ ANDROID_HOME - Environment variable that points to your Android SDK installation Errors: 2 Warnings: 0 Android ✖ Adb √ Select the device / emulator you want to use » Emulator Pixel_5_API_33 (disconnected) ✔ Adb ✔ Android SDK configured. You might need to restart your PC for all changes to take effect.! C:\Users[사용자이름]\AppData\Local\Google\AndroidStudio2024.1\log idea.log WARN - Emulator: Medium Phone API 35 - Emulator terminated with exit code -529697949 C:\Windows\System32>npx react-native -v 11.3.7 C:\Windows\System32>java -version openjdk version "17.0.8.1" 2023-08-24 OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) 사용자 변수의 PATH 사용자 변수 해결이 잘 안 되네요 ㅠㅠ ANDROID_HOME 환경 변수는 C 드라이브 밑에 제가 만든 폴더 경로(SDK 설치 단계에서 한 경로)로 잘 해두었습니다. Graphics 설정을 Software로 변경해보고 Windows 보안에서 폴더 제거해보고 인텔 그래픽 드라이버 업데이트해보고 메모리도 키워 보고
안녕하세요 선생님. 이전 두 질문에 대한 답변이 많은 도움이 되었습니다. 감사합니다. 2133번 문제의 DP 1번 풀이에서 O(N^2) 풀이를 소개해주셨는데 아래와 같이 dp 테이블을 갱신할 때 sum_dp 테이블을 같이 갱신을 해주면 시간복잡도가 O(N)으로 줄일 수 있지 않나 싶어 질문드립니다. N = int(input()) if N % 2 != 0: print(0) else: n = N//2 dp = [1] * (n+1) sum_dp = [1] * (n+1) for i in range(1,n+1): dp[i] = sum_dp[i-1] * 2 + dp[i-1] sum_dp[i] = sum_dp[i-1] + dp[i] print(dp[-1]) 그리고 이건 다른 종류의 질문인데 혹시 그래프 부분이 실제로 코테에 많이 등장하나요? 제가 조금 급하게 준비하고 있는 상태라 이론을 필수 알고리즘2까지만 들어도 될지 아니면 그래프까지 다 들어야될지 고민중입니다. 조언 주시면 감사하겠습니다!
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
import {Router, Request, Response} from "express"; import {User} from "../entities/User"; import { validate, Validate } from "class-validator"; const register = async (req: Request, res: Response) => { const {email, username, password} = req.body; try{ let errors: any = {}; //이메일/유저이름 단일성 확인 const emailUser = await User.findOneBy({email}); const usernameUser = await User.findOneBy({username}); //이미 있으면 erros 객체에 넣음 if(emailUser) errors.email = "이미 해당 이메일 주소가 사용되었습니다." if(usernameUser) errors.username = "이미 사용자 이름이 사용되었습니다." //에러가 있으면 return으로 에러를 response 보내줌 if(Object.keys(errors).length > 0){ return res.status(400).json(errors) } const user = new User(); user.email = email; user.username = username; user.password = password; //엔터티에 정해 놓은 조건으로 user 데이터 유호성 검사를 해줌 errors = await validate(user); //유저 정보를 user table에 저장 await user.save() return res.json(user); } catch(error){ console.error(error); return res.status(500).json({error}) } } const router = Router(); router.post("/register", register); export default router 맨 위 코드(auth.ts)에서 사진과 같이 overload 에러가 뜹니다. 유저이름/이메일 중복 및 에러 처리하는 코드 중 return으로 응답을 반환하는 중 타입이 맞지 않아서 생기는 오류 같은데 어떻게 해결할 수 있을까요??
위의 코드를 그대로 입력하고 baseline 코드까지 문제가 없다가 label에서 다음과 같은 에러가 발생했습니다. KeyError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key) 3804 try: -> 3805 return self._engine.get_loc(casted_key) 3806 except KeyError as err: index.pyx in pandas._libs.index.IndexEngine.get_loc() index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'Gender' The above exception was the direct cause of the following exception: 아래는 입력한 코드입니다. 어떤 부분이 문제일까요? ㅠㅠ #label from sklearn.preprocessing import LabelEncoder for col in cols : le = LabelEncoder() train[col] = le.fit_transform(train[col]) test[col] = le.transform(test[col]) train[cols].head()
안녕하세요. dir 이나 __all 관련해서,,, print(sklearn.__all__) 은 알겠는데요. 그 다음,,, from sklearn.ensemble import RandomForestClassifier 여기서,, randaomforestclassifier 이게 생각이 나지 않을때 이걸 찾을 수 있는 방법은 없는지요?
안녕하세요, 작업형3을 공부하던 중 궁금한 점이 생겨 문의드립니다. 어떤 상황에서 T검정, 카이제곱 검정, 회귀분석, 분산분석(ANOVA)를 수행하는건지 명확히 분류가 잘 안 되는데 위와 같이 T검정, 카이제곱 검정, 회귀분석, 분산분석 중 어떤 것을 수행할지는 문제에서 주어지는 사항일까요? 감사합니다!
train = pd.read_csv('/kaggle/input/working8-2/churn_train.csv') test = pd.read_csv('/kaggle/input/working8-2/churn_test.csv') target = train.pop('TotalCharges') train = pd.get_dummies(train) test = pd.get_dummies(test) 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=2022) from sklearn.metrics import mean_absolute_error from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(random_state=2022, max_depth=7, n_estimators=600) rf.fit(X_tr,y_tr) pred = rf.predict(X_val) answer = rf.predict(test) rf.predict(X_val)까지는 잘 예측이 되어, 866.4986350062683의 값을 얻었습니다. 그리하여 마지막으로 본 test파일을 예측하여 제출하려고 하는데, 계속해서 오류가 발생하네요 ㅠㅠㅠ 아래는 에러 코드입니다. ValueError Traceback (most recent call last) Cell In[97], line 14 12 rf.fit(X_tr,y_tr) 13 pred = rf.predict(X_val) ---> 14 answer = rf.predict(test) File /opt/conda/lib/python3.10/site-packages/sklearn/ensemble/_forest.py:981, in ForestRegressor.predict(self, X) 979 check_is_fitted(self) 980 # Check data --> 981 X = self._validate_X_predict(X) 983 # Assign chunk of trees to jobs 984 n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) File /opt/conda/lib/python3.10/site-packages/sklearn/ensemble/_forest.py:602, in BaseForest._validate_X_predict(self, X) 599 """ 600 Validate X whenever one tries to predict, apply, predict_proba.""" 601 check_is_fitted(self) --> 602 X = self._validate_data(X, dtype=DTYPE, accept_sparse="csr", reset=False) 603 if issparse(X) and (X.indices.dtype != np.intc or X.indptr.dtype != np.intc): 604 raise ValueError("No support for np.int64 index based sparse matrices") File /opt/conda/lib/python3.10/site-packages/sklearn/base.py:548, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, **check_params) 483 def _validate_data( 484 self, 485 X="no_validation", (...) 489 **check_params, 490 ): 491 """Validate input data and set or check the `n_features_in_` attribute. 492 493 Parameters (...) 546 validated. 547 """ --> 548 self._check_feature_names(X, reset=reset) 550 if y is None and self._get_tags()["requires_y"]: 551 raise ValueError( 552 f"This {self.__class__.__name__} estimator " 553 "requires y to be passed, but the target y is None." 554 ) File /opt/conda/lib/python3.10/site-packages/sklearn/base.py:481, in BaseEstimator._check_feature_names(self, X, reset) 476 if not missing_names and not unexpected_names: 477 message += ( 478 "Feature names must be in the same order as they were in fit.\n" 479 ) --> 481 raise ValueError(message) ValueError: The feature names should match those that were passed during fit. Feature names unseen at fit time: - customerID_CUST0001 - customerID_CUST0002 - customerID_CUST0006 - customerID_CUST0007 - customerID_CUST0008 - ... Feature names seen at fit time, yet now missing: - customerID_CUST0000 - customerID_CUST0003 - customerID_CUST0004 - customerID_CUST0005 - customerID_CUST0009 - ...