강의 홍보
개요
- 파이썬을 활용한 공간 시각화에 대해 기술하도록 한다.
- 각 패키지의 쓰임새와 용도를 확인하도록 한다.
- 예제를 통해 확인한 뒤, 국내 데이터를 적용해보도록 한다.
- 한글 폰트상의 문제점 외에 다른 문제점은 없는지 확인해본다.
- 우선 참고한 자료는 아래와 같다.
기본 환경설정
- 구글 코랩의 환경설정을 살펴보자.
- 파이썬 버전 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'
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를 사용할 수 있다.
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
/content/drive/My Drive/Colab Notebooks/inflearn/Python/Kaggle_Edu/02_kaggle_eda/03_map/data
[0m[01;34m'상가(상권)정보_201912.'[0m/ customer_rate_02.xlsx pivot_table_04.xlsx
census.csv merge_03.xlsx
city.geojson missing_values_01.xlsx
공간시각화 파일에 대한 기본 개념
geometry는 Point, 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를 지원함.
geojson을 geopandas로 읽게 될 경우, properties는 GeoDataFrame이 된다.
(1) Geopandas의 개념
geopandas는 크게 2가지의 데이터 의존성이 있다.
Vector: points, lines, and polygons.
RASTER: 일종의 격자(grid)로 생각하면 된다. (예: Topographical Map)
- 크게 2개의 Library가 필요하다.
Fiona: Open GIS Simple Features와 파이썬과 geopandas를 연결하는 일종의 다리 역할을 수행한다.
GDAL은 rater 데이터를 변환하는 것
OGR은 vector 데이터를 변환하는 것
