Verifying Outlier Values

이상값의 정의

  • 다소 주관적이며(Somewhat Subjective), 특정 분포의 중심경향성, 퍼진 정도와 형태에 따라 밀접한 관련이 있다.
    • 평균에서 표준편차보다 몇 배 더 떨어져 있다거나, 즉, 정규분포를 이루고 있지 않을 때
    • 왜도 또는 첨도가 발생할 때
  • 균등분포(Uniform Distribution)는, 발생할 확률이 모두 같다.
    • 만약, 확진자수가 최소 1부터 최대 10,000,000까지 균등하게 분포한다면, 어떤 값도 이상값으로 고려하지 않는다.
  • 이상값을 파악하려면, 반드시, 각 변수의 분포를 먼저 이해해야 한다.

라이브러리 및 데이터 불러오기

  • 실습을 위한 데이터를 불러온다.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
import scipy.stats as scistat

covidtotals = pd.read_csv("data/covidtotals.csv")
covidtotals.set_index("iso_code", inplace = True)

case_vars = ["location", "total_cases", "total_deaths", "total_cases_pm", "total_deaths_pm"]
demo_vars = ["population", "pop_density", "median_age", "gdp_per_capita", "hosp_beds"]

print(covidtotals.head())
            lastdate     location  total_cases  total_deaths  total_cases_pm  \
iso_code                                                                       
AFG       2020-06-01  Afghanistan        15205           257         390.589   
ALB       2020-06-01      Albania         1137            33         395.093   
DZA       2020-06-01      Algeria         9394           653         214.225   
AND       2020-06-01      Andorra          764            51        9888.048   
AGO       2020-06-01       Angola           86             4           2.617   

          total_deaths_pm  population  pop_density  median_age  \
iso_code                                                         
AFG                 6.602  38928341.0       54.422        18.6   
ALB                11.467   2877800.0      104.871        38.0   
DZA                14.891  43851043.0       17.348        29.1   
AND               660.066     77265.0      163.755         NaN   
AGO                 0.122  32866268.0       23.890        16.8   

          gdp_per_capita  hosp_beds  
iso_code                             
AFG             1803.987       0.50  
ALB            11803.431       2.89  
DZA            13913.839       1.90  
AND                  NaN        NaN  
AGO             5819.495        NaN  
  • describe() 함수를 통해 수치 데이터의 분포를 확인하도록 한다.
covid_case_df = covidtotals.loc[:, case_vars]
print(covid_case_df.describe())
        total_cases   total_deaths  total_cases_pm  total_deaths_pm
count  2.100000e+02     210.000000      210.000000       210.000000
mean   2.921614e+04    1770.714286     1355.357943        55.659129
std    1.363978e+05    8705.565857     2625.277497       144.785816
min    0.000000e+00       0.000000        0.000000         0.000000
25%    1.757500e+02       4.000000       92.541500         0.884750
50%    1.242500e+03      25.500000      280.928500         6.154000
75%    1.011700e+04     241.250000     1801.394750        31.777250
max    1.790191e+06  104383.000000    19771.348000      1237.551000
  • 백분위수(quantile)로 데이터를 표시한다.
print(covid_case_df.quantile(np.arange(0.0, 1.1, 0.1)))
     total_cases  total_deaths  total_cases_pm  total_deaths_pm
0.0          0.0           0.0          0.0000           0.0000
0.1         22.9           0.0         17.9986           0.0000
0.2        105.2           2.0         56.2910           0.3752
0.3        302.0           6.7        115.4341           1.7183
0.4        762.0          12.0        213.9734           3.9566
0.5       1242.5          25.5        280.9285           6.1540
0.6       2514.6          54.6        543.9562          12.2452
0.7       6959.8         137.2       1071.2442          25.9459
0.8      16847.2         323.2       2206.2982          49.9658
0.9      46513.1        1616.9       3765.1363         138.9045
1.0    1790191.0      104383.0      19771.3480        1237.5510
  • 왜도는 분포가 얼마나 대칭적인지를 나타냄
  • 왜도와 첨도는 어떻게 대칭적인지를 설명하며, 분포의 꼬리가 각각 얼마나 두꺼운지 나타냄.
