최근 R markdown을 사용할 일이 생겼는데

굉장히 유용해 보인다!



원리를 보면 간단하다.


R code를 R markdown이 HTML form으로 만들어 주는데 이를  호스팅해서 사용하면 된다.

Shiny server가 있으면 Shiny를 이용해도 된다.


<출처 : http://www.dartistics.com/rmarkdown-shiny.html>


Shiny server를 이용하면 Log in 기능도 있고 따로 관리할 필요가 없어 편리할 듯


R markdown에서 만든 html을 호스팅 해보았다.

링크 (pw:test)


분석 결과나 Plot을 공유할 때, Excel이나 PPT로 공유하면 보여줄 수 있는 뷰가 한정적이었다.

또 사람 손을 타다 보니 에러가 많았다.


PHP로 로그인 기능만 구현하면 꽤 유용하게 사용할 수 있을 듯



'Data Science' 카테고리의 다른 글

plotly chart (embedded to web)  (0) 2017.06.12
분석 프로세스  (0) 2017.05.25
데이터 유형  (0) 2017.04.26
Tree  (0) 2017.04.09
Neural networks  (0) 2017.03.13

Plotly chart



R의 shiny는 데이터 시각화를 웹을 통해 공유할 수 있도록 한다.

쉽게 다른 사람들과 데이터를 공유할 수 있는 장점이 있지만 간단한 interactive plot을 공유하기에는 불편한 감이 있다.



<Shiny를 이용한 Animation>



plotly는 interactive chart를 쉽게 웹페이지에 공유 할 수 있도록 해준다.



<interactive plot>



위의 plot은 내 plotly 계정에서 생성하여 blog에 embeded 하였다.

Web page를 통해 공유할 수 있다는 점이 무척 마음에 들었지만

더 마음에 들었던 것은 아래 내용이다.



PPT에 embeded url을 통해 실을 수 있다 ㅎㅎㅎ


animation을 만들 수도 있기에 효과적으로 사용할 수 있을 것 같다.







'Data Science' 카테고리의 다른 글

r markdown  (0) 2017.07.04
분석 프로세스  (0) 2017.05.25
데이터 유형  (0) 2017.04.26
Tree  (0) 2017.04.09
Neural networks  (0) 2017.03.13


분석 절차


  분석 업무을 어디서 부터 어떻게 시작해야할지 몰라 막막할 때가 있다. 느꼈던 것들을 나름대로 정리해 보려 한다.


1. 구체적인 분석주제 및 목적 설정


  분석 주제를 명확하게 선정해야 한다. 중요한 일인데 간과하는 경우가 많다. 데이터를 던져 주고 "뭔가 분석해주세요."라고 하는 경우가

있는데 이렇게 분석 목적이 명확하지 않으면 막상 분석했을 때, Client가 원하지 않았던 방향으로 분석이 진행되는 경우가 생긴다.

분석이 끝났는데, 다시 처음부터 시작해야하는 경우가 생긴다. 그래서 요청자가 무엇을 분석하고 싶은지 명확하게 커뮤니케이션하고

문서로 남겨야 한다. 시작이 반이다라는 말처럼, 처음에 공을 많이 들여야한다. 그래야 뒤로 갈수록 편해지는 것 같다.


2. EDA


  분석 목적과 주제도 정했다. 그러면 분석을 시작해야하는데 무작정 이것 뽑아보고 저것 뽑아보고 하면 시간이 너무 많이 소요된다. 

효율적으로 진행하기 위해서 EDA를 해야한다. EDA의 목적은 데이터의 구조를 파악하고 변수간의 특징을 

파악하는 것인데, Plot을 그려 보는 직관적이고 효율적인 것 같다.


  첫째, 데이터 구조를 파악한다. 

Python 유저라면 tbl.describe(), R유저라면 summary(tbl), str(tbl)등을 통해 각 열이 어떤 데이터로 구성되어있는지 파악한다.

missing value가 있는지도 이때 확인한다. 뒤에 가서 알고리즘을 돌릴때 missing value가 있으면 안돌아가는 경우가 있다.

