NumPy with ndarray

강의 홍보

Numpy ndarray 개요

  • 넘파이 array()는 ndarray로 변환 가능
  • 생성된 ndarray배열의 shape변수는 ndarray의 크기, 행과 열의 수를 튜플 형태로 가지고 있으며, 이를 통해 ndarray 배열의 차원까지 알 수 있음

(1) 배열이란?

  • NumPy에서 배열은 동일한 타입의 값을 가짐
  • shape는 각 차원의 크기를 튜플로 표시한다.
  • 차원이란 무엇일까?
    • 1차원은 보통 하나의 을 의미
    • 2차원은 평면을 의미하고, 데이터 분석에서는 보통 데이터프레임을 의미한다.
    • 3차원은 공간을 의미하고, 딥러닝에서는 보통 이미지를 의미한다. (RGB)

shape와 ndim

  • 코드를 통해서 shapendim 함수를 확인해본다.

(1) 함수 활용 예제

  • 우선 소스코드를 통해 1차원, 2차원, 3차원 함수를 만들어 봅니다.
import numpy as np
array1 = np.array([1,2,3,4,5])
print('array1 type:',type(array1))
print('array1 array 형태:',array1.shape)

array2 = np.array([[1,2,3,4,5],
                  [2,3,4,5,6]])
print('array2 type:',type(array2))
print('array2 array 형태:',array2.shape)

array3 = np.array([[[1,2,3,4,5,6]], [[3,4,5,6,7,8]]])
print('array3 type:',type(array3))
print('array3 array 형태:',array3.shape)
array1 type: <class 'numpy.ndarray'>
array1 array 형태: (5,)
array2 type: <class 'numpy.ndarray'>
array2 array 형태: (2, 5)
array3 type: <class 'numpy.ndarray'>
array3 array 형태: (2, 1, 6)

(2) shape

  • 1차원의 shape는 (3, )인데, 이는 array로 5개의 데이터를 가지고 있다는 뜻임
  • 2차원의 shape는 (2, 5)이며, 이는 array로 2차원 데이터로 2 x 5 = 10, 즉 총 10개의 데이터가 있음
  • 3차원의 shape는 (2, 1, 6)이며, 이는 array로 3차원 데이터로 2 x 1 x 6 = 12, 즉 총 12개의 데이터가 있음
  • 차원을 직관적으로 확인하려면 ndim 메서드를 사용하면 된다.
print('array1: {:0}차원, array2: {:1}차원, array3: {:2}차원'.format(array1.ndim, array2.ndim, array3.ndim))
array1: 1차원, array2: 2차원, array3:  3차원

데이터 타입

  • ndarray내 데이터값은 숫자 값, 문자열 값, 불 값 모두 가능
  • 숫자형의 경우 int형, float형 등이 제공됨
    • int: 8, 16, 32
    • float: 16, 32, 64, 128
  • 간단한 예제로 확인한다.
num_list = [7, 8, 9, 10]
print(type(num_list))
num_array = np.array(num_list)
print(type(num_array))
print(num_array, num_array.dtype)
<class 'list'>
<class 'numpy.ndarray'>
[ 7  8  9 10] int64

reshape의 중요성

  • shape를 통해 데이터를 이해하는 것은 매우 중요하다.
  • 머신러닝 알고리즘 또는 선형대수를 잘 모른다 할지라도, 머신러닝 및 데이터 세트 간의 입출력과 변환 수행 시, 1차원 데이터 또는 다차원 데이터를 요구하는 경우가 있다.
    • 이 때, 차원이 달라서 오류가 발생할 가능성이 크니, 주의를 해야 한다.
  • 이 때, 차원을 맞추는 방법으로 reshape()를 활용한다.

(1) 소스 예제

  • 다음 예제는 0~14까지의 1차원 ndarray2x5형태로, 그리고 5x2 2차원 ndarray로 변환한다.
array1 = np.arange(15)
print('array1:\n', array1)

array2 = array1.reshape(3,5)
print('array2:\n',array2)