covid_case_df.skew(axis=0, numeric_only = True)
total_cases        10.804275
total_deaths        8.929816
total_cases_pm      4.396091
total_deaths_pm     4.674417
dtype: float64
covid_case_df.kurtosis(axis=0, numeric_only = True)
total_cases        134.979577
total_deaths        95.737841
total_cases_pm      25.242790
total_deaths_pm     27.238232
dtype: float64
  • 정규성 검정을 테스트 한다.
  • p값 0.05미만에서 95% 수준에서 정규분포의 귀무가설을 기각하고, 대립가설을 채택한다.
    • 귀무가설: 표본의 모집단이 정규분포를 이루고 있다.
    • 대립가설: 표본의 모집단이 정규분포를 이루고 있지 않다.
scistat.shapiro(covid_case_df['total_cases'])
ShapiroResult(statistic=0.19379639625549316, pvalue=3.753789128593843e-29)
scistat.shapiro(covid_case_df['total_deaths'])
ShapiroResult(statistic=0.19832086563110352, pvalue=4.3427896631016077e-29)
scistat.shapiro(covid_case_df['total_cases_pm'])
ShapiroResult(statistic=0.5220695734024048, pvalue=1.3972683006509067e-23)
scistat.shapiro(covid_case_df['total_deaths_pm'])
ShapiroResult(statistic=0.41877639293670654, pvalue=1.361060423265974e-25)
  • 위 4개의 feature 모두 정규분포를 이루고 있지 않음을 확인할 수 있다.
  • 이번에는 qqplot을 그린다.
sm.qqplot(covid_case_df[["total_cases"]].sort_values(["total_cases"]), line = "s")
plt.title("QQ Plot of Total Cases")
Text(0.5, 1.0, 'QQ Plot of Total Cases')

png

Finding Missing Values

데이터 가져오기

import pandas as pd

covidtotals = pd.read_csv("data/covidtotalswithmissings.csv")
print(covidtotals.head())
  iso_code    lastdate     location  total_cases  total_deaths  \
0      AFG  2020-06-01  Afghanistan        15205           257   
1      ALB  2020-06-01      Albania         1137            33   
2      DZA  2020-06-01      Algeria         9394           653   
3      AND  2020-06-01      Andorra          764            51   
4      AGO  2020-06-01       Angola           86             4   

   total_cases_pm  total_deaths_pm  population  pop_density  median_age  \
0         390.589            6.602  38928341.0       54.422        18.6   
1         395.093           11.467   2877800.0      104.871        38.0   
2         214.225           14.891  43851043.0       17.348        29.1   
3        9888.048          660.066     77265.0      163.755         NaN   
4           2.617            0.122  32866268.0       23.890        16.8   

   gdp_per_capita  hosp_beds  
0        1803.987       0.50  
1       11803.431       2.89  
2       13913.839       1.90  
3             NaN        NaN  
4        5819.495        NaN  
  • Missing Value 확인
  • 일부 feature에서 missing value가 있는 것을 확인함.