그때 되서 Data handling 하려고하면 피곤해진다.  처음에 공을 많이 들여야 편해지는 것 같다.


  둘째, Plot을 그려본다.

예를 들어 쿠폰 성과 분석이 주제라면, 쿠폰 사용자와 비사용자를 나눠 Profiling을 해본다. 이렇게 Plot을 돌려보다 보면

사용자와 비사용자의 차이점을 발견하게 되고 어떤 변수가 쿠폰 사용에영향을 미치는지 파악할 수 있게된다.     

 

<타이타닉, 상관계수 plot,s package : seaborn (python)>

 

위는 타이타닉 탑승자 데이터를 상관계수표로 나타낸 것이다. 위 표를 보면 Survived와 연관성이 있는 변수들을 파악해볼 수 있다.

Fare, pclass등이 연관성이 높아 보인다. 추가로 Fare, plass의 상관도가 높게 나타나는데, 이 경우 생존을 결정짓는 변수로 Fare와 pclass가

비슷한 영향을 미쳤다고 볼 수 있다. 그래서 Fare와 pclass 중 하나를 선택하거나 파생변수를 만들어서 분석하는 것이 적절해 보인다.

 

예로 든 쿠폰 분석도 위와 같은 Plot을 그려 볼 수 있다. 연령, 성별, 가입채널등의 변수와 쿠폰사용여부를 넣고 돌리면 쿠폰사용과

연관이 있는 변수를 파악할 수 있다.

 

3. Feature Selection

 

 

 

  사실 이부분이 가장 어려운 것 같다. Data의 Column이 많은 경우 어떤 column을 선택할지 고민이 많이된다.

데이터 분석에서 도메인 지식이 필요하다고들 하는데. Feature selection 때문이라는 생각이 든다. Feature selection을 구글링 해보면

이런 말이 나온다. "Feature selection은 Engineering과 Art의 조합이다" 즉 도메인에 대한 지식이 있으면 어떤 변수가 영향을 미쳤을지

대략적인 감이 온다. 하지만 이 감만 믿기에는 확실하지가 않다. 그래서 Algorithm도 필요하다. Feature selection에는 여러가지 방법이

있지만 내가 주로 사용하는 알고리즘은 Randomforest다.

Randomforest에는 Feature importance라는 변수 중요성(?)을 수치로 제공해준다. 측정 방법에는 purity, Gini를 구하는 방법등

여러가지가 있지만 자세한 내용은 다음에 다뤄야겠다.

 

위에서 EDA한 내용 + Alogirthm을 통해 얻은 중요 변수를 구하고, 감+직관(?)으로 변수를 선택, 조정하는 것이 좋을 것 같다.

Nueral network를 사용하면 예측은 쉽게 할 수 있겠지만, 어떤 변수가 영향을 미쳤는지는 설명할 수가 없다. 그래서 앞서 말한

방법으로 진행하는 것이 분석관점에서는 좋은 것 같다.

 

<생존 Vs 변수들,타이타닉 데이터>

R에서는 ggplot의 facet, python에서는 seaborn을 사용한다

 

4. Algorithm

 

  드디어 Algorithm을 돌릴 수 있다. 이 부분이 가장 간단하다. 앞에서 선택한 변수를 대상으로 데이터 형식을 맞춰서 패키지에 넣고 돌리면 오차율,

정확도까지 패키지가 다 계산 해준다. 이때, 한가지 패키지만 돌릴 것이 아니라 여러가지 패키지를 돌려보고 성능이 좋은 알고리즘을 선택하는

것이 좋다.

 

나름대로 느끼고 배운 것들을 정리해봤다!

 

*참고

https://www.linkedin.com/pulse/why-you-should-fire-your-data-scientist-benjamin-taylor

 

 

 

 

 

 

'Data Science' 카테고리의 다른 글

r markdown  (0) 2017.07.04
plotly chart (embedded to web)  (0) 2017.06.12
데이터 유형  (0) 2017.04.26
Tree  (0) 2017.04.09
Neural networks  (0) 2017.03.13

데이터 전처리에 있어 dplyr을 주로 사용하다보니 list, dataframe, matrix 사용법과 의미를 잊어 버리곤 한다.

