728x90
728x90
728x90

df = df.nlargest(10, col)  # col이란 column값 기준으로 상위 10개 rows를 선별

 

728x90

'CS' 카테고리의 다른 글

[Ubuntu]command man과 info  (0) 2020.11.12
[Ubuntu]command tr  (0) 2020.11.12
[Pandas]dataframe의 row를 shuffle하기  (0) 2020.11.10
(미완)[SQL]기본 쿼리 예제 모음  (0) 2020.11.07
(미완)[Python]Global Interpreter Lock에 대해서  (0) 2020.11.06
728x90

df = df.sample(frac=1)  # row 전체 shuffle

df = df.sample(frac=1).reset_index(drop=True)  # shuffling하고 index reset

 

728x90
728x90

한 A(algorithm)이 주어졌을 때 expected test error를 구할 수 있다.

그 expected test error을 decomposition

expected test error(given A)

= Variance + Bias + Noise, 기본적으로 셋다 낮은게 좋겠지만...

 

A:algorithm

D:training set

 

Variance는

Given A,

(Over D 예측값 평균)과

(Specific D 예측값) 사이의 분산을 가리킨다.(over D)

High variance

->D1에 대한 A의 예측값이 D2에 대한 A의 예측값과 큰 차이가 잦음

->학습데이터를 달리하면 A의 예측이 크게 달라짐

 

Bias는

Given A,

(Over D 예측값 평균)과

(x의 label 평균) 사이의 분산을 가리킨다.(over x)

High bias

->D를 어케 잡든 A의 예측값은 x의 label과 큰 차이가 잦음

->즉 학습데이터 탓은 아니고 A 자체 내재된 문제

->이를, A가 특정 modeling(e.g. linear classifier)에 biased됐다고 표현함

 

Noise는 D, A와는 상관없이

x의 feature representation(인간이 지닌 감각으로 나타내봤자, feature를 모두 사용하였는지, 측정에서의 오류는 없는 지 등 오류가 있기마련)과 x의 data distrbituion 사이의 오류

x의 feature representation을 최선으로 했는 상황에선 줄일 수가 없음

->즉 D나 A를 달리한다해서 줄어들 지 않을 error

->irreducible error

 

요약:

-Given A(an algorithm), expected test error는 Variance + Bias + Noise로 나뉜다.

-Variance는 학습데이터가 달라짐에 따라 학습한 algorithm이 달라지는 정도를 나타낸다. 즉, 크면 학습데이터 탓

-Bias는 A의 역량에 달렸다. 즉, 크면 알고리즘 탓

-Noise는 irreducible error, 즉, 크면 알고리즘도 학습데이터 탓도 아님

-따라서, 알고리즘이 주어지면 학습 데이터를 어케 하냐에 따라, Bias/Variance tradeoff가 존재

 

해결법:

High variance을 낮추기!

-A의 complexity를 낮추기

-학습데이터 늘리기

-bagging(bootstrap aggregating, replacement하면서 sampling) 학습 데이터를 다양하게 조합

 

High bias을 낮추기!

-A의 complexity를 높이기(즉 더 복잡한 모델 사용)

-A의 features를 늘리기

-boosting, 이전 모델의 오류를 고려하여 계속 모델 변화

 

 

참고자료:

www.cs.cornell.edu/courses/cs4780/2018fa/lectures/lecturenote12.html

 

Lecture 12: Bias Variance Tradeoff

Lecture 12: Bias-Variance Tradeoff Video II As usual, we are given a dataset $D = \{(\mathbf{x}_1, y_1), \dots, (\mathbf{x}_n,y_n)\}$, drawn i.i.d. from some distribution $P(X,Y)$. Throughout this lecture we assume a regression setting, i.e. $y \in \mathbb

www.cs.cornell.edu

www.slideshare.net/freepsw/boosting-bagging-vs-boosting/

 

boosting 기법 이해 (bagging vs boosting)

xgboost를 이해하기 위해서 찾아보다가 내가 궁금한 내용을 따로 정리하였으나, 역시 구체적인 수식은 아직 모르겠다. 요즘 Kaggle에서 유명한 Xgboost가 뭘까? Ensemble중 하나인 Boosting기법? Ensemble 유

www.slideshare.net

 

728x90
728x90

쿼리문을 최적화하는 것은 다른 문제이지만,

기본 쿼리문을 익히는 것은 단순 반복, 습관화하는 것일 뿐이다.

다만, 각 기능의 핵심 예제들을 한번에 보기 위하여 정리한다.

 