covidtotals.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 210 entries, 0 to 209
Data columns (total 12 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   iso_code         210 non-null    object 
 1   lastdate         210 non-null    object 
 2   location         210 non-null    object 
 3   total_cases      210 non-null    int64  
 4   total_deaths     210 non-null    int64  
 5   total_cases_pm   209 non-null    float64
 6   total_deaths_pm  209 non-null    float64
 7   population       210 non-null    float64
 8   pop_density      198 non-null    float64
 9   median_age       186 non-null    float64
 10  gdp_per_capita   182 non-null    float64
 11  hosp_beds        164 non-null    float64
dtypes: float64(7), int64(2), object(3)
memory usage: 19.8+ KB
  • 데이터를 크게 두개의 기분으로 분류한다.
    • Covid case & Demographic Columns
case_vars = ["location", "total_cases", "total_deaths", "total_cases_pm", "total_deaths_pm"]
demo_vars = ["population", "pop_density", "median_age", "gdp_per_capita", "hosp_beds"]
  • axis 설정을 통해 인구통계와 Covid Cased의 결측치 값을 설정한다.
covidtotals[demo_vars].isnull().sum(axis=0)
population         0
pop_density       12
median_age        24
gdp_per_capita    28
hosp_beds         46
dtype: int64
covidtotals[case_vars].isnull().sum(axis=0)
location           0
total_cases        0
total_deaths       0
total_cases_pm     1
total_deaths_pm    1
dtype: int64
  • 이번에는 행 방향으로 발생한 결측치를 확인한다.
  • 결측치가 없는 행은 156개이고, 1개만 있는 행은 24개 순으로 집계 되었다.
demovars_misscnt = covidtotals[demo_vars].isnull().sum(axis=1)
demovars_misscnt.value_counts()
0    156
1     24
2     12
3     10
4      8
dtype: int64
  • 인구통계 데이터가 3가지 이상 누락된 국가를 나열한다.
    • 5개의 값만 추출했다.
print(covidtotals.loc[demovars_misscnt >= 3, ['location'] + demo_vars].head(5).T)
                     3         5                                24  \
location        Andorra  Anguilla  Bonaire Sint Eustatius and Saba   
population      77265.0   15002.0                          26221.0   
pop_density     163.755       NaN                              NaN   
median_age          NaN       NaN                              NaN   
gdp_per_capita      NaN       NaN                              NaN   
hosp_beds           NaN       NaN                              NaN   

                                    28              64  
location        British Virgin Islands  Faeroe Islands  
population                     30237.0         48865.0  
pop_density                    207.973          35.308  
median_age                         NaN             NaN  
gdp_per_capita                     NaN             NaN  
hosp_beds                          NaN             NaN  
  • 이번에는 코로나 사례 데이터에서 누락값을 확인한다.
    • 홍콩만 사례가 누락된 것을 확인할 수 있다.
totvars_misscnt = covidtotals[case_vars].isnull().sum(axis=1)
totvars_misscnt.value_counts()
0    209
2      1
dtype: int64
print(covidtotals.loc[totvars_misscnt == 2, ['location'] + case_vars].T)
                        87
location         Hong Kong
location         Hong Kong
total_cases              0
total_deaths             0
total_cases_pm         NaN
total_deaths_pm        NaN
print(covidtotals[covidtotals['location'] == "Hong Kong"])
   iso_code    lastdate   location  total_cases  total_deaths  total_cases_pm  \
87      HKG  2020-05-26  Hong Kong            0             0             NaN   

    total_deaths_pm  population  pop_density  median_age  gdp_per_capita  \
87              NaN   7496988.0     7039.714        44.8        56054.92   

    hosp_beds  
87        NaN  

방법 1. Inplace 사용

# 결측치 채우기
covidtotals = pd.read_csv("data/covidtotalswithmissings.csv")
covidtotals2 = covidtotals.copy()
covidtotals2[case_vars].isnull().sum(axis = 0) 
location           0
total_cases        0
total_deaths       0
total_cases_pm     1
total_deaths_pm    1
dtype: int64
covidtotals2.total_cases_pm.fillna(covidtotals2.total_cases/(covidtotals2.population/10000000), inplace = True)
covidtotals2.total_deaths_pm.fillna(covidtotals2.total_deaths/(covidtotals2.population/10000000), inplace = True)
covidtotals2[case_vars].isnull().sum(axis = 0) 
location           0
total_cases        0
total_deaths       0
total_cases_pm     0
total_deaths_pm    0
dtype: int64

방법 2. 매칭을 통한 대체

covidtotals = pd.read_csv("data/covidtotalswithmissings.csv")
covidtotals2 = covidtotals.copy()
covidtotals2[case_vars].isnull().sum(axis = 0) 
location           0
total_cases        0
total_deaths       0
total_cases_pm     1
total_deaths_pm    1
dtype: int64
covidtotals2.loc[:, 'total_cases_pm'] = covidtotals2.loc[:, 'total_cases_pm'].fillna(value=covidtotals2.total_cases/(covidtotals.population/10000000))
covidtotals2.loc[:, 'total_deaths_pm'] = covidtotals2.loc[:, 'total_deaths_pm'].fillna(value=covidtotals2.total_deaths/(covidtotals.population/10000000))
covidtotals2[case_vars].isnull().sum(axis = 0) 
location           0
total_cases        0
total_deaths       0
total_cases_pm     0
total_deaths_pm    0
dtype: int64

References

Walker, M. (2020). Python Data Cleaning Cookbook: Modern techniques and Python tools to detect and remove dirty data and extract key insights. Packt Publishing.

결정 트리 학습 이론

개요

결정 트리의 예

  • 결정 트리는 여러가지 연속된 질문을 학습하여 분류하는 것이 원칙이다.
  • 다음의 간단한 예를 들어본다.

  • 결정 트리는 크게 3가지로 구성이 되어 있다.
    • 트리 내부 노드, 리프 노드, 그리고 가지로 구성이 되어 있다.
    • 어떻게 질문을 하느냐에 따라서 분류가 결정된다.
  • 결정 트리는 숫자에도 적용할 수 있다.
    • 예) 키가 160cm보다 큰가요?