list, matrix를 자주 사용하진 않는데 용할 일이 꼭 생긴다. 그럴때마다 구글링을 하는건 좋은 방법이 아닌 것 같다.


Vectors


a <- c(1,2,5.3,6,-2,4) # numeric vector
b <- c("one","two","three") # character vector
c <- c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE) #logical vector


a[c(2,4)] # 2nd and 4th elements of vector



Matrix


# generates 5 x 4 numeric matrix 
y<-matrix(1:20, nrow=5,ncol=4)

# another example
cells <- c(1,26,24,68)
rnames <- c("R1", "R2")
cnames <- c("C1", "C2") 
mymatrix <- matrix(cells, nrow=2, ncol=2, byrow=TRUE,
  dimnames=list(rnames, cnames))


x[,4] # 4th column of matrix
x[3,] # 3rd row of matrix 
x[2:4,1:3] # rows 2,3,4 of columns 1,2,3



Dataframe


d <- c(1,2,3,4)
e <- c("red", "white", "red", NA)
f <- c(TRUE,TRUE,TRUE,FALSE)
mydata <- data.frame(d,e,f)
names(mydata) <- c("ID","Color","Passed") # variable names


myframe[3:5] # columns 3,4,5 of data frame
myframe[c("ID","Age")] # columns ID and Age from data frame
myframe$X1 # variable x1 in the data frame


Lists


# example of a list with 4 components - 
# a string, a numeric vector, a matrix, and a scaler 
w <- list(name="Fred", mynumbers=a, mymatrix=y, age=5.3)

# example of a list containing two lists 
v <- c(list1,list2)


mylist[[2]] # 2nd component of the list
mylist[["mynumbers"]] # component named mynumbers in list


Factors


Tell R that a variable is nominal by making it a factor. The factor stores the nominal values as a vector of integers in the range [ 1... k ] (where k is the number of unique values in the nominal variable), and an internal vector of character strings (the original values) mapped to these integers.



# variable gender with 20 "male" entries and 
# 30 "female" entries 
gender <- c(rep("male",20), rep("female", 30)) 
gender <- factor(gender) 
# stores gender as 20 1s and 30 2s and associates
# 1=female, 2=male internally (alphabetically)
# R now treats gender as a nominal variable 
summary(gender)




# variable rating coded as "large", "medium", "small'
rating <- ordered(rating)
# recodes rating to 1,2,3 and associates
# 1=large, 2=medium, 3=small internally
# R now treats rating as ordinal



http://www.statmethods.net/input/datatypes.html


'Data Science' 카테고리의 다른 글

plotly chart (embedded to web)  (0) 2017.06.12
분석 프로세스  (0) 2017.05.25
Tree  (0) 2017.04.09
Neural networks  (0) 2017.03.13
Random forest  (0) 2017.03.05

트리의 장점은?


<Titanic Decision tree>


1) 트리를 만드는 계산 비용은 N개의 데이터 개수에 대해서 logN으로 매우 낮음

2) 해석하기 편리하다. 직관적


변수 설정 방법


스무 고개를 할 때의 과정과 유사하다. "남자인가요?"라는 질문 전에 "사람인가요?"라는 질문을 보통 먼저한다.

"남자인가요?" "사람인가요?"의 순으로 질문을 하지 않는다.

왜냐하면 모든 남자는 사람이기 때문이다.


변수의 값을 앎으로써 얼마나 추가적인 정보를 얻게 되는지를 계산함으로써 변수를 정한다.

이를 수치화하는 데는 정보 이론 (정보 엔트로피)가 사용된다.


적용방법(ID3)


다음 분류 스텝에서 특정 변수를 선택했을 때 전체 트레이팅 데이터의 엔트로피가 얼마나 줄어드는지를 살핀다.

ID3 알고리즘은 각 변수의 알고리즘 이득을 계산하고, 가장 높은 값을 갖는 변수를 선택한다.

각 단계에서 최고의 변수는 선택되고 제고된다.


ID3 알고리즘