간단한 쿼리문은 의미를 적지 않고 넘어간다.

유의사항을 남기도록 하자.

 

(1) (=)

SELECT population

FROM world
WHERE name = 'France'

 

(2) (in category)

SELECT name, population

FROM world
WHERE name IN ('Brazil', 'Russia', 'India', 'China');

name이 category candidates에 속하는 걸로 table 반환

 

(3) (in range)

SELECT name, area

FROM world
WHERE area BETWEEN 250000 AND 300000

(각 숫자는 inclusive이다, 즉 해당 값도 포함시켜 반환함)

 

(4) (multiple conditions)

SELECT name,length(name)

FROM world

WHERE length(name)=5 and region='Europe'

(조건절에 있는 칼럼이 꼭 select한 column일 필요는 없음)

 

(5) (order by)

SELECT select_list

FROM table_name

ORDER BY column1, column2 DESC

(정렬 default는 ASC이므로 column1은 ASC로 ordering)

(column 1기준으로 ASC하고, column 1 값은 고정하고 column2로 DESC함)

 

(6) (order by, making new column)

SELECT orderNumber, orderlinenumber, quantityOrdered * priceEach

FROM orderdetails

ORDER BY quantityOrdered * priceEach DESC;

(이렇게 기존 column을 곱해가지고 new column을 기준으로 order by 가능하기도하고 select도 가능)

 

(7) (order by, making new column, using alias)

SELECT orderNumber, orderLineNumber, quantityOrdered * priceEach AS subtotal

FROM orderdetails

ORDER BY subtotal DESC;

(이렇게 making new column한 것의 alias를 줘서, order by시에 alias를 쓰는게 가능)

 

(8) (order by, custom order)

SELECT orderNumber, status

FROM orders

ORDER BY FIELD(status, 'In Process', 'On Hold', 'Cancelled', 'Resolved', 'Disputed', 'Shipped');

(FIELD(status, 'In Process', ...) 부분은 index of the status in the list ['In Process', ...]을 반환함)

(따라서 이 쿼리문의 결과는 status field에 In Process인 값부터 'Shipped'까지 정렬되어 반환)

 

(9) (like)

SELECT firstName, lastName

FROM employees

WHERE lastName LIKE '%son'

ORDER BY firstName;

(LIKE condition은 특정 pattern이면 True를 반환)

(wild card인 %는 any string of zero or more characters)

(wild card인 _는 any "single" character)

 

(10) (IS NULL)

SELECT lastName, firstName, reportsTo

FROM employees

WHERE reportsTo IS NULL;

(Database에서 NULL이란 missing or unknown을 가리킴, empty string이나 0을 가리키는게 아니니 주의)

 

(11) (<> 혹은 !=)

SELECT lastname, firstname, jobtitle

FROM employees

WHERE jobtitle <> 'Sales Rep';

 

(12) (> 혹은 <)

SELECT lastname, firstname, officeCode

FROM employees

WHERE officecode > 5;

 

(13) (DISTINCT)

SELECT DISTINCT state

FROM customers;

(state column을 가져오면서 duplicates row는 1개만 가져온다.)

(이 때, NULL이 중복이면 1개의 NULL row만 가져온다.)

 

(14) (IS NOT NULL)

SELECT state, city

FROM customers

WHERE state IS NOT NULL

ORDER BY state, city;

 

(15) (DISTINCT multiple columns)

SELECT DISTINCT state, city

FROM customers

WHERE state IS NOT NULL

ORDER BY state, city;

(이 때는 state, city 둘의 값이 동시에 같은 rows를 duplicate row로 취급하여 1개만 반환함)

 

(16) (GROUP BY)

SELECT state

FROM customers

GROUP BY state;

(이는 SELECT DISTINCT state FROM customers;와 같다. 즉 DISTINCT는 GROUP BY의 special case로 보자.)

(MySQl 8.0미만 버전에서는 GROUP BY가 implicit sorting을 하게 된다. 그 이상 버전에서는 하지 않음)

 

(17) (DISTINCT with an aggregate function)

SELECT COUNT(DISTINCT state)

FROM customers

WHERE country = 'USA';

(aggregate function인 COUNT, SUM, AVG 같은 것을 함께 써서 duplicated rows가 없는 취합이 가능)

 

(18) (DISTINCT with LIMIT)

SELECT DISTINCT state

FROM customers

WHERE state IS NOT NULL

LIMIT 5; 

(MySQL은 LIMIT만큼의 결과를 찾은 즉시 searching을 그만 둔다.)

 