결정 트리의 주요 원리

  • 결정 트리는 트리의 루트(Root)에서 시작하여, 정보 이득(Information Gain, IG)가 최대가 되는 특성으로 데이터를 나눔
  • 반복 과정(분류할 수 있는 연속적인 질문)을 통해 계속적으로 분류함
    • 전문 용어로는 Until the leaves are pure.
  • 결정 트리에서 가장 중요한 것은 정보 이득 최대화임(Maximizing Information Gain)

Heroku Dash App 배포 - Windows 10

개요

  • WindowsVirtualenv를 활용하여 빠르게 App 배포를 해본다.

1. 프로그램 다운로드

tutorial_01.png

  • 이럴 경우에는 환경변수를 강제로 잡는다.
C:\Program Files\heroku\bin
  • Heroku가 제대로 환경설정이 되어 있는지 확인하려면, 터미널에서 다음 명령어를 입력해 확인한다.
$ heroku -v
heroku/7.53.0 win32-x64 node-v12.21.0
(base)

2. Getting Started

$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/93982084-f22f-4a6b-b347-94f1aa4b6b47?requestor=SFMyNTY.g2gDbQAAAA4xMTIuMTQ0LjIyOC43Nm4GACiKMnR9AWIAAVGA.j9hng63oLOpCVOcHcWyOYDqT4s11jMHDtEesGw5xUD4
heroku: Waiting for login...
Logging in... done
Logged in as your_email@gmail.com
  • Github Repo를 생성하고, git clone 으로 바탕화면(또는 적정한 곳)에 Repo를 내려 받는다.
$ git clone https://github.com/your_name/heroku-app-green.git
  • heroku_app 경로에서 다음과 같이 실행한다.
    • 이 때, 프로젝트 폴더명, github repo 이름, heroku 이름이 동일해야 한다.
    • 또 한가지 주의해야 할 점은 name 방식이다. 무료 방식이기 때문에, 타 사용자가 해당 주소를 사용하고 있다면, 쓸수 없다. 또한, heroku_app 과 같은 형식도 되지 않는다.
    • 아래는 heroku app 생성 실패 내역이다.
$ heroku create heroku-app
 »   Warning: heroku update available from 7.53.0 to 7.59.2.
Creating heroku-app... !
 !    Name heroku-app is already taken                   
  • 정상적으로 설치가 완료되면 다음과 같이 뜬다.
$ heroku create heroku-app-green
 »   Warning: heroku update available from 7.53.0 to 7.59.2.
Creating heroku-app-green... done
https://heroku-app-green.herokuapp.com/ | https://git.heroku.com/heroku-app-green.git
(base)
  • heroku login을 진행한다.
$ heroku login
heroku: Press any key to open up the browser to login or q to exit: 
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/9320abcd-b8c6-406d-9198-ca14d1e59a26?requestor=SFMyNTY.g2gDbQAAAA4yMjEuMTU3LjM3LjIxNm4GAGgtTBB7AWIAAVGA.GlyVc8jbyiW6NG0MVzCS0bOjtzBWvYRfjB9-gnkQaoQ
Logging in... done
Logged in as your_email_address
  • 이제 마지막으로 heroku app에 repository를 생성한다.
$ heroku git:remote -a your_app
 »   Warning: heroku update available from 7.53.0 to 7.59.2.
set git remote heroku to https://git.heroku.com/heroku-app-green.git
  • heroku-app-green 이 생긴 것을 확인할 수 있다.

tutorial_02.png

Hexo Blog 재연결

문제점

  • 몇몇 수강생이 노트북과 데스트탑 자리 모두에서 깃헙 블로그를 운영하고 싶어함.
  • 또한, 기존에 올라간 블로그 소스를 그대로 사용하고 싶어함.
  • 그런데, 제대로 반영이 안되는 경우가 있음.

해결책

  • 그런 경우 아래와 같이 순차적으로 진행하면 된다.
$ hexo init your_blog_repo # 여기는 각자 소스 레포 확인
$ cd myblog
$ git init 
$ git remote add origin https://github.com/your_name/your_blog_repo.git # 각자 소스 레포 주소
  • 아래 명령어에서 에러가 발생이 있다.
$ git pull --set-upstream origin main # 에러 발생
  • 그런 경우, 아래 명령어를 추가한다. 기존의 디렉토리와 파일을 모두 삭제한다는 뜻이다.
$ git clean -d -f
  • 그리고 에러가 발생했던 명령어를 다시 실행한다.
  • 이 때에는 이제 정상적으로 실행되는 것을 확인할 수 있다.