1) IF 모든 예제들이 같은 라벨을 갖는다면 라벨과 함께 잎 노드를 반환

2) Else if 테스트할 변수들이 더이상 존재하지 않는다면 가장 일반적인 라벨들을 사용하여 잎 토드를 반환

3) 엔트로피를 이용하여 정보 이득을 최대화 하는 변수를 고르고 다음 노드로 선택

4) 선택한 변수의 값에 대해서 각각 노드의 가지를 추가

5) 각 가지에 대해서 

     -  변수 집합으로 부터 선택 변수를 제거하고 엔트로피를 계산

     -  반복적으로 수행하여 현재 예제들의 집합에 대한 상대적인 이득을 계산 



또 다른 적용방법 (지니 불순도)


결정 트리의 목표는 잎 노드가 같은 클래스에 속하는 데이터들을 묶는 것이다.

위의 Titanic Decision tree도 결국, 생존자와 사상자를 구분 할 수 있는 변수와 값들을 찾는 것이다.


잎 노드가 순수하다면 해당 잎에 속한 모든 트레이닝 데이터는 하나의 클래스를 갖는다.

즉, 여성일 경우 모두 생존했다면 Survived의 잎은 pure하게 된다.

pure의 정도를 수치화하여 변수를 선택하는 방법이 지니 불순도를 이용한 방법이다. 


시중에 나와있는 다수의 패키지들은 지니 불순도를 이용하는 것 같다. 



데이터 분석에도 유형이 있는 것 같다. 크게 2가지 유형이 있는 것 같은데

첫번째는 학습자 성능에 초점을 맞춘 유형 (이미지 분류, 패턴인식 등) 시스템에 들어가는 것들

두번째는 데이터를 해석하는 것에 초점을 맞춘 유형 (Feature selection등), 컨설팅이나 Business analysis에서  많이 하는 사용 하는 것 같다.

ex.재방문을 유도하기 위해서는 어떤 부분을 어떻게 터치해줘야하는가?와 같은 질문들에 대한 대답


Decision tree는 너무나 직관적이고 이해하기 쉽기 때문에 활용도가 굉장히 높음


직관적이라는 건 생각보다 훨씬 큰 장점인 듯 하다 ㅎㅎㅎㅎ


'Data Science' 카테고리의 다른 글

분석 프로세스  (0) 2017.05.25
데이터 유형  (0) 2017.04.26
Neural networks  (0) 2017.03.13
Random forest  (0) 2017.03.05
qplot  (0) 2017.02.05

Random forest. Neural Network


import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler

from time import time

np.random.seed(1337)

df = pd.read_csv('/Users/train.csv')


df['Sex'] = df['Sex'].map({'female':0, 'male':1})
df['Embarked'] = df['Embarked'].map({'C':1, 'S':2, 'Q':3})


df_train = df.iloc[:172,:]

df_train = df_train.drop(['Name', 'Ticket', 'Cabin'], axis=1)
df_train = df_train.dropna()



scaler = StandardScaler()
features = ['Pclass','Sex','Age','Fare']

X_train = scaler.fit_transform(df_train[features].values)
y_train = df_train['Survived'].values
y_train_onehot = pd.get_dummies(df_train['Survived']).values


df_test = df.iloc[712:,:]

df_test = df_test.drop(['Name', 'Ticket', 'Cabin'], axis=1)
df_test = df_test.dropna()

X_test = scaler.transform(df_test[features].values)
y_test = df_test['Survived'].values



#To create a basis for comparison, we train a Random Forest model and record the accuracy on the test set.


from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(random_state=0, verbose=3)
model = model.fit(X_train, y_train)

y_prediction = model.predict(X_test)
print "\naccuracy", np.sum(y_prediction == y_test) / float(len(y_test))



# 1-layer Neural Network

print X_train[0]

W = np.random.rand(2,4)*0.01

b = np.random.rand(2,) * 0.01

print b


result = np.dot(W, X_train[0]) + b


def softmax(x):
return np.exp(x) / np.exp(x).sum()

result = softmax(result)

print result

print y_train_onehot[0]

label_index = np.argmax(y_train_onehot[0])