array3 = array1.reshape(5,3)
print('array3:\n',array3)
array1:
 [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
array2:
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
array3:
 [[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]]
array1.reshape(4,3)
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-8-a40469ec5825> in <module>()
----> 1 array1.reshape(4,3)


ValueError: cannot reshape array of size 15 into shape (4,3)
  • 위 에러는 변경이 불가능한데, 당연한 얘기이지만, size가 맞지 않다.

(2) -1의 활용

  • 실전에서는 주로 -1을 활용한다.
  • -1을 인자로 사용하면 원래 ndarray와 호환되는 새로운 shape로 변환해준다.
  • 예제를 통해서 살펴보도록 한다.
array_1 = np.arange(15)
print(array_1)

array_2 = array_1.reshape(-1,5)
print('array2 shape:',array_2.shape)

array_3 = array_1.reshape(5,-1)
print('array3 shape:',array_3.shape)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
array2 shape: (3, 5)
array3 shape: (5, 3)
  • array_1은 1차원 ndarray로 0~14까지의 데이터를 가지고 있다.
  • array_2array_1과 호환될 수 있는 2차원 ndarray로 변환되고, 고정된 5개의 칼럼에 맞는 로우를 자동으로 새롭게 생성해 변환하는 의미를 가진다.
    • array_3도 반대로 적용할 수 있다.
  • 그런데, 호환될 수 없는 형태는 에러가 날 것이다.

(3) 차원변환

  • 3차원을 2차원으로, 1차원을 2차원으로 변경하는 코드를 작성할 수 있다.
  • 이 때, reshape(a1, a2, a3)에서, b = a1 x a2 x a3의 값이 arrange(b)이 된다.
array_1 = np.arange(27)
array_3d = array_1.reshape((3,3,3))
print('array3d:\n',array_3d.tolist())

# 3차원 ndarray를 2차원 ndarray로 변환
array_5 = array_3d.reshape(-1,1)
print('array5:\n',array_5.tolist())
print('array5 shape:',array_5.shape)

# 1차원 ndarray를 2차원 ndarray로 변환
array_6 = array_1.reshape(-1,1)
print('array6:\n',array_6.tolist())
print('array6 shape:',array_6.shape)
array3d:
 [[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]
array5:
 [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26]]
array5 shape: (27, 1)
array6:
 [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26]]
array6 shape: (27, 1)

선형대수 연산

  • 행렬 내적은 행렬 곱이며, np.dot()을 활용한다.

xgboost and kaggle with R

개요

  • R 강의를 진행하면서 xgboost를 R로 구현하고 싶었다.
  • kaggle에 있는 데이터를 불러와서 제출까지 가는 과정을 담았으니 입문자들에게 작은 도움이 되기를 바란다.

XGBoost 개요

Tree boosting is a highly effective and widely used machine learning method. In this paper, we describe a scalable end-to-end tree boosting system called XGBoost, which is used widely by data scientists to achieve state-of-the-art results on many machine learning challenges. We propose a novel sparsity-aware algorithm for sparse data and weighted quantile sketch for approximate tree learning. More importantly, we provide insights on cache access patterns, data compression and sharding to build a scalable tree boosting system. By combining these insights, XGBoost scales beyond billions of examples using far fewer resources than existing systems.

Kaggle with R

강의 홍보

개요

  • R 입문부터 머신러닝까지 가르치게 되었다.
  • 실제 Kaggle 대회 참여 독려를 위해 R에서 Kaggle 데이터를 불러와 머신러닝을 진행하는 것을 기획하였다.
  • pins 패키지를 활용하면 보다 쉽게 할 수 있다.

(1) Kaggle API with R

  • 먼저 [Kaggle]에 회원 가입을 한다.
  • 회원 가입 진행 후, Kaggle에서 kaggle.json 파일을 다운로드 받는다.

ch 13 - Reliability

Intro

  • PLS-SEM의 분석과정에서 척도(측정변수와 잠재변수)의 신뢰도와 타당도를 확보하는 것은 매우 중요하며, 신뢰도와 타당도가 확보되지 않으면 모델 추정 결과가 의미가 없기 때문임
  • 즉, 구조모델의 추정을 실행하려면 사전에 반드시 측정모델에 대한 평가과정을 통해 신뢰도와 타당도 확보 필요

I. 주요 개념

(1) 신뢰도

  • 잠재변수의 측정에 있어서 얼마나 일관성이 있는가의 정도 의미
    • 검사도구의 일관성을 말하며, 일관성이란 잠재변수를 여러 번에 걸쳐 측정했을 때 매번 같은 결과를 도출할 수 있는 정도.
    • 내적 일관성 신뢰(Internal Consistency Reliability)로 평가

(2) 타당도

  • 타당도의 기본 정의는 실제 측정하고자 하는 잠재변수를 정확하게 측정하고 있는 정도
    • PLS-SEM에서는 집중타당도(Convergent Validity)와 판별타당도(Discriminant Validity)를 사용한다.
    • 전자는 하나의 잠재변수를 측정하기 위해 사용되는 척도의 구성항목들 간에 상관관계가 높아야 집중타당도가 있다고 볼 수 있고, 후자는 하나의 잠재변수와 다른 잠재변수간 상관관계가 낮을수록 판별 타당도가 높다고 판단함.