$ git pull --set-upstream origin main # 에러 발생 안함 / 소스 확인
  • 이제 정상적으로 환경 세팅은 된 것이다. 순차적으로 아래와 같이 진행하도록 한다.
    • 이 때, theme 폴더에 본인의 테마 소스코드가 잘 있는지 확인을 하도록 한다.
$ npm install 
$ hexo clean
$ hexo generate
$ hexo server

Kaggle Survey Data Transformation Tip

Intro

  • Data Transformation is always important to visualise.
  • Here, I just introduced to get value counts in different dataset.
  • If you are newbie, please be aware of this code before you dive into visualization.
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
/kaggle/input/kaggle-survey-2021/kaggle_survey_2021_responses.csv
/kaggle/input/kaggle-survey-2021/supplementary_data/kaggle_survey_2021_methodology.pdf
/kaggle/input/kaggle-survey-2021/supplementary_data/kaggle_survey_2021_answer_choices.pdf

Data Import

  • Import raw data and split into questions dataset and survey dataset.
df = pd.read_csv("../input/kaggle-survey-2021/kaggle_survey_2021_responses.csv")
questions = df.iloc[0, :].T
questions
/opt/conda/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3441: DtypeWarning: Columns (0,195,201,285,286,287,288,289,290,291,292) have mixed types.Specify dtype option on import or set low_memory=False.
  exec(code_obj, self.user_global_ns, self.user_ns)