print label_index

print "predicted label-0 probability", result[label_index]


loss = -np.log(result[label_index])

print "loss for first passenger", loss

min_loss = 1000
best_weights = ()

start = time()

for i in xrange(1000):
W = np.random.rand(2, 4) / 10
b = np.random.rand(2, ) / 10

scores = []
loss = 0

for j in xrange(X_train.shape[0]):
result = np.dot(W, X_train[j]) + b
result = softmax(result)
scores.append(list(result))

label_index = np.argmax(y_train_onehot[j])
loss += -np.log(result[label_index])

loss = loss / float(X_train.shape[0])
y_prediction = np.argmax(np.array(scores), axis=1)
accuracy = np.sum(y_prediction == y_train) / float(len(y_train))

if loss < min_loss:
min_loss = loss
best_weights = (W, b)
print "loss %s accuracy %s loop %s" % (round(loss, 3), round(accuracy, 3), i)

print "\ntime taken %s seconds" % str(time() - start)


W, b = best_weights
scores = []

for j in xrange(X_test.shape[0]):
result = np.dot(W, X_test[j]) + b
result = softmax(result)
scores.append(list(result))

y_prediction = np.argmax(np.array(scores), axis=1)

print "accuracy", np.sum(y_prediction == y_test) / float(len(y_test))


# 2-layer Neural Network

W_1 = np.random.rand(100, 4) * 0.01
b_1 = np.random.rand(100,) * 0.01
W_2 = np.random.rand(2, 100) * 0.01
b_2 = np.random.rand(2,) * 0.01

result = np.dot(W_1, X_train[0]) + b_1
result = np.dot(W_2, result) + b_2

min_loss = 1000
best_weights = ()

start = time()

for i in xrange(1000):
W_1 = np.random.rand(100, 4) * 0.01
b_1 = np.random.rand(100, ) * 0.01
W_2 = np.random.rand(2, 100) * 0.01
b_2 = np.random.rand(2, ) * 0.01

scores = []
loss = 0

for j in xrange(X_train.shape[0]):
result = np.dot(W_1, X_train[j]) + b_1
result = np.dot(W_2, result) + b_2
result = softmax(result)
scores.append(list(result))

label_index = np.argmax(y_train_onehot[j])
loss += -np.log(result[label_index])

loss = loss / float(X_train.shape[0])
y_prediction = np.argmax(np.array(scores), axis=1)
accuracy = np.sum(y_prediction == y_train) / float(len(y_train))

if loss < min_loss:
min_loss = loss
best_weights = (W_1, b_1, W_2, b_2)
print "loss %s accuracy %s loop %s" % (round(loss, 3), round(accuracy, 3), i)

print "\ntime taken %s seconds" % str(time() - start)

W_1, b_1, W_2, b_2 = best_weights
scores = []

for j in xrange(X_test.shape[0]):
result = np.dot(W_1, X_test[j]) + b_1
result = np.dot(W_2, result) + b_2
result = softmax(result)
scores.append(list(result))

y_prediction = np.argmax(np.array(scores), axis=1)

print "accuracy", np.sum(y_prediction == y_test) / float(len(y_test))

https://github.com/savarin/neural-networks




Deep learning이란???


서칭을 해보니 전에 포스팅한 Monte Carlo Simulation이나 Optimization의 로직과 유사한 점이 느껴졌다.

위 코드는 Titanic dataset에 1-Layer neural network를 사용한 코드인데,


input -> Function1 -> Output 에 필요한 Function1을 구하여 예측을 한다.


이때 Function1은 Loop를 돌려 Error가 최소가 되는 Parameter를 구하여 만든다.


(2-Layer Neural Network는 input -> Function1 -> Function2 -> Output와 같은 로직)


Optimization, Monte Carlo method에서는 일정 범위오차에 수렴하게 되는 parameter를 구했던 것 같다.



Deep learning, Monte Carlo simulation은 귀납적. Optimization은 연역적인 느낌

Deep learning이 뜨는 이유가 조금씩 이해된다.


데이터는 갈수록 많아지고 Computing power는 좋아지니 그럴 수 밖에 없겠다.