(19) (AND with NULL)

SELECT customername, country, state

FROM customers

WHERE country = 'USA' AND state = 'Victoria';

(NULL AND TRUE는 NULL을 반환, 즉 country가 'USA'이고 state가 null이면 select하지 않음)

(NULL AND FALSE는 FALSE을 반환)

 

(20) (OR AND가 존재할 때 판단 순서, Operator precedence)

SELECT true OR false AND false;

(이는 false AND false를 먼저 계산하여 false, 이후 true OR false계산하여 true, 따라서 1을 반환)

 

(21) (OR AND가 존재할 때 순서를 강제하기)

SELECT (true OR false) AND false:

(이렇게 순서를 괄호로 강제하면 true OR false에서 true, true AND false에서 false, 따라서 0을 반환)

 

(22) (OR AND가 여럿 존재하면 반드시 괄호 쓰기)

SELECT customername, country, creditLimit

FROM customers

WHERE country = 'USA' OR country = 'France' AND creditlimit > 10000;

(이 경우 결과는 (country='FRANCE' AND creditlimit>10000) or (country='USA')를 반환함)

(아마도 이 쿼리를 작성한 사람은 이 결과를 원한게 아닐 것이다.)

((country = 'USA' OR count = 'France') AND creditlimit > 10000; 을 사용했어야 했다.)

 

 

 

 

참고자료:

www.mysqltutorial.org/mysql-where/

 

MySQL WHERE

This tutorial shows you how to use MySQL WHERE clause to filter rows based on specified conditions.

www.mysqltutorial.org

 

728x90
728x90

math.stackexchange.com/questions/2656231/proving-that-softmax-converges-to-argmax-as-we-scale-x

728x90
728x90

GIL(Global Interpreter Lock)이란

In CPython, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe. 

 

deadlock이란

 

 

race condition이란

thread는 자기가 속한 process 내에 shared memory에 접근할 수가 있는데,

다수의 thread가 shared memory에 동시에 접근할 수도 있다.

이 때 다수의 thread가 동시에 한 변수에 각자의 작업을 한 것이,

각 thread가 작업한 것이 타 thread에 반영이 즉각 이루어 지지 않을 수가 있다. 이 현상을 race condition이라 한다.

즉, 다수 thread가 특정 값을 동시에 접근하여 변경하는 것을 가리킴

 

thread-safe란

race condition을 방지하며 thread가 작동함

 

mutex(mutual exclusion)란

 

 

참고자료:

dgkim5360.tistory.com/entry/understanding-the-global-interpreter-lock-of-cpython

 

왜 Python에는 GIL이 있는가

Python 사용자라면 한 번 쯤은 들어봤을 (안 들어봤다 해도 괜찮아요) 악명 높은 GIL (Global Interpreter Lock)에 대해 정리해본다. Global Interpreter Lock 그래서 GIL은 무엇인가? Python Wiki에서는 이렇게..

dgkim5360.tistory.com

timewizhan.tistory.com/entry/Global-Interpreter-Lock-GIL

 

Global Interpreter Lock (GIL)

해당 글은 아래 글을 번역 및 의역한 것이다. (보다 자세한 부분은 첨부된 페이지를 참조) https://realpython.com/python-gil/#why-wasnt-it-removed-in-python-3 Python의 Global Interpreter Lock (GIL)은 mute..

timewizhan.tistory.com

namu.wiki/w/Deadlock

 

Deadlock - 나무위키

먼 길아기가 잠드는 걸 보고 가려고 아빠는 머리맡에 앉아 계시고. 아빠가 가시는 걸 보고 자려고 아기는 말똥말똥 잠을 안 자고. Deadlock. 교착 상태. 운영체제 혹은 소프트웨어의 잘못된 자원 관

namu.wiki

 

728x90
728x90

SGD(mini-batch로 gradient계산하고 그것을 즉각 반영)은 GD(학습데이터 전체로 gradient계산)보다 gradient 반영을 잦게 함으로써 수렴 속도 증가 이점이 존재

 

Momentum Optimization

현재 local gradient*learning_rate(η)를 weight에 적용하고 이전 weight 변화량에 friction(β)을 곱한 것을 더해주자.

즉, 현재 local gradient*learning_rate만큼 변화 주고, 예전에 가던 방향을 또 가자!

->이로써 평지를 좀 더 빠르게 탈출할 수 있다.

->friction의 존재로 local optimum에서의 진동을 막아준다.

 

