Programmings

EDA with Python - NumPy basic

강의 홍보

공지

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

I. 개요

  • 파이썬 처음 입문하는 사람들을 위해서 작성하였다. 탐색작 자료분석(EDA: Exploratory Data Analysis)을 위해 가장 기초적인 뼈대가 되는 NumPy에 대해서 학습하도록 합니다.

II. Array 만들기

  • 1차원, 2차원, 3차원의 Array를 만들고 학습니다.
  • 먼저 numpy 라이브러리를 불러옵니다.
# import numpy
import numpy as np
print(np.__version__)
1.18.4
  • 현재 구글 코랩에서 제공하는 numpy 버전은 1.18.4로 확인되고 있습니다.

(1) 1차원 Array 만들기

  • 1차원 Array를 만들어 봅시다.
my_1D_array = np.array([1,3,5,7])
print(my_1D_array)
type(my_1D_array)
[1 3 5 7]





numpy.ndarray

(2) 2차원 Array 만들기

  • 이번에는 2차원 Array를 만듭니다.
my_2D_array = np.array([[1, 2, 3, 4], [2, 4, 9, 16], [4, 8, 18, 32]])
print(my_2D_array)
type(my_2D_array)
[[ 1  2  3  4]
 [ 2  4  9 16]
 [ 4  8 18 32]]





numpy.ndarray

(3) 3차원 Array 만들기

  • 이번에는 3차원 Array를 만듭니다.
my_3D_array = np.array([[[ 1, 2 , 3 , 4],[ 5 , 6 , 7 ,8]], [[ 1, 2, 3, 4],[ 9, 10, 11, 12]]])
print(my_3D_array)
type(my_3D_array)
[[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 1  2  3  4]
  [ 9 10 11 12]]]





numpy.ndarray

III. Array Information

  • 실무에서는 데이터를 어떤 형태로 수집되는지 바로 판단하기가 어렵습니다.
  • 따라서, 수집받은 데이터를 다양한 방식으로 출력하여 정보를 알아가는 것이 좋습니다.
  • 대표적으로, ndim, shape, dtype을 통해서 확인합니다.
    • ndim은 배열의 차원수를 의미합니다.
    • shape는 tuple의 index개수와 각 index가 보유하는 elements의 개수를 반환합니다.
    • dtype는 각 게체의 데이터 타입을 표시합니다.

(1) 함수 작성

  • 저장된 1차원, 2차원, 3차원의 Array를 활용합니다.
  • 먼저, 빠르게 확인하기 위해 함수를 작성합니다.
def check_array_info(arr_obj): 
  if isinstance(arr_obj, (np.ndarray)):
    print("The current dimension is :", arr_obj.ndim)
    print("The current shape is :", arr_obj.shape)
    print("The current dtype is :", arr_obj.dtype)
    print("The current value is :\n", arr_obj)

(1) 1차원 Array의 정보 확인

  • 이제 정보를 확인합니다.
check_array_info(my_1D_array)
The current dimension is : 1
The current shape is : (4,)
The current dtype is : int64
The current value is :
 [1 3 5 7]
  • 1차원 shape의 경우에는 (4,)만 표시가 되었는데, 이는 요소의 개수만 출력됨을 의미합니다.

(2) 2차원 Array의 정보 확인

  • 2차원 배열의 정보를 확인합니다.
check_array_info(my_2D_array)
The current dimension is : 2
The current shape is : (3, 4)
The current dtype is : int64
The current value is :
 [[ 1  2  3  4]
 [ 2  4  9 16]
 [ 4  8 18 32]]

(3) 3차원 Array의 정보 확인

  • 3차원 배열의 정보를 확인합니다.
check_array_info(my_3D_array)
The current dimension is : 3
The current shape is : (2, 2, 4)
The current dtype is : int64
The current value is :
 [[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 1  2  3  4]
  [ 9 10 11 12]]]

IV. Creating An Array

  • 이제 다양한 방식으로 NumPy를 작성해보자.