(3) PLS-SEM 분석 결과의 쳬계적인 평가 단계

  • 반영적 측정모델: 내적 일관성 신뢰도, 집중타당도, 판별타당도
  • 형성적 측정모델: 집중타당도, 다중공선성, 외부가중치와 외부적재치의 유의성과 적합성
  • 구조모델의 평가기준: 다중공선성, 결정계수 $R^2$, 효과크기 $f^2$, 예측적 적합성 $Q^2$, 경로계수의 유의성과 적합성
  • PLS-SEM의 평가 단계: 제 1단계는 측정모델(Outer Model)을 평가하는 것이며, 제 2단계는 구조모델(Inner Model)을 평가하는 것이다.

II. 설문조사 데이터 분석

  • 이제 설문지를 분석해본다.
  • 필수 패키지를 확인한다.
library(readr) 
library(dplyr)
library(kableExtra) 
library(psy) # 신뢰도
library(corrplot) # 상관계수
library(psychometric) # 타당도 

(1) 데이터 수집

  • 먼저 수집된 설문조사 데이터를 확인한다.
data <- read_csv('data/thesis_mater.csv') %>% 
  distinct() %>% # 중복데이터 제거
  rename(Position = founder_employee, # 출력을 위한 변수명 정리
         Age = age_of_respondent, 
         Education = Education_Level) %>% 
  slice(-c(1:10)) %>% 
  dplyr::select(-c(Firm_Age:Business_Area))

data %>% 
  head() %>% 
  kable() %>% 
  kable_styling("striped") %>% 
  scroll_box(width = "100%")
EI_1EI_2EI_3EP_1EP_2EP_3ER_1ER_2ER_3SS_1SS_2SS_3SC_1SC_2SC_3SR_1SR_2SR_3F1F2F3NF1NF2NF3Firm_AgeFirm_SizeWE1WE2WE3genderfounder_employeeage_of_respondentEducation_LevelBusiness_Area
2343343241133332212233135 years aboveAbove 15 membersNo, I don't have experienceYesYesFemaleEmployee30-39Undergraduate SchoolOthers
552353444222222222222322Less than 2 yearsLess than 5 membersNo, I don't have experienceNoYesMaleEmployeeYounger than 30Undergraduate SchoolMedia and Entertainment
1221121212211221212111115 years aboveLess than 5 membersAs founder or employee, I have startup experiences more than 3 timesNoYesFemaleFounder of CompanyYounger than 30Undergraduate SchoolOthers
332121213213111233332322Less than 2 yearsLess than 5 membersNo, I don't have experienceYesYesMaleEmployeeYounger than 30Undergraduate SchoolOthers
5352544444545555554544553-4 yearsLess than 5 membersAs founder or employee, I have startup experiences more than 3 timesNoYesMaleFounder of Company30-39Undergraduate SchoolOthers
1331332314123312211231315 years above5-9 membersAs founder or employee, I have startup experience, one timeNoNoFemaleEmployeeYounger than 30Undergraduate SchoolOthers

(2) 상관관계 확인

  • 각 척도(Item)에서의 상관관계를 확인해본다.
M <- cor(data)

corrplot(M, type="upper", order="hclust", 
         col=RColorBrewer::brewer.pal(n=8, name="RdBu"))

Global Development Resources

공지

제 전공과 관련하여 주요 자료를 정리하였습니다. 데이터과학의 다양한 이론 중에서 국제개발에 적용시킬만한 내용이 무엇인지 고민하며 계속적으로 자료를 업데이트 할 예정입니다.

OECD 자료

UN 자료

Project Management

ch 12 - Demographic of Respondent in R

Intro

  • 지난 시간에 설문조사 전처리에 대해 배웠다면 이번에는 경영/사회과학 논문에서 필수적으로 기재해야 하는 표본의 특성을 간단한 프로그램으로 요약하는 것을 코딩한다.

(1) 주요 패키지

  • 이번 포스트부터 gt 패키지를 사용하려고 한다.
    • gt: ggplot2와 같이 Table를 문법으로 컨트롤 할 수 있도록 구현된 패키지이다.
    • kableExtra: HTML로 출력할 수 있도록 도와주는 패키지이다.
library(readr)
library(dplyr)
library(gt)
library(gtsummary)

I. 데이터 가져오기

  • 우선 데이터를 불러온다.
data <- read_csv('data/thesis_mater.csv') %>% 
  distinct() %>% # 중복데이터 제거
  rename(Position = founder_employee, # 출력을 위한 변수명 정리
         Age = age_of_respondent, 
         Education = Education_Level)
glimpse(data %>% select(Firm_Age:Business_Area))
  • 전체 34개의 변수 중에서, 문자열 관련 데이터만 추출하였다.
  • 어떤 데이터를 표본의 특성으로 삼아야 할까?
    • 위 10개의 데이터에는 통제변수1가 들어가 있다.
    • 통제변수는 표본의 특징이 아니기 때문에 통제변인을 제외한 나머지 변수들을 추출한다.