NAG(Nesterov Accelerated Gradient)

이전 weight변화량에 friction곱한 것을 더해준 다음에 그 지점을 local로 보고 gradient*learning_rate를 반영

->즉 momentum vector가 주로 올바른 방향으로(to global optimum)가는 데

그 때 가고나서 gradient를 계산하는게 더 빠르게 수렴한다.

 

AdaGrad(Adaptive Gradient Descent)

각 weight의 i-th position마다 gradient를 누적해둔 term이 존재하고 

그 누적값이 큰 곳은 적게 이동

그 누적값이 적은 곳은 상대적으로 크게 이동

->learning_rate decay효과가 생기므로 learning_rate tuning cost 감소

하지만, 누적term이 계속 쌓이기 때문에, 너무 일찍이 learing_rate가 decay해서 학습이 멈춰버릴 수도 있다.

 

RMSProp(Root mean Square Propagation)

AdaGrad에서 누적값에 exponential moving average(decay_rate β)로 채우자.

즉, 오랜 과거 누적값은 상쇄시켜 AdaGrad를 하자는 것, 왜냐하면 AdaGrad의 누적값이 항상 커져서 이른 학습 종료가 잦기 때문

->AdaGrad의 learning_rate decay 효과가 여전히 있으므로 learning_rate tuning cost감소

 

 

Adam(Adaptive Moment estimation)

기존 Momentum Optimization에서 Momentum에 붙은 friction, 이 때 (1-friction)을 gradient에 추가

RMSProp에서 누적값 차용

Moment와 누적값 모두 초기 boosting((1-friction)과 (1-decay_rate)를 iteration 횟수만큼 나눔)

따라서 moment에 누적값을 나눈 것 * learning_rate를 weight에 적용

즉, Adjusted Momentum Optimization과 RMSProp을 합친 형태

 

NADAM(Nesterov 방식이었던 Accelerated를 Adam에 적용, Accelerated Adaptive Moment estimation)

Adam에서 moment를 Nesterov방식을 차용하여 더 빠른 수렴속도를 얻음

 

 

 

결국 정리하면

moment개념이 있고(Momentum)

moment먼저타고 gradient구하기(Nesterov)

gradient 누적하여 step size 정정(AdaGrad)

gradient 옛 누적값 상쇄(RMSProp)

Momentum + RMSProp(Adam)

Nesterov + RMSProp(Nadam)

 

 

 

추가로, gradient 대신에 2차항까지 써서, 즉 Hessian까지 써서 weight를 update하는 것은?

->수많은 parameter에 제곱개수의 계산이 필요하므로 doesn't fit in memory and large computing resources

 

728x90
728x90

학습하는 것:

각 node마다 4개씩 parameters가 생긴다. scaling term, shift term, mean term, std term.

이 중 scaling term과 shift term은 trainable이고, 남은 2개는 moving average로 계산한다.(non-trainable)

mean term과 shift term은 training이 마친 후 prediction때 batch mean, batch std가 없으니 사용함

(mean term과 shift term은 어찌보면 trainable인데 keras에서는 trainable로 잡진 않음, 즉 backpropagation 대상이 아니기 때문임)

 

mean term, std term이 moving average로 계산되는 방법:

