Geospatial Analysis Using Python - Basic

강의 홍보

개요

  • 파이썬을 활용한 공간 시각화에 대해 기술하도록 한다.
  • 각 패키지의 쓰임새와 용도를 확인하도록 한다.
    • 예제를 통해 확인한 뒤, 국내 데이터를 적용해보도록 한다.
    • 한글 폰트상의 문제점 외에 다른 문제점은 없는지 확인해본다.
  • 우선 참고한 자료는 아래와 같다.

기본 환경설정

  • 구글 코랩의 환경설정을 살펴보자.
    • 파이썬 버전 3.6.9을 현재 사용중이다. (2020년 8월 기준)
import sys
sys.version_info
sys.version_info(major=3, minor=6, micro=9, releaselevel='final', serial=0)
  • 이번에는 OS 플랫폼을 확인한다.
    • 현재 Ubuntu 18.04 버전을 사용중이다.
import platform
platform.platform()
'Linux-4.19.112+-x86_64-with-Ubuntu-18.04-bionic'
  • 이번에는 CPU 관련된 정보를 확인해본다.
    • CPU 제논 2.3GHz
!cat /proc/cpuinfo
processor	: 0
vendor_id	: GenuineIntel
cpu family	: 6
model		: 79
model name	: Intel(R) Xeon(R) CPU @ 2.20GHz
stepping	: 0
microcode	: 0x1
cpu MHz		: 2200.000
cache size	: 56320 KB
physical id	: 0
siblings	: 2
core id		: 0
cpu cores	: 1
apicid		: 0
initial apicid	: 0
fpu		: yes
fpu_exception	: yes
cpuid level	: 13
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities
bugs		: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa
bogomips	: 4400.00
clflush size	: 64
cache_alignment	: 64
address sizes	: 46 bits physical, 48 bits virtual
power management:

processor	: 1
vendor_id	: GenuineIntel
cpu family	: 6
model		: 79
model name	: Intel(R) Xeon(R) CPU @ 2.20GHz
stepping	: 0
microcode	: 0x1
cpu MHz		: 2200.000
cache size	: 56320 KB
physical id	: 0
siblings	: 2
core id		: 0
cpu cores	: 1
apicid		: 1
initial apicid	: 1
fpu		: yes
fpu_exception	: yes
cpuid level	: 13
wp		: yes
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities
bugs		: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa
bogomips	: 4400.00
clflush size	: 64
cache_alignment	: 64
address sizes	: 46 bits physical, 48 bits virtual
power management:
  • 메모리 정보를 확인해본다.
    • 무료 버전의 경우 약 13GB를 사용할 수 있다.
!cat /proc/meminfo
MemTotal:       13333552 kB
MemFree:        10691516 kB
MemAvailable:   12499620 kB
Buffers:           76712 kB
Cached:          1886808 kB
SwapCached:            0 kB
Active:           668976 kB
Inactive:        1678968 kB
Active(anon):     360932 kB
Inactive(anon):      360 kB
Active(file):     308044 kB
Inactive(file):  1678608 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:              1992 kB
Writeback:             0 kB
AnonPages:        384360 kB
Mapped:           179824 kB
Shmem:               972 kB
Slab:             164416 kB
SReclaimable:     124572 kB
SUnreclaim:        39844 kB
KernelStack:        3872 kB
PageTables:         4924 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     6666776 kB
Committed_AS:    2491516 kB
VmallocTotal:   34359738367 kB
VmallocUsed:           0 kB
VmallocChunk:          0 kB
Percpu:              952 kB
AnonHugePages:         0 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:      107708 kB
DirectMap2M:     5134336 kB
DirectMap1G:    10485760 kB
  • GPU 사용이 가능하면 /device:GPU:0이라고 확인이 될 것이다.
    • 만약 런타임 유형 변경에서 None으로 설정 하면, ' '만 출력이 된다.
import tensorflow as tf
tf.test.gpu_device_name()
'/device:GPU:0'