생각해보면 방정식의 해를 구하는 방법중 Newton method도 비슷한 로직인 것 같다.

f(a) < 0, f(b) > 0인 a,b사이의 어느 근사값을 구했던 것 같은데 Loop를 만들었던 것 같다.


equation을 만들기도 힘들고, 풀기도 힘드니 막 찍어서 오차가 최소가 되는 함수를 만든다.


Deep learning이 정말 새로운 개념은 아닌 것 같다는 생각이 많이 든다.

예전부터 있었던 개념인데 컴퓨터로 이제 구현할 수 있게된 느낌..






'Data Science' 카테고리의 다른 글

데이터 유형  (0) 2017.04.26
Tree  (0) 2017.04.09
Random forest  (0) 2017.03.05
qplot  (0) 2017.02.05
ggplot2  (1) 2016.06.19

Random forest model



Goal.

titanic data에 Random forest model을 이용해 생존자를 예측해본다.




Random forest란?



Why random forest ? 



**특징 1)  변수 Scaling이 필요 없음

          2) 민감하지 않음. 특정 Parameter에 크게 영향을 받지 않음 




Process 

python




Pandas (Extract data)


import pandas as pd
import numpy as np

df = pd.read_csv('data.csv')

Pandas( classing data)


df_train = df_train.drop(['Name', 'Ticket', 'Cabin'], axis=1)
df_train = df_train.dropna()
df_train['Sex'] = df_train['Sex'].map({'female':0, 'male':1})
df_train['Embarked'] = df_train['Embarked'].map({'C':1, 'S':2, 'Q':3})

##Character는 Numeric으로 데이터 타입을 변경해줘야한다.
##결측값 처리 해줘야함
##결측치 처리 방법 찾아볼것

Scikit learn - Training the model

from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(n_estimators=100, random_state=0)
model = model.fit(X_train, y_train)

Scikit learn - Making prediction


df_test = df_test.drop(['Name', 'Ticket', 'Cabin'], axis=1)

df_test = df_test.dropna()

df_test['Sex'] = df_test['Sex'].map({'female': 0, 'male':1})
df_test['Embarked'] = df_test['Embarked'].map({'C':1, 'S':2, 'Q':3})

X_test = df_test.iloc[:, 2:]
y_test = df_test['Survived']
y_prediction = model.predict(X_test)

Evaluation


np.sum(y_prediction == y_test) / float(len(y_test))


** Tree visualization 방법 찾아 볼 것 !


'Data Science' 카테고리의 다른 글

Tree  (0) 2017.04.09
Neural networks  (0) 2017.03.13
qplot  (0) 2017.02.05
ggplot2  (1) 2016.06.19
dplyr package  (1) 2016.06.12

Why qplot???


qplot makes it easy to

produce complex plots, often requiring several lines of code using other plotting

systems, in one line. qplot() can do this because it's based on the grammar

of graphics, which allows you to create a simple, yet expressive, description

of the plot.


"ggplot2, Hadely wickham"


1. qplot


qplot( x, y, data, geom, facets, colour.fill)


1.1) Colour, Shape


qplot(carat, price, data = diamonds, colour = color )

qplot(carat, price, data = diamonds, shpae= color )




1.2) Transparency


qplot(carat, price, data =diamonds, alpha = I(1/20))

alpha : 투명도

data가 많을 때, 그냥 plot으로 그릴 경우 한눈에 들어오지 않음



1.3) Add Smooth line to chart


qplot(carat, price, data = sample_n(diamonds,1000) , geom = c("point", "smooth"),

      span = 0.2)


span : wiggly (구불거림의 정도 설정)

sample_n : dplyr package


sample size가 클경우 아래 방식을 사용 ( n > 1000)


library(mgcv)

qplot(carat, price, data = dsmall, geom = c("point", "smooth"),

method = "gam", formula = y ~ s(x))

qplot(carat, price, data = dsmall, geom = c("point", "smooth"),

method = "gam", formula = y ~ s(x, bs = "cs"))



library(splines)

qplot(carat, price, data = dsmall, geom = c("point", "smooth"),

method = "lm")