## Rows: 103
## Columns: 10
## $ Firm_Age      <chr> "5 years above", "Less than 2 years", "5 years above", …
## $ Firm_Size     <chr> "Above 15 members", "Less than 5 members", "Less than 5…
## $ WE1           <chr> "No, I don't have experience", "No, I don't have experi…
## $ WE2           <chr> "Yes", "No", "No", "Yes", "No", "No", "No", "No", "No",…
## $ WE3           <chr> "Yes", "Yes", "Yes", "Yes", "Yes", "No", "Yes", "No", "…
## $ gender        <chr> "Female", "Male", "Female", "Male", "Male", "Female", "…
## $ Position      <chr> "Employee", "Employee", "Founder of Company", "Employee…
## $ Age           <chr> "30-39", "Younger than 30", "Younger than 30", "Younger…
## $ Education     <chr> "Undergraduate School", "Undergraduate School", "Underg…
## $ Business_Area <chr> "Others", "Media and Entertainment", "Others", "Others"…
  • 표본의 특성을 기술하는 데이터는 아래와 같이 추출한다.
    • gender, founder_employee, age_of_respondent, educational_level, business_area
data2 <- data %>% 
  select(gender, Position, Age, Education, Business_Area)

glimpse(data2)
## Rows: 103
## Columns: 5
## $ gender        <chr> "Female", "Male", "Female", "Male", "Male", "Female", "…
## $ Position      <chr> "Employee", "Employee", "Founder of Company", "Employee…
## $ Age           <chr> "30-39", "Younger than 30", "Younger than 30", "Younger…
## $ Education     <chr> "Undergraduate School", "Undergraduate School", "Underg…
## $ Business_Area <chr> "Others", "Media and Entertainment", "Others", "Others"…

II. 표본 특성 표 출력

  • 보통 논문에 들어가는 표본의 특징은 Category, Frequency, and Percentage(%) 정도만 필요하다.
  • 이 때, Table을 가공해줄 수 있는 gtsummary 패키지를 활용한다.
set_gtsummary_theme(theme_gtsummary_journal(journal = "jama"))

data2 %>% 
  tbl_summary(by = gender) %>% 
  add_overall() %>% 
  add_n() %>% 
  modify_header(label = "**Variable**") %>% # update the column header
  bold_labels()
VariableNOverall, N = 103Female, N = 621Male, N = 411
Position103
Employee68 (66)35 (56)33 (80)
Founder of Company35 (34)27 (44)8 (20)
Age103
30-3937 (36)19 (31)18 (44)
40-498 (7.8)4 (6.5)4 (9.8)
50 or above2 (1.9)2 (3.2)0 (0)
Younger than 3056 (54)37 (60)19 (46)
Education103
Graduate School25 (24)15 (24)10 (24)
High School7 (6.8)6 (9.7)1 (2.4)
Undergraduate School71 (69)41 (66)30 (73)
Business_Area103
E-Commerce16 (16)11 (18)5 (12)
Education4 (3.9)2 (3.2)2 (4.9)
Energy1 (1.0)0 (0)1 (2.4)
Enterprise Services4 (3.9)2 (3.2)2 (4.9)
Fintech9 (8.7)6 (9.7)3 (7.3)
Logistics5 (4.9)1 (1.6)4 (9.8)
Manufacturing3 (2.9)2 (3.2)1 (2.4)
Media and Entertainment7 (6.8)4 (6.5)3 (7.3)
Medical and Healthcare1 (1.0)1 (1.6)0 (0)
Online to Offline Commerce2 (1.9)1 (1.6)1 (2.4)
Others45 (44)31 (50)14 (34)
Real Estate and Household1 (1.0)0 (0)1 (2.4)
Transportation/Automotive4 (3.9)0 (0)4 (9.8)
Travel1 (1.0)1 (1.6)0 (0)

1 Statistics presented: n (%)

ch05 - Log Scale Visualisation

공지

  • 본 포스트를 읽고 가급적 전체 내용 숙지를 위해 구매하는 것을 권유한다.

개요

  • 수치형 자료를 Y축으로 놓는 그래프는 언제나 힘들었다.
  • log Scale을 통해 값의 크기를 줄이기는 하지만, Y축을 어떻게 표현하는 것이 좋을지에 대한 고민은 늘 있어왔다.
  • 시각화 이론 중심의 포스팅이기에 코드 리뷰 및 해석은 생략한다.

문제점

  • log Scale을 적용했을 때와 그렇지 않을 때의 그래프를 비교해본다.

(1) 패키지 불러오기

  • 각각의 패키지를 불러온다.
  • 이 때, 데이터는 dviz.supp 저자인 Claus O. WilkeGithub Repo에서 가져와야 한다.
    • 경고: 이 부분이 초급자 분들에게는 쉽지가 않다.
  • 우선, 사전에 설치해야 할 패키지가 존재한다.
  • 현재 필자 개발환경 Spec은 다음과 같다.
> sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.6
  • 아래는 추가적으로 설치한 파일이다.
install.packages("devtools")

devtools::install_github("wilkelab/cowplot")
library(cowplot)

install.packages("colorspace")
library(colorspace)

devtools::install_github("clauswilke/colorblindr")
library(colorblindr)

devtools::install_github("clauswilke/dviz.supp")
library(dviz.supp)
  • 위 패키지들을 설치하는데 꽤 시간이 걸렸다.
library(lubridate) # 날짜 관련 패키지
library(forcats)   # 시계열 관련 패키지
library(tidyr)     # 데이터 핸들링 패키지
library(ggrepel)   # 시각화 관련 패키지
library(dviz.supp) # 저자의 개인 Repo 패키지: 교재 있는 데이터 활용 및 그래프를 구현하려면 필수적으로 설치 되어야 함.
library(kableExtra) # 데이터 출력 Table을 HTML로 변환하기 위한 패키지 

(2) 데이터 확인

  • 데이터는 US_Census 데이터를 기반으로 한다.
    • 자료 출처: 2010년도 미국 10개년 인구조사
  • 주의: 한글 폰트는 일단 생략했다.

소스코드 참조: https://github.com/clauswilke/dataviz/blob/master/coordinate_systems_axes.Rmd

ch 11 - Data Import & Label Encoding in R

Intro

  • 설문조사가 끝났으면 이제 정리를 해야 한다.
  • 일련의 과정은 보통 코딩이라 부른다.

(1) 주요 패키지

  • 이번 포스트부터 gt 패키지를 사용하려고 한다.
    • gt: ggplot2와 같이 Table를 문법으로 컨트롤 할 수 있도록 구현된 패키지이다.
    • kableExtra: HTML로 출력할 수 있도록 도와주는 패키지이다.

문제점

  • SmartPLS 프로그램을 쓴다 하더라도 기본적으로 모든 데이터의 entry는 수치형으로 일단 바뀌어 있어야 한다.
  • 우선 데이터를 불러와서 확인해보자.
library(tidyverse)
library(gt)
library(kableExtra)


# 데이터 불러오기
data <- read_csv("data/thesis_mater.csv")

data %>% 
  head() %>% 
  kable() %>% 
  kable_styling("striped") %>% 
  scroll_box(width = "100%")
EI_1EI_2EI_3EP_1EP_2EP_3ER_1ER_2ER_3SS_1SS_2SS_3SC_1SC_2SC_3SR_1SR_2SR_3F1F2F3NF1NF2NF3Firm_AgeFirm_SizeWE1WE2WE3genderfounder_employeeage_of_respondentEducation_LevelBusiness_Area
2343343241133332212233135 years aboveAbove 15 membersNo, I don't have experienceYesYesFemaleEmployee30-39Undergraduate SchoolOthers
552353444222222222222322Less than 2 yearsLess than 5 membersNo, I don't have experienceNoYesMaleEmployeeYounger than 30Undergraduate SchoolMedia and Entertainment
1221121212211221212111115 years aboveLess than 5 membersAs founder or employee, I have startup experiences more than 3 timesNoYesFemaleFounder of CompanyYounger than 30Undergraduate SchoolOthers
332121213213111233332322Less than 2 yearsLess than 5 membersNo, I don't have experienceYesYesMaleEmployeeYounger than 30Undergraduate SchoolOthers
5352544444545555554544553-4 yearsLess than 5 membersAs founder or employee, I have startup experiences more than 3 timesNoYesMaleFounder of Company30-39Undergraduate SchoolOthers
1331332314123312211231315 years above5-9 membersAs founder or employee, I have startup experience, one timeNoNoFemaleEmployeeYounger than 30Undergraduate SchoolOthers
  • 위 데이터에서 보면 알 수 있듯이, WE1 ~ Business_Area 까지의 데이터는 모두 문자로 되어 있다.
  • Python에서는 LabelEncoder라는 것이 있다.
  • R에서는 기본 문법인 factor만 있어도 가능하다.

Factor의 활용

  • 이제 본격적으로 코딩을 시작한다.
  • 데이터 전처리에서 쉬운 방법은 없다.

(1) 기본

  • 가상의 데이터를 만든 후 factor를 활용하자.
temp <- data.frame(x = c(1, 1, 2), 
                   gender = c("Female", "Male", "Male"))
temp
##   x gender
## 1 1 Female
## 2 1   Male
## 3 2   Male
  • 이제 gender를 변환하자.