# Array of ones
ones = np.ones((3,4))
check_array_info(ones)
The current dimension is : 2
The current shape is : (3, 4)
The current dtype is : float64
The current value is :
 [[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
# Array of zeros
zeros = np.zeros((1,2,3), dtype=np.int16)
check_array_info(zeros)
The current dimension is : 3
The current shape is : (1, 2, 3)
The current dtype is : int16
The current value is :
 [[[0 0 0]
  [0 0 0]]]
# Array with random values
np_random = np.random.random((2,2))
check_array_info(np_random)
The current dimension is : 2
The current shape is : (2, 2)
The current dtype is : float64
The current value is :
 [[0.47775118 0.60277821]
 [0.01818544 0.23499141]]
# Empty Array
empty_array = np.empty((3,2))
check_array_info(empty_array)
The current dimension is : 2
The current shape is : (3, 2)
The current dtype is : float64
The current value is :
 [[2.31101775e-316 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]]
# Full Array
full_array = np.full((2,2), 7)
check_array_info(full_array)
The current dimension is : 2
The current shape is : (2, 2)
The current dtype is : int64
The current value is :
 [[7 7]
 [7 7]]
# Array of evenly_spaced values
even_spaced_array = np.arange(10, 25, 5)
check_array_info(even_spaced_array)
The current dimension is : 1
The current shape is : (3,)
The current dtype is : int64
The current value is :
 [10 15 20]
even_spaced_array2 = np.linspace(0, 2, 9)
check_array_info(even_spaced_array2)
The current dimension is : 1
The current shape is : (9,)
The current dtype is : float64
The current value is :
 [0.   0.25 0.5  0.75 1.   1.25 1.5  1.75 2.  ]

V. Array의 메모리 체크

  • 머신러닝과 딥러닝을 수행하려면 반드시 메모리 체크가 필수다.
  • 이 부분과 관련된 함수를 작성하여 기존에 저장된 1차원, 2차원, 3차원 배열의 객체를 출력하여 본다.

(1) 함수 작성

  • check_memory_info라는 함수를 만들어보자.
def check_memory_info(arr_obj): 
  if isinstance(arr_obj, (np.ndarray)): 
    print("The current size is :", arr_obj.size)
    print("The current flags is :", arr_obj.flags)
    print("The current itemzise is :", arr_obj.itemsize)
    print("The current total consumed bytes is :", arr_obj.nbytes)
  • sizeelement의 전체 개수를 의미한다.
  • flagsmemory layout의 정보를 출력한다.
  • itemsize는 bytes 당 한 배열의 길이를 출력한다.
  • nbytes는 객체가 소비하는 전체 bytes를 출력한다.

(1) 1차원 Array의 메모리 정보 확인

check_memory_info(my_1D_array)
The current size is : 4
The current flags is :   C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The current itemzise is : 8
The current total consumed bytes is : 32

(1) 2차원 Array의 메모리 정보 확인

check_memory_info(my_2D_array)
The current size is : 12
The current flags is :   C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The current itemzise is : 8
The current total consumed bytes is : 96

(3) 1차원 Array의 메모리 정보 확인

check_memory_info(my_3D_array)
The current size is : 16
The current flags is :   C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The current itemzise is : 8
The current total consumed bytes is : 128

VI. 결론

  • NumPy는 파이썬에서 다루는 데이터과학에서 다루는 매우 중요한 토대가 되는 라이브러이이다.
  • 간단하게 NumPy를 활용한 배열에 대해 학습하였다.
  • 또한, Array를 다양하게 만들어보고, Array가 가지고 있는 다양한 정보를 확인할 수 있는 여러 함수에 대해 익히는 시간을 가졌다.
  • 그러나, 여기까지는 사실상 기초이고, 이제 배열의 연산에 대해 익히는 시간을 가져야 한다.
  • 다음 시간에 Broadcasting이라는 기법을 학습할 것이다.

Reference

Mukhiya, Suresh Kumar, and Usman Ahmed. “Hands-On Exploratory Data Analysis with Python.” Packt Publishing, Mar. 2020, www.packtpub.com/data/hands-on-exploratory-data-analysis-with-python.

EDA with Personal Email - Overview

강의 홍보

공지

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

I. Matplotlib & Seaborn

(1) 기본 개요

Matplotlib는 파이썬 표준 시각화 도구라고 불리워지며 파이썬 그래프의 기본 토대가 된다고 해도 무방하다. 객체지향 프로그래밍을 지원하므로 세세하게 꾸밀 수 있다.

Google Colab Intro

강의 홍보

I. 들어가며

  • 빅데이터 시대에 맞춰서 다양한 툴이 나오는 가운데, Google Colab은 가히 혁명적이라 할 수 있다.
  • 과거 높은 사양의 컴퓨터에서만 수행할 수 있었던 머신러닝과 딥러닝을 구글 코랩의 환경에서 무료로 배울 수 있는 기회를 구글이 제공하기 시작했다.
  • 간단하게 아래 소스코드를 실행하여 CPU와 GPU의 연산속도를 비교 해보자.

II. Data Transformation 예제

  • 이제 간단하게 데이터 가공의 예를 실습해보자.

(1) 딕셔너리에서 시리즈로 변환하기

  • 다음의 소스코드를 실행하여 딕셔너리에서 시리즈로 변환하는 것을 실습해보자.
# pandas 불러오기
import pandas as pd

# key:value 형태로 딕셔너리를 만들고 temp_dic으로 저장
temp_dic = {'evan': 30, 'chloe': 27}
print(temp_dic)
{'evan': 30, 'chloe': 27}
# 시리즈로 변환하고 출력값 확인
data = pd.Series(temp_dic)
print(data)
evan     30
chloe    27
dtype: int64
  • 위 출력값에서 인덱스는 evanchloe이다.

(2) 리스트에서 시리즈로 변환하기

  • 이번에는 리스트에서 시리즈로 변환한다. 이 때 출력값의 인덱스가 어떻게 나타나는지 확인해본다.
import pandas as pd
temp_list = ['2020-05-29', 1.11, '가나다', 'ABC', 100, True]
data = pd.Series(temp_list)
print(data)
0    2020-05-29
1          1.11
2           가나다
3           ABC
4           100
5          True
dtype: object
  • 이번에는 인덱스의 값이 자동으로 0부터 시작하는 것을 알 수 있다.

III. Data Visualisation 예제

  • 이번에는 간단하게 시각화를 작성해본다.
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
             bottom=menMeans, yerr=womenStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

png

Data Transformation - Merging Data

강의 홍보

공지

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

  • 데이터는 코로나 데이터를 활용했다.

I. Data Transform Overview

  • 데이터 변환은 데이터를 하나의 형식이나 구조에서 다른 형식이나 구조로 변환하는 데 사용되는 기법이다.

Ch21 Conditional Expressions

I. 구글 클라우드 설정

본격적인 빅쿼리 실습에 앞서서, Python과 연동하는 예제를 준비하였다. 빅쿼리 시작에 앞서서 선행적으로 클라우드 사용을 해야 한다.

  1. 만약 GCP 프로젝트가 없다면, 계정을 연동한다. Go to Cloud Resource Manager
  2. 그리고, 비용결제를 위한 카드를 등록한다. Enable billing
  3. 마지막으로 BigQuery API를 사용해야 하기 때문에 빅쿼리 API 사용허가를 내준다.Enable BigQuery

위 API를 이용하지 않으면 Python 또는 R과 연동해서 사용할 수는 없다. 자주 쓰는것이 아니라면 비용은 거의 발생하지 않으니 염려하지 않아도 된다. 비용관리에 대한 자세한 내용은 BigQuery 권장사항: 비용 관리에서 확인하기를 바란다.

Ch20 Logical Operations

I. 구글 클라우드 설정

본격적인 빅쿼리 실습에 앞서서, Python과 연동하는 예제를 준비하였다. 빅쿼리 시작에 앞서서 선행적으로 클라우드 사용을 해야 한다.

  1. 만약 GCP 프로젝트가 없다면, 계정을 연동한다. Go to Cloud Resource Manager
  2. 그리고, 비용결제를 위한 카드를 등록한다. Enable billing
  3. 마지막으로 BigQuery API를 사용해야 하기 때문에 빅쿼리 API 사용허가를 내준다.Enable BigQuery

위 API를 이용하지 않으면 Python 또는 R과 연동해서 사용할 수는 없다. 자주 쓰는것이 아니라면 비용은 거의 발생하지 않으니 염려하지 않아도 된다. 비용관리에 대한 자세한 내용은 BigQuery 권장사항: 비용 관리에서 확인하기를 바란다.

Ch19 Comparisons Decimal Calculations

I. 구글 클라우드 설정

본격적인 빅쿼리 실습에 앞서서, Python과 연동하는 예제를 준비하였다. 빅쿼리 시작에 앞서서 선행적으로 클라우드 사용을 해야 한다.

  1. 만약 GCP 프로젝트가 없다면, 계정을 연동한다. Go to Cloud Resource Manager
  2. 그리고, 비용결제를 위한 카드를 등록한다. Enable billing
  3. 마지막으로 BigQuery API를 사용해야 하기 때문에 빅쿼리 API 사용허가를 내준다.Enable BigQuery

위 API를 이용하지 않으면 Python 또는 R과 연동해서 사용할 수는 없다. 자주 쓰는것이 아니라면 비용은 거의 발생하지 않으니 염려하지 않아도 된다. 비용관리에 대한 자세한 내용은 BigQuery 권장사항: 비용 관리에서 확인하기를 바란다.

matplotlib - 09 lollipop

강의 홍보

공지

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

I. Matplotlib & Seaborn

(1) 기본 개요

Matplotlib는 파이썬 표준 시각화 도구라고 불리워지며 파이썬 그래프의 기본 토대가 된다고 해도 무방하다. 객체지향 프로그래밍을 지원하므로 세세하게 꾸밀 수 있다.

Ch18 Mathematical Functions

I. 구글 클라우드 설정

본격적인 빅쿼리 실습에 앞서서, Python과 연동하는 예제를 준비하였다. 빅쿼리 시작에 앞서서 선행적으로 클라우드 사용을 해야 한다.

  1. 만약 GCP 프로젝트가 없다면, 계정을 연동한다. Go to Cloud Resource Manager
  2. 그리고, 비용결제를 위한 카드를 등록한다. Enable billing
  3. 마지막으로 BigQuery API를 사용해야 하기 때문에 빅쿼리 API 사용허가를 내준다.Enable BigQuery

위 API를 이용하지 않으면 Python 또는 R과 연동해서 사용할 수는 없다. 자주 쓰는것이 아니라면 비용은 거의 발생하지 않으니 염려하지 않아도 된다. 비용관리에 대한 자세한 내용은 BigQuery 권장사항: 비용 관리에서 확인하기를 바란다.

Kakao Arena 3 EDA on Google Colab

공지

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

이전 포스트인 Colab + Drive + Github Workflow 실전 테스트용으로 생각하면서 읽어주기를 바란다.

I. 개요

  • 프로젝트 폴더 내에서 간단하게 EDA를 실습하는 시간을 갖도록 한다.
  • 관련 패키지는 우선 다른 곳에서 설치 되었다는 것을 가정한다.
  • 본 포스트의 핵심은 환경설정이 Google Colab + Drive내에서 작업하는 것이다.

II. 패키지 불러오기

  • 다음과 같은 순서로 실행한다.
  • 첫째, 나눔고딕 한글 폰트를 설치한다.
  • 둘째, 내부 패키지를 먼저 불러온다.
  • 셋째, 런타임을 다시 실행한다.
  • 넷째, Drive 마운트를 진행한다.
  • 다섯째, 외부 패키지를 불러온다.

(1) 나눔고딕 폰트 불러오기

  • 다음과 같은 방식으로 폰트를 불러온다.
%config InlineBackend.figure_format = 'retina'
!sudo apt-get -qq -y install fonts-nanum
The following NEW packages will be installed:
  fonts-nanum
0 upgraded, 1 newly installed, 0 to remove and 31 not upgraded.
Need to get 9,604 kB of archives.
After this operation, 29.5 MB of additional disk space will be used.
Selecting previously unselected package fonts-nanum.
(Reading database ... 144433 files and directories currently installed.)
Preparing to unpack .../fonts-nanum_20170925-1_all.deb ...
Unpacking fonts-nanum (20170925-1) ...
Setting up fonts-nanum (20170925-1) ...
Processing triggers for fontconfig (2.12.6-0ubuntu2) ...

(2) 내부에 기 설치된 패키지 불러오기

  • 관련 패키지를 불러온다.
from datetime import timedelta, datetime
import glob
from itertools import chain
import json
import os
import re

import numpy as np
import pandas as pd

from wordcloud import WordCloud
import nltk
from nltk.corpus import stopwords
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer

from pandas.plotting import register_matplotlib_converters
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fontpath = '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf'
font = fm.FontProperties(fname=fontpath, size=9)
plt.rc('font', family='NanumBarunGothic') 
plt.rcParams["figure.figsize"] = (20, 10)
register_matplotlib_converters()
mpl.font_manager._rebuild()
mpl.pyplot.rc('font', family='NanumGothic')
fm._rebuild()

(3) 외부 패키지인 konlpy 불러오기

  • 다음 코드를 실행하기 전 반드시 [런타임]-[런타임 다시 시작]을 누르자.
# 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).
import os, sys
my_path = '/content/notebooks'
os.symlink('/content/drive/My Drive/Colab Notebooks/competition/pkgs_folder', my_path)
sys.path.insert(0,my_path)
from konlpy.tag import Twitter
  • 위 코드에서 만약 에러가 나면 처음부터 다시 해야 하니, 유의 바란다.
pd.options.mode.chained_assignment = None

III. 데이터 불러오기

  • 이제 깃허브 프로젝트인 competition으로 파일 경로를 변경 한 뒤, 데이터를 불러오도록 한다.
# import join used to join ROOT path and MY_GOOGLE_DRIVE_PATH
from os.path import join  

# path to your project on Google Drive
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/competition'

PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH)
%cd "{PROJECT_PATH}"
/content/drive/My Drive/Colab Notebooks/competition
!git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   .gitignore
	deleted:    kakao_arena_3/source/temp.ipynb
	deleted:    kakao_arena_3/source/temp2.ipynb

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	kakao_arena_3/source/kakao_arena_3_eda.ipynb

no changes added to commit (use "git add" and/or "git commit -a")
!ls
kakao_arena_3  pkgs_folder  README.md
# genre_gn_all.json
genre_gn_all = pd.read_json('kakao_arena_3/data/genre_gn_all.json', typ = 'series')
# 장르코드 : gnr_code, 장르명 : gnr_name
genre_gn_all = pd.DataFrame(genre_gn_all, columns = ['gnr_name']).reset_index().rename(columns = {'index' : 'gnr_code'})
print(genre_gn_all.head())
  gnr_code gnr_name
0   GN0100      발라드
1   GN0101   세부장르전체
2   GN0102      '80
3   GN0103      '90
4   GN0104      '00
# 장르코드 뒷자리 두 자리가 00이 아닌 코드를 필터링
dtl_gnr_code = genre_gn_all[genre_gn_all['gnr_code'].str[-2:] != '00']
dtl_gnr_code.rename(columns = {'gnr_code' : 'dtl_gnr_code', 'gnr_name' : 'dtl_gnr_name'}, inplace = True)
print(dtl_gnr_code.head())
  dtl_gnr_code dtl_gnr_name
1       GN0101       세부장르전체
2       GN0102          '80
3       GN0103          '90
4       GN0104          '00
5       GN0105         '10-

IV. 데이터 시각화 구현

  • 한글 시각화를 구현한다.
# Plotting a bar graph of the number of stores in each city, for the first ten cities listed
# in the column 'City'
dtl_gnr_name_count  = dtl_gnr_code['dtl_gnr_name'].value_counts()
dtl_gnr_name_count = dtl_gnr_name_count[:10,]
plt.figure(figsize=(10,5))
sns.barplot(dtl_gnr_name_count.index, dtl_gnr_name_count.values, alpha=0.8)
plt.title('한글 시각화 테스트')
plt.ylabel('Number of Occurrences', fontsize=12)
plt.xlabel('세부장르', fontsize=12)
plt.show()

png