new batch mean(a)과 new batch std(b가 들어오면 직전까지의 mean term(A), std term(B) 에 대해

갱신을 다음과 같이 한다.

new mean term(A') = A*momentum + a*(1-momentum)

new std term(B') = B*momentum + b*(1-momentum)

이러한 방식을 exponential moving average라 한다.

(대개, newbie에게 적은 가중치를 주고, 직전꺼에 크게 줌)

 

효과:

-vanishing gradient 현상 감소

-weight initialization 의존성 감소

-large learning rate 사용 가능 -> 학습속도 상승

-overfit 방지(as a regulizer)

-계산량이 늘어나 보이지만, 직전 Batch Normalization layer앞에 dense layer가 있다면, Dense layer의 weight, bias를 수정하면, 계산량이 늘지 않게 가능

 

단점:

-직전 layer가 없다면 계산량이 늘어남(prediction때 좀 느려질 수 있음)

 

728x90
728x90

DBMS의 정의:

a software system that enables users to define, create, maintain and control access to the database.

 

DBMS의 특징:

데이터 무결성(Integrity), 즉 primary key역할을 하는 경우 not null, unique등의 제약조건이 필요

데이터의 독립성, 즉 데이터베이스의 크기가 변경되거나 저장소가 변경되어도 DBMS는 잘 동작 해야한다.

보안, 계정별 접근권한에 따른 접근만 가능

데이터 중복 최소화, 여러계정이 데이터베이스를 공유하여 접근함으로써, 각 계정마다 데이터를 중복해서 가질 필요가 없음

응용 프로그램 제작 및 수정이 쉬워짐, 통일된 파일 형식으로 프로그램 작성|유지보수 등이 일관됨

데이터의 안전성 향상, 백업|복원 기능을 제공 

 

간단한 예로

회원정보.xlsx(column이 회원코드, 회원이름, 회원주소 etc),

구매정보.xlsx(column이 회원코드, 회원주소, 상품코드 etc),

이 때 회원이 회원주소를 수정했다면 일일이 두개 파일 모두 수정해야한다.

엑셀파일이 2개가 아니라 많다면?

 

SQL(Structured Query Language)란 DBMS를 통해 정보의 입출력, 관리 등을 할 때 사용하는 언어

표준화된 언어로 각각의 DBMS는 거의다 호환되지만 약간의 차이가 존재하는 형태

클라이언트에서 질의하고 서버가 처리한 후 클라이언트에게 결과를 주는 형태의 대화식 언어

 

 

RDBMS(Relational DBMS)란

데이터를 row와 column을 이루는 하나의 이상의 테이블(=관계, relation)으로 정리하며 primary key가 각 row를 식별한다. 

각 table을 join하여 사용하는 것이 큰 특징

 

 

참고자료:

www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9791162242780&orderClick=LAG&Kc=

 

이것이 MySQL이다 - 교보문고

2016년 출간 후 데이터베이스 도서 분야 부동의 베스트셀러 1위를 지켜오던 『이것이 MySQL이다』가 MySQL 8.0 버전을 반영하여 개정되었다. 특히 ‘파이썬 기초 및 파이썬과 데이터베이스의 연동’,

www.kyobobook.co.kr

en.wikipedia.org/wiki/Relational_database

 

Relational database - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Digital database whose organization is based on the relational model of data A relational database is a digital database based on the relational model of data, as proposed by E. F. Cod

en.wikipedia.org

 

728x90
728x90

빠른 이유로는 3가지 이유가 있다.

1. numpy.ndarray는 a collection of similar data-types that are densely packed in memory.

(반면, list는 different data-types을 가질 수 있고 computation하는 데에 있어서 몇가지 과정을 더 타야한다.)

(이 부분은 하단의 설명을 다시 보자.)

2. numpy는 한 task를 subtask로 알아서 나눠서 parallely하게 작동하기도 한다.

(예를 들면, np.dot()을 수행할 때, argument의 size가 크면 cpu core 전부를 쓰는 것을 확인할 수 있다.)

3. numpy는 C언어로 구현되어 있어서 더 빠르게 작동한다.

 

 

하늘색이 실제 저장된 값

ndarray는 element조회시 "data"에 접근 후, 모든 데이터를 쭉 접근 가능

쭉이란, 각 값들이 메모리에 연속적으로 저장되어 있음

게다가 각 element가 같은 dtype이라, +N byte형태로 빠른 element 연속 접근이 가능

 

list의 경우 각 파란색 값이 메모리에 연속적으로 존재하지 않음

ob_item 내에 각 element의 reference(메모리 주소)를 갖고 있다.

그 reference를 타고 가더라도, 객체 자체가 있고, 그 객체 내에 ob_digit(객체가 int라면)로 가야 element에 접근

즉, 접근단계가 ndarray(1)에 비해 list(3)가 접근 단계가 많다.

그리고 next element에 접근할 때도 ndarray(1)인데 list(3)이므로 접근 방식 자체에서 느린 구조이다.

 

결론

ndarray는

dtype이 similar한 녀석들로 만들면 고속 접근이 가능

 

list는

dtype이 different하더라도 담을 수가 있음, 따라서 무한한 정수가 가능(담긴 element int가 아무리 커져도 int32 형태로 제한이 걸릴 일은 없다는 것)

 

 

참고자료:

towardsdatascience.com/how-fast-numpy-really-is-e9111df44347

 

How Fast Numpy Really is and Why?

A comparison with standard Python Lists.

towardsdatascience.com

spyhce.com/blog/cpython-data-structures

 

CPython data structures | Spyhce blog

In this article we have a look at the underlying C implementation, how these types work and what tweaks are there to make them faster. Learn more!

spyhce.com

www.youtube.com/watch?v=fiYD0yCou4k

 

728x90

+ Recent posts