temp$gender <- as.numeric(factor(temp$gender))
temp
##   x gender
## 1 1      1
## 2 1      2
## 3 2      2
  • factor로 변환한 뒤, as.numeric으로 형 변환을 하면 쉽게 바꿀수는 있다.
  • 위와 같이 형변환을 하면 1이 무엇을 의미하는지, 2는 무엇을 의미하는지 알 수 없게 된다. (즉, 정보의 손실이 올 수 있다.)

(2) 응용

  • 이제 factor를 조금 더 활용해 본다.
  • 같은 가상의 데이터를 사용한다.
temp <- data.frame(x = c(1, 1, 2), 
                   gender = c("Female", "Male", "Male"))

temp$gender <- as.numeric(factor(temp$gender), 
                          levels = c("Female", "Male"), 
                          labels = c(1, 2))

temp
##   x gender
## 1 1      1
## 2 1      2
## 3 2      2
  • 결과는 똑같다. 그러나, 각 label에 대한 해석이 보다 명확해지기 때문에 추후 분석결과보고서를 작성할 때 보다 쉽게 작성할 수 있다.

(3) 적용

  • 이제 내 데이터에 적용해보자.
  • 적용해야 할 변수는 모두 Firm_Age ~ Business_Area 까지이다.
  • 여기에서 하나의 Rule을 만들어야 한다.
    • 각 범주마다 하나씩 맞추는 노가다는 지양해야 한다.
    • 따라서, 범주의 값은 모두 알파벳순으로 정렬한다.
    • 이를 프로그래밍으로 해결한다.
temp <- data.frame(x = c(1, 1, 2), 
                   gender = c("Female", "Male", "Male"),
                   grade = c("A", "B", "C"))

temp
##   x gender grade
## 1 1 Female     A
## 2 1   Male     B
## 3 2   Male     C
  • 데이터가 하나 더 생겼다. 다음과 같은 함수를 만든다.
factor2numeric <- function(x) {
  # input 변수가 문자형인지 확인하여 다음 코드를 실행한다. 
  # 만약 문자가 아니면 `else` 코드로 넘어간다. 
  if(is.character(x) == TRUE) { 
      # levels 함수를 사용하면 알파벳으로 자동 정렬해준다.
      char_levels <- levels(factor(x)) 
      
      # 변환되기 전 factor의 `level`를 확인한다.
      print("----변환 시작 전----")
      print(char_levels)   
      
      # factor형으로 변환했다. 
      x <- factor(x, 
                  levels = char_levels, 
                  labels = c(1:length(char_levels))) # 이 코드는 labels 숫자로 정의한다. 
     
       # 변환되기 전 factor의 `level`를 확인한다.
      print(levels(x)) 
      print("----변환 종료----")
  } else {
    # 에러 메시지를 출력한다
    print("This is not character!!")
  } 
  return(x)
}

# 전체 데이터에서 character인 데이터를 사용자 정의 함수를 적용하였다. 
data2 <- data %>% 
  mutate_if(is.character, factor2numeric)
## [1] "----변환 시작 전----"
## [1] "3-4 years"         "5 years above"     "Less than 2 years"
## [1] "1" "2" "3"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "10-14 members"       "5-9 members"         "Above 15 members"   
## [4] "Less than 5 members"
## [1] "1" "2" "3" "4"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "As founder or employee,  I have startup experience, one time"        
## [2] "As founder or employee, I have startup experiences more than 3 times"
## [3] "As founder or employee, I have startup experiences, two times"       
## [4] "No, I don't have experience"                                         
## [1] "1" "2" "3" "4"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "No"  "Yes"
## [1] "1" "2"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "No"  "Yes"
## [1] "1" "2"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "Female" "Male"  
## [1] "1" "2"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "Employee"           "Founder of Company"
## [1] "1" "2"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "30-39"           "40-49"           "50 or above"     "Younger than 30"
## [1] "1" "2" "3" "4"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
## [1] "Graduate School"      "High School"          "Undergraduate School"
## [1] "1" "2" "3"
## [1] "----변환 종료----"
## [1] "----변환 시작 전----"
##  [1] "E-Commerce"                 "Education"                 
##  [3] "Energy"                     "Enterprise Services"       
##  [5] "Fintech"                    "Logistics"                 
##  [7] "Manufacturing"              "Media and Entertainment"   
##  [9] "Medical and Healthcare"     "Online to Offline Commerce"
## [11] "Others"                     "Real Estate and Household" 
## [13] "Transportation/Automotive"  "Travel"                    
##  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14"
## [1] "----변환 종료----"

(4) 중복치와 결측치 확인

  • 모든 것을 온라인으로 받다보니, 중복치와 결측치가 발생할 수 있다.
  • 따라서 해당 내용이 있는지 확인한다.
sum(duplicated(data2))
## [1] 5
  • 중복치가 5개 인것으로 확인이 된다.
  • 중복치를 제거하는 것은 간단하다.