Time from Start to Finish (seconds)                                Duration (in seconds)
Q1                                                           What is your age (# years)?
Q2                                                What is your gender? - Selected Choice
Q3                                             In which country do you currently reside?
Q4                                     What is the highest level of formal education ...
                                                             ...                        
Q38_B_Part_8                           In the next 2 years, do you hope to become mor...
Q38_B_Part_9                           In the next 2 years, do you hope to become mor...
Q38_B_Part_10                          In the next 2 years, do you hope to become mor...
Q38_B_Part_11                          In the next 2 years, do you hope to become mor...
Q38_B_OTHER                            In the next 2 years, do you hope to become mor...
Name: 0, Length: 369, dtype: object
df = df.iloc[1:, :]

Quick Data Review

  • All survey responses are count-based dataset.
  • It’s easy to check using value counts()
df['Q1'].value_counts()
25-29    4931
18-21    4901
22-24    4694
30-34    3441
35-39    2504
40-44    1890
45-49    1375
50-54     964
55-59     592
60-69     553
70+       128
Name: Q1, dtype: int64

Problem

  • Some questions are not easy to counts because of Supplementary Questions.
questions.index.tolist()[7:20]
['Q7_Part_1',
 'Q7_Part_2',
 'Q7_Part_3',
 'Q7_Part_4',
 'Q7_Part_5',
 'Q7_Part_6',
 'Q7_Part_7',
 'Q7_Part_8',
 'Q7_Part_9',
 'Q7_Part_10',
 'Q7_Part_11',
 'Q7_Part_12',
 'Q7_OTHER']
def sub_questions_count(question_num, part_num, text = False):
  part_questions = []

  if text in ["A", "B"]:
    part_questions = ['Q' + str(question_num) + "_" + text + '_Part_' + str(j) for j in range(1, part_num)]
    part_questions.append('Q' + str(question_num) + "_" + text + '_OTHER')
  else:
    part_questions = ['Q' + str(question_num) + '_Part_' + str(j) for j in range(1, part_num)]
    part_questions.append('Q' + str(question_num) + '_OTHER')

  # category count
  categories = []
  counts = []
  for i in part_questions:
    category = df[i].value_counts().index[0]
    val = df[i].value_counts()[0]
    categories.append(category)
    counts.append(val)

  combined_df = pd.DataFrame()
  combined_df['Category'] = categories
  combined_df['Count'] = counts

  combined_df = combined_df.sort_values(['Count'], ascending = False)
  return combined_df

Test

  • Case 1
# Test 
# 'Q38_B_Part_11',
print(sub_questions_count(38, 11, "B").reset_index(drop=True))
                  Category  Count
0             TensorBoard    4239
1                  MLflow    2747
2        Weights & Biases    1583
3              Neptune.ai    1276
4                 ClearML    1020
5                Polyaxon     737
6                Guild.ai     729
7    Domino Model Monitor     666
8                Comet.ml     633
9      Sacred + Omniboard     591
10                   Other    377

Case 2.

M1 Mac Tensorflow Installation in R

개요

  • M1 Mac에서 텐서플로를 설치 한다.
  • 필자의 현재 M1 환경은 아래와 같다.
sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Big Sur 11.6

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.3.5    dplyr_1.0.7      tfdatasets_2.7.0 keras_2.7.0     
[5] reticulate_1.22  tensorflow_2.7.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.7        compiler_4.1.2    pillar_1.6.4      prettyunits_1.1.1
 [5] base64enc_0.1-3   tools_4.1.2       progress_1.2.2    digest_0.6.28    
 [9] zeallot_0.1.0     nlme_3.1-153      gtable_0.3.0      jsonlite_1.7.2   
[13] lifecycle_1.0.1   tibble_3.1.6      lattice_0.20-45   mgcv_1.8-38      
[17] pkgconfig_2.0.3   png_0.1-7         rlang_0.4.12      Matrix_1.3-4     
[21] cli_3.1.0         rstudioapi_0.13   withr_2.4.2       generics_0.1.1   
[25] vctrs_0.3.8       hms_1.1.1         rprojroot_2.0.2   grid_4.1.2       
[29] tidyselect_1.1.1  glue_1.5.0        here_1.0.1        R6_2.5.1         
[33] fansi_0.5.0       farver_2.1.0      purrr_0.3.4       magrittr_2.0.1   
[37] whisker_0.4       splines_4.1.2     scales_1.1.1      tfruns_1.5.0     
[41] ellipsis_0.3.2    colorspace_2.0-2  labeling_0.4.2    utf8_1.2.2       
[45] munsell_0.5.0     crayon_1.4.2 

Miniforge3 설치

Matplotlib 한글 폰트 추가 (Mac)

개요

  • Mac 유저를 위해 한글 폰트 추가하는 방법을 설명한다.
  • 기본 코드는 Windows에서도 동작한다.
  • 폰트 추가 방법은 생략한다.

한글 폰트 깨진 시각화

  • 간단하게 깨진 한글이 들어간 시각화를 구현한다.
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import matplotlib as mpl
 
plt.plot([1, 2, 3, 4, 5])
plt.title("테스트")
plt.show()
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 53580 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 49828 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:238: RuntimeWarning: Glyph 53944 missing from current font.
  font.set_text(s, 0.0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 53580 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 49828 missing from current font.
  font.set_text(s, 0, flags=flags)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py:201: RuntimeWarning: Glyph 53944 missing from current font.
  font.set_text(s, 0, flags=flags)

png

RcppMeCab 패키지 설치 (Windows)

개요

  • Mecab-ko 형태소 분석기 사용 위해서는 Rcppmecab 패키지를 설치해야 함.
  • RcppMeCab 패키지 설치 앞서서 설치할 파일이 있음.

설치 파일

위 파일을 다운로드 받은 후, “C:\mecab"에서 압축을 해제한다.

MeCab_install_01.png

MeCab_install_02.png

RcppMecab 패키지 불러오기.

  • 이제 패키지를 불러오도록 한다.
  • 해당 패키지는 Github 버전으로 설치해야 하기 때문에 아래와 같이 설치를 한다.
library(remotes)
install_github("junhewk/RcppMeCab")
Downloading GitHub repo junhewk/RcppMeCab@HEAD
Installing 3 packages: BH, RcppParallel, Rcpp
.
.
** testing if installed package keeps a record of temporary installation path
* DONE (RcppMeCab)
library(RcppMeCab)

테스트

  • 실제 잘 실행되는지 테스트를 해본다.
library(remotes)
install_github("junhewk/RcppMeCab", force = TRUE)

library(RcppMeCab)

# 테스트
text = "안녕하세요!"
pos(sentence = text)
# $`�ȳ\xe7\xc7ϼ��\xe4!`
# [1] "�/SY"           "ȳ/SL"            "\xe7\xc7\xcf/SH" "���\xe4/SY"  
# [5] "!/SF" 
text2 = enc2utf8(text)

pos(sentence = text2)
# $`안녕하세요!`
# [1] "안녕/NNG"   "하/XSV"     "세요/EP+EF" "!/SF"

R 강의 소개

Python 강의 소개

Hexo Blog 이미지 추가

Hexo 이미지 추가

방법 1. Global Asset Folder

  • 가장 간편한 방법은 source 폴더 아래 images 폴더를 별도로 만든다.
  • 마크다운에서 아래와 같이 입력을 한다.
![](/images/image.jpg)


# hexo logo 테스트
- 이미지
![](/images/Hexo-logo.png)
  • hexo server를 실행한 뒤 결과를 확인한다.

result_01.png