한글 폰트 설정

  • 시각화 출력 시, 한글 폰트는 별도로 설치 및 설정해줘야 한다.
    • 폰트 설치, 폰트 불러오기, 그리고 런타임 재실행 순으로 해준다.

(1) 폰트 설치

  • 우분투 명령어 apt-get을 통해 나눔 폰트를 설치한다.
!apt-get update -qq
!apt-get install fonts-nanum* -qq
Selecting previously unselected package fonts-nanum.
(Reading database ... 144540 files and directories currently installed.)
Preparing to unpack .../fonts-nanum_20170925-1_all.deb ...
Unpacking fonts-nanum (20170925-1) ...
Selecting previously unselected package fonts-nanum-eco.
Preparing to unpack .../fonts-nanum-eco_1.000-6_all.deb ...
Unpacking fonts-nanum-eco (1.000-6) ...
Selecting previously unselected package fonts-nanum-extra.
Preparing to unpack .../fonts-nanum-extra_20170925-1_all.deb ...
Unpacking fonts-nanum-extra (20170925-1) ...
Selecting previously unselected package fonts-nanum-coding.
Preparing to unpack .../fonts-nanum-coding_2.5-1_all.deb ...
Unpacking fonts-nanum-coding (2.5-1) ...
Setting up fonts-nanum-extra (20170925-1) ...
Setting up fonts-nanum (20170925-1) ...
Setting up fonts-nanum-coding (2.5-1) ...
Setting up fonts-nanum-eco (1.000-6) ...
Processing triggers for fontconfig (2.12.6-0ubuntu2) ...

(2) 폰트 설정

# 설치된 나눔 폰트 출력
# 만약, 설치했는데도, 리스트가 [] 로 출력된다면 런타임을 다시 시작해주세요

import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

sys_font=fm.findSystemFonts()
nanum_font = [f for f in sys_font if 'Nanum' in f]
print(f"nanum_font number: {len(nanum_font)}")
nanum_font

!python --version
def current_font():
  print(f"현재 설정된 폰트 글꼴: {plt.rcParams['font.family']}, 현재 설정된 폰트 사이즈: {plt.rcParams['font.size']}")  # 파이썬 3.6 이상 사용가능
        
current_font()
nanum_font number: 31
Python 3.6.9
현재 설정된 폰트 글꼴: ['sans-serif'], 현재 설정된 폰트 사이즈: 10.0
  • 현재 설정된 폰트 글꼴은 ['sans-serif']인 것으로 확인된다.
    • 이제 sans-serif를 나눔고딕으로 변경한다.
path = '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf'  
font_name = fm.FontProperties(fname=path, size=14).get_name()
plt.rc('font', family=font_name)

current_font()
현재 설정된 폰트 글꼴: ['NanumBarunGothic'], 현재 설정된 폰트 사이즈: 10.0

(3) 전체 노트북에 반영

  • 이렇게 설정이 된 후에는 fm._rebuild()를 통해 재 설정 한다.
  • 현재 나올 모든 환경 설정을 아래와 같이 설정한다.
fm._rebuild()

# 노트북 전체 폰트 및 차트 크기 설정
plt.rcParams['font.family'] = 'NanumBarunGothic'
plt.rcParams["font.size"] = 14
plt.rcParams["figure.figsize"] = (12,6)

# matplotlib에서 마이너스 부호가 깨질 때
import matplotlib as mpl
mpl.rcParams['axes.unicode_minus'] = False

print('설정 되어있는 폰트 사이즈 : {}'.format(plt.rcParams['font.size']))
print('설정 되어있는 폰트 글꼴 : {}'.format(plt.rcParams['font.family']))
print('설정 되어있는 차트 크기 : {}'.format(plt.rcParams["figure.figsize"]))
설정 되어있는 폰트 사이즈 : 14.0
설정 되어있는 폰트 글꼴 : ['NanumBarunGothic']
설정 되어있는 차트 크기 : [12.0, 6.0]

(4) 공간시각화 관련 패키지 설정 방법

  • rtree 패키지 설치가 문제가 될 수 있기 때문에 다음과 같이 설치를 진행한다.