data3 <- data2 %>% distinct()
  • 이번에는 결측치를 확인한다.
colSums(is.na(data3))
##              EI_1              EI_2              EI_3              EP_1 
##                 0                 0                 0                 0 
##              EP_2              EP_3              ER_1              ER_2 
##                 0                 0                 0                 0 
##              ER_3              SS_1              SS_2              SS_3 
##                 0                 0                 0                 0 
##              SC_1              SC_2              SC_3              SR_1 
##                 0                 0                 0                 0 
##              SR_2              SR_3                F1                F2 
##                 0                 0                 0                 0 
##                F3               NF1               NF2               NF3 
##                 0                 0                 0                 0 
##          Firm_Age         Firm_Size               WE1               WE2 
##                 0                 0                 0                 0 
##               WE3            gender  founder_employee age_of_respondent 
##                 0                 0                 0                 0 
##   Education_Level     Business_Area 
##                 0                 0
  • column마다 결측치를 확인한 결과 모두 0인 것을 확인할 수 있다.

(5) 결과 확인

  • 이제 변환된 결과를 확인한다.
# 결과값을 확인한다. 
data3 %>% 
  head() %>% 
  kable() %>% 
  kable_styling("striped") %>% 
  scroll_box(width = "100%")
EI_1EI_2EI_3EP_1EP_2EP_3ER_1ER_2ER_3SS_1SS_2SS_3SC_1SC_2SC_3SR_1SR_2SR_3F1F2F3NF1NF2NF3Firm_AgeFirm_SizeWE1WE2WE3genderfounder_employeeage_of_respondentEducation_LevelBusiness_Area
23433432411333322122331323422111311
5523534442222222222223223441221438
12211212122112212121111124212124311
33212121321311123333232234422214311
53525444445455555545445514212221311
13313323141233122112313122111114311

파일 내보내기

  • 이제 SmartPLS에서 사용할 수 있도록 csv 파일 형태로 내보낸다.
write_csv(data3, "~/Desktop/thesis_master2.csv")

소결론

  • 데이터 전처리는 중요하다. 그러나, 시간이 조금 걸린다.
  • 설문조사에서 특히 문제가 되는 부분은 문자열 데이터를 수치형 데이터로 변환해주는 문제가 있다.
    • 이를 프로그래밍으로 해결하면 보다 쉽게 접근할 수 있다.
  • 이제 본격적으로 분석을 해보자.

ch 10 - 연구모델 개발과 가설 설정

I. 연구모델 개발과 가설 설정

  • 교재에서는 스마트폰 프로젝트의 연구모델 데이터를 기반으로 작성하였지만, 이번 포스트 이후 부터는 필자의 학위논문 데이터를 기반으로 책 내용과 병행하려고 한다.

(1) 연구모델 개요

  • 학위논문 주제: The Mediating Effect of Entrepreneurial Performance on the Relationship between Entrepre-neurial Orientation and Social Capital: The cases from the Philippines
  • 주요요인은 기업가적지향성, 사회적자본이며, 종속변수는 기업의 성과로 구성되어 있다. png
  • 설문지 공개관련:
    • 설문지 Sample이 필요하신 분들은 2021년 2월 이후에 요청하기를 바란다. (졸업이후)
    • 교재는 스마트폰 프로젝트의 연구 모델이라는 주제로 Sample 설문지 문항에 대한 내용이 있다. (p 127)

(2) 연구모델 개발

  • 연구모델은 아래와 같다. png

데이콘 대회 참여 - 제주 신용카드 데이터 경진대회 피벗테이블 작성

강의 홍보

공지

  • 본 포스트는 필자의 수업을 듣는 사람들을 위해 작성하였습니다.

I. 구글 드라이브와 Colab과 연동

  • 구글 드라이브와 Colab과 연동하면 보다 쉽게 데이터에 접근할 수 있다.
  • 구글 인증만 하면 된다.
# Google Drive와 마운트
from google.colab import drive
ROOT = '/content/drive'
drive.mount(ROOT)

(1) 데이터 다운로드

(2) 구글 드라이브에 다운로드 받은 폴더를 올린다.

  • 이 때, 경로통일을 위해 Colab Notebooks/python_elice/dacon/data로 경로 지정을 한다.
# Project Folder 연결
from os.path import join  

MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/python_elice/dacon/data'
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH)
print(PROJECT_PATH)
/content/drive/My Drive/Colab Notebooks/python_elice/dacon/data
  • 아래 코드를 반드시 실행시켜야 해당 경로로 이동된다.
%cd "{PROJECT_PATH}"
/content/drive/My Drive/Colab Notebooks/python_elice/dacon/data
  • 실제 업로드된 데이터가 있는지 확인한다.