fits linear model


qplot(carat, price, data = dsmall, geom = c("point", "smooth"),

method = "lm", formula = y ~ ns(x,5))

fits natural spline line





'Data Science' 카테고리의 다른 글

Neural networks  (0) 2017.03.13
Random forest  (0) 2017.03.05
ggplot2  (1) 2016.06.19
dplyr package  (1) 2016.06.12
온라인 판매자 시뮬레이션(Monte-Carlo Simulation)  (1) 2016.01.03


이민호님의 깃허브( http://lumiamitie.github.io/ )를 참고하여 실습

ggplot2 뿐만 아니라 유용한 패키지가 많이 소개 되어있으니 참고하면 좋을듯



ggplot2는 


1. Layer

2. Sclae

3. Coordinate system

4. facetting specification

5. Guides


5가지로 요인으로 구성된다.


그중 첫번째 요인인 Layer는 1) Data 2) Mapping 3) Statiscal Transformation 4) Geometric Object 5) Position으로 나뉜다.

이민호님의 깃허브를 보면 자세하게 정리되어있으니 이를 참조할 것( http://lumiamitie.github.io )


요즘 실습 데이터로 쓰고 있는 코비의 슛 데이터를 불러온다.


setwd("C:/Users/user/Desktop/kob")

rd=read.csv("data.csv",header=T)



ggplot() +

  layer(data=rd,

        mapping = aes(x=loc_x, y=loc_y, colour=combined_shot_type),

        geom='point',

        stat='identity',

        position='identity')



CTRL+R


 점프샷이 압도적으로 많으니 점프샷은 지운다

rd2=subset(rd,combined_shot_type!='Jump Shot')


ggplot() +

  layer(data=rd2,

        mapping = aes(x=loc_x, y=loc_y, colour=combined_shot_type),

        geom='point',

        stat='identity',

        position='identity')





뱅크샷은 보통 중앙에서 많이 쏠줄 알았는데 그렇지 않았음

외곽 특히 왼쪽 외곽에서 슛을 많이 하는 것을 볼 수 있다.



 ggplot() +

  layer(data=rd2,

        mapping = aes(x=loc_x, y=loc_y, colour=combined_shot_type),

        geom='point',

        stat='identity',

        position='identity')


그런데 코드가 좀 길다. stat, position의 경우 'identity'라는 default값이 설정되어 있다.

이럴때는! 


ggplot()+

geom_point(data=rd2,  aes(x=loc_x, y=loc_y, colour=combined_shot_type))


로 짧게 표현 할 수 있다. 즉, 자주 사용하는 그래프 개형은 함수로 만들어져 있는듯

shortcut 함수들은 google에 물어볼것


 다음엔

ggplot2의 layer를 제외한 나머지 요인들을 정리 할 것!!








'Data Science' 카테고리의 다른 글

Neural networks  (0) 2017.03.13
Random forest  (0) 2017.03.05
qplot  (0) 2017.02.05
dplyr package  (1) 2016.06.12
온라인 판매자 시뮬레이션(Monte-Carlo Simulation)  (1) 2016.01.03

<코비 브라이언트의 슛팅 기록, kaggle>


R로 Data preprocessing을 하면 쉽지않다.

dplyr 패키지를 사용하면 이런 수고를 덜 수 있다.


dplyr은 Hadley Wickham이 만든 데이터 정제 페키지다.

패키지의 주요 내용을 정리하고 실습해봐야지



dplyr의 주요 함수로는 

1. filter()

2. arrange()

3. select()

4. distinct()

5. mutate()

6. summarise()

7. sample_n() 이 있다.



1. filter()


 SQL의 where 절이라고 생각하면 될 것 같다. 내가 보고 싶은 데이터의 조건을 걸 수 있는 함수다.

   ex) 수학성적이 90점이상인 학생들의 데이터 ( filter(data,수학성적>90)


-syntax


filter(data, var1=="value1",var2=="value2")

var1이 value1 and var2가 value2인 row를 불러온다.


filter(data, var1=="value1" | var2=="value2")

var1이 value1 or var2가 value2인 row를 불러온다.


filter(data, var3>100)

var3이 100보다 큰 row를 불러온다. 대소관계까지 가능!!








<OPPONENT가 POR인 row만 불러온다.>


2. arrange()


SQL의 order by절. 데이터를 정렬해주는 함수

ex) 수학 성적을 기준으로 오름차순하여 데이터를 정렬해