!apt install libspatialindex-dev
!pip install rtree
!pip install geopandas
Reading package lists... Done
Building dependency tree       
Reading state information... Done
libspatialindex-dev is already the newest version (1.8.5-5).
The following package was automatically installed and is no longer required:
  libnvidia-common-440
Use 'apt autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 60 not upgraded.
Requirement already satisfied: rtree in /usr/local/lib/python3.6/dist-packages (0.9.4)
Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from rtree) (49.2.0)
Requirement already satisfied: geopandas in /usr/local/lib/python3.6/dist-packages (0.8.1)
Requirement already satisfied: pyproj>=2.2.0 in /usr/local/lib/python3.6/dist-packages (from geopandas) (2.6.1.post1)
Requirement already satisfied: fiona in /usr/local/lib/python3.6/dist-packages (from geopandas) (1.8.13.post1)
Requirement already satisfied: shapely in /usr/local/lib/python3.6/dist-packages (from geopandas) (1.7.0)
Requirement already satisfied: pandas>=0.23.0 in /usr/local/lib/python3.6/dist-packages (from geopandas) (1.0.5)
Requirement already satisfied: cligj>=0.5 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (0.5.0)
Requirement already satisfied: attrs>=17 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (19.3.0)
Requirement already satisfied: six>=1.7 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (1.15.0)
Requirement already satisfied: munch in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (2.5.0)
Requirement already satisfied: click<8,>=4.0 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (7.1.2)
Requirement already satisfied: click-plugins>=1.0 in /usr/local/lib/python3.6/dist-packages (from fiona->geopandas) (1.1.1)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.0->geopandas) (2.8.1)
Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.0->geopandas) (1.18.5)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.23.0->geopandas) (2018.9)

구글 드라이브와 연동

  • 우선 구글 드라이브와 계정 연동을 진행한다.
# Mount Google Drive
from google.colab import drive # import drive from google colab

ROOT = "/content/drive"     # default location for the drive
print(ROOT)                 # print content of ROOT (Optional)
drive.mount(ROOT)           # we mount the google drive at /content/drive
/content/drive
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
  • 데이터가 있는 경로로 이동한다.
from os.path import join  

MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/inflearn/Python/Kaggle_Edu/02_kaggle_eda/03_map/data' # 프로젝트 경로
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH) # 프로젝트 경로
print(PROJECT_PATH)
/content/drive/My Drive/Colab Notebooks/inflearn/Python/Kaggle_Edu/02_kaggle_eda/03_map/data
%cd "{PROJECT_PATH}"
/content/drive/My Drive/Colab Notebooks/inflearn/Python/Kaggle_Edu/02_kaggle_eda/03_map/data
%ls
'상가(상권)정보_201912.'/   customer_rate_02.xlsx    pivot_table_04.xlsx
 census.csv                 merge_03.xlsx
 city.geojson               missing_values_01.xlsx

공간시각화 파일에 대한 기본 개념

  • geometryPoint, Line, Polygon을 저장할 수 있다.
  • 파일의 구성도는 다음과 같다.
$ ls map_files/

map.dbf
map.shp
map.shx
  • shp는 전체 geometry를 의미한다.
  • dbf는 각 geometry에 대한 속성(atrributes)값을 가지고 있다.
  • shx는 각 속성 값을 shp안에 있는 geometry를 연결한다.

Geopandas 의존성

  • GeoJSON은 MultiPoint, MultiLineString, MultiPolygon을 포함한 MultiGeometry를 지원함.
  • geojsongeopandas로 읽게 될 경우, propertiesGeoDataFrame이 된다.

(1) Geopandas의 개념

  • geopandas는 크게 2가지의 데이터 의존성이 있다.
    • Vector: points, lines, and polygons.
    • RASTER: 일종의 격자(grid)로 생각하면 된다. (예: Topographical Map)
  • 크게 2개의 Library가 필요하다.
    • Fiona: Open GIS Simple Features와 파이썬과 geopandas를 연결하는 일종의 다리 역할을 수행한다.
    • GDALrater 데이터를 변환하는 것
    • OGR은 vector 데이터를 변환하는 것