!ls
201901-202003.csv  submission.csv
  • 만약 에러가 발생이 되면 경로가 잘못 지정된 것이니, 폴더 경로를 재확인한다.
  • 경로에러가 발생할 시, 숙련자는 수정이 바로 가능하지만, 비숙련자는 가급적 [런타임 초기화]를 클릭한 후, 처음부터 다시 실행시키는 것을 추천한다.

(3) 데이터 불러오기

  • 지난주간 과제로 내주었던 판다스 데이터를 불러오도록 한다.
  • 시간이 다소 소요될 수 있다.
import pandas as pd
train = pd.read_csv("201901-202003.csv")
train.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 24697792 entries, 0 to 24697791
Data columns (total 12 columns):
 #   Column        Dtype 
---  ------        ----- 
 0   REG_YYMM      int64 
 1   CARD_SIDO_NM  object
 2   CARD_CCG_NM   object
 3   STD_CLSS_NM   object
 4   HOM_SIDO_NM   object
 5   HOM_CCG_NM    object
 6   AGE           object
 7   SEX_CTGO_CD   int64 
 8   FLC           int64 
 9   CSTMR_CNT     int64 
 10  AMT           int64 
 11  CNT           int64 
dtypes: int64(6), object(6)
memory usage: 2.2+ GB

(4) 데이터 샘플링

  • 전체 데이터를 시각화 등 사용하면 시각화 시, 다소 느리게 출력될 수 있으니, 연습 차원에서는 가급적 샘플링 기법을 적용해서 데이터를 재정한다.
  • 1000개의 데이터만 객체로 저장한다.
sample_train = train.sample(n=100000, random_state=1)
  • 원 데이터와 샘플 데이터의 행의 크기를 비교한다.
len(train)
24697792
len(sample_train)
100000
  • 물론, 위 샘플을 조금 늘려도 좋긴하지만, 가급적 시각화 코드가 모두 작성이 된 이후에 해보는 것을 추천한다.

II. 과제 - 피벗테이블

  • 판다스 패키지를 활용한다.
  • AMT는 매출 데이터이다.
  • 과제 1. 시도별 매출 데이터의 피벗테이블을 작성한다.
  • 과제 2. 업종별 매출 데이터의 피벗테이블을 작성한다.
  • 마지막 과제 3. 시도별-업종별 매출 데이터의 피벗테이블을 작성한다.
  • (옵션), 날짜별로 매출 데이터의 피벗테이블을 작성한다.

(공통) 판다스 피벗 테이블

  • 가장 좋은 교재는 메뉴얼이다.
  • 주요 파라미터는 다음과 같다.
    • data: DataFrame
    • values: Column to aggregate
    • index: column, array or list
    • aggfunc: function, list of functions, dict, default numpy.mean

(1) 시도별 매출 데이터

  • 시도별 매출 데이터의 피벗테이블을 작성한다.
pd.pivot_table(sample_train,                        # 데이터
               index='CARD_SIDO_NM',                # 기준변수
               values = 'AMT',                      # 타겟변수
               aggfunc="sum")                       # 산술식
  • 결과를 확인한다.

(2) 업종별 매출 데이터의 피벗테이블

  • 이번에는 업종별 피벗테이블을 작성해본다.
pd.pivot_table(sample_train,                        # 데이터
               index='STD_CLSS_NM',                 # 기준변수
               values = 'AMT',                      # 타겟변수
               aggfunc="sum")                       # 산술식
  • 결과를 확인한다.

(3) 시도별-업종별 매출 데이터의 피벗테이블

  • 이 때에는 피벗테이블에서 상위 5개의 데이터만 출력하도록 한다.
  • 표시될 행이 많아야 하기 때문에 아래와 같이 setting을 한다.
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
pivoted = pd.pivot_table(sample_train,                                   
                         index=['CARD_SIDO_NM', 'STD_CLSS_NM'],          
                         values = 'AMT',                               
                         aggfunc="sum")
pivoted\
.sort_values(['CARD_SIDO_NM', 'AMT'], ascending=[True, False])\
.groupby('CARD_SIDO_NM').head(5)\
.reset_index()\
.set_index(['CARD_SIDO_NM','STD_CLSS_NM'])

(4) 옵션-날짜별 매출 데이터의 피벗테이블

  • 이번에는 날짜별 매출 데이터의 피벗테이블 작성
pd.pivot_table(sample_train,                        # 데이터
               index='REG_YYMM',                    # 기준변수
               values = 'AMT',                      # 타겟변수
               aggfunc="sum")                       # 산술식

III. 과제 - 시각화

(1) 월별 막대그래프

  • 간단한 예제로 옵션-날짜별 매출 데이터의 피벗테이블을 작성한다.
pd.pivot_table(sample_train, index='REG_YYMM', values = 'AMT', aggfunc="sum").plot(kind='bar')                   

png