묻고 답해요
164만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결C 프로그래밍 - 입문부터 게임 개발까지
sizeof에서 오류가 나는 것 같아서 물어보고 싶습니다.
#include <stdio.h> int main(void) { char name[256]; printf("이름이 뭐에요? "); scanf_s("%s", name, sizeof(name)); int age; printf("몇살이세요? "); scanf_s("%d", &age); float weight; printf("몸무게는 몇 kg 이에요? "); scanf_s("%f", &weight); double height; printf("키는 몇 cm 이에요? "); scanf_s("%lf", &height); char what[256]; printf("어떤 범죄를 저질렀나요? "); scanf_s("%s", what, sizeof(what)); //조서 내용 출력 printf("\n\n--- 범죄자 정보 ---\n\n"); printf("이름 : %s\n", name); printf("나이 : %d\n", age); printf("몸무게 : %.2f\n", weight); printf("키 : %.2lf\n", height); pirntf("범죄 : %s\n", what); return 0; } 으로 코딩문을 작성했는데 C6328 크기 불일치: 'unsigned __int64'이(가) _Param_(3)으로 전달되었습니다. 다음 호출에는 'unsigned int'이(가) 필요합니다. 'scanf_s'. 라는 오류가 뜨는데 어디가 잘못된건지 잘 모르겠습니다.
-
미해결만들면서 배우는 리액트 : 기초
useState()괄호안에 함수를 넣을때..궁금한점..
궁금한점이 있어요! 컴포넌트 함수의 속성값을 받아올때는 { }중괄호를 사용하여 함수값을 호출하는데 useState()괄호안에 파라미터값을 적용할때에 useState({CAT1})이 아니라 useState(CAT1)으로 선언하는 이유를 알 수 있을까요..ㅠㅠㅠㅠ
-
미해결[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
express.static 질문드리고 싶습니다
강사님 안녕하세요 현재 폴더에 kkk라는 폴더를 만들었습니다 kkk 폴더 내에도 필요한 파일들을 채웠습니다 여기서 제가 실험을 해봤습니다 kkk 폴더에서 cookie2.html을 지웠습니다 그런데 이렇게 하고 실행해봤더니 cookie2.html을 잘 불러왔습니다 혹시 제가 잘못 이해하고 있는 부분이 있는 것 같아서 질문드리고 싶습니다 가르쳐주시면 감사하겠습니다
-
미해결설계독학맛비's 실전 Verilog HDL Season 1 (Clock부터 Internal Memory까지)
gedit 말고 vim 으로 해보려고 하는데요...
일단 설치는 했고 실행도 했습니다만 vim에 관해 아예 모르는 상황에서 이 수업 내용의 vim내용만으로도 따라잡을 수 있을지 염려되어 여쭤봅니다
-
미해결[리뉴얼] 코딩자율학습 제로초의 자바스크립트 입문
addEventListener 이전 예제와 비교
이전 쿵쿵따나 끝말잇기에서 $button.addEventListener('click', onClickButton); 도 리턴값이 없어 undefined 를 반환하는데 왜 버튼을 누르면 실행이 되는지 궁금합니다. $document.queyrSelector(#num-0).addEventListener('click', onClickNumber('0')); 여기서는 매개변수를 썼기 때문에 함수 자체를 쓴 게 아니라 함수 반환값을 쓴 것인가요?? 이전 쿵쿵따, 끝말잇기 addEventListener 코드와 이번 코드의 다른 점이 무엇인지 궁금합니다..ㅠㅠ 만약 위처럼 이해한 게 맞다면, 자바스크립트에서는 함수에 매개변수가 있어야 할 경우 모두 함수를 반환하는 고차함수로 작성해야 하나요??
-
미해결[개정판] 파이썬 머신러닝 완벽 가이드
ValueError: x and y must have same first dimension, but have shapes (53,) and (144,) 와 Input contains NaN, infinity or a value too large for dtype('float64'). 에러 두 가지
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 강의 내용을 질문할 경우 몇분 몇초의 내용에 대한 것인지 반드시 기재 부탁드립니다. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 3장 평가 부분 공부하면서 두 가지 에러가 나서 문의합니다. 개념부분 설명하며 코드 작성할 때는 잘 되었는데, 당뇨병 데이터 가지고 실습 예제하는 중에는 빨갛게 표시된 부분에 해당 에러가 발생합니다. 전체 코드를 올리니 답변 부탁드립니다! ^^ # 분류의 성능 평가지표 - 이진 분류: 긍정/부정과 같은 2개의 결괏값만을 가짐(아래의 성능 지표는 이진 분류에서 특히 중요하게 강조하는 지표임) - 멀티 분류: 여러 개의 결정 클래스 값을 가짐 ## 정확도 accuracy ## 오차행렬 confusion matrix ## 정밀도, 재현율 precision, recall ## F1 score ## ROC AUC ## 1. 정확도 : 실제 데이터에서 예측 데이터가 얼마나 같은지 판단하는 지표 예측 결과가 동일한 데이터 건수/전체 예측 데이터 건수 왜곡이 발생할 수 있음 from sklearn.base import BaseEstimator class MyDummyClassifier(BaseEstimator): # 학습하지 않은 경우에도 높은 확률을 보일 수 있다! 주의!! def fit(self, X, y=None): pass def predict(self, X): pred=np.zeros((X.shape[0], 1)) for i in range(X.shape[0]): if X['Sex'].iloc[i] == 1: pred[i]=0 else: pred[i]=1 return pred import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn import preprocessing titanic_df= pd.read_csv('./train.csv') def encode_features(dataDF): features=['Cabin', 'Sex', 'Embarked'] for feature in features: le = preprocessing.LabelEncoder() le = le.fit(dataDF[feature]) dataDF[feature] = le.transform(dataDF[feature]) return dataDF titanic_df = encode_features(titanic_df) titanic_df.head() def fillna(df): df['Age'].fillna(df['Age'].mean(), inplace=True) df['Cabin'].fillna('N', inplace=True) df['Embarked'].fillna('N', inplace =True) df['Fare'].fillna(0, inplace=True) return df def drop_features(df): df.drop(['PassengerId', 'Name', 'Ticket'], axis=1, inplace=True) return df def format_features(df): df['Cabin'] = df['Cabin'].str[:1] features=['Cabin', 'Sex', 'Embarked'] for feature in features: le = LabelEncoder() le=le.fit(df[feature]) df[feature] = le.transform(df[feature]) return df def transform_features(df): df=fillna(df) df= drop_features(df) df= format_features(df) return df titanic_df = pd.read_csv('./train.csv') y_titanic_df = titanic_df['Survived'] X_titanic_df = titanic_df.drop('Survived', axis=1) X_titanic_df X_titanic_df= transform_features(X_titanic_df) X_titanic_df X_train, X_test, y_train, y_test = train_test_split(X_titanic_df, y_titanic_df, test_size=0.2, random_state=0) myclf= MyDummyClassifier() myclf.fit(X_train, y_train) mypredictions= myclf.predict(X_test) print(accuracy_score(y_test, mypredictions)) from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.base import BaseEstimator from sklearn.metrics import accuracy_score import numpy as np import pandas as pd class MyFakeClassifier(BaseEstimator): def fit(self, X, y): pass def predict(self, X): return np.zeros((len(X), 1), dtype=bool) digits= load_digits() y=(digits.target==7).astype(int)#True라면 astype(int)로 1로 변환, 아니면 False니 0으로 변환 X_train, X_test, y_train, y_test = train_test_split(digits.data, y, random_state=11) print(y_test.shape) print(pd.Series(y_test).value_counts()) fakeclf= MyFakeClassifier() fakeclf.fit(X_train, y_train) fakepred= fakeclf.predict(X_test) print(accuracy_score(y_test, fakepred)) # 따라서 불균형한 lableSets에서는 평가수치로 사용돼서는 안 된다!!!! # 2. 오차행렬 confusion matrix - 학습된 분류 모델이 예측을 수행하면서 얼마나 헷갈리고 있는지 함께 보여주는 지표다 - 이진 분류의 예측 오류 얼마인지? + 어떠한 유형의 예측 오류가 발생하고 있는지? - TN FP - FN TP ## 정확도 * (TN+ TP)/(TN+FP+FN+TP) * 불균형한 레이블 세트에서는 * 매우 적은 수의 결과값에 positive를 설정해 1값을 부여하고, 그렇지 않은 경우는 negative로 0값을 부여하는 경우가 많다. ## 정밀도 * TP / (FP+TP) * 예측을 Positive로 한 대상 중 예측과 실제 값이 Positive로 일치한 데이터의 비율 * Positive 예측 성능을 더욱 정밀하게 측정하기 위한 평가 지표 * 양성 예측도 * 언제 중요한가? 실제 nagative 데이터를 positive데이터로 판단하면 안되는 경우 (가짠데 진짜라고 판단하면 안되는 경우) * FP 낮추는 데 초점을 둔다!!!!!! ## 재현율 recalls * TP/(FN+TP) * 실제값이 Positive인 대상 중 * 예측과 실제 값이 Positive로 일치한 데이터의 비율 * 민감도 Sensitivity 또는 TPR True positive rate * 언제 중요하는가? 실제 positive 양성 데이터를 nagative로 잘못 판단하면 안되는 경우 (진짠데 가짜라고 판단하면 안되는 경우) * FN 낮추는데 초점을 둔다!!!!!!!! ### Trade-off - 분류의 결정 임곗값 Threshold를 조정해 정밀도 또는 재현율의 수치를 높일 수 있다. - 그런데 이들은 상호 보완적인 평가 지표라서 어느 한쪽을 강제로 높이면, 다른 하나의 수치는 떨어진다. # 정확도 from sklearn.metrics import confusion_matrix confusion_matrix(y_test, fakepred) # 정밀도, 재현율 from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix def get_clf_eval(y_test, pred): confusion= confusion_matrix(y_test, pred) accuracy= accuracy_score(y_test, pred) precision= precision_score(y_test, pred) recall= recall_score(y_test, pred) print(confusion) print(f"정확도:{accuracy}, 정밀도:{precision}, 재현율:{recall}") import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression titanic_df = pd.read_csv('./train.csv') y_titanic_df = titanic_df['Survived'] X_titanic_df = titanic_df.drop('Survived', axis=1) X_titanic_df = transform_features(X_titanic_df) X_train, X_test, y_train, y_test = train_test_split(X_titanic_df, y_titanic_df, test_size= 0.20, random_state = 11) lr_clf= LogisticRegression() lr_clf.fit(X_train, y_train) pred = lr_clf.predict(X_test) print(y_test.shape) print(pred.shape) get_clf_eval(y_test, pred) # trade-off # predict_proba() 반환결과: 예측 확률 결과 # predict() 반환 결과: 예측 결과 클래스값 pred_proba = lr_clf.predict_proba(X_test) pred = lr_clf.predict(X_test) print(pred_proba.shape) print(pred_proba[:3]) pred_proba_result = np.concatenate([pred_proba, pred.reshape(-1, 1)], axis=1) print(pred_proba_result[:3]) from sklearn.preprocessing import Binarizer X=[[1, -1, 2], [2,1,4], [2,2,-2]] binarizer= Binarizer(threshold=1.1) print(binarizer.fit_transform(X)) custom_threshold= 0.5 pred_proba_1 = pred_proba[:, 1].reshape(-1,1) binarizer = Binarizer(threshold=custom_threshold).fit(pred_proba_1) custom_predict = binarizer.transform(pred_proba_1) get_clf_eval(y_test, custom_predict) custom_threshold= 0.3 pred_proba_1 = pred_proba[:, 1].reshape(-1,1) binarizer = Binarizer(threshold=custom_threshold).fit(pred_proba_1) custom_predict = binarizer.transform(pred_proba_1) get_clf_eval(y_test, custom_predict) # 잘모르겠는 부분 임곗값에 따라 정밀도와 재현율이 달라지는 이유?가 잘 이해가 안됨! thresholds= [0.4, 0.5, 0.6, 0.7] def get_eval_by_threshold(y_test, pred_proba_c1, thresholds): for custom_threshold in thresholds: binarizer= Binarizer(threshold = custom_threshold).fit(pred_proba_c1) custom_predict= binarizer.transform(pred_proba_c1) print(custom_threshold) get_clf_eval(y_test, custom_predict) get_eval_by_threshold(y_test, pred_proba[:, 1].reshape(-1,1), thresholds) # precision_recall_curve() from sklearn.metrics import precision_recall_curve pred_proba_class1 = lr_clf.predict_proba(X_test)[:,1] precisions, recalls, thresholds = precision_recall_curve(y_test, pred_proba_class1) print(thresholds.shape) thr_index = np.arange(0, thresholds.shape[0], 15) print(thr_index) print(np.round(thresholds[thr_index], 2)) print(f"정밀도{np.round(precisions[thr_index], 3)}") print(f"재현율{np.round(recalls[thr_index], 3)}") import matplotlib.pyplot as plt import matplotlib.ticker as ticker %matplotlib inline def precision_recall_curve_plot(y_test, pred_proba_c1): precision, recalls, threshold = precision_recall_curve(y_test, pred_proba_c1) plt.figure(figsize=(8,6)) threshold_boundary = threshold.shape[0] plt.plot(thresholds, precisions[0:threshold_boundary], linestyle='--', label='precision') plt.plot(thresholds, recalls[0:threshold_boundary], label='recall') start, end = plt.xlim() plt.xticks(np.round(np.arange(start, end, 0.1),2)) plt.xlabel('Threshold value') plt.ylabel('Precision and recall value') plt.legend() plt.grid() plt.show() precision_recall_curve_plot(y_test, lr_clf.predict_proba(X_test)[:, 1]) # F1 스코어 - F1 score는 정밀도와 재현율을 결합한 지표로서 둘이 어느 한 쪽으로 치우치지 않는 수치를 나타낼 때 상대적으로 높은 값을 가짐 #F1 score from sklearn.metrics import f1_score f1 = f1_score(y_test, pred) print(f1) def get_clf_eval(y_test, pred): confusion = confusion_matrix(y_test, pred) accuracy = accuracy_score(y_test, pred) precision= precision_score(y_test, pred) recall = recall_score(y_test, pred) f1= f1_score(y_test, pred) print(confusion) print(accuracy, precision, recall, f1) thresholds = [0.4, 0.45, 0.50, 0.55, 0.60] pred_proba = lr_clf.predict_proba(X_test) get_eval_by_threshold(y_test, pred_proba[:,1].reshape(-1, 1), thresholds) # ROC곡선 - 이진 분류의 예측 성능 측정에서 중요하게 사용되는 지표 - Receiver Operation characteristic curve 수신자 판단 곡선 - FPR False Positive Rate 이 변할 때, TPR 재현율=민감도 True Positive Rate이 어떻게 변하는지 나타내는 곡선 - TPR <-> TNR 특이성 Specificity True Negative Rate, - FPR= 1-TNR, 1-특이성 from sklearn.metrics import roc_curve pred_proba_class1 = lr_clf.predict_proba(X_test)[:,1] fprs, tprs, thresholds = roc_curve(y_test, pred_proba_class1) print(thresholds) #thresholds[0]은 max예측확률+1로 임의 설정된다. 이를 제외하기 위해 np.arange는 1부터 시작한다. thr_index=np.arange(1, thresholds.shape[0],5) print(thr_index) print(np.round(thresholds[thr_index],2)) def roc_curve_plot(y_test, pred_proba_c1): fprs, tprs, thrsholds = roc_curve(y_test, pred_proba_c1) plt.plot(fprs, tprs, label = 'ROC') plt.plot([0,1], [0,1], 'k--', label='Random') start, end= plt.xlim() plt.xticks(np.round(np.arange(start, end, 0.1),2)) plt.xlim(0,1) plt.ylim(0,1) plt.xlabel('FPR(1-Sensitivity)') plt.ylabel('TPR(recall)') plt.legend() roc_curve_plot(y_test, pred_proba[:,1]) # AUC - ROC 곡선 자체는 FPR과 TPR의 변화 값을 보는 데 이용하며 분류의 성능 지표로 사용되는 것은 ROC 곡선 면적에 기반한 AUC값으로 결정한다. AUC 값은 ROC 곡선 밑의 면적을 구한 것으로 일반적으로 1에 가까울 수록 좋은 수치다. -Area Under Curve - AUC 수치가 커지려면 FPR이 작은 상태에서 얼마나 큰 TPR을 얻을 수 있느냐가 관건이다. 직사각형에 가까운 곡선! from sklearn.metrics import roc_auc_score pred_proba = lr_clf.predict_proba(X_test)[:,1] roc_score = roc_auc_score(y_test, pred_proba) print(roc_score) def get_clf_eval(y_test, pred=None, pred_proba= None): confusion = confusion_matrix(y_test, pred) accuracy = accuracy_score(y_test, pred) precision= precision_score(y_test, pred) recall = recall_score(y_test, pred) f1= f1_score(y_test, pred) roc_auc= roc_auc_score(y_test, pred_proba) print(confusion) print(accuracy, precision, recall, f1, roc_auc) get_clf_eval(y_test, pred, pred_proba) #prediction about pima inidans diabetes #inline: 브라우저 내부(inline)에 바로 그려지도록 해주는 코드 import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score from sklearn.metrics import f1_score, confusion_matrix, precision_recall_curve, roc_curve from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression diabetes_data = pd.read_csv('diabetes.csv') print(diabetes_data['Outcome'].value_counts()) diabetes_data.head(3) diabetes_data.info() X= diabetes_data.iloc[:, :-1] X y= diabetes_data.iloc[:, -1] y X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 156, stratify=y) #stratify(층을 이룬다) : 지정한 Data의 비율을 유지한다. 예를 들어, Label Set인 Y가 25%의 0과 75%의 1로 이루어진 Binary Set일 때, # stratify=Y로 설정하면 나누어진 데이터셋들도 0과 1을 각각 25%, 75%로 유지한 채 분할된다. lr_clf = LogisticRegression() lr_clf.fit(X_train, y_train) pred = lr_clf.predict(X_test) pred_proba = lr_clf.predict_proba(X_test)[:, 1] get_clf_eval(y_test, pred, pred_proba) pred_proba_c1 = lr_clf.predict_proba(X_test)[:, -1] print(pred_proba_c1.shape) print(y_test.shape) precision_recall_curve_plot(y_test, pred_proba_c1) ValueError: x and y must have same first dimension, but have shapes (53,) and (144, diabetes_data.describe() # bins 파라미터는 히스토그램의 가로축 구간의 개수를 지정 # cumulative는 누적히스토그램 plt.hist(diabetes_data['Glucose'], cumulative=False, bins=10) plt.hist(diabetes_data['Glucose'], bins=15) zero_features = ['Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI'] total_count = diabetes_data['Glucose'].count() for feature in zero_features: zero_count = diabetes_data[diabetes_data[feature]==0][feature].count() print(feature) print(zero_count) print(f'{feature}은 0인 데이터 계수가 {zero_count}이므로 퍼센트는 {100*zero_count/total_count}') mean_zero_features=diabetes_data[zero_features].mean() mean_zero_features diabetes_data[zero_features]= diabetes_data[zero_features].replace(0, mean_zero_features) diabetes_data[zero_features].head(10) X=diabetes_data.iloc[:, :-1] y = diabetes_data.iloc[:, -1] scaler=StandardScaler() X_scaled = scaler.fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state= 156, stratify=y) lr_clf= LogisticRegression() lr_clf.fit(X_train, y_train) pred= lr_clf.predict(X_test) pred_proba = lr_clf.predict_proba(X_test)[:, 1] get_clf_eval(y_test, pred, pred_proba) precision_recall_curve_plot(y_test, pred_proba) ValueError: x and y must have same first dimension, but have shapes (53,) and (144,) thresholds=[0.3, 0.33, 0.36, 0.39, 0.42, 0.45] pred_proba = lr_clf.predict_proba(X_test) def get_eval_by_threshold(y_test, pred_proba_c1, thresholds): for custom_threshold in thresholds: binarizer= Binarizer(threshold = custom_threshold).fit(pred_proba_c1) custom_predict= binarizer.transform(pred_proba_c1) print(custom_threshold) get_clf_eval(y_test, custom_predict) get_eval_by_threshold(y_test, pred_proba[:, 1].reshape(-1,1), thresholds) Input contains NaN, infinity or a value too large for dtype('float64'). binarizer=Binarizer(threshold=0.48) pred_th_048=binarizer.fit_transform(pred_proba[:, 1].reshape(-1,1)) get_clf_eval(y_test, pred_th_048, pred_proba[:, 1])
-
미해결초보자도 만들 수 있는 스크롤 인터렉션. 1편 자바스크립트
8강 자바스크립트 버전이없어요
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.
-
미해결스프링 DB 1편 - 데이터 접근 핵심 원리
Spring을 공부하면서 애플리케이션 영역에서 트랜잭션을 적용을 권고하는 사유가 있을지 궁금합니다.
이전에 닷넷 + MSSQL개발 환경에서는 트랜잭션을 애플리케이션 영역이 아닌 프로시저 내에서(쿼리문 영역) 트랜잭션 설정하는것을 권고했었는데요. Spring 환경으로 넘어가면서 동일한 MSSQL사용하지만 애플리케이션 설정하는것을 권고하더라구요. 도저히 이 부분에 대해서 왜 어플리케이션 영역에서 설정해야 하는지 이유를 잘 모르겠습니다. 감사합니다.
-
해결됨[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
express body-parser에 대해 질문드리고 싶습니다
강사님 안녕하세요 body-parser에 대해 질문드리고 싶습니다 소스코드는 지난번에 질문드렸던 소스코드에서 bodyParser를 이용하는 소스코드를 추가했습니다 const express = require('express'); const path = require('path'); const { nextTick, rawListeners } = require('process'); const morgan = require('morgan'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const app = express(); app.set('port', process.env.PORT || 3000); //'port' 라는 속성에 포트번호 3000번을 설정합니다. //서버의 포트를 3000번으로 지정합니다. //app.use(morgan('dev')); //쿠키를 객체화 시킵니다. app.use(cookieParser()); //cookieparser를 사용하기 위해 app.use(express.json()); app.use(express.urlencoded({extended: true})); //post요청에 의한 req.body를 사용하기 위해서 //login 경로의 경우입니다. app.get('/login', (req, res, next) => { req.cookies // 쿠키 객체화 a=req.query; b=req.params; c=req.body; console.log("req.query "+req.query); console.log("req.params "+req.params); console.log("req.body "+req.body); console.log("req.query.name "+req.query.name); console.log("req.params.name "+req.params.name); console.log("req.body.name "+req.body.name); // expires.setMinutes(expires.getMinutes() + 5); const expires = new Date(); expires.setMinutes(expires.getMinutes() + 5); res.cookie('name', encodeURIComponent(req.query.name),{ expires: expires, httpOnly: true, path: '/', }) res.redirect('/'); }); app.get('/', (req,res)=>{ console.log("req.url "+req.url); if(req.cookies.name)//name이라는 쿠키가 있는 경우입니다. { //res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.send(`${req.cookies.name}님 안녕하세요`);//쿠키에 넣은 이름이 웹페이지에 출력됩니다 } else{ //로그인도 아니고, 쿠키도 없는 경우입니다. //next(createError(404)); try { // console.log("진입"); //res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); //익스프레스에서는 writeHead를 쓰면 안된다 에러가 생긴다 //res.send( ) 할 때 이미 자동으로 res.status().send() 이런 식으로 헤더를 설정해준다 //res.sendFile(path.join(__dirname, '/cookie2.html'));//cookie2.html 파일을 클라이언트에게 보내준다 //console.log(err.status) console.log("진입"); res.setHeader('Content-Type', 'text/html'); //익스프레스에서는 writeHead를 쓰면 에러가 생긴다 그러므로 setHeader를 써라 res.sendFile(path.join(__dirname, 'cookie2.html')); //cookie2.html 파일을 클라이언트에게 보내준다 } catch (err) { // res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }); // res.end(err.message); next(err); //콜백함수에 err 라는 인자가 있는 app.use로 이동한다 } } }); // app.get('/:id',(req,res)=>{ // console.log("req.url "+req.url); // console.log("req.params.id "+req.params.id); // res.send(`Hello ${req.params.id}`); // }) //아래는 에러처리입니다. app.use((req,res,next)=>{ // 찾는 경로가 없으면 get을 다 지나서 use로 온다 console.log("req.url "+req.url); next(createError(404)); //찾는 경로가 없으면 404처리 }) app.use((err,req,res,next)=>{ // /favicon.ico도 여기로 간다 에러도 여기로 간다 console.log("req.url "+req.url); console.log(res.locals.message); res.locals.message = err.message; res.locals.error = req.app.get(`env`) === `development` ? err:{}; console.log(err.status) res.status(err.status ||500).send(err.message); }); app.listen(3000, () => { console.log(app.get('port'), '번 포트에서 서버 대기 중입니다!'); }); 그런데 name 이 Hello를 잡아주는 것은 req.query.name 은 잡아줬는데 req.body.name 은 잡아주지 못했습니다 그 이유가 궁금해서, 공식문서도 찾아보고 강사님의 POST PUT DELETE 요청 보내기 강의도 다시 찾아봤습니다 [리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지 - 인프런 | 학습 페이지 (inflearn.com) 익스프레스 body-parser의 req.body 는 axios.post('경로',{ name }) 이런 식으로 axios.post의 2번째 인자만 받아주는 건가 싶었습니다 질문 드리기 전에 좀 더 충분히 찾아보기 위해서 WEB3 - Express - 9.1. 미들웨어의 사용 - body parser - YouTube생활코딩님 채널의 유튜브 강의도 참고해봤는데, axios.post('경로',{ name }) 로 보내주지 않아도 form 태그로 전송해준 속성들은 다 받아주는 것 같았습니다 혹시 req.query.name은 hello을 받아주는데 req.body.name은 hello를 못받아주고 req.body는 빈 객체가 되는 이유가 이해하기 어려워서 가르쳐주시면 감사하겠습니다
-
해결됨[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
res.send와 favicon에 대해 질문드리고 싶습니다
강사님 안녕하세요 약간 햇갈리는 부분이 있어서 질문드리고 싶습니다 http://localhost:3000/ 을 입력하면 req.url이 처음에는 /이고 마지막에는 /favicon.ico 가 되어서요 그래서 제가 63행에 저 라우터를 넣으면 req.url이 처음에는 / 일 때, cookie2.html이 웹페이지에 나온 다음에 마지막에는 /favicon.ico 때문에 웹브라우저 페이지에는 Hello favicon 으로 변경될 줄 알았습니다 그런데, 웹페이지가 안바뀌고 cookie2.html 이 그대로 유지되는 이유가 이해가 어려워서 질문드리고 싶습니다 가르쳐주시면 감사하겠습니다
-
미해결[리뉴얼] 파이썬입문과 크롤링기초 부트캠프 [파이썬, 웹, 데이터 이해 기본까지] (업데이트)
크롤링 프로그램 오나성: 크롤링한 데이터에서 다시 크롤링하기2
계속 오류나서 보니 작성해주신 파일 보니 아래 조건문이 추가되어있네요. 왜 추가해야되는지 이해를 못하겠어서 공지사항 보려고 하는데, 못찾겠습니다. 어디로 들어가면 될지요 ㅠ link_re = re.compile('^http://') ..... if link_re.match(title['href']):
-
미해결Axure RP 9,10 - 서비스 기획자를 위한 최적의 프로토타이핑 툴
메뉴 콜랩스 구현 방법이 있을까요?
아래 그림에서 체크한 콜랩스(용어가 맞는지 모르겠네요..) 버튼을 클릭하면 왼편 메뉴에서 아이콘만 남기고 접히게 하고(이거는 그림을 하나 더 그리면 될 듯 하고요) 오른편의 다이내믹 패널 부분이 왼편으로 당겨져서 오게 하고 싶은데 액셔에서 가능할까요?
-
미해결파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)
4중 for문 질문
import sys # input = sys.stdin.readline sys.stdin = open("/Users/yerim/Downloads/pythonalgorithm_formac/문자열&1,2차원리스트탐색/10. 스도쿠 검사/in3.txt", 'r') G = [] for _ in range(9): G.append(list(map(int, input().split()))) # 1. 가로, 세로 1줄씩은 그 1줄을 임시리스트에 담아서 set()화 하여 중복을 없앤 후, 그 리스트의 길이가 9인지 확인한다! # 2. 3x3칸은 2중 for문 3번 3번 돌려서 G[i][j]를 sum에 더하여 3x3의 총 합이 45가 아니면 "NO" 출력 temp = set() for ix in range(9): for jx in range(9): temp.add(G[ix][jx]) if len(temp) != 9: print("No") sys.exit() temp = set() for iy in range(9): for jy in range(9): temp.add(G[jy][iy]) if len(temp) != 9: print("No") sys.exit() temp = set() sum = 0 for i in range(0, 9, 3): for j in range(0, 9, 3): sum += G[i][j] + G[i+1][j] + G[i+2][j] sum += G[i][j+1] + G[i+1][j+1] + G[i+2][j+1] sum += G[i][j+2] + G[i+1][j+2] + G[i+2][j+2] if sum != 45: print("No") sys.exit() sum = 0 # set 사용해도 될 듯(3X3) => 4중 for문을 해야 짧아질 듯! # for i in range(0, 9, 3): # for j in range(0, 9, 3): # temp.add(G[i][j]) # temp.add(G[i+1][j]) # temp.add(G[i+2][j]) # temp.add(G[i][j+1]) # temp.add(G[i+1][j+1]) # temp.add(G[i+2][j+1]) # temp.add(G[i][j+2]) # temp.add(G[i+1][j+2]) # temp.add(G[i+2][j+2]) # if len(temp) != 9: # print("No") # sys.exit() # temp = set() print("Yes") - 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요 선생님! 제 코드입니다. for i in range(0, 9, 3): for j in range(0, 9, 3): sum += G[i][j] + G[i+1][j] + G[i+2][j] sum += G[i][j+1] + G[i+1][j+1] + G[i+2][j+1] sum += G[i][j+2] + G[i+1][j+2] + G[i+2][j+2] 이 부분에서 강의에서는 4중 for문을 사용했던데, 저는 2중 for문을 사용했지만 결국 돌아가는 원리는 똑같은 것 같거든요. 이러면 4중 for문이든 2중이든 시간복잡도 면에서는 별 차이가 없는 건가요?ㅎㅎ
-
미해결자바스크립트 : 기초부터 실전까지 올인원
깃허브에는 잘올라가있는데 netlify에 올리려고하면 오류가 나오네요 왜그런걸까요?
(사진)
-
미해결Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)
강의자료 문의드립니다.
안녕하세요, 강의를 듣고 있는 학새입니다. 다름이 아니라, 강의자료를 인쇄해서 공부하는 것을 선호하여 찾아보려 하였는데 작년 질문글들에 곧 올려주신다는 글들을 보았는데 강의자료가 어디에 올라가 있는지 찾기 어려워 문의드립니다. 어디에서 강의자료들을 다운받을 수 있을까요?
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
시퀄라이즈 질문입니다!
const fullPost = await Post.findOne({ where: { id: post.id }, include: [{ model: Image, }, { model: Comment, include: [{ model: User, // 댓글 작성자 attributes: ['id', 'nickname'], }], }, { model: User, // 게시글 작성자 attributes: ['id', 'nickname'], }, { model: User, // 좋아요 누른 사람 as: 'Likers', attributes: ['id'], }] }); 노드 서버에서 fullPost를 보내주는데 이때 게시글 작성자는 User 이름으로 좋아요나 댓글 작성자는 Likers, Comments 이름으로 보내지는 것으로 확인되는데 이게 User는 무조건 로우가 하나인 객체 값을 가지고 Likers, Comments는 배열로 객체 요소를 여러 개 가져서 시퀄라이즈에서 자동으로 's'를 붙여서 보내는 식으로 이해하면 될까요?? p.s. 질문하면서 생각이 난건데 시퀄라이즈에서 관계를 정의할 때 Post는 User(게시글 작성자)에 대해 belongsTo이고,Likers, Comments, Images 같은 경우는 belongsToMany이거나 hasMany이기 때문에 시퀄라이즈에서 's'를 붙여서 보내고 배열 형태로 객체 요소들을 넣어서 보내는 것이라고 이해하면 될까요? 아래 mainPosts 요소 하나 올립니다!
-
미해결풀스택을 위한 탄탄한 프런트엔드 부트캠프 (HTML, CSS, 바닐라 자바스크립트 + ES6) [풀스택 Part2]
모던 웹을 위한 웹접근성, 크로스 브라우징, 이미지 포맷 이해
화면이 없이 소리만 나옵니다.
-
미해결[개정판] 딥러닝 컴퓨터 비전 완벽 가이드
Mmdetection 학습 중 unexpected keyword가 발생했습니다
현재 제공해주신 코드 바탕으로 mmdetection에서 ssd300 모델을 학습시키는 실습을 진행 중입니다. 그런데 train용 데이터셋을 생성하는 코드에서 아래와 같은 오류가 나타납니다. # train용 Dataset 생성. datasets = [build_dataset(cfg.data.train)] TypeError: DisasterDataset: __init__() got an unexpected keyword argument 'times' 제가 대충 찾아본 결과 config 파일 내 data 부분에서 repeatdataset에 times라는 인수가 있고, 이 부분에 문제가 있다고 합니다.(저는 지금 파일을 수정해서 disasterdataset으로 바뀌고 times=5 인수만 남아있는 상태) data = dict( samples_per_gpu=8, workers_per_gpu=3, train=dict( type='DisasterDataset', times=5, dataset=dict( type='CocoDataset', ann_file='data/coco/annotations/instances_train2017.json', img_prefix='data/coco/train2017/', (출처: https://github.com/open-mmlab/mmdetection/issues/5980) 그래서 cfg를 수정하면서 이 부분을 없애거나 주석처리 해서 해결하고자 하는데, 아래처럼 cfg내 요소를 수정할 수는 있는데, 없애거나 주석처리 하는 방법은 모르겠습니다. cfg.data.train.type = 'DisasterDataset' cfg.data.train.data_root = '/content/train/' cfg.data.train.ann_file = 'xBD_train.json' cfg.data.train.img_prefix = 'images 이 문제를 해결하는 방법에 대해 답변 듣고싶습니다. 이 repeatdataset 부분(코드에서는 data 밑 disasterdataset)을 수정하는 방법 이외에도 다른 방법이 있다면 꼭 배우고 싶습니다. 늘 좋은 강의 잘 듣고 있습니다. 감사합니다. 맨 아래는 문제가 생긴 cfg 전체 파일을 작성합니다. input_size = 300 model = dict( type='SingleStageDetector', backbone=dict( type='SSDVGG', depth=16, with_last_pool=False, ceil_mode=True, out_indices=(3, 4), out_feature_indices=(22, 34), init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://vgg16_caffe')), neck=dict( type='SSDNeck', in_channels=(512, 1024), out_channels=(512, 1024, 512, 256, 256, 256), level_strides=(2, 2, 1, 1), level_paddings=(1, 1, 0, 0), l2_norm_scale=20), bbox_head=dict( type='SSDHead', in_channels=(512, 1024, 512, 256, 256, 256), num_classes=4, anchor_generator=dict( type='SSDAnchorGenerator', scale_major=False, input_size=300, basesize_ratio_range=(0.15, 0.9), strides=[8, 16, 32, 64, 100, 300], ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2])), train_cfg=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.0, ignore_iof_thr=-1, gt_max_assign_all=False), smoothl1_beta=1.0, allowed_border=-1, pos_weight=-1, neg_pos_ratio=3, debug=False), test_cfg=dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.45), min_bbox_size=0, score_thr=0.02, max_per_img=200)) cudnn_benchmark = True dataset_type = 'DisasterDataset' data_root = '/content/train/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Expand', mean=[123.675, 116.28, 103.53], to_rgb=True, ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(300, 300), keep_ratio=False), dict(type='RandomFlip', flip_ratio=0.5), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(300, 300), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=3, train=dict( type='DisasterDataset', times=5, dataset=dict( type='CocoDataset', ann_file='data/coco/annotations/instances_train2017.json', img_prefix='data/coco/train2017/', pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict( type='Expand', mean=[123.675, 116.28, 103.53], to_rgb=True, ratio_range=(1, 4)), dict( type='MinIoURandomCrop', min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), min_crop_size=0.3), dict(type='Resize', img_scale=(300, 300), keep_ratio=False), dict(type='RandomFlip', flip_ratio=0.5), dict( type='PhotoMetricDistortion', brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ]), data_root='/content/train/', ann_file='xBD_train.json', img_prefix='images'), val=dict( type='DisasterDataset', ann_file='xBD_train.json', img_prefix='images', pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(300, 300), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ], data_root='/content/train/'), test=dict( type='DisasterDataset', ann_file='xBD_test.json', img_prefix='images', pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(300, 300), flip=False, transforms=[ dict(type='Resize', keep_ratio=False), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ], data_root='/content/test/')) evaluation = dict(interval=10, metric=['bbox']) optimizer = dict(type='Adam', lr=0.0001, weight_decay=0.0001) optimizer_config = dict() lr_config = dict( policy='step', warmup=None, warmup_iters=500, warmup_ratio=0.001, step=[16, 22]) runner = dict(type='EpochBasedRunner', max_epochs=30) checkpoint_config = dict(interval=10) log_config = dict( interval=10, hooks=[ dict(type='TextLoggerHook', interval=10), dict( type='WandbLoggerHook', interval=1, init_kwargs=dict(project='xBD', name='test')) ]) custom_hooks = [ dict(type='NumClassCheckHook'), dict(type='CheckInvalidLossHook', interval=50, priority='VERY_LOW') ] dist_params = dict(backend='nccl') log_level = 'INFO' load_from = '/content/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_coco_20200204-1efe0ed5.pth' resume_from = None workflow = [('train', 1)] opencv_num_threads = 0 mp_start_method = 'fork' auto_scale_lr = dict(enable=False, base_batch_size=64) work_dir = '/content/drive/MyDrive/xBD/log_task1' seed = 0 gpu_ids = range(0, 1) device = 'cuda'
-
미해결스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
회원가입 등록시 데이터가 안들어옴
안녕하세요 좋은 강의 잘 보고 있습니다. 코드를 열심히 따라 치고 하고 있는데,[회원 웹 기능 -등록]강의에서 , 이름을 입력하면 그 값이 들어오고 redirect로 /로 넘어가야하는데 넘어가지 않습니다. aaa라는 이름을 넣고 등록을 누르면 사진과 같이 등록 폼 초기화가 되고 url만 바뀌는것을 볼 수 있습니다. http는 get으로 보내지는것 같습니다 코드는 강사님과 열심히 비교 해봤을 때 문제가 없어보이는데 무엇이 문제일까요 계속 해결해보다가...질문 남깁니다.
-
미해결[개정판] 딥러닝 컴퓨터 비전 완벽 가이드
training 할때 오류가 발생하는데.. 왜이럴까요 ㅠㅠ
항상 좋은강의 잘듣고 있습니다. necleus 데이터를 학습시키는 중에 아래 처럼 오류가 나요ㅜ train이 잘 돌다가 데이터로더쪽에 오류가 나는데.. 검색해봐도 잘모르겠어요 ㅜㅜ 데이터 변환할때 이런 오류가 뜨던데 이것때문인거 같기도 하고.. 도와주세요 ㅜ