Seaborn Visualisation Tutorial - Basic

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

시각화 기본적 원리

  1. 비교, 대조, 차이를 드러내라.
  2. 인과관계와 상관관계를 보여라.
  3. 한 도표에 여러 변수를 보여라.
  4. 텍스트, 숫자, 이미지, 그래프 같은 데이터들을 한 곳에 통합하라.
  5. 사용된 데이터의 출처를 그래프 안이나 각주로 밝혀라.
  6. 의미 있는 내용을 담아라.

데이터 변수 종류에 따른 시각화의 종류

  • 시각화는 그냥 그리는 것이 아니다. 변수의 종류에 따른 기법이 존재한다.
    • 다만, Python & R의 방법론의 차이가 있을 뿐이다.
  • 원리를 알면, 다음은 검색 및 연습을 통해 다듬어진다.

입문자를 위한 머신러닝 튜토리얼 - 교차검증

개요

  • 교차검증의 의미를 이해한다.
  • 교차검증을 위한 간단한 실습을 진행한다.

교차검증이란

  • 교차검증은 기본적으로 과적합을 예방하기 위한 방법론 중 하나이다.
  • 교차검증을 쉽게 이해하는 방법은 수능시험을 보기 위해 수능과 비슷한 유형의 모의고사를 보는 것과 같다.

(1) K폴드 교차검증 개요

  • 데이터의 수가 적을 때 사용한다.
    • 검증 데이터의 수도 적기 때문에 검증 성능의 신뢰도가 떨어진다.
    • 이 때, K-폴드 방법을 사용한다.
  • 그림을 보며 이해하자.

  • 데이터의 편향을 방지하기 위한 것
    • 데이터를 K개로 나누어 K-1개를 분할하고 나머지는 평가에 사용
    • 모델의 검증 점수는 K개의 검증 점수 평균이 된다.

(2) 소스코드를 통한 검증

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from scipy import stats
from sklearn.datasets import load_boston
%matplotlib inline

# boston 데이타셋 로드
boston = load_boston()

# boston 데이타셋 DataFrame 변환 
bostonDF = pd.DataFrame(boston.data , columns = boston.feature_names)

# boston dataset의 target array는 주택 가격임. 이를 PRICE 컬럼으로 DataFrame에 추가함. 
bostonDF['PRICE'] = boston.target
print('Boston 데이타셋 크기 :',bostonDF.shape)
bostonDF.head()
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
  import pandas.util.testing as tm


Boston 데이타셋 크기 : (506, 14)
  • 데이터 시각화를 진행한다.
# 2개의 행과 4개의 열을 가진 subplots를 이용. axs는 4x2개의 ax를 가짐.
fig, axs = plt.subplots(figsize=(16,8) , ncols=4 , nrows=2)
lm_features = ['RM','ZN','INDUS','NOX','AGE','PTRATIO','LSTAT','RAD']
for i , feature in enumerate(lm_features):
    row = int(i/4)
    col = i%4
    
    # 시본의 regplot을 이용해 산점도와 선형 회귀 직선을 함께 표현
    sns.regplot(x=feature , y='PRICE', data=bostonDF , ax=axs[row][col])

png

입문자를 위한 머신러닝 분류 튜토리얼 - Decision Tree

개요

  • 사이킷런(scikit-learn)은 파이썬 머신러닝 라이브러리이다.
  • 파이썬에서 나오는 최신 알고리즘들도 이제는 사이킷런에 통합하는 형태로 취하고 있다.
  • 구글 코랩은 기본적으로 사이킷런까지 설치가 완료되기에 별도의 설치가 필요없는 장점이 있다.
  • Note: 본 포스트는 머신러닝 자체를 처음 접하는 분들을 위한 것이기 때문에, 어느정도 경험이 있으신 분들은 필자의 다른 포스트를 읽어주시기를 바랍니다.