arragne(data, 수학성적) ##오름차순이 기본값으로 설정되어있다.

aarage(data, desc(수학성적)) #내림차순은 desc를 앞에 걸어준다



그외.. select(), distinct(), mutate()등등의 함수가 있는데 내가 굳이 정리할 필요가 없을 것 같다.

왜냐면

https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html







정리는 깔끔히 되어있으니 나는

데이터 정제에 자주 활용되는 것들을 실제로 실습해보고 정리해보려고 한다.



Kaggle에서 받은 코비 브라이언트의 경기 기록중 shot_zone_area, shot_type의 개수와 성공횟수를 구하고 싶다.

왼쪽 외곽(3점)에서 몇번 슛을 했는지, 몇번 성공했는지

왼쪽 외곽(2점)에서 몇번 슛을 했는지, 몇번 성공했는지 구하고 싶다.


SQL로 쓰면


SELECT  SHOT_ZONE_AREA,

SHOT_TYPE,

COUNT(SHOT_ID),

SUM(SHOT_MADE_FLAG)

  FROM  RD

 GROUP

      BY  SHOT_ZONE_AREA,

SHOT_TYPE

정도가 되겠지?? 길고 귀찮다.

그런데 dplyr을 사용하면???


df=group_by(rd,shot_zone_area,shot_type)

value=summarise(df, count=n(), succ=sum(shot_made_flag,na.rm=T))

단 2줄이면 끝


여기서 group_by는 rd를 shot_zone_area, shot_type으로 묶겠다는 뜻. 즉..shot_zone_area에 왼쪽,중앙,오른쪽 shot_type에 점프슛,덩크,레이업이 있다면 왼쪽 (점프슛, 덩크, 레이업), 중앙 (점프슛, 덩크, 레이업), 오른쪽 (점프슛, 덩크, 레이업) 각각의 슈팅수와 성공횟수를 구한다는 뜻

data frame으로 보면...



< 요롷게 된다ㅎㅎㅎ>


이렇게 구하고 나니 궁금한 것이 생긴다. 그래서 성공률은 얼마야??? dataframe에 성공확률을 추가하자!

새로운 column을 추가하는 명령어는 mutate()를 사용한다.


df=data.frame(value)

df2=mutate(df,prob=succ/count)


위의 value를 data.frame으로 설정해주고 prob이라는 컬럼을 만든다. prob에는 succ(성공횟수)/count(갯수)가 들어가게 된다.
Ctrl + R 돌려본다


<요롷게 prob가 추가된다. 소수가 너무길어서 눈에 안들어온다면.. >


요롷게...반올림하고 %를 붙인다.

df2=mutate(df,prob=paste(round(succ/count,digits=3)*100,"%"))



<깔끔하다ㅎㅎㅎ>


이걸 SQL로 뽑으려면 어떻게 해야할까..생각해보니 count, succ를 뽑은 dataframe에 select문을 한번더 걸어서 prob를 구해야 할 것 같다.

복잡하다.

근데 R로 작성하면 훨씬 유연하게 작업을 할 수 있다.


 어찌보면 사소한 부분일 수 있지만 작업하다보면 이런 사소한 것들이 애를 먹일때가 있다. 그런면에서 dplyr 패키지는 굉장히

유용한 패키지인 것 같다.


좀 더 써보면서 유용한 것들은 정리해서 업데이트해야짛ㅎㅎㅎ




'Data Science' 카테고리의 다른 글

Neural networks  (0) 2017.03.13
Random forest  (0) 2017.03.05
qplot  (0) 2017.02.05
ggplot2  (1) 2016.06.19
온라인 판매자 시뮬레이션(Monte-Carlo Simulation)  (1) 2016.01.03

+ Recent posts