패키지 불러오기

  • 패키지는 시간에 지남에 따라 계속 업그레이드가 되기 때문에 꼭 버전 체크를 하는 것을 권장한다.
    • 필자가 글을 남겼을 때는 2020년 8월 16일에 작성했음을 기억하자.
import sklearn
print(sklearn.__version__)
0.22.2.post1

머신러닝 워크플로우

  • 가장 간단한 데이터인 iris 데이터의 종 분류를 진행하도록 한다.
  • 사실, 이 예제는 매우 간단하기 때문에, 전체적인 프로세스를 익히는 관점에서 확인하기를 바란다.

(1) 지도학습의 정의

  • 지도학습(Supervised Learning)의 가장 큰 특징 중의 하나는 위와 같이 분류 결정값이 사전에 정의가 되어야 한다.
    • 만약, 사전에 분류가 된 것이 없다면 어떻게 할 수 있을까? 당연한 말이지만, 머신러닝 수행하기 전 데이터 수집이 필수가 된다.
  • 위 꽃을 분류하는 것 같이, 명확한 정답이 주어진 데이터를 먼저 학습 한 뒤, 미지의 정답을 예측하는 것을 지도학습이라 부른다.

입문자를 위한 머신러닝 분류 튜토리얼 - IRIS 분류

개요

  • 사이킷런(scikit-learn)은 파이썬 머신러닝 라이브러리이다.
  • 파이썬에서 나오는 최신 알고리즘들도 이제는 사이킷런에 통합하는 형태로 취하고 있다.
  • 구글 코랩은 기본적으로 사이킷런까지 설치가 완료되기에 별도의 설치가 필요없는 장점이 있다.
  • Note: 본 포스트는 머신러닝 자체를 처음 접하는 분들을 위한 것이기 때문에, 어느정도 경험이 있으신 분들은 필자의 다른 포스트를 읽어주시기를 바랍니다.

패키지 불러오기

  • 패키지는 시간에 지남에 따라 계속 업그레이드가 되기 때문에 꼭 버전 체크를 하는 것을 권장한다.
    • 필자가 글을 남겼을 때는 2020년 8월 16일에 작성했음을 기억하자.
import sklearn
print(sklearn.__version__)
0.22.2.post1

머신러닝 워크플로우

  • 가장 간단한 데이터인 iris 데이터의 종 분류를 진행하도록 한다.
  • 사실, 이 예제는 매우 간단하기 때문에, 전체적인 프로세스를 익히는 관점에서 확인하기를 바란다.

(1) 지도학습의 정의

  • 지도학습(Supervised Learning)의 가장 큰 특징 중의 하나는 위와 같이 분류 결정값이 사전에 정의가 되어야 한다.
    • 만약, 사전에 분류가 된 것이 없다면 어떻게 할 수 있을까? 당연한 말이지만, 머신러닝 수행하기 전 데이터 수집이 필수가 된다.
  • 위 꽃을 분류하는 것 같이, 명확한 정답이 주어진 데이터를 먼저 학습 한 뒤, 미지의 정답을 예측하는 것을 지도학습이라 부른다.

Data Science Resources

개요

  • 제 개인 참조하려고 만든 게시글입니다.
  • 언제나 좋은 글 및 싸이트, 패키지를 만들어 배포하는 모든 Data Scientist, Analyst 분들 존경합니다.

(1) Tools

I. 머신러닝/딥러닝 관련 자료

(1) 머신러닝

(2) 딥러닝 논문

(3) 추천시스템

(4) 강의자료

(5) 딥러닝 논문 로드맵

II. 통계

(1) 구조방정식

  • SmartPLS: 기본 튜토리얼 및 원서 제공

III. 문서 자동화 & autoEDA

(1) R 기반

(2) Python 기반

IV. 데이터과학을 위한 Tools

V. GUI (Graphical User Interface)

(1) Python

  • Tkinter
    • [Sample Tutorial](Cats vs Dogs Classification (with 98.7% Accuracy) using CNN Keras – Deep Learning Project for Beginner)

VI. 시각화

(1) 공간시각화

(2) 파이썬 시각화

(3) 파이썬 대시보드

V. MLOps

기타

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"))