달력

3

« 2024/3 »

  • 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
  • 27
  • 28
  • 29
  • 30
  • 31

'Programming'에 해당되는 글 54

  1. 2021.02.17 파이썬 캔들 차트, plotly-01 #Candlestick Charts 살펴보기
  2. 2021.02.16 파이썬 차트, plotly-00 #시작
  3. 2021.01.24 C# Datetime
  4. 2021.01.19 KRX 회원사별 어디갔니?
  5. 2020.12.08 패스트캠퍼스 파이썬을 활용한 데이터 전처리 Level UP 챌린지 참여 후기
  6. 2020.11.29 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 28회차 미션
  7. 2020.11.28 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 27회차 미션
  8. 2020.11.27 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 26회차 미션
  9. 2020.11.26 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 25회차 미션
  10. 2020.11.25 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 24회차 미션
  11. 2020.11.24 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 23회차 미션
  12. 2020.11.23 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 22회차 미션
  13. 2020.11.22 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 21회차 미션
  14. 2020.11.21 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 20회차 미션
  15. 2020.11.20 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 19회차 미션
  16. 2020.11.19 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 18회차 미션
  17. 2020.11.18 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 17회차 미션
  18. 2020.11.17 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 16회차 미션
  19. 2020.11.16 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 15회차 미션
  20. 2020.11.15 [패스트캠퍼스 수강 후기] 데이터전처리 100% 환급 챌린지 14회차 미션
728x90
반응형

# 시작에 이어서 우리에게 필요한(?) 캔들 차트 그리기를 알아보도록 하겠습니다.

 

# 오늘도 스스로를 위한 공부시작!!!!

 

# 오늘도 소스는 plotly 공식 사이트를 참고해 보았습니다.


[참고 사이트]

plotly.com/python/candlestick-charts/

 

# 주식 정보들을 다루다 보면 필연적으로 pandas 와 많이 부딪치게 되는 것 같습니다. pandas 에 정보를 담아서 주가를 그려보도록 하겠습니다.

# 주가 데이터셋 또한 plotly 에서 제공해주기 때문에 연습할 때 용이합니다.

# 전체코드
import plotly.graph_objects as go

import pandas as pd
from datetime import datetime

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])])

fig.show()

차트 예시

# 실행해보면 밑에 컨트롤바와 함께 이쁜 차트가 자동으로 완성됩니다.

# 마수를 캔들위에 놓으면 캔들의 시가, 고가, 종가, 저가를 알수가 있고, 아래의 컨트롤바를 움직이면 확대하거나 해서 원하는 시간대로 이동할수도 있습니다.


 

[코드 살펴보기]

 

import plotly.graph_objects as go

# import 를 해주는 것이고, as 는 보통 go 로 통상적으로 많이 사용하고 있습니다.

import pandas as pd

# pandas 도 import

# 만약 설치가 안되어있다면 jupyter notebook 에서 아래와 같이 설치하여 실행하시기 바랍니다.

!pip install pandas
from datetime import datetime

# datetime 은 왜 import 했는지 모르겠네요~^^ 사이트에서 제공하는 코드소스인데도.. 뭔가 쓸데 없는 것이..~^^;;;;

# 사용을 하지 않으므로 주석처리 또는 삭제 처리 해주셔도 되네요.

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

# dataframe 형태로 사이트에서 제공해주는 데이터셋을 불러와 정보를 담습니다.

fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])])

# 정보를 불어모녀 x축과 y축에 각각 정보를 줘야 합니다. fig에 위와 같이 x 축에는 날짜 항목을 불러오고, y축에는 open(시가), high(고가), low(저가), close(종가) 불러 옵니다. 여기서는 애플의 주가를 불러왔나보네요.

fig.show()

# 마지막으로 정보 불러온것을 보여줍니다.

# mpl_finance 를 이용해서 candlestick 을 그리시는 분들도 있지만. 저는 plotly 가 더 저한테는 맞는것 같더라구요. ^^

 

# 다음에도 plotly 사이트에 있는 문서들을 좀 더 살펴보고 하나씩 하나씩 공부해 나가도록 하겠습니다.


[이전글]

2021/02/16 - [Programming/Python] - plotly-00 #시작

728x90
반응형
:
Posted by 패치#노트
2021. 2. 16. 09:52

파이썬 차트, plotly-00 #시작 Programming/Python2021. 2. 16. 09:52

728x90
반응형

# 파이썬으로 주식 데이터를 분석하다면 그래프를 무조건 사용하게 되어 있다.

나는 초창기에 기본적인 matplotlib을 가지고 시도했었으나 plotly 를 알고 나서부터는 이것만 사용하게 되었다.

 

# 가장 큰 차이점은 matplotlib 의 경우 주가 데이터를 그리더라도 활용도가 plotly 보다 훨~~~~씬 뒤처지는 개인적인 느낌이 있어서 plotly만 사용하고 있는 중이다.

 추후에 더 좋은 것이 나온다면..... 음...~ move move~~

 

# 오늘은 시작하는 느낌으로 기초부터 시작하고

점점 내가 활용하고 있는 단계까지 작성을 해볼려고 한다.

 

# 나를 위한 공부 start!!!!

 

[설치]

pip install plotly

만약 주피터 노트북을 사용한다면

!pip install plotly

 

[공식 사이트]

plotly.com/

 

Plotly: The front end for ML and data science models

Plotly creates & stewards the leading data viz & UI tools for ML, data science, engineering, and the sciences. Language support for Python, R, Julia, and JavaScript.

plotly.com

# 대부분 Jupyter notebook을 활용해서 그래프를 그리고 있으므로 Jupyter notebook 위주로 설명

 

plotly.com/python/getting-started/

[그래프 그려보기]

import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()

 

Jupyter notebook 구현

# matplotlib은 이미지를 화면에 찍어내지만, plotly 는 위와 같이 쉽게 active 하게 그릴 수 있다.

728x90
반응형
:
Posted by 패치#노트
2021. 1. 24. 18:02

C# Datetime Programming/C#2021. 1. 24. 18:02

728x90
반응형

https://thedeveloperblog.com/datetime-performance

C# DateTime Performance Class

Home | Contact Us CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript C# DateTime Performance Class This C# performance class optimizes accesses to the DateTime.Now method. DateTime performance. A program uses DateTime.Now to frequen

thedeveloperblog.com

728x90
반응형

'Programming > C#' 카테고리의 다른 글

변수, 딕셔너리 등등 변수명은 영문으로!!!!  (0) 2021.04.13
:
Posted by 패치#노트
2021. 1. 19. 18:43

KRX 회원사별 어디갔니? Programming/Python2021. 1. 19. 18:43

728x90
반응형

매일 저녁 돌리던 KRX 크롤링...ㅠ.ㅠ 홈페이지가 개편이 되면서 원래 자료를 취합해오던 회원사별 메뉴가 없어졌다.

어디로 간거냐..

 

한참을 뒤지던중...

[출처] KRX 홈페이지

 

이젠 데이터상품으로 데이터 장사를...........

내가 주식시장에 가져다준 돈이 얼마인데...ㅠ.ㅠ

 

이런것도..맘대로.. 못 보공. 흥.칫.뿡

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

패스트캠퍼스

[파이썬을 활용한 데이터 전처리 Level UP]

챌린지 참여 후기

 

마지막 실전 프로젝트를 정리하기전 이번 챌린지 이벤트 참여에 대한 소회..

 

나에게 아직은 데이터분석은 생소한 분야임에는 틀림이 없다. 하지만 한단계 레벨업을 하기 위해서는 반드시 필요하다가 나 스스로가 깨닫고 있다.

수 많은 용어들과 통계학, 라이브러리 등 적응이 잘 안 되고 있지만 반복적인 학습을 통해서 매일매일 해나가도 보면 언젠가는 도달 할 수 있지 않을까?

아직도 늦었다고 생각하는가?

오늘도 한 걸음만 더 나아가보자!!!

할 수 있다!!!!!

해야만 한다!!!!!


 

01. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 01. (1) 문제 소개

* 대회 소개

- 출처 : 삼성 신용카드 매출 예측 경진대회

 . 문제 제공자 : FUNDA (데이콘)

 . 소상공인 가맹점 신용카드 빅데이터와 AI로 매출 예측 분석 

dacon.io/competitions/official/140472/overview/

 

상점 신용카드 매출 예측 경진대회

출처 : DACON - Data Science Competition

dacon.io

// 하나의 레코드가 하나로 대응 되는 거라고 생각하면 된다.

 

02. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 02-1. (2) 학습 데이터 구축 (이론)

* 기본 데이터 구조 설계

 - 레코드가 수집된 시간 기준으로 3개월 이후의 총 매출을 예측하도록 구조를 설계해야 한다.

 - 시점은 월단위로 정의

 

* 시점변수 생성

// 시점 변수 생성이 필요하다.

 - 시점 변수 생성 : 시점 (t) = (연도 - 2016 ) * 12 + 월

 

* 변주 변수 탐색

// 부적절하다고 하는 것은 데이터 기반이 아니라고 생각하면 된다.

// 범주형 변수로 상태 공간이 매우 커서, 더미화하기에는 부적절하다고 판단했다.

// 결측은 제거하지 않고 없음이라고 변환한다.

 

* 학습 데이터 구조 작성

// 정리되지 않은 데이터를 바탕으로 학습 데이터를 생성해야 하는 경우에는 레코드의 단위를 고려하여 학습 데이터의 구조를 먼저 작성하는 것이 바람직하다.

// 중복을 제거

 

* 평균 할부율 부착

// 할부를 많이 하는 그룹이 있을 것 같아서 groupby 를 이용해서 생성 replace 를 이용해서 다시 만들었고

 

* 기존 데이터에 부착 테크닉

// concat, merge 를 이용하면 일반적인 것은 붙일 수 있는데

// 다른 데이터에서 붙여야 하므로 case1 t가 유니크한 경우, 각 데이터를 정렬 후, 한 데이터에 대해 shift 를 사용

// case 2. t 가 유니크하지 않은 경우, t_1 변수를 생성

 

* 기존 데이터 부착 테크닉 Case 1

// shift 를 이용해서 concat 수행

// df2.shift(1)

// 시계열 예측에서 많이 쓰이는 패턴이다.

 

* 기존 데이터 부착 테크닉 Case 2

// 새로운 컬럼은 생성하서 merge를 수행한다.

 

* 기존 매출 합계 부착

 

* 기존 지역별 매출 합계 부착

 

* 라벨 부착하기

// 라벨의 경우에는 어떤 시점 t 에 상점 id 별로 붙이고 1 2 3 에 대해서 더 해준다.

 

03. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 02-2. (2) 학습 데이터 구축 (실습)

 

// region 에 결측이 있지만 대체를 하기에는 힘들고 제거를 하기에는 힘들다. 그래서 없음으로 표시

// 변수 목록 탐색을 통해서 상점 ID 가 일치 하는지 탐색을 해야 한다.

 

* 학습 데이터 구축

// 일자에서 연, 월, 일을 구분 해야 하므로 split 을 사용해서 구분

// 데이터 병합을 위한 새로운 컬럼 생성 및 기존 시간 변수를 삭제한다.

 

* 불필요한 변수 제거

// card_id, card_company는 특징으로 사용하기에는 너무 세분화 될수 있어서, 특징으로 유요할 가능성이 없다고 삭제.

// 주관적인 판단으로 처리한 것이다.

 

* 업종 특성, 지역, 할부 평균 탐색

// 대부분이 일시불이므로, installment_term 변수를 할부인지 아닌지 여부로 변환해야 한다.

// astype(int) 로 해서 할부는 0 , 할부하지 않은 것은 1로 나타난다.

 

// 상점별 평균 할부 비율

// .mean( ) 함수를 통해서 각 평균을 구해서 store_id 를 본다.

 

// 지역은 region 제거를 할수 없기 때문에 없음으로 대체 '없음'

// 업종도 비슷하다.

 

// 피벗 테이블을 생성하고 결측을 바로 앞 값으로 채울 수 있다.

// 값이 없는 경우는 결측으로 출력이 나옴.

// ffill 바로 앞 값과 bfill 그 다음은 바로 뒤값으로 채워준다.

 

// 변수 실수를 줄여야 한다.

// 모델 학습을 적용하기 위한 일반적인 전처리에 대한 준비를 했다.

 

04. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 03. (3) 학습 데이터 탐색 및 전처리

* 학습 데이터 기초 탐색 및 전처리

 - 특징과 라벨 분리

// 필요없는 라벨들은 drop 으로 제거 해준다. axis = 1

 

 - 학습데이터와 평가 데이터로 데이터 분할

// 특징 대비 샘플이 많다는 것을 알 수 있다. 37673

// 회귀 문제 예측 문제라고 예상하면 된다.

 

 - 이상치 제거

// IQR rule 을 위배하지 않는 bool list 계산 (True : 이상치 없음, False : 이상치 있음)

// Y_condition 이상치가 아닌 값들로 구성된것

 

 - 치우침 제거

// 모두 좌로 치우침을 확인 할수가 있다.

// 왜도의 절대값이 1.5이상인 컬럼만 가져왔다.

// Train_X.skew().abs() > 1.5

 

// 스케일링 수행

sklearn.preprocessing MinMaxScaler 수행

 

// 원래는 데이터 프레임을 정의하는 것이 좋기는 한데 메모리 문제로 처음부터 정의하지 않음

// 아무리 꼼꼼하더라도 모든 변수를 제거 할 필요는 없다.

 

// abs( ) Documentation

docs.python.org/3/library/functions.html#abs

abs(x)

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

 

3. Data model — Python 3.9.1rc1 documentation

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define

docs.python.org

object.__abs__(self)

 

 

05. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 04. (4) 모델 학습

// 모델 선택

// 샘플 대비 특징이 적고, 특징의 타입이 전부연속형으로 같다.

// kNN, RandomForestRegressor, LightGBM 고려함.

// 신경망을 쓰기에는 변수가 적기 때문에 좋은 결과를 기대하기는 어렵다.

 

// sklearn.ensemble.RandomForestRegressor Documentation

scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html

class sklearn.ensemble.RandomForestRegressor(n_estimators=100, *, criterion='mse', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None)

A random forest regressor.

A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the max_samples parameter if bootstrap=True (default), otherwise the whole dataset is used to build each tree.

Read more in the User Guide.

 

Parameters

n_estimatorsint, default=100

The number of trees in the forest.

Changed in version 0.22: The default value of n_estimators changed from 10 to 100 in 0.22.

criterion{“mse”, “mae”}, default=”mse”

The function to measure the quality of a split. Supported criteria are “mse” for the mean squared error, which is equal to variance reduction as feature selection criterion, and “mae” for the mean absolute error.

New in version 0.18: Mean Absolute Error (MAE) criterion.

max_depthint, default=None

The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.

min_samples_splitint or float, default=2

The minimum number of samples required to split an internal node:

  • If int, then consider min_samples_split as the minimum number.

  • If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split.

Changed in version 0.18: Added float values for fractions.

min_samples_leafint or float, default=1

The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression.

  • If int, then consider min_samples_leaf as the minimum number.

  • If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node.

Changed in version 0.18: Added float values for fractions.

min_weight_fraction_leaffloat, default=0.0

The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.

max_features{“auto”, “sqrt”, “log2”}, int or float, default=”auto”

The number of features to consider when looking for the best split:

  • If int, then consider max_features features at each split.

  • If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split.

  • If “auto”, then max_features=n_features.

  • If “sqrt”, then max_features=sqrt(n_features).

  • If “log2”, then max_features=log2(n_features).

  • If None, then max_features=n_features.

Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features.

max_leaf_nodesint, default=None

Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.

min_impurity_decreasefloat, default=0.0

A node will be split if this split induces a decrease of the impurity greater than or equal to this value.

The weighted impurity decrease equation is the following:

N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity)

where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child.

N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed.

New in version 0.19.

min_impurity_splitfloat, default=None

Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf.

Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 0.25. Use min_impurity_decrease instead.

bootstrapbool, default=True

Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree.

oob_scorebool, default=False

whether to use out-of-bag samples to estimate the R^2 on unseen data.

n_jobsint, default=None

The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

random_stateint or RandomState, default=None

Controls both the randomness of the bootstrapping of the samples used when building trees (if bootstrap=True) and the sampling of the features to consider when looking for the best split at each node (if max_features < n_features). See Glossary for details.

verboseint, default=0

Controls the verbosity when fitting and predicting.

warm_startbool, default=False

When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See the Glossary.

ccp_alphanon-negative float, default=0.0

Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details.

New in version 0.22.

max_samplesint or float, default=None

If bootstrap is True, the number of samples to draw from X to train each base estimator.

  • If None (default), then draw X.shape[0] samples.

  • If int, then draw max_samples samples.

  • If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1).

New in version 0.22.

 

Attributes

base_estimator_DecisionTreeRegressor

The child estimator template used to create the collection of fitted sub-estimators.

estimators_list of DecisionTreeRegressor

The collection of fitted sub-estimators.

feature_importances_ndarray of shape (n_features,)

The impurity-based feature importances.

n_features_int

The number of features when fit is performed.

n_outputs_int

The number of outputs when fit is performed.

oob_score_float

Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True.

oob_prediction_ndarray of shape (n_samples,)

Prediction computed with out-of-bag estimate on the training set. This attribute exists only when oob_score is True.

 

 

// 파라미터 그리드를 생성하고 하이퍼 마라미터 그리드를 parma_dict 에 추가함.

 

// sklearn.metrics.mean_absolute_error Documentation

scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html

sklearn.metrics.mean_absolute_error(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average')

Mean absolute error regression loss

Read more in the User Guide.

 

Parameters

y_truearray-like of shape (n_samples,) or (n_samples, n_outputs)

Ground truth (correct) target values.

y_predarray-like of shape (n_samples,) or (n_samples, n_outputs)

Estimated target values.

sample_weightarray-like of shape (n_samples,), optional

Sample weights.

multioutputstring in [‘raw_values’, ‘uniform_average’] or array-like of shape (n_outputs)

Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

‘raw_values’ :

Returns a full set of errors in case of multioutput input.

‘uniform_average’ :

Errors of all outputs are averaged with uniform weight.

 

Returns

lossfloat or ndarray of floats

If multioutput is ‘raw_values’, then mean absolute error is returned for each output separately. If multioutput is ‘uniform_average’ or an ndarray of weights, then the weighted average of all output errors is returned.

MAE output is non-negative floating point. The best value is 0.0.

 

// 값이 작을 수록 좋기 때문에 초기 값은 매우 큰 값으로 정의함.

// LightGBM 에서 DataFrame 이 잘 처리 되지 않는 것을 방지하기 위해서 .values 를 사용하였다.

 

06. Ch 23. 진짜 문제를 해결해 보자 (1) - 상점 신용카드 매출 예측 - 05. (5) 모델 적용

// 모델 학습이 다 끝나서 새로 들어온 데이터에서 대해서 예측을 해보는 것이다.

// pipeline 을 이용해서 구축할 수 있다.

 

 

07. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 01. (1) 문제 소개

 

* 아파트 실거래가 예측

 

// 실제 데이터는 크기가 크기 때문에 샘플 데이터로 주었다.

// 참조 데이터는 대회 문제 해결을 위해, 강사가 직접 수집한 데이터이며, 어떠한 정제도 하지 않았다.

 

08. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 02. (2) 변수 변환 및 부착

 

* 변수 부착시에 자주 발생하는 이슈 및 해결 방안

// 데이터 크기가 줄어도는 경우가 존재한다.

// np.isin 함수 사용

 

// numpy.isin Documentation

numpy.org/doc/stable/reference/generated/numpy.isin.html

numpy.isin(element, test_elements, assume_unique=False, invert=False)

Calculates element in test_elements, broadcasting over element only. Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise.

 

Parameters

elementarray_like

Input array.

test_elementsarray_like

The values against which to test each value of element. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters.

assume_uniquebool, optional

If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

invertbool, optional

If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False. np.isin(a, b, invert=True) is equivalent to (but faster than) np.invert(np.isin(a, b)).

 

Returns

isinndarray, bool

Has the same shape as element. The values element[isin] are in test_elements.

 

* 불필요한 변수 제거

// 사용하지 않는 변수들은 미리 삭제하여 메모리 부담을 줄여준다.

 

* 범주 변수 구간화 : floor 변수

// floor 변수는 이론적으로는 연속형 변수지만, 범주형 변수로 간주하는 것이 적절하다.

// 너무 정교하게 하면 과최적화가 일어날 수가 있다.

// 박스플롯을 그려서 군집을 세분화한다.

 

* 시세 변수 추가

// groypby를 이용, 구별 전체 평균 시세 변수 추가

// 구별 작년 평균 시세, 구별 작년 거래량 변수 추가

// 아파트별 평균가격 변수 추가

 

* 실습

// engine = 'python' 에러를 줄이기 위해

 

// 일치하지 않는 경우를 확인해야 한다.

 

// isin 함수를 통해서 확인

// df_loc 가 ref_df_loc에 포함되지 않는 경우가 다수 있음을 확인했다.

 

// 시도와 법정동이 완전히 똑같은 행이 있어 제거를 하고, dong 에 리가 붙어 있으면 제거 해야 한다.

 

// apartment_id 를 삭제 할려고 했으나 완전히 유니크하지 않으므로 어느정도 사용이 가능할 것이라 보여서 살펴뒀음.

 

09. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 03. (3) 외부 데이터 부착

// 공원 데이터를 추가 한다.

// 동별로 유형에 공원수를 계산한 뒤, 데이터를 부착한다.

 

// 어린이집 데이터를 추가

// 처리에 관한 방법은 비슷하지만 어떤식으로 정리를 해야 할지는 많은 경험치가 필요할 듯 보인다.

 

10. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 04. (4) 모델 학습

* 데이터 분리

// 라벨 변수 할당

// 불필요한 변수를 제거하여 정의

// 학습 데이터의 크기가(27012, 22) 임을 확인, 특징 22개 데이터의 크기는 27012 이다.

 

// 더미화

// 샘플 대비 특징이 많지 않고, 범주형 변수의 개수도 많지 않아 더미화를 하더라도 큰 문제가 없다고 판단

 

* 결측 대체

// 원 데이터에는 결측이 없으나, 과거 거래와 관련돈 변수를 부착하는 과정에서 과거가 없는 데이터에 대한 결측이 생성된다.

 

* 모델 재학습

// 학습 데이터와 평가 데이터를 부착하고, 재학습을 실시함.

// 시간이 허락되면 해주는 것이 바람직하다.

 

* 실습

// 샘플 대비 특징이 매우 적다는 것은 더미화 가능하다

// 샘플이 충분히 많이 있으므로 트리 뿐만 아니라 트리 기반의 앙상블도 적절함.

 

* 더미화시킴

 

* 변수 부착 과정에서 생성된 결측 대체

 

// key 가 모델 function

 

// sklearn.metrics.mean_absolute_error 를 사용함.

 

// LGB 은 아스키 코드가 포함되면 작동안하는 경우가 있기 때문에 ndarrary 로 작업을 한다.

 

11. Ch 24. 진짜 문제를 해결해 보자 (2) - 아파트 실거래가 예측 - 05. (5) 모델 적용

 

* 파이프라인 구축

// 새로들어온 데이터의 아파트 값 예측

// 파이프라인 사용에 필요한 모든 요소를 pickle 을 사용하였음

 

// pckl 로 저장함.

// pickle.dump

// pickle 의 파일들은 binary 로 수행한다.

 

// pickle Documentation

docs.python.org/3/library/pickle.html

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” 1 or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”.

 

Comparison with json

There are fundamental differences between the pickle protocols and JSON (JavaScript Object Notation):

  • JSON is a text serialization format (it outputs unicode text, although most of the time it is then encoded to utf-8), while pickle is a binary serialization format;

  • JSON is human-readable, while pickle is not;

  • JSON is interoperable and widely used outside of the Python ecosystem, while pickle is Python-specific;

  • JSON, by default, can only represent a subset of the Python built-in types, and no custom classes; pickle can represent an extremely large number of Python types (many of them automatically, by clever usage of Python’s introspection facilities; complex cases can be tackled by implementing specific object APIs);

  • Unlike pickle, deserializing untrusted JSON does not in itself create an arbitrary code execution vulnerability.

// 솔직히 난 json 타입을 더 선호하기는 하던데..

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 28 회차 미션 시작]

 

* 복습

 - 마지막 미션!!!!

 - 범주형 변수 문자에 대한 처리 방법

 - 이상치 제거.. 그리고 스케일링

 


[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 01. 문제 정의 및 탐색 방법]

 

 

* 문제 정의

// 하나의 값에 치우친 데이터로 편향되는 문제

// 클래스 불균형 문제가 있는 모델은 정확도가 높고, 재현율이 매우 낮은 경향이 있다.

 

 

* 용어 정의

// 다수 클래스 : 대부분 샘플이 속한 클래스

// 소수 클래스 : 대부분 샘플이 속하지 않은 클래스

 

* 발생 원인

 

 

 

* 탐색 방법 (1) 클래스 불균형 비율

 

 

// 9 이상이면 편향된 모델이 학습될 가능성이 있다.

 

 

 

* 탐색 방법 (2) k- 최근접 이웃을 활용하는 방법

 

 

// k 값은 5~ 11 정도.. 보통은 11정도를 선호하는 수치이다.

 

* 문제 해결의 기본 아이디어

 

 

// 소수 클래스에 대한 결정 공간을 넓히는 것이다.

 


 

[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 02-1. 재샘플링 - 오버샘플링과 언더 샘플링(이론)]

 

 

 

* 분류 : 오버샘플링과 언더샘플링

 

 

 

* 어디에 만들고 어느 것을 지울까?

// 결정 경계에 가까운 다수 클래스 샘플을 제거하고, 결정 경계에 가까운 소수 클래스 샘플을 생성해야 한다.

 

 

// 평가 데이터에 대해서는 절대로 재샘플링을 적용하면 안된다!!!!

 

* 대표적인 오버샘플링 알고리즘 : SMOTE

 

 

 

 

* imblearn.over_sampling.SMOTE Documentation

imbalanced-learn.org/stable/generated/imblearn.over_sampling.SMOTE.html

classimblearn.over_sampling.SMOTE(*, sampling_strategy='auto', random_state=None, k_neighbors=5, n_jobs=None)[source]

Class to perform over-sampling using SMOTE.

This object is an implementation of SMOTE - Synthetic Minority Over-sampling Technique as presented in [1].

Read more in the User Guide.

 

Parameters

sampling_strategyfloat, str, dict or callable, default=’auto’

Sampling information to resample the data set.

  • When float, it corresponds to the desired ratio of the number of samples in the minority class over the number of samples in the majority class after resampling. Therefore, the ratio is expressed as 

     where 

     is the number of samples in the minority class after resampling and 

     is the number of samples in the majority class.

    Warning

    float is only available for binary classification. An error is raised for multi-class classification.

  • When str, specify the class targeted by the resampling. The number of samples in the different classes will be equalized. Possible choices are:

    'minority': resample only the minority class;

    'not minority': resample all classes but the minority class;

    'not majority': resample all classes but the majority class;

    'all': resample all classes;

    'auto': equivalent to 'not majority'.

  • When dict, the keys correspond to the targeted classes. The values correspond to the desired number of samples for each targeted class.

  • When callable, function taking y and returns a dict. The keys correspond to the targeted classes. The values correspond to the desired number of samples for each class.

random_stateint, RandomState instance, default=None

Control the randomization of the algorithm.

  • If int, random_state is the seed used by the random number generator;

  • If RandomState instance, random_state is the random number generator;

  • If None, the random number generator is the RandomState instance used by np.random.

k_neighborsint or object, default=5

If int, number of nearest neighbours to used to construct synthetic samples. If object, an estimator that inherits from sklearn.neighbors.base.KNeighborsMixin that will be used to find the k_neighbors.

n_jobsint, default=None

Number of CPU cores used during the cross-validation loop. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

 

* 대표적인 언더샘플링 알고리즘 : NearMiss

// 평균 거리가 짧은 다수 클래스 샘플을 순서대로 제거하는 방법이다.

 

 

// version 2 소수 클래스 샘플까지의 평균 거리를 사용한다.

 

* imblearn.under_sampling.NearMiss Documentation

imbalanced-learn.org/stable/generated/imblearn.under_sampling.NearMiss.html

classimblearn.under_sampling.NearMiss(*, sampling_strategy='auto', version=1, n_neighbors=3, n_neighbors_ver3=3, n_jobs=None)[source]

Class to perform under-sampling based on NearMiss methods.

Read more in the User Guide.

 

Parameters

sampling_strategyfloat, str, dict, callable, default=’auto’

Sampling information to sample the data set.

  • When float, it corresponds to the desired ratio of the number of samples in the minority class over the number of samples in the majority class after resampling. Therefore, the ratio is expressed as 

     where 

     is the number of samples in the minority class and 

     is the number of samples in the majority class after resampling.

    Warning

    float is only available for binary classification. An error is raised for multi-class classification.

  • When str, specify the class targeted by the resampling. The number of samples in the different classes will be equalized. Possible choices are:

    'majority': resample only the majority class;

    'not minority': resample all classes but the minority class;

    'not majority': resample all classes but the majority class;

    'all': resample all classes;

    'auto': equivalent to 'not minority'.

  • When dict, the keys correspond to the targeted classes. The values correspond to the desired number of samples for each targeted class.

  • When callable, function taking y and returns a dict. The keys correspond to the targeted classes. The values correspond to the desired number of samples for each class.

versionint, default=1

Version of the NearMiss to use. Possible values are 1, 2 or 3.

n_neighborsint or object, default=3

If int, size of the neighbourhood to consider to compute the average distance to the minority point samples. If object, an estimator that inherits from sklearn.neighbors.base.KNeighborsMixin that will be used to find the k_neighbors.

n_neighbors_ver3int or object, default=3

If int, NearMiss-3 algorithm start by a phase of re-sampling. This parameter correspond to the number of neighbours selected create the subset in which the selection will be performed. If object, an estimator that inherits from sklearn.neighbors.base.KNeighborsMixin that will be used to find the k_neighbors.

n_jobsint, default=None

Number of CPU cores used during the cross-validation loop. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

 


[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 02-2. 재샘플링 - 오버샘플링과 언더 샘플링(실습)]

 

 

// kNN 을 사용해서 클래스 불균형도 테스트를 해준다.

// KNeighborsClassifier

// 재현율 0% 로 불균형이 심각한 수준이라 볼 수 있다.

 

 

 

 

 

 

[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 03-1 비용 민감 모델 (이론)]

 

 

// 모델의 학습 변경한 모델이라고 볼 수 있다. 전처리라고 보기는 좀 어렵다.

 

* 정의

// 비용을 위양성 비용보다 크게 설정

 

 

 

* 확률 모델

 

 

 

* 관련문법: .predict_proba

 

 

 

* Tip.Numpy 와 Pandas 잘 쓰는 기본 원칙 : 가능하면 배열 단위 연산을 하라

// 유니버설 함수, 브로드캐스팅, 마스크 연산을 최대한 활용

 

 

 

* 비확률 모델 (1) 서포트 벡터 머신

 

 

 

* 비확률 모델 (2) 의사결정 나무

 

 

 

* 관련문법 : class_weight

 


[05. Part 5) Ch 20. 편향된 모델은 쓸모 없어 - 클래스 불균형 문제 - 03-2 비용 민감 모델 (실습)]

 

* 실습

// kNN 을 사용한 클래스 불균형 테스트들을 사용

 

 

// cost_sensitive_model 의 함수를 만들어 준다.

 

// 둔감하다는 표현이 더 좋은 표현이라고 생각하면 된다.

 

 

 

// class weight 도 튜닝을 해야 한다고 보면 된다.

 

// sklearn.svm.SVC Documentation

scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html

class sklearn.svm.SVC(*, C=1.0, kernel='rbf', degree=3, gamma='scale', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape='ovr', break_ties=False, random_state=None)

C-Support Vector Classification.

The implementation is based on libsvm. The fit time scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples. For large datasets consider using sklearn.svm.LinearSVC or sklearn.linear_model.SGDClassifier instead, possibly after a sklearn.kernel_approximation.Nystroem transformer.

The multiclass support is handled according to a one-vs-one scheme.

For details on the precise mathematical formulation of the provided kernel functions and how gamma, coef0 and degree affect each other, see the corresponding section in the narrative documentation: Kernel functions.

Read more in the User Guide.

 

Parameters

Cfloat, default=1.0

Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.

kernel{‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’}, default=’rbf’

Specifies the kernel type to be used in the algorithm. It must be one of ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’ or a callable. If none is given, ‘rbf’ will be used. If a callable is given it is used to pre-compute the kernel matrix from data matrices; that matrix should be an array of shape (n_samples, n_samples).

degreeint, default=3

Degree of the polynomial kernel function (‘poly’). Ignored by all other kernels.

gamma{‘scale’, ‘auto’} or float, default=’scale’

Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’.

  • if gamma='scale' (default) is passed then it uses 1 / (n_features * X.var()) as value of gamma,

  • if ‘auto’, uses 1 / n_features.

Changed in version 0.22: The default value of gamma changed from ‘auto’ to ‘scale’.

coef0float, default=0.0

Independent term in kernel function. It is only significant in ‘poly’ and ‘sigmoid’.

shrinkingbool, default=True

Whether to use the shrinking heuristic. See the User Guide.

probabilitybool, default=False

Whether to enable probability estimates. This must be enabled prior to calling fit, will slow down that method as it internally uses 5-fold cross-validation, and predict_proba may be inconsistent with predict. Read more in the User Guide.

tolfloat, default=1e-3

Tolerance for stopping criterion.

cache_sizefloat, default=200

Specify the size of the kernel cache (in MB).

class_weightdict or ‘balanced’, default=None

Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y))

verbosebool, default=False

Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context.

max_iterint, default=-1

Hard limit on iterations within solver, or -1 for no limit.

decision_function_shape{‘ovo’, ‘ovr’}, default=’ovr’

Whether to return a one-vs-rest (‘ovr’) decision function of shape (n_samples, n_classes) as all other classifiers, or the original one-vs-one (‘ovo’) decision function of libsvm which has shape (n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one (‘ovo’) is always used as multi-class strategy. The parameter is ignored for binary classification.

Changed in version 0.19: decision_function_shape is ‘ovr’ by default.

New in version 0.17: decision_function_shape=’ovr’ is recommended.

Changed in version 0.17: Deprecated decision_function_shape=’ovo’ and None.

break_tiesbool, default=False

If true, decision_function_shape='ovr', and number of classes > 2, predict will break ties according to the confidence values of decision_function; otherwise the first class among the tied classes is returned. Please note that breaking ties comes at a relatively high computational cost compared to a simple predict.

New in version 0.22.

random_stateint or RandomState instance, default=None

Controls the pseudo random number generation for shuffling the data for probability estimates. Ignored when probability is False. Pass an int for reproducible output across multiple function calls. See Glossary.

 

Attributes

support_ndarray of shape (n_SV,)

Indices of support vectors.

support_vectors_ndarray of shape (n_SV, n_features)

Support vectors.

n_support_ndarray of shape (n_class,), dtype=int32

Number of support vectors for each class.

dual_coef_ndarray of shape (n_class-1, n_SV)

Dual coefficients of the support vector in the decision function (see Mathematical formulation), multiplied by their targets. For multiclass, coefficient for all 1-vs-1 classifiers. The layout of the coefficients in the multiclass case is somewhat non-trivial. See the multi-class section of the User Guide for details.

coef_ndarray of shape (n_class * (n_class-1) / 2, n_features)

Weights assigned to the features (coefficients in the primal problem). This is only available in the case of a linear kernel.

coef_ is a readonly property derived from dual_coef_ and support_vectors_.

intercept_ndarray of shape (n_class * (n_class-1) / 2,)

Constants in decision function.

fit_status_int

0 if correctly fitted, 1 otherwise (will raise warning)

classes_ndarray of shape (n_classes,)

The classes labels.

probA_ndarray of shape (n_class * (n_class-1) / 2)probB_ndarray of shape (n_class * (n_class-1) / 2)

If probability=True, it corresponds to the parameters learned in Platt scaling to produce probability estimates from decision values. If probability=False, it’s an empty array. Platt scaling uses the logistic function 1 / (1 + exp(decision_value * probA_ + probB_)) where probA_ and probB_ are learned from the dataset [2]. For more information on the multiclass case and training procedure see section 8 of [1].

class_weight_ndarray of shape (n_class,)

Multipliers of parameter C for each class. Computed based on the class_weight parameter.

shape_fit_tuple of int of shape (n_dimensions_of_X,)

Array dimensions of training vector X.

 

Methods

decision_function(X)

Evaluates the decision function for the samples in X.

fit(X, y[, sample_weight])

Fit the SVM model according to the given training data.

get_params([deep])

Get parameters for this estimator.

predict(X)

Perform classification on samples in X.

score(X, y[, sample_weight])

Return the mean accuracy on the given test data and labels.

set_params(**params)

Set the parameters of this estimator.

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - 각 불균형 문제에 대해서 샘플링 및 비용 민감 모델을 어떻게 다룰 것인지에 대해서 학습했다.

 

 

 

https://bit.ly/3m7bW22

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 27 회차 미션 시작]

 

* 복습

 - sklearn.impute.SimpleImputer, fillna를 이용해서 ffill, bfill  처리

 - 결측치 예측 모델 활용 방법

 



[04. Part 4) Ch 18. 문자보다는 숫자 범주형 변수 문제 - 01. 문제 정의 및 해결 방법]

* 문제 정의

 - 데이터에 범주형 변수가 포함되어 있어, 대다수의 지도 학습 모델이 학습되지 않거나 비정상적으로 학습되는 문제를 의미

  . str 타입의 범주형 변수가 포함되면 대다수의 지도 학습 모델 자체가 학습이 되지 않음

  . int 혹은 float 타입의 범주형 변수는 모델 학습은 되나, 비정상적으로 학습이 되지만, 입문자는 이를 놓치는 경우가 종종있다.

 

 - 모델 학습을 위해 범주형 변수는 반드시 숫자로 변환되어야 하지만, 임의로 설정하는 것은 매우 부적절하다.

  . (예시) 종교 변수 : 기독교 = 1, 불교 = 2, 천주교 =3

   불교는 기독교의 2배라는 등의 대수 관계가 실제로 존재하지 않지만, 이처럼 변환하면 비상적인 관계가 생성된다.

// 적절한 숫자로 변화 되어야 한다.

 

 - 특히, 코드화된 범주형 변수도 적절한 숫자로 변환해줘야 한다.

 

* 범주형 변수 판별

 - 범주형 변수는 상태 공간의 크기가 유한한 변수를 의미하며, 반드시 모데인이나 변수의 상태 공간을 바탕으로 판단해야 한다.

 

 - int 혹은 float 타입으로 정의된 변수는 반드시 연속형 변수가 아닐 수 있다는 점에 주의해야 한다.

 

 - (예시) 월(month)은 비록 숫자지만 범주형 변수이다.

 

* 범주형 변수 변환 방법 (1) 더미화

 - 가장 일반적인 범주형 변수를 변환하는 방법으로, 범주형 변수가 특정 값을 취하는지 여부를 나타내는 더미 변수를 생성하는 방법

// 추론할 수 있기 때문에.. 있으나마나한 데이터이기 때문에 그렇다.

// Tree 계열에서는 설명력을 위해서 넣는 경우도 있다.

 

* 범주형 변수 변환 방법 (2) 연속형 변수로 치환

 - 범주형 변수의 상태 공간 크기가 클 때, 더미화는 과하게 많은 변수를 추가해서 차원 저주 문제로 이어질 수 있다.

 

 - 라벨 정보를 활용하여 범주 변수를 연속형 변수로 치환하면 기존 변수가 가지는 일부 손실될 수 있고 활용이 어렵다는 단점이 있으나, 차원의 크기가 변하지 않으며 더 효율적인 변수로 변환할 수 있다는 장점이 있다.

 

 


 

[04. Part 4) Ch 18. 문자보다는 숫자 범주형 변수 문제 - 02. 관련 문법 및 실습]

* Series.unique( )

 - Seires 에 포함된 유니크한 값을 반환해주는 함수로, 상태 공간을 확인하는데 사용

 

* feature_engine.categorical_encoders.OneHotCategoricalEncoder

 - 더미화를 하기 위한 함수로, 활용 방법은 sklearn 의 인스턴스의 활용 방법과 유사하다.

 

 - 주요 입력

  . variables : 더미화 대상이 되는 범주형 변수의 이름 목록 (주의 : 해당 변수는 반드시 str 타입이어야 한다.)

  . drop_last : 한 범주 변수로부터 만든 더미 변수 가운데 마지막 더미 변수를 제거할 지를 결정

  . top_categories : 한 범주 변수로부터 만드는 더미 변수 개수를 설정하며, 빈도 기준으로 자른다.

 

 - 참고 : pandas.get_dummies( ) 는 이 함수보다 사용이 휠씬 간단하지만, 학습 데이터에 포함된 범주형 변수를 처리한 방식으로 새로 들어온 데이터에 적용이 불가능하기 때문에, 실제적으로 활용이 어렵다.

 

* 실습

// 범주형 변수 들을 판별 하고 난 다음에 더미화를 이용해서 범주 변수들을 처리 한다.

 

// pandas.Series.unique Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html

Series.unique()

Return unique values of Series object.

Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort.

 

Returns

ndarray or ExtensionArray

The unique values returned as a NumPy array. See Notes.

 

// feature_engine.categorical_encoders.OneHotCategoricalEncoder Documentation

feature-engine.readthedocs.io/en/latest/encoders/OneHotCategoricalEncoder.html

classfeature_engine.categorical_encoders.OneHotCategoricalEncoder(top_categories=None, variables=None, drop_last=False)

One hot encoding consists in replacing the categorical variable by a combination of binary variables which take value 0 or 1, to indicate if a certain category is present in an observation.

Each one of the binary variables are also known as dummy variables. For example, from the categorical variable “Gender” with categories ‘female’ and ‘male’, we can generate the boolean variable “female”, which takes 1 if the person is female or 0 otherwise. We can also generate the variable male, which takes 1 if the person is “male” and 0 otherwise.

The encoder has the option to generate one dummy variable per category, or to create dummy variables only for the top n most popular categories, that is, the categories that are shown by the majority of the observations.

If dummy variables are created for all the categories of a variable, you have the option to drop one category not to create information redundancy. That is, encoding into k-1 variables, where k is the number if unique categories.

The encoder will encode only categorical variables (type ‘object’). A list of variables can be passed as an argument. If no variables are passed as argument, the encoder will find and encode categorical variables (object type).

The encoder first finds the categories to be encoded for each variable (fit).

The encoder then creates one dummy variable per category for each variable (transform).

Note: new categories in the data to transform, that is, those that did not appear in the training set, will be ignored (no binary variable will be created for them).

Parameters

  • top_categories (int, default=None) – If None, a dummy variable will be created for each category of the variable. Alternatively, top_categories indicates the number of most frequent categories to encode. Dummy variables will be created only for those popular categories and the rest will be ignored. Note that this is equivalent to grouping all the remaining categories in one group.

  • variables (list) – The list of categorical variables that will be encoded. If None, the encoder will find and select all object type variables.

  • drop_last (boolean, default=False) – Only used if top_categories = None. It indicates whether to create dummy variables for all the categories (k dummies), or if set to True, it will ignore the last variable of the list (k-1 dummies).

fit(X, y=None)[source]

Learns the unique categories per variable. If top_categories is indicated, it will learn the most popular categories. Alternatively, it learns all unique categories per variable.

Parameters

  • X (pandas dataframe of shape = [n_samples, n_features]) – The training input samples. Can be the entire dataframe, not just seleted variables.

  • y (pandas series, default=None) – Target. It is not needed in this encoded. You can pass y or None.

encoder_dict\_

The dictionary containing the categories for which dummy variables will be created.

Type

dictionary

transform(X)[source]

Creates the dummy / binary variables.

Parameters

X (pandas dataframe of shape = [n_samples, n_features]) – The data to transform.

Returns

X_transformed – The shape of the dataframe will be different from the original as it includes the dummy variables.

Return type

pandas dataframe.


 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 01. 특징과 라벨 간 약한 관계 및 비선형]

* 들어가기전에

 - 변수 분포 문제란 일반화된 모델을 학습하는데 어려움이 있는 분포를 가지는 변수가 있어, 일반화된 모델을 학습하지 못하는 문제로, 입문자가 가장 쉽게 무시하고 접근하기 어려워하는 문제

 

 

* 문제 정의

 - 특징과 라벨 간 관계가 없거나 매우 약하다면, 어떠한 전처리 및 모델링을 하더라도 예측력이 높은 모델을 학습할 수 없다.

 

 - 그러나 특징과 라벨 간 비선형 관계가 존재한다면, 적절한 전처리를 모델 성능을 크게 향상 시킬 수 있다.

 - Tip. 대다수의 머신러닝 모델은 선형식을 포함한다.

 

* 해결 방안

 - 가장 이상적인 해결 방안은 각 특징에 대해, 특징과 라벨 간 관계를 나타내는 그래프를 통해 적절한 특징 변환을 수행해야 한다.

// 어떤 것이 좋을지 모르기 때문에 다 만들어서 확인을 해보는 것이다.

 

 

 - 하지만 특징 개수가 많고, 다른 특징에 의한 영향도 존재하는 등 그래프를 통해 적절한 변환 방법을 선택하는 것은 쉽지 않아, 다양한 변환 방법을 사용하여 특징을 생성한 뒤 특징 선택을 수행해야 한다.

 

* 실습

// 5겹 교차 검증 기반의 평가를 수행한다.

// 로그와 제곱 관련 변수만 추가했을 뿐인데 성능이 좋아졌다.

// 특징을 선택을 할때 무조건 좋아 지는 것은 아니다.


[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 02. 이상치 제거 (1) IQR 규칙 활용]

 

* 문제 정의 및 해결 방안

 - 변수 범위에서 많이 벗어난 아주 작은 값이나 아주 큰 값으로, 일반화된 모델을 생성하는데 악영향을 끼치는 값으로 이상치를 포함하는 레코드를 제거하는 방법으로 이상치를 제거한다. (절대 추정의 대상이 아님에 주의)

 

* 이상치 판단 방법 1. IQR 규칙 활용

 - 변수별로 IQR 규칙을 만족하지 않는 샘플들을 판단하여 삭제 하는 방법

 - 직관적이고 사용이 간편하다는 장점이 있지만, 단일 변수로 이상치를 판단하기 어려운 경우가 있다는 문제가 있다. (이전 페이지의 그림에서 표시된 이상치의 X 값은 이상치라고 보기 힘든 구간에 있었음에 주목한다.)

 

 

* numpy.quantile

 - Array 의 q번째 quantile 을 구하는 함수

 - 주요 입력

  . a : input array (list, ndarray, array 등)

  . q : quantile (0 과 1 사이)

 

* 실습

// 이상치가 있는 경우를 지워줘야 한다.

// 이상치의 비율이 30% 이상일 수는 없고, 1% 미만인것이 바람직하다.

 

// numpy.quantile Documentation

numpy.org/doc/stable/reference/generated/numpy.quantile.html

numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)

 

Compute the q-th quantile of the data along the specified axis.

New in version 1.15.0.

 

Parameters

aarray_like

Input array or object that can be converted to an array.

qarray_like of float

Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.

axis{int, tuple of int, None}, optional

Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.

outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.

overwrite_inputbool, optional

If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.

interpolation{‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}

This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points i < j:

  • linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.

  • lower: i.

  • higher: j.

  • nearest: i or j, whichever is nearest.

  • midpoint: (i + j) / 2.

keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.

 

Returns

quantilescalar or ndarray

If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

 


[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 03. 이상치 제거 (2) 밀도 기반 군집화 활용]

 

* 이상치 판단 방법 2. 밀도 기반 군집화 수행

// 특정 반경내에서는 중심점.. 중심점에 안 들어오면 경계점 그 모두에 속하지 않는 것들이 이상치라고 부른다.

 

* sklearn.cluster.DBSCAN Documentation

scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html

class sklearn.cluster.DBSCAN(eps=0.5, *, min_samples=5, metric='euclidean', metric_params=None, algorithm='auto', leaf_size=30, p=None, n_jobs=None)

Perform DBSCAN clustering from vector array or distance matrix.

DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density.

Read more in the User Guide.

 

Parameters

epsfloat, default=0.5

The maximum distance between two samples for one to be considered as in the neighborhood of the other. This is not a maximum bound on the distances of points within a cluster. This is the most important DBSCAN parameter to choose appropriately for your data set and distance function.

min_samplesint, default=5

The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.

metricstring, or callable, default=’euclidean’

The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by sklearn.metrics.pairwise_distances for its metric parameter. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. X may be a Glossary, in which case only “nonzero” elements may be considered neighbors for DBSCAN.

New in version 0.17: metric precomputed to accept precomputed sparse matrix.

metric_paramsdict, default=None

Additional keyword arguments for the metric function.

New in version 0.19.

algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’

The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details.

leaf_sizeint, default=30

Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.

pfloat, default=None

The power of the Minkowski metric to be used to calculate distance between points.

n_jobsint, default=None

The number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

 

Attributes

core_sample_indices_ndarray of shape (n_core_samples,)

Indices of core samples.

components_ndarray of shape (n_core_samples, n_features)

Copy of each core sample found by training.

labels_ndarray of shape (n_samples)

Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1.

 

* 실습

// cdist 은 DBSCAN 을 볼때 참고할 때를 위해서 가져온 library 이다.

 

// 파라미터를 조정하면서 값들을 확인한다.


 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 04. 특징 간 상관성 제거]

* 문제 정의

// 특징간 상관성이 높으면 강건한 파라미터 추정이 어렵다.

 

* 해결방법 (1) VIF 활용

// 다른 특징을 사용한 회귀 모델이 높은 R^2 을 보이는 경우

 

* 해결방법 (2) 주성분 분석

// 특징이 서로 직교

 

* sklearn.decomposition.PCA Documentation

scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html

class sklearn.decomposition.PCA(n_components=None, *, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', random_state=None)

Principal component analysis (PCA).

Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. The input data is centered but not scaled for each feature before applying the SVD.

It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, depending on the shape of the input data and the number of components to extract.

It can also use the scipy.sparse.linalg ARPACK implementation of the truncated SVD.

Notice that this class does not support sparse input. See TruncatedSVD for an alternative with sparse data.

Read more in the User Guide.

 

Parameters

n_componentsint, float, None or str

Number of components to keep. if n_components is not set all components are kept:

n_components == min(n_samples, n_features)

If n_components == 'mle' and svd_solver == 'full', Minka’s MLE is used to guess the dimension. Use of n_components == 'mle' will interpret svd_solver == 'auto' as svd_solver == 'full'.

If 0 < n_components < 1 and svd_solver == 'full', select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components.

If svd_solver == 'arpack', the number of components must be strictly less than the minimum of n_features and n_samples.

Hence, the None case results in:

n_components == min(n_samples, n_features) - 1

copybool, default=True

If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead.

whitenbool, optional (default False)

When True (False by default) the components_ vectors are multiplied by the square root of n_samples and then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances.

Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometime improve the predictive accuracy of the downstream estimators by making their data respect some hard-wired assumptions.

svd_solverstr {‘auto’, ‘full’, ‘arpack’, ‘randomized’}If auto :

The solver is selected by a default policy based on X.shape and n_components: if the input data is larger than 500x500 and the number of components to extract is lower than 80% of the smallest dimension of the data, then the more efficient ‘randomized’ method is enabled. Otherwise the exact full SVD is computed and optionally truncated afterwards.

If full :

run exact full SVD calling the standard LAPACK solver via scipy.linalg.svd and select the components by postprocessing

If arpack :

run SVD truncated to n_components calling ARPACK solver via scipy.sparse.linalg.svds. It requires strictly 0 < n_components < min(X.shape)

If randomized :

run randomized SVD by the method of Halko et al.

New in version 0.18.0.

tolfloat >= 0, optional (default .0)

Tolerance for singular values computed by svd_solver == ‘arpack’.

New in version 0.18.0.

iterated_powerint >= 0, or ‘auto’, (default ‘auto’)

Number of iterations for the power method computed by svd_solver == ‘randomized’.

New in version 0.18.0.

random_stateint, RandomState instance, default=None

Used when svd_solver == ‘arpack’ or ‘randomized’. Pass an int for reproducible results across multiple function calls. See Glossary.

New in version 0.18.0.

 

Attributes

components_array, shape (n_components, n_features)

Principal axes in feature space, representing the directions of maximum variance in the data. The components are sorted by explained_variance_.

explained_variance_array, shape (n_components,)

The amount of variance explained by each of the selected components.

Equal to n_components largest eigenvalues of the covariance matrix of X.

New in version 0.18.

explained_variance_ratio_array, shape (n_components,)

Percentage of variance explained by each of the selected components.

If n_components is not set then all components are stored and the sum of the ratios is equal to 1.0.

singular_values_array, shape (n_components,)

The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the n_components variables in the lower-dimensional space.

New in version 0.19.

mean_array, shape (n_features,)

Per-feature empirical mean, estimated from the training set.

Equal to X.mean(axis=0).

n_components_int

The estimated number of components. When n_components is set to ‘mle’ or a number between 0 and 1 (with svd_solver == ‘full’) this number is estimated from input data. Otherwise it equals the parameter n_components, or the lesser value of n_features and n_samples if n_components is None.

n_features_int

Number of features in the training data.

n_samples_int

Number of samples in the training data.

noise_variance_float

The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. It is required to compute the estimated data covariance and score samples.

Equal to the average of (min(n_features, n_samples) - n_components) smallest eigenvalues of the covariance matrix of X.

 

* 실습

// 특징간 상관 관계가 너무 크다.

// VIF 계산. LinearRegression 으로 작업한 후 R sqaure 

 

// PCA 를 활용

 


 

 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 05. 변수 치우침 제거]

 

* 문제 정의

// 치우친 반대 방향의 값(꼬리 부분) 들이 이상치 처럼 작용할 가능성이 크다.

 

* 탐색 방법 : 왜도(skewness)

 

// 왜도의 절대값이 1.5이상 이면 치우쳤다고 판단할 수 있다.

 

* scipy.stats

 - scipy.stats.mode

 - scipy.stats.skew

 - scipy.stats.kurtosis

 

* 해결방안

 

* 실습

 

// scipy.stats.mode Documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html

scipy.stats.mode(a, axis=0, nan_policy='propagate')[source]

Return an array of the modal (most common) value in the passed array.

If there is more than one such value, only the smallest is returned. The bin-count for the modal bins is also returned.

Parameters

aarray_like

n-dimensional array of which to find mode(s).

axisint or None, optional

Axis along which to operate. Default is 0. If None, compute over the whole array a.

nan_policy{‘propagate’, ‘raise’, ‘omit’}, optional

Defines how to handle when input contains nan. The following options are available (default is ‘propagate’):

  • ‘propagate’: returns nan

  • ‘raise’: throws an error

  • ‘omit’: performs the calculations ignoring nan values

Returns

modendarray

Array of modal values.

countndarray

Array of counts for each mode.

 

 

//scipy.stats.skew Documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html

scipy.stats.skew(a, axis=0, bias=True, nan_policy='propagate')[source]

Compute the sample skewness of a data set.

For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero means that there is more weight in the right tail of the distribution. The function skewtest can be used to determine if the skewness value is close enough to zero, statistically speaking.

 

Parameters

andarray

Input array.

axisint or None, optional

Axis along which skewness is calculated. Default is 0. If None, compute over the whole array a.

biasbool, optional

If False, then the calculations are corrected for statistical bias.

nan_policy{‘propagate’, ‘raise’, ‘omit’}, optional

Defines how to handle when input contains nan. The following options are available (default is ‘propagate’):

  • ‘propagate’: returns nan

  • ‘raise’: throws an error

  • ‘omit’: performs the calculations ignoring nan values

Returns

skewnessndarray

The skewness of values along an axis, returning 0 where all values are equal.

 

 

 

// scipy.stats.kurtosis Documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html

scipy.stats.kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate')[source]

Compute the kurtosis (Fisher or Pearson) of a dataset.

Kurtosis is the fourth central moment divided by the square of the variance. If Fisher’s definition is used, then 3.0 is subtracted from the result to give 0.0 for a normal distribution.

If bias is False then the kurtosis is calculated using k statistics to eliminate bias coming from biased moment estimators

Use kurtosistest to see if result is close enough to normal.

 

Parameters

aarray

Data for which the kurtosis is calculated.

axisint or None, optional

Axis along which the kurtosis is calculated. Default is 0. If None, compute over the whole array a.

fisherbool, optional

If True, Fisher’s definition is used (normal ==> 0.0). If False, Pearson’s definition is used (normal ==> 3.0).

biasbool, optional

If False, then the calculations are corrected for statistical bias.

nan_policy{‘propagate’, ‘raise’, ‘omit’}, optional

Defines how to handle when input contains nan. ‘propagate’ returns nan, ‘raise’ throws an error, ‘omit’ performs the calculations ignoring nan values. Default is ‘propagate’.

 

Returns

kurtosisarray

The kurtosis of values along an axis. If all values are equal, return -3 for Fisher’s definition and 0 for Pearson’s definition.


 

[05. Part 5) Ch 19. 이상적인 분포를 만들순 없을까 변수 분포 문제 - 06. 스케일링]

* 문제 정의

// 특징간 스케일이 달라서 발생하는 문제이다.

// 거리 기반 모델 -> 스케일이 큰 변수에 영향을 받는 모델

// 작은것 -> 회귀모델, 서포트 벡터 머신, 신경망

// 영향이 없는 것 -> 나이브베이즈 의사결정나무

 

* 해결방법

// 스케일을 줄이는 것!

// standard Scaling 보다는 Min_max 스케일링이 좀 더 맞다고 본다.

 

* sklearn.preprocessing.MinMaxScaler & StandardScaler Documentation

- sklearn.preprocessing.MinMaxScaler

scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html

class sklearn.preprocessing.MinMaxScaler(feature_range=(0, 1), *, copy=True)

Transform features by scaling each feature to a given range.

This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.

The transformation is given by:

X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min

where min, max = feature_range.

This transformation is often used as an alternative to zero mean, unit variance scaling.

Read more in the User Guide.

 

Parameters

feature_rangetuple (min, max), default=(0, 1)

Desired range of transformed data.

copybool, default=True

Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).

 

Attributes

min_ndarray of shape (n_features,)

Per feature adjustment for minimum. Equivalent to min - X.min(axis=0) * self.scale_

scale_ndarray of shape (n_features,)

Per feature relative scaling of the data. Equivalent to (max - min) / (X.max(axis=0) - X.min(axis=0))

New in version 0.17: scale_ attribute.

data_min_ndarray of shape (n_features,)

Per feature minimum seen in the data

New in version 0.17: data_min_

data_max_ndarray of shape (n_features,)

Per feature maximum seen in the data

New in version 0.17: data_max_

data_range_ndarray of shape (n_features,)

Per feature range (data_max_ - data_min_) seen in the data

New in version 0.17: data_range_

n_samples_seen_int

The number of samples processed by the estimator. It will be reset on new calls to fit, but increments across partial_fit calls.

 

 

- sklearn.preprocessing.MinMaxScaler

scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html

class sklearn.preprocessing.StandardScaler(*, copy=True, with_mean=True, with_std=True)

Standardize features by removing the mean and scaling to unit variance

The standard score of a sample x is calculated as:

z = (x - u) / s

where u is the mean of the training samples or zero if with_mean=False, and s is the standard deviation of the training samples or one if with_std=False.

Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. Mean and standard deviation are then stored to be used on later data using transform.

Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual features do not more or less look like standard normally distributed data (e.g. Gaussian with 0 mean and unit variance).

For instance many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the L1 and L2 regularizers of linear models) assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected.

This scaler can also be applied to sparse CSR or CSC matrices by passing with_mean=False to avoid breaking the sparsity structure of the data.

Read more in the User Guide.

 

Parameters

copyboolean, optional, default True

If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned.

with_meanboolean, True by default

If True, center the data before scaling. This does not work (and will raise an exception) when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory.

with_stdboolean, True by default

If True, scale the data to unit variance (or equivalently, unit standard deviation).

 

Attributes

scale_ndarray or None, shape (n_features,)

Per feature relative scaling of the data. This is calculated using np.sqrt(var_). Equal to None when with_std=False.

New in version 0.17: scale_

mean_ndarray or None, shape (n_features,)

The mean value for each feature in the training set. Equal to None when with_mean=False.

var_ndarray or None, shape (n_features,)

The variance for each feature in the training set. Used to compute scale_. Equal to None when with_std=False.

n_samples_seen_int or array, shape (n_features,)

The number of samples processed by the estimator for each feature. If there are not missing samples, the n_samples_seen will be an integer, otherwise it will be an array. Will be reset on new calls to fit, but increments across partial_fit calls.

 


 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - 범주형 변수 문자에 대한 처리 방법

 - 이상적인 분포형에 대한 내용... 특히 스케일링. 이건 잘해야지~

 

 

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 26 회차 미션 시작]

 

* 복습

- 결측치 제거 및 groupby 등 함수 활용하기

 


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 03. 해결 방법 (2) 대표 값으로 대체]

* 대표 값으로 대체 (SimpleImpute)

 - 가장 널리 사용되는 방법이지만, (1) 소수 특징에 결측이 쏠린 경우와 (2) 특징 간 상관성이 큰 경우에는 활용하기 부적절하다.

 

 

* 관련문법 : sklearn 을 이용한 전처리 모델

 - sklearn 을 이용한 대부분의 전처리 모델의 활용 과정의 이해는 매우 중요하며, 특히 평가 데이터는 전처리 모델을 학습하는데 사용하지 않음에 주목해야 한다.

 

 

* 관련문법 : sklearn.impute.SimpleImputer

 

 - 결측이 있는 변수의 대표값으로 결측을 대체하는 인스턴스

 

 - 주요 입력

  . strategy : 대표 통계량을 지정 ('mean', 'most_frequent', 'median')

 

 - 변수 타입에 따라 두 개의 인스턴스를 같이 적용해야 할 수 있다.

 

* 실습

// 학습 데이터와 평가 데이터로 분리를 해주고.. -> model_selection 으로 통해서

 

// 대표값을 평균을 사용할지 최빈값을 사용할지 결정이 어렵다면 . 둘다 사용해야 한다.

// 데이터를 각각 분할 해서 사용한다.

 

 

// sklearn.impute.SimpleImputer Documentation

scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html

class sklearn.impute.SimpleImputer(*, missing_values=nan, strategy='mean', fill_value=None, verbose=0, copy=True, add_indicator=False)

Imputation transformer for completing missing values.

Read more in the User Guide.

New in version 0.20: SimpleImputer replaces the previous sklearn.preprocessing.Imputer estimator which is now removed.

 

Parameters

missing_valuesnumber, string, np.nan (default) or None

The placeholder for the missing values. All occurrences of missing_values will be imputed. For pandas’ dataframes with nullable integer dtypes with missing values, missing_values should be set to np.nan, since pd.NA will be converted to np.nan.

strategystring, default=’mean’

The imputation strategy.

  • If “mean”, then replace missing values using the mean along each column. Can only be used with numeric data.

  • If “median”, then replace missing values using the median along each column. Can only be used with numeric data.

  • If “most_frequent”, then replace missing using the most frequent value along each column. Can be used with strings or numeric data.

  • If “constant”, then replace missing values with fill_value. Can be used with strings or numeric data.

New in version 0.20: strategy=”constant” for fixed value imputation.

fill_valuestring or numerical value, default=None

When strategy == “constant”, fill_value is used to replace all occurrences of missing_values. If left to the default, fill_value will be 0 when imputing numerical data and “missing_value” for strings or object data types.

verboseinteger, default=0

Controls the verbosity of the imputer.

copyboolean, default=True

If True, a copy of X will be created. If False, imputation will be done in-place whenever possible. Note that, in the following cases, a new copy will always be made, even if copy=False:

  • If X is not an array of floating values;

  • If X is encoded as a CSR matrix;

  • If add_indicator=True.

add_indicatorboolean, default=False

If True, a MissingIndicator transform will stack onto output of the imputer’s transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won’t appear on the missing indicator even if there are missing values at transform/test time.

 

Attributes

statistics_array of shape (n_features,)

The imputation fill value for each feature. Computing statistics can result in np.nan values. During transform, features corresponding to np.nan statistics will be discarded.

indicator_sklearn.impute.MissingIndicator

Indicator used to add binary indicators for missing values. None if add_indicator is False.

 

Methods

fit(X[, y])

Fit the imputer on X.

fit_transform(X[, y])

Fit to data, then transform it.

get_params([deep])

Get parameters for this estimator.

set_params(**params)

Set the parameters of this estimator.

transform(X)

Impute all missing values in X.

 


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 03. 해결 방법 (3) 근처 값으로 대체]

 

// 시계열 변수에 한정이다. 일반 변수에는 사용할 수가 없다.

 

* 근처 값으로 대체

 - 시계열 변수인 경우에는 결측이 바로 이전 값 혹은 이후 값과 유사할 가능성이 높다.

 

* 관련문법 : DataFrame.fillna

 - 결측치를 특정 값이나 방법으로 채우는 함수

 

 - 주요 입력

  . value : 결측치를 대체할 값

  . method : 결측치를 대체할 방법

   .. ffill : 결측치 이전의 유효한 값 가운데 가장 가까운 값으로 채운다.

   .. bfill : 결측치 이후의 유효한 값 가운데 가장 가까운 값으로 채운다.

 

// ffill 로 먼저 채우주고, 만약에 V2 a 처럼 NaN 앞에 Value 가 없다면 bfill 로 채워준다.

 

* 실습

// 시간 순서가 꼬이면 안된다. 시계열에 대해서만 사용할 수 있다.

// 분할하기 전에 결측치 대체가 가능한 유일한 케이스라고 보면 된다.

 

// 새로 들어온 데이터는 bfill 처럼 바로 뒤에 값을 참조하기 어렵다. 그래서 ffill 을 먼저 사용하고, bfill 을 사용한다.

 

 

// DataFrame.fillna Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)

Fill NA/NaN values using the specified method.

Parameters

valuescalar, dict, Series, or DataFrame

Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list.

method{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None

Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap.

axis{0 or ‘index’, 1 or ‘columns’}

Axis along which to fill missing values.

inplacebool, default False

If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame).

limitint, default None

If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.

downcastdict, default is None

A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible).

 

Returns

DataFrame or None

Object with missing values filled or None if inplace=True.

 


[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 03. 해결 방법 (4) 결측치 예측 모델 활용]

* 결측치 예측 모델 정의

 - 결측이 발생하지 않은 컬럼을 바탕으로 결측치를 예측하는 모델을 학습하고 활용하는 방법

 

 - (예시) V2 열에 포함된 결측 값을 추정

 

* 결측치 예측 모델 활용

 - 결측치 예측 모델은 어느 상황에서도 무난하게 활용할 수 있으나, 사용 조건 및 단점을 반드시 숙지해야 한다.

 

 - 사용 조건 및 단점

  . 조건 1. 결측이 소수 컬럼에 쏠리면 안 된다.

  . 조건 2. 특징 간에 관계가 존재해야 한다.

  . 단점 : 다른 결측치 처리 방법에 비해 시간이 오래 소요된다.

 

 

* 관련문법 : sklearn.impute.KNNImputer

 

 - 결측이 아닌 값만 사용하여 이웃을 구한 뒤, 이웃들의 값의 대표값으로 결측을 대체하는 결측치 예측 모델

 

 - 주요 입력

  . n_neighbors : 이웃 수 (주의 : 너무 적으면 결측 대체가 정상적으로 이뤄지지 않을 수 있으므로, 5 정도가 적절)

 

 

* 실습

 // n_neighbors = 5 는 크게 잡는것 보다 적당한 수치로 잡아서 인스턴스화 작업을 한다.

 

 

// sklearn.impute.KNNImputer Documentation

scikit-learn.org/stable/modules/generated/sklearn.impute.KNNImputer.html

class sklearn.impute.KNNImputer(*, missing_values=nan, n_neighbors=5, weights='uniform', metric='nan_euclidean', copy=True, add_indicator=False)

Imputation for completing missing values using k-Nearest Neighbors.

Each sample’s missing values are imputed using the mean value from n_neighbors nearest neighbors found in the training set. Two samples are close if the features that neither is missing are close.

Read more in the User Guide.

New in version 0.22.

 

Parameters

missing_valuesnumber, string, np.nan or None, default=`np.nan`

The placeholder for the missing values. All occurrences of missing_values will be imputed. For pandas’ dataframes with nullable integer dtypes with missing values, missing_values should be set to np.nan, since pd.NA will be converted to np.nan.

n_neighborsint, default=5

Number of neighboring samples to use for imputation.

weights{‘uniform’, ‘distance’} or callable, default=’uniform’

Weight function used in prediction. Possible values:

  • ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally.

  • ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away.

  • callable : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights.

metric{‘nan_euclidean’} or callable, default=’nan_euclidean’

Distance metric for searching neighbors. Possible values:

  • ‘nan_euclidean’

  • callable : a user-defined function which conforms to the definition of _pairwise_callable(X, Y, metric, **kwds). The function accepts two arrays, X and Y, and a missing_values keyword in kwds and returns a scalar distance value.

copybool, default=True

If True, a copy of X will be created. If False, imputation will be done in-place whenever possible.

add_indicatorbool, default=False

If True, a MissingIndicator transform will stack onto the output of the imputer’s transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won’t appear on the missing indicator even if there are missing values at transform/test time.

 

Attributes

indicator_sklearn.impute.MissingIndicator

Indicator used to add binary indicators for missing values. None if add_indicator is False.

 

Methods

fit(X[, y])

Fit the imputer on X.

fit_transform(X[, y])

Fit to data, then transform it.

get_params([deep])

Get parameters for this estimator.

set_params(**params)

Set the parameters of this estimator.

transform(X)

Impute all missing values in X.


 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - sklearn.impute.SimpleImputer, fillna를 이용해서 ffill, bfill 을 어떻게 처리를 할 것인지에 대해서도 알아 보았다.

 - 결측치 예측 모델 활용 방법

 

 

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 24 회차 미션 시작]

 

* 복습

- merge, concat, apply, argsort, haversine 작업을 했었음. 

 



[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 05. 유형 (5) 데이터 요약이 포함되는 경우]

* 문제 정의 및 해결 방안

 - 보통 1 : N 병합인 경우에 사용되며, 거래 데이터 및 로그 데이터와 병합하는 경우에 주로 사용된다.

 

 - 중복 레코드를 포하하는 데이터를 요약한 후 병합 하는 방식으로 문제를 해결한다.

// 보통은 부모 데이터를 기준으로 요약을 하는 것이다.

 

* 관련문법 : DataFrame.groupby( )

 - 조건부 통계량 (조건에 따른 대상의 통계량)을 계산하기 위한 함수로 머신러닝 프로세스 뿐만 아니라, 통계 분석 등에서도 굉장히 자주 활용된다.

 

 - 주요 입력

  . by : 조건 변수 (컬럼명 혹은 컬럼명 리스트로 입력)

  . as_index : 조건 변수를 index 로 설정할 것인지 여부

 

 - 활용 예시

  . df.groupby(['성별'])['신장'].mean( ) # 성별 (조건)에 따른 신장 (대상)의 평균 (통계량)

 

* 실습

// merge 를 통해서 demo_df 에 rename 한 것을 붙이는 것이다.

 

// grouby 함수에 대해서는 지난번에도 다뤘던것 같은데, 다시 한번 중요하기에 다시금 Documentation 을 아래와 같이 첨부한다.

 

// pandas.DataFrame.groupby Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)[source]

Group DataFrame using a mapper or by a Series of columns.

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

 

Parameters

bymapping, function, label, or list of labels

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If an ndarray is passed, the values are used as-is determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Split along rows (0) or columns (1).

levelint, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particular level or levels.

as_indexbool, default True

For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

sortbool, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

group_keysbool, default True

When calling apply, add group keys to index to identify pieces.

squeezebool, default False

Reduce the dimensionality of the return type if possible, otherwise return a consistent type.

Deprecated since version 1.1.0.

observedbool, default False

This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers.

New in version 0.23.0.

dropnabool, default True

If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups

New in version 1.1.0.

 

Returns

DataFrameGroupBy

Returns a groupby object that contains information about the groups.

 

 


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 01. 문제 정의]

* 문제 정의

 - 데이터에 결측치가 있어, 모델 학습 자체가 되지 않는 문제

 

 - 결측치는 크게 NaN 과 None 으로 구분된다.

  . NaN : 값이 있어야 하는데 없는 결측으로, 대체, 추정, 예측 등으로 처리

  . None : 값이 없는게 값인 결측 (e.g., 직업 - 백수) 으로 새로운 값으로 정의하는 방식으로 처리

 

 - 결측치 처리 방법 자체는 매우 간단하나, 상황에 따른 처리 방법 선택이 매우 중요

 

* 용어 정의

 - 결측 레코드 : 결측치를 포함하는 레코드

 

 - 결측치 비율 : 결측 레코드 수 / 전체 레코드 개수


 

 

[04. Part 4) Ch 17. 왜 여기엔 값이 없을까 결측치 문제 - 02. 해결 방법 (1) 삭제]

* 행 단위 결측 삭제

 - 행 단위 결측 삭제는 결측 레코드를 삭제하는 매우 간단한 방법이지만, 두 가지 조건을 만족하는 경우에만 수행할 수 있다.

 

* 열 단위 결측 삭제

 - 열 다누이 결측 삭제는 결측 레코드를 포함하는 열을 삭제하는 매우 간단한 방법이지만, 두 가지 조건을 만족하는 경우에만 사용 가능하다.

  . 소수 변수에 결측이 많이 포함되어 있다.

  . 해당 변수들이 크게 중요하지 않음 (by 도메인 지식)

 

* 관련 문법 : Series / DataFrame.isnull

 - 값이 결측이면 True 를, 그렇지 않으면 False 를 반환 (notnull 함수와 반대로 작동)

 

 - sum 함수와 같이 사용하여 결측치 분포를 확인하는데 주로 사용

 

* 관련문법 : DataFrame.dropna

 - 결측치가 포함된 행이나 열을 제거하는데 사용

 

 - 주요 입력

  . axis : 1 이면 결측이 포함된 열을 삭제하며, 0 이면 결측이 포함된 행을 삭제

  . how : 'any'면 결측이 하나라도 포함되면 삭제하며, 'all'이면 모든 갑싱 결측인 경우만 삭제 (주로 any 로 설정)

 

* 실습

// 학습데이터 기준으로 나눠야 한다.

 

// unique 한 값들을 습관적으로 찍어보는 것이 중요하다.

 

 

 

 

// pandas.DataFrame.isnull Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isnull.html

DataFrame.isnull()

Detect missing values.

Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True).

ReturnsDataFrame

Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value.

 

// pandas.Series.isnull Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isnull.html

Series.isnull()

Detect missing values.

Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True).

ReturnsSeries

Mask of bool values for each element in Series that indicates whether an element is not an NA value.

 

// pandas.DataFrame.dropna Documentation

 

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html

DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)[source]

Remove missing values.

See the User Guide for more on which values are considered missing, and how to work with missing data.

 

Parameters

axis{0 or ‘index’, 1 or ‘columns’}, default 0

Determine if rows or columns which contain missing values are removed.

  • 0, or ‘index’ : Drop rows which contain missing values.

  • 1, or ‘columns’ : Drop columns which contain missing value.

Changed in version 1.0.0: Pass tuple or list to drop on multiple axes. Only a single axis is allowed.

how{‘any’, ‘all’}, default ‘any’

Determine if row or column is removed from DataFrame, when we have at least one NA or all NA.

  • ‘any’ : If any NA values are present, drop that row or column.

  • ‘all’ : If all values are NA, drop that row or column.

threshint, optional

Require that many non-NA values.

subsetarray-like, optional

Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include.

inplacebool, default False

If True, do operation inplace and return None.

 

Returns

DataFrame

DataFrame with NA entries dropped from it.

 

// 참고를 위해서 series에서는 어떤식으로 dropna 가 이뤄지는지 찾아보았다.

// pandas.Series.dropna Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html#pandas.Series.dropna

Series.dropna(axis=0, inplace=False, how=None)[source]

Return a new Series with missing values removed.

See the User Guide for more on which values are considered missing, and how to work with missing data.

 

Parameters

axis{0 or ‘index’}, default 0

There is only one axis to drop values from.

inplacebool, default False

If True, do operation inplace and return None.

howstr, optional

Not in use. Kept for compatibility.

 

Returns

Series

Series with NA entries dropped from it.


 

 

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - 결측치 제거 및 groupby 등의 함수에 대해서 살펴 볼 수 있었다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 24 회차 미션 시작]

 

* 복습

- 파라미터 튜닝

 


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 03. 유형 (3) 포맷이 다른 키 변수가 있는 경우 (1) 참조 데이터가 필요 없는 경우]

* 참조 데이터가 필요 없는 경우의 병합

 

 - 시간과 날짜 컬럼 등은 데이터에 다라 포맷이 다른 경우가 잦음

 

 - 키 변수의 포맷이 다른 두 DataFrame 에 대해 merge 를 적용하면, 비정상적으로 병합이 이뤄질 수 있으므로, 하나의 컬럼을 다른 컬럼의 포맷에 맞게 변경해주는 작업이 필요하다.

 

* 관련 문법 : Series.apply

 

 - Series 에 있는 모든 요소에 func 을 일괄 적용하는 함수 (built-in 함수인 map 함수와 유사)

 

 - 주요 입력

  . func : Series 의 한 요소를 처리하는 함수

 

 - apply 함수는 머신러닝 코드의 효율성을 위해 굉장히 자주 사용된다.

 

* 실습

 

// df1 => 2018-01-01

// df2 => 2018년 1월 1일

// 으로 되어 있기 때문에 각각 포맷을 바꿔 줘야 한다.

 

// 함수를 짜서 각각 바꿔준다.

// 01 이 있기 때문에 int로 바꿔 준 다음에 1 의 string 타입으로 변경한것이다.

// 다음에는 merge 를 사용해서 각각 합쳐주는 방법이다.

 

// Series.apply Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html

Series.apply(func, convert_dtype=True, args=(), **kwds)

Invoke function on values of Series.

Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.

Parameters

funcfunction

Python function or NumPy ufunc to apply.

convert_dtypebool, default True

Try to find better dtype for elementwise function results. If False, leave as dtype=object.

argstuple

Positional arguments passed to func after the series value.

**kwds

Additional keyword arguments passed to func.

Returns

Series or DataFrame

If func returns a Series object the result will be a DataFrame.

 


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 03. 유형 (3) 포맷이 다른 키 변수가 있는 경우 (2) 참조 데이터가 필요한 경우]

 

* 참조 데이터가 필요한 경우의 병합

 

 - 도로명 주소 / 지번 주소, 회원명 / 회원 번호 등과 같이 일정한 패턴이 없이 포맷이 다른 경우에는 컬럼 값을 참조 데이터를 이용하여 변경해야 한다.

// Series 로 되어 있는 것이 참조 데이터이다.

 

* 관련 문법 : Series.to_dict( )

 - Seires 의 Index 를 key, Data 를 Value 로 하는 사전으로 변환

 

 - replace 등 사전을 입력받는 함수를 사용할 때 주로 사용

 

* 관련문법 : Series.replace

 - dict 을 입력 받아, Series 내에 있는 요소 가운데 key 와 같은 값을 value 로 변환해줌

 

 

* 실습

// ref_df 를 사전으로 변환. set_index 로 index 를 변경해준다.

 

// add_prefix( ) 찾아보기

 

// Padnas.Series.to_dict Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_dict.html

 

Series.to_dict(into=<class 'dict'>)

Convert Series to {label -> value} dict or dict-like object.

 

Parameters

intoclass, default dict

The collections.abc.Mapping subclass to use as the return object. Can be the actual class or an empty instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized.

 

Returns

collections.abc.Mapping

Key-value representation of Series.

 

 

// Pandas.Series.replace Documenation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html

Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')

Replace values given in to_replace with value.

Values of the Series are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value.

 

Parameters

to_replacestr, regex, list, dict, Series, int, float, or None

How to find the values that will be replaced.

  • numeric, str or regex:

    • numeric: numeric values equal to to_replace will be replaced with value

    • str: string exactly matching to_replace will be replaced with value

    • regex: regexs matching to_replace will be replaced with value

  • list of str, regex, or numeric:

    • First, if to_replace and value are both lists, they must be the same length.

    • Second, if regex=True then all of the strings in both lists will be interpreted as regexs otherwise they will match directly. This doesn’t matter much for value since there are only a few possible substitution regexes you can use.

    • str, regex and numeric rules apply as above.

  • dict:

    • Dicts can be used to specify different replacement values for different existing values. For example, {'a': 'b', 'y': 'z'} replaces the value ‘a’ with ‘b’ and ‘y’ with ‘z’. To use a dict in this way the value parameter should be None.

    • For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column ‘a’ and the value ‘z’ in column ‘b’ and replaces these values with whatever is specified in value. The value parameter should not be None in this case. You can treat this as a special case of passing two lists except that you are specifying the column to search in.

    • For a DataFrame nested dictionaries, e.g., {'a': {'b': np.nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with NaN. The value parameter should be None to use a nested dict in this way. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) cannot be regular expressions.

  • None:

    • This means that the regex argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If value is also None then this must be a nested dictionary or Series.

See the examples section for examples of each of these.

valuescalar, dict, list, str, regex, default None

Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed.

inplacebool, default False

If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True.

limitint, default None

Maximum size gap to forward or backward fill.

regexbool or same types as to_replace, default False

Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case to_replace must be None.

method{‘pad’, ‘ffill’, ‘bfill’, None}

The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.

Changed in version 0.23.0: Added to DataFrame.

 

Returns

Series

Object after replacement.

 

Raises

AssertionError

  • If regex is not a bool and to_replace is not None.

TypeError

  • If to_replace is not a scalar, array-like, dict, or None

  • If to_replace is a dict and value is not a list, dict, ndarray, or Series

  • If to_replace is None and regex is not compilable into a regular expression or is a list, dict, ndarray, or Series.

  • When replacing multiple bool or datetime64 objects and the arguments to to_replace does not match the type of the value being replaced

ValueError

  • If a list or an ndarray is passed to to_replace and value but they are not the same length.

// pandas.DataFrame.add_prefix Documentation

pandas.pydata.org/docs/reference/api/pandas.DataFrame.add_prefix.html

DataFrame.add_prefix(prefix)

Prefix labels with string prefix.

For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed.

 

Parameters

prefixstr

The string to add before each label.

 

Returns

Series or DataFrame

New Series or DataFrame with updated labels.


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 04. 유형 (4) 거리 기반 병합이 필요한 경우]

* 문제 정의 및 해결 방안

 - 아파트 가격 예측 등 지역이 포함되는 문제에서 주소나 위치 변수 등을 기준으로 거리가 가까운 레코드 및 관련 통계치를 통합해야 하는 경우가 종종 있음

// 특히나 지리 데이터를 처리 할 때 많이 일어난다.

 

 - 일반적으로 (1) 각 데이터에 포함된 간 거리를 나타내는 거리 행렬을 생성하고, (2) 거리 행렬의 행 혹은 열 기준 최소 값을 가지는 인덱스를 바탕으로 이웃을 탐색한 뒤, (3) 이웃을 기존 데이터에 부착하는 방식으로 해결함

 

 

* 관련문법 : scipy.spatial.distance.cdist

 

 - 두 개의 행렬을 바탕으로 거리 행렬을 반환하는 함수

 

 - 주요 입력

  . XA : 거리 행렬 계산 대상인 행렬 (ndarray 및 DataFrame) 로, 함수 출력의 행에 해당

  . XB : 거리 행렬 계산 대상인 행렬 (ndarrary 및 DataFrame) 로, 함수 출력의 열에 해당

  . metric : 거리 척도 ('cityblock', 'correlation', 'cosine', 'euclidean', 'jaccard', 'matching' 등)

 

* 관련문법 : ndarray.argsort

 - 작은 값부터 순서대로 데이터의 위치를 반환하는 함수로, 이웃을 찾는데 주로 활용 되는 함수

 

 - 주요 입력

  . axis : 0 이면 열별 위치를, 1이면 행별 위치를 반환

 

 

* 실습

// 각각의 데이터를 merge 를 해준다. 순서를 지키면서 해야 한다. 아니면 merge 가 되지 않는다.

 

// 역에 대한 위경도로 확인한다.

// 거리 행렬 생성을 위한 컬럼들을 추출한다.

 

// 위경도 거리 계산을 위한 모듈을 설치한다.

// !pip install haversine 현실감을 위해서 이 라이브러리를 설치 한다.

!pip install haversine

pypi.org/project/haversine/

Calculate the distance (in various units) between two points on Earth using their latitude and longitude.

 

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
 - merge, apply, argsort, haversine 등을 배울 수 있었다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 23 회차 미션 시작]

 

* 복습

 - 지도학습할 때의 Grid 서치 및 parameterGrid 에 대해서 배울 수 있었다. 지도 학습에 대해서는 추후에 좀 더 공부가 필요할 것  같다.

 



[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 04. 복잡도 파라미터 튜닝 방법]

 

* 복잡도 파라미터 튜닝 개요

 - 복잡도 파라미터란 복잡도에 영향을 주는 파라미터로, 이 값에 따라 과적합 정도가 결정되므로 매우 신중하게 튜닝해야 한다.

// 약하다는 의미는 복잡도에 영향을 줄수도 있고 안 줄 수도 있다는 있다는 의미이다.

 

 

 

* 학습시 우연성이 개입되는 모델의 복잡도 파라미터 튜닝

// 학습할 때마다 다른 값을 가지는 모델

 - 경사하강법 등의 방법으로 학습되는 모델 (예 : 회귀모델, 신경망 등)은 초기 값에 의한 영향이 매우 크다.

 

 - 따라서 복잡도 파라미터 변화에 따른 성능 변화의 패턴을 확인하기 어려운 경우가 많으므로, seed 를 고정한 뒤 튜닝을 수행해야 한다.

// 좋은 seed 를 알 수가 없다. seed 를 고정한 뒤 여러가지 서치를 해봐야 한다.

// seed 도 하나의 축으로 들어간다고 볼 수 있다.

 

* 복잡도 파라미터 튜닝

 - seed 가 고정되어 있거나, 학습시 우연 요소가 개입되지 않는 모델의 경우에는 복잡도 파라미터에 따른 성능 변화 패턴 확인이 상대적으로 쉽다.

 

 - 복잡도 파라미터가 둘 이상인 경우에는 서로 영향을 주기 때문에 반드시 두 파라미터를 같이 조정해야 한다.

 

 - 파라미터 그리드 크기를 줄이기 위해, 몇 가지 파라미터 값을 테스트한 후 범위를 설정하는 것이 바람직하다.

 

* 실습

 

// 크로스 를 쓰면 좋겠지만 학습 데이터와 평가 데이터를 구분을 했다.

// 샘플 156 개, 특징 60 개 이 된다면 단순한 모델이 필요하다는 것이다.

// 일반적으로 단순한 모델이 좋을 가능성이 크다는 이야기이다.

 

// Case 1. 복잡도 파라미터가 한 개이면서, 단순하고, 우연성이 어느정도 있는 모델 (Logistic Regression)

// 테스트 함수 생성하고 파라미터 그리드를 통해서 튜닝을 해본다.

 

// Case 2. 복잡도 파라미터가 두 개이면서, 단순하고, 우연성이 거의 없는 모델 (Decision Tree)

// max depth 가 크고 (복잡도 증가) min_samples_leaf 가 큰 경우 (복잡도 감소) 좋은 성능이 나온다.

 

// Case 3. 복잡도 파라미터가 하나이면서, 우연성이 있는 모델 (신경망)

// (5, 5) f1 - score 가 0 이 나왔다는 것은 초기값의 영향으로 보인다.

// (10, ) 가 best score 가 나왔지만.. 좀 더 많은 판단을 위해서 확인 해봐야 한다. -> 벗어나는지 등을 결정해야 한다.


 

[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 01. 유형 (1) 파일 자체가 나뉘어 저장된 경우]

 

 

* 개요

 - 지도학습 모델을 학습하려면 아래와 같이 반드시 하나의 통합된 데이터 집합이 필요하다.

 

- 많은 경우에 데이터가 두 개 이상으로 나뉘어져 있어, 이들을 반드시 통합하는 전처리를 수행해야 한다.

 

* 문제 정의 및 해결방안

 - 센서, 로그, 거래 데이터 등과 같이 크기가 매우 큰 데이터는 시간과 ID 등에 따라 분할되어 저장된다.

 

 - pandas.concat 함수를 사용하면 손쉽게 해결할 수 있다.

 

- 통합해야 하는 데이터가 많은 경우에는 빈 데이터 프레임을 생성한 뒤, 이 데이터 프레임과 반복문을 사용하여 불러온 데이터를 concat 함수를 이용하면 효율적으로 통합할 수 있다.

 

* 관련 문법 : pandas.concat

 - 둘 이상의 데이터 프레임을 이어 붙이는 데 사용하는 함수

 

 - 주요입력

  . objs : DataFrame 을 요소로 하는 리스트 (입력 예시 : [df1, df2]) 로 입력 순서대로 병합이 된다.

  . ignore_index : True 면 기존 인덱스를 무시하고 새로운 인덱스를 부여하며, False 면 기존 인덱스를 사용한다.

. axis : 0 이면 행 단위로 병합을 수행하며, 1 이면 열 단위로 병합을 수행한다.

 

* Tip. Axis 키워드

 - axis 키워드는 numpy 및 pandas 의 많은 함수에 사용되는 키워드로, 연산 등을 수행할 때 축의 방향을 결정하는 역할을 한다.

 

 - axis 가 0 이면 행을, 1 이면 열을 나타내지만 이렇게만 기억하면 논리적으로 이상한 점이 존재한다.

  . (예시 1) sum(axis=0) : 열 기준 합

  . (예시 2) concat([df1, df2][, axis = 0) : 행 단위 병합

 

- aixs 키워드는 그 함수의 결과 구조가 벡터 형태 (1차원) 인지, 행렬 형태 (2차원) 인지에 따라, 그 역할이 조금씩 다르다.

 

* 관련 문법 : os.listdir

 - 주요 입력

   . path : 입력된 경로 (path) 상에 있는 모든 파일명을 리스트 형태로 반환

 

* 실습

 - 5월 데이터는 평가 데이터로 쓸거고, 5월 이전 데이터는 학습데이터로 쓸것이기 때문에 이렇게 작업한다.

 

// 이 함수에 대해서는 chatper 4에서도 공부를 했어지만 다시 한번 Dcoumentation 을 참고해 본다.

// pandas.concat Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

pandas.concat(objs: Union[Iterable[‘DataFrame’], Mapping[Label, ‘DataFrame’]], axis='0', join: str = "'outer'", ignore_index: bool = 'False', keys='None', levels='None', names='None', verify_integrity: bool = 'False', sort: bool = 'False', copy: bool = 'True') → ’DataFrame’
pandas.concat(objs: Union[Iterable[FrameOrSeries], Mapping[Label, FrameOrSeries]], axis='0', join: str = "'outer'", ignore_index: bool = 'False', keys='None', levels='None', names='None', verify_integrity: bool = 'False', sort: bool = 'False', copy: bool = 'True') → FrameOrSeriesUnion

Concatenate pandas objects along a particular axis with optional set logic along the other axes.

Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on the passed axis number.

 

Parameters

objsa sequence or mapping of Series or DataFrame objects

If a mapping is passed, the sorted keys will be used as the keys argument, unless it is passed, in which case the values will be selected (see below). Any None objects will be dropped silently unless they are all None in which case a ValueError will be raised.

axis{0/’index’, 1/’columns’}, default 0

The axis to concatenate along.

join{‘inner’, ‘outer’}, default ‘outer’

How to handle indexes on other axis (or axes).

ignore_indexbool, default False

If True, do not use the index values along the concatenation axis. The resulting axis will be labeled 0, …, n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other axes are still respected in the join.

keyssequence, default None

If multiple levels passed, should contain tuples. Construct hierarchical index using the passed keys as the outermost level.

levelslist of sequences, default None

Specific levels (unique values) to use for constructing a MultiIndex. Otherwise they will be inferred from the keys.

nameslist, default None

Names for the levels in the resulting hierarchical index.

verify_integritybool, default False

Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation.

sortbool, default False

Sort non-concatenation axis if it is not already aligned when join is ‘outer’. This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

New in version 0.23.0.

Changed in version 1.0.0: Changed to not sort by default.

copybool, default True

If False, do not copy data unnecessarily.

 

Returns

object, type of objs

When concatenating all Series along the index (axis=0), a Series is returned. When objs contains at least one DataFrame, a DataFrame is returned. When concatenating along the columns (axis=1), a DataFrame is returned.

 


[04. Part 4) Ch 16. 흩어진 데이터 다 모여라 - 데이터 파편화 문제 - 02. 유형 (2) 명시적인 키 변수가 있는 경우]

* 문제 정의 및 해결 방안

 - 효율적인 데이터 베이스 관리를 위해, 잘 정제된 데이터일지라도 데이터가 키 변수를 기준으로 나뉘어 저장되는 경우가 매우 흔함

 

 - SQL 에서는 JOIN 을 이용하여 해결하며, python 에서는 merge 를 이용하여 해결한다.

 - 일반적인 경우는 해결이 어렵지 않지만, 다양한 케이스가 존재할 수 있으므로 반드시 핵심을 기억해야 한다.

  (1) 어느 컬럼이 키 변수 역할을 할 수 있는지 확인하고, 키 변수를 통일해야 한다.

  (2) 레코드의 단위를 명확히 해야 한다.

 

* 관련문법 : pandas.merge

 - 키 변수를 기준으루 두개의 데이터 프레임을 병합(join)하는 함수

 

 - 주요입력

   . left : 통합 대상 데이터 프레임 1

   . right : 통합 대상 데이터 프레임 2

   . on : 통합 기준 key 변수 및 변수 리스트 (입력을 하지 않으면, 이름이 같은 변수를 key 로 식별함)
   . left_on : 데이터 프레임 1의 key 변수 및 변수 리스트
   . right_on : 데이터 프레임 2의 key 변수 및 변수 리스트
   . left_index : 데이터 프레임 1의 인덱스를 key 변수로 사용할 지 여부
   . right_index : 데이터 프레임 2의 인덱스를 key 변수로 사용할 지 여부

 

* 실습

 - on 을 안써도 되긴 하지만, 가능하면 작성해주는 것이 더 좋다.

 

// 이 함수도 다시

// pandas.merge Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

 

DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes='_x', '_y', copy=True, indicator=False, validate=None)[source]

Merge DataFrame or named Series objects with a database-style join.

The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on.

Parameters

rightDataFrame or named Series

Object to merge with.

how{‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’

Type of merge to be performed.

  • left: use only keys from left frame, similar to a SQL left outer join; preserve key order.

  • right: use only keys from right frame, similar to a SQL right outer join; preserve key order.

  • outer: use union of keys from both frames, similar to a SQL full outer join; sort keys lexicographically.

  • inner: use intersection of keys from both frames, similar to a SQL inner join; preserve the order of the left keys.

onlabel or list

Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames.

left_onlabel or list, or array-like

Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns.

right_onlabel or list, or array-like

Column or index level names to join on in the right DataFrame. Can also be an array or list of arrays of the length of the right DataFrame. These arrays are treated as if they are columns.

left_indexbool, default False

Use the index from the left DataFrame as the join key(s). If it is a MultiIndex, the number of keys in the other DataFrame (either the index or a number of columns) must match the number of levels.

right_indexbool, default False

Use the index from the right DataFrame as the join key. Same caveats as left_index.

sortbool, default False

Sort the join keys lexicographically in the result DataFrame. If False, the order of the join keys depends on the join type (how keyword).

suffixeslist-like, default is (“_x”, “_y”)

A length-2 sequence where each element is optionally a string indicating the suffix to add to overlapping column names in left and right respectively. Pass a value of None instead of a string to indicate that the column name from left or right should be left as-is, with no suffix. At least one of the values must not be None.

copybool, default True

If False, avoid copy if possible.

indicatorbool or str, default False

If True, adds a column to the output DataFrame called “_merge” with information on the source of each row. The column can be given a different name by providing a string argument. The column will have a Categorical type with the value of “left_only” for observations whose merge key only appears in the left DataFrame, “right_only” for observations whose merge key only appears in the right DataFrame, and “both” if the observation’s merge key is found in both DataFrames.

validatestr, optional

If specified, checks if merge is of specified type.

  • “one_to_one” or “1:1”: check if merge keys are unique in both left and right datasets.

  • “one_to_many” or “1:m”: check if merge keys are unique in left dataset.

  • “many_to_one” or “m:1”: check if merge keys are unique in right dataset.

  • “many_to_many” or “m:m”: allowed, but does not result in checks.

Returns

DataFrame

A DataFrame of the two merged objects.


 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 복잡도 파라미터 튜닝에서는 다양한 파라미터에 대해서 어떤식을 튜닝을 해야 되는지.. 단순하다고 나쁜 것도 아니고 복잡하다고 좋은 것도 아니라.. 그 상황에 맞는 경험치!!^^!!

- 데이터 합치 파트는 Chapter 4 에 나와 있는 함수들을 다시 한번 되돌아 볼 수 있는 기회였다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 22 회차 미션 시작]

 

* 복습

 - 모델 개발 프로세스에 대해서 배웠고, 지도학습에서는 선형회귀, 의사결정나무, 신경망 등에 대해서도 배워 볼 수 있었다.


[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 01. 그리드 서치]

* 모델 및 파라미터 선정 문제

 - 어떠한 데이터에 대해서도 우수한 모델과 그 하이퍼 파라미터는 절대 존재하지 않는다.

 - 또한, 분석적인 방법으로 좋은 모델과 하이퍼 파라미터를 선정하는 것도 불가능하다.

 

* 그리드 서치 개요

 - 하이퍼 파라미터 그리드는 한 모델의 하이퍼 파라미터 조합을 나타내며, 그리드 서치란 하이퍼 파라미터 그리드에 속한 모든 파라미터 조합을 비교 평가하는 방법을 의미

 

// 거리 척도

 - 예시 : k - 최근접 이웃의 파라미터 그리드

 => 총 여섯 개의 하이퍼 파라미터 조합에 대한 성능을 평가하여, 그 중 가장 우수한 하이퍼 파라미터를 선택

 

* 그리드 서치 코드 구현

 - sklearn 을 활용하여 그리드 서치를 구현하려면 사전 형태로 하이퍼 파라미터 그리드를 정의해야 한다.

  . key: 하이퍼 라미터명(str)

  . value : 해당 파라미터의 범위 (list)

 

 

* 그리드 서치 코드 구현 : GridSearchCV

 - sklearn.model_selection.GridSearchCV

  . 주요 입력

   .. estimator : 모델 (sklearn 인스턴스)

   .. param_grid : 파라미터 그리드 (사전)

   .. cv : k 겹 교차 검증에서의 k (2 이상의 자연수)

   .. scoring_func : 평가 함수 (sklearn 평가 함수)

 

  . GridSearchCV 인스턴스(GSCV) 의 주요 method 및 attribute

   .. GSCV = GridSearchCV (estimator, param_grid, cv, scoring_func) : 인스턴스화

   .. GSCV.fit(X, Y) : 특징 벡터 X 와 라벨 Y 에 대해 param_grid 에 속한 파라미터를 갖는 모델을 k - 겹 교차 검증 방식으로 평가하여, 그 중 가장 우수한 파라미터를 찾는다.

   .. GSCV.get_params( ) : 가장 우수한 파라미터를 반환

 

 . 사용이 편하다는 장점이 있지만, k - 겹 교차 검증 방식을 사용하기에 느리고, 성능 향상을 위한 전처리 기법을 적용할 수 없다는 단점이 있다.

 

* 그리드 서치 코드 구현 : ParameterGrid

 - sklearn.model_selection.ParameterGrid

  . param_grid (사전 형태의 하이퍼 파라미터 그리드) 를 입력 받아, 가능한 모든 파라미터 조합 (사전) 을 요소로 하는 generator 를 반환하는 함수

  . GridSearchCV 에 비해 사용이 어렵다는 단점이 있지만, 성능 향상을 위한 전처리 기법을 적용하는데 문제가 없어서 실무에서 휠씬 자주 사용된다.

 

* ParameterGrid 사용을 위해 알아야 하는 문법 (1/2)

 - 파이썬 함수의 입력으로 사전 자료형을 사용하는 경우에는 ** 를 사전 앞에 붙여야 한다.

- 이를 활용하면, ParameterGrid 인스턴스를 순회하는 사전 자료형인 변수(파라미터)를 모델의 입력으로 넣을 수 있다.

 

* ParameterGrid 사용을 위해 알아야 하는 문법 (2/2)

 - ParameterGrid 인스턴스를 순회하면서 성능이 가장 우수한 값을 찾으려면 최대값(최소값) 을 찾는 알고리즘을 알아야 한다.

  . 내장 함수인 max 함수나 min 함수를 사용해도 되지만, 평가해야 하는 하이퍼 파라미터 개수가 많으면 불필요한 메모리 낭비로 이어질 수 있으며, 더욱이 모델도 같이 추가되야 하므로 메모리 에러로 이어지기 쉽다.

 

 - 알고리즘 예시 : L = [10, 20, 30, 10, 20] 에서의 최대닶을 찾아라.

 

* 실습

// 비교를 위해서 list 형태로 바꿔준다.

// 실제로는 바꿔주지 않고 parametergrid(grid) 로 순회한다.

 

// a 와 b 의 순서는 크게 상관이 없다.

 

// max_value 는 메우 작은 값을 설정 한다. 음의 무한대를 주는 것이 좋지만, domain 이 있으면 그 가장 값을 지정한다.

 

// 최소값 min_value 는 매우 큰 값으로 잡아 준다. 나머지는 동일하게 적용한다.

 

// 모델은 여러가지로 적용해보는 것이 좋다.

 

 

// sklearn.model_selection.GridSearchCV Documentation

scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

class sklearn.model_selection.GridSearchCV(estimator, param_grid, *, scoring=None, n_jobs=None, iid='deprecated', refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score=nan, return_train_score=False)

Exhaustive search over specified parameter values for an estimator.

Important members are fit, predict.

GridSearchCV implements a “fit” and a “score” method. It also implements “predict”, “predict_proba”, “decision_function”, “transform” and “inverse_transform” if they are implemented in the estimator used.

The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid.

Read more in the User Guide.

Parameters

estimatorestimator object.

This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a score function, or scoring must be passed.

param_griddict or list of dictionaries

Dictionary with parameters names (str) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings.

scoringstr, callable, list/tuple or dict, default=None

A single str (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) to evaluate the predictions on the test set.

For evaluating multiple metrics, either give a list of (unique) strings or a dict with names as keys and callables as values.

NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each.

See Specifying multiple metrics for evaluation for an example.

If None, the estimator’s score method is used.

n_jobsint, default=None

Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

Changed in version v0.20: n_jobs default changed from 1 to None

pre_dispatchint, or str, default=n_jobs

Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be:

  • None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs

  • An int, giving the exact number of total jobs that are spawned

  • A str, giving an expression as a function of n_jobs, as in ‘2*n_jobs’

iidbool, default=False

If True, return the average score across folds, weighted by the number of samples in each test set. In this case, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds.

Deprecated since version 0.22: Parameter iid is deprecated in 0.22 and will be removed in 0.24

cvint, cross-validation generator or an iterable, default=None

Determines the cross-validation splitting strategy. Possible inputs for cv are:

  • None, to use the default 5-fold cross validation,

  • integer, to specify the number of folds in a (Stratified)KFold,

  • CV splitter,

  • An iterable yielding (train, test) splits as arrays of indices.

For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used.

Refer User Guide for the various cross-validation strategies that can be used here.

Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.

refitbool, str, or callable, default=True

Refit an estimator using the best found parameters on the whole dataset.

For multiple metric evaluation, this needs to be a str denoting the scorer that would be used to find the best parameters for refitting the estimator at the end.

Where there are considerations other than maximum score in choosing a best estimator, refit can be set to a function which returns the selected best_index_ given cv_results_. In that case, the best_estimator_ and best_params_ will be set according to the returned best_index_ while the best_score_ attribute will not be available.

The refitted estimator is made available at the best_estimator_ attribute and permits using predict directly on this GridSearchCV instance.

Also for multiple metric evaluation, the attributes best_index_, best_score_ and best_params_ will only be available if refit is set and all of them will be determined w.r.t this specific scorer.

See scoring parameter to know more about multiple metric evaluation.

Changed in version 0.20: Support for callable added.

verboseinteger

Controls the verbosity: the higher, the more messages.

error_score‘raise’ or numeric, default=np.nan

Value to assign to the score if an error occurs in estimator fitting. If set to ‘raise’, the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error.

return_train_scorebool, default=False

If False, the cv_results_ attribute will not include training scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance.

New in version 0.19.

Changed in version 0.21: Default value was changed from True to False

Attributes

cv_results_dict of numpy (masked) ndarrays

A dict with keys as column headers and values as columns, that can be imported into a pandas DataFrame.

For instance the below given table

 

           

param_kernel

param_gamma param_degree split0_test_score…

 

rank_t…

‘poly’

2

0.80

2

‘poly’

3

0.70

4

‘rbf’

0.1

0.80

3

‘rbf’

0.2

0.93

1

 

will be represented by a cv_results_ dict of:

{ 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], mask = [False False False False]...) 'param_gamma': masked_array(data = [-- -- 0.1 0.2], mask = [ True True False False]...), 'param_degree': masked_array(data = [2.0 3.0 -- --], mask = [False False True True]...), 'split0_test_score' : [0.80, 0.70, 0.80, 0.93], 'split1_test_score' : [0.82, 0.50, 0.70, 0.78], 'mean_test_score' : [0.81, 0.60, 0.75, 0.85], 'std_test_score' : [0.01, 0.10, 0.05, 0.08], 'rank_test_score' : [2, 4, 3, 1], 'split0_train_score' : [0.80, 0.92, 0.70, 0.93], 'split1_train_score' : [0.82, 0.55, 0.70, 0.87], 'mean_train_score' : [0.81, 0.74, 0.70, 0.90], 'std_train_score' : [0.01, 0.19, 0.00, 0.03], 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], 'mean_score_time' : [0.01, 0.06, 0.04, 0.04], 'std_score_time' : [0.00, 0.00, 0.00, 0.01], 'params' : [{'kernel': 'poly', 'degree': 2}, ...], }

NOTE

The key 'params' is used to store a list of parameter settings dicts for all the parameter candidates.

The mean_fit_time, std_fit_time, mean_score_time and std_score_time are all in seconds.

For multi-metric evaluation, the scores for all the scorers are available in the cv_results_ dict at the keys ending with that scorer’s name ('_<scorer_name>') instead of '_score' shown above. (‘split0_test_precision’, ‘mean_train_precision’ etc.)

best_estimator_estimator

Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False.

See refit parameter for more information on allowed values.

best_score_float

Mean cross-validated score of the best_estimator

For multi-metric evaluation, this is present only if refit is specified.

This attribute is not available if refit is a function.

best_params_dict

Parameter setting that gave the best results on the hold out data.

For multi-metric evaluation, this is present only if refit is specified.

best_index_int

The index (of the cv_results_ arrays) which corresponds to the best candidate parameter setting.

The dict at search.cv_results_['params'][search.best_index_] gives the parameter setting for the best model, that gives the highest mean score (search.best_score_).

For multi-metric evaluation, this is present only if refit is specified.

scorer_function or a dict

Scorer function used on the held out data to choose the best parameters for the model.

For multi-metric evaluation, this attribute holds the validated scoring dict which maps the scorer key to the scorer callable.

n_splits_int

The number of cross-validation splits (folds/iterations).

refit_time_float

Seconds used for refitting the best model on the whole dataset.

This is present only if refit is not False.

New in version 0.20.

 

 

// sklearn.model_selection.ParameterGrid Documentation

scikit-learn.org/stable/modules/generated/sklearn.model_selection.ParameterGrid.html

 

class sklearn.model_selection.ParameterGrid(param_grid)[source]

Grid of parameters with a discrete number of values for each.

Can be used to iterate over parameter value combinations with the Python built-in function iter.

Read more in the User Guide.

Parametersparam_griddict of str to sequence, or sequence of such

The parameter grid to explore, as a dictionary mapping estimator parameters to sequences of allowed values.

An empty dict signifies default parameters.

A sequence of dicts signifies a sequence of grids to search, and is useful to avoid exploring parameter combinations that make no sense or have no effect. See the examples below.

 


 

[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 02. 기준 (1) 변수 타입]

* 변수 타입 확인 방법

 - DataGrame.dtypes

  . DataFrame 에 포함된 컬럼들의 데이터 타입 ( object, int64, float64, bool 등 ) 을 반환

 

 - DataFrame.infer_objects( ).dtypes

  . DataFrame 에 포함된 컬럼들의 데이터 타입을 추론한 결과를 반환

  . (예) ['1', '2'] 라는 값을 가진 컬럼은 비록 object 타입이나, int 타입이라고 추론할 수 있다.

 

 - 주의 : string type 이라고 해서 반드시 범주형이 아니며, int 혹은 float type 이라고 해서 반드시 연속형은 아니다. 반드시 상태 공간의 크기와 도메인 지식 등을 고려해야 한다.

 

* 변수 타입에 따른 적절한 모델

 - 주의 : 모델 성능에는 변수 타입만 영향을 주는 것이 아니므로, 다른 요소도 반드시 고려해야 한다.

 

* 혼합형 변쉥 적절하지 않은 모델 (1) 회귀 모델

 - 혼합형 변수인 경우에는 당연히 변수의 스케일 차이가 존재하는 경우가 흔하다.

 

 - 변수의 스케일에 따라 계수 값이 크게 달라지므로, 예측 안정성이 크게 떨어진다.

  . 모든 특징이 라벨에 독립적으로 영향을 준다면, 이진형 특징의 계수 절대값이 스케일이 큰 연속형 특징의 계수 절대값 보다 크게 설정된다.

  . 이진형 특징 값에 따라 예측 값이 크게 변동한다.

 

 - 스케일일ㅇ을 하더라도 이진형 특징의 분포가 변하지 않으므로, 이진형 특징의 값에 따른 영향력이 크게 줄지 않는다. 

 

* 혼합형 변수에 적절하지 않은 모델 (2) 나이브 베이즈

 - 나이브베이즈는 하나의 확률 분포를 가정하기 때문에, 혼합형 변수를 가지는 데이터에 부적절하다.

  . (예시) 베르누이 분포는 연속형 값을 가지는 확률 분포 추정에 매우 부적절

 

 - 따라서 나이브베이즈는 혼합형 변수인 경우에는 절대로 고려해서는 안 되는 모델이다.

 

* 혼합형 변수에 적절하지 않은 모델 (3) k - 최근접 이웃

 - 스케일이 큰 변수에 의해 거리가 사실상 결정되므로, k-NN 은 혼합형 변수에 적절하지 않다.

 

 - 단, 코사인 유사도를 사용하는 경우나, 스케일링을 적용하는 경우에는 큰 무리 없이 사용 가능하다.

 


 

[03. Part 3) Ch 15. 이럴땐 이걸 쓰고, 저럴땐 저걸 쓰고 - 지도 학습 모델 & 파라미터 선택 - 03. 기준 (2) 데이터 크기]

* 샘플 개수와 특징 개수에 따른 과적합 (remind)

 

* 샘플 개수와 특징 개수에 따른 적절한 모델

 

* 실습

// random_state 가 있는 모델은 모두 같은 값으로 설정한다.

 

// 모델별 k 겹 교차 검증 기반 (k=5) 의 MAE 값으로 계산한다.

 

// cv 는 폴더의 갯수. k 값

 

// 특징이 적으면 복잡한 모델은 나오기 어렵다.

 

// 샘플이 매우 적고 특징이 상대적으로 많은 경우

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 지도학습할 때의 Grid 서치 및 parameterGrid 에 대해서 배울 수 있었다. 동영상 순서가 이상해서 처음엔 약간 이상했지만~^^;;

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 20 회차 미션 시작]

* 복습

 - 지난번 실습에 대해서도 학습했었고, 특히 지도학습에 대한 부분들이 다시 한번 복습을 해야 할 것 같다.

 


[03. Part 3) Ch 14. 이건 꼭 알아야 해 - 지도 학습 모델의 핵심 개념 - 02. 모델 개발 프로세스]

* 책에서나 볼 수 있는 프로세스

// 이상적인 프로세스라고 보면 된다.

 

* 문제 정의

 - 전체 프로세스 가운데 가장 중요한 단계로, 명확한 목적 의식을 가지고 프로세스를 시작해야 한다.

// 어떤 것을 예측할 것인것인지, 어떤것을 특징으로 사용할 것인지를 정확하게 지정해야 한다.

 

 - 이 단계에서 수행하는 활동은 다음과 같다.

  . 과업 종류 결정 (분류 , 예측 등)

  . 클래스 정의

  . 도메인 지식 기반의 특징 정의

// 데이터가 수집전이라서 그 분야에 관련된 지식인 도메인 지식을 활용해야 한다.

  . 사용 데이터 정의

 

* 데이터 수집

 - 문제 정의에서 정의한 데이터를 수집하는 단계로, 크롤링, 센서 활용, 로그 활용 등으로 데이터를 수집

// survey 등도 활용할 수 있다.

 - 기업 내 구축된 DB에서 SQL을 통해 추출하는 경우가 가장 많으며, 이때는 클래스를 중심으로 수집

 

* 데이터 탐색

// 이 강의에서 초점을 두고 있는 단계

 - 데이터가 어떻게 생겼는지를 확인하여, 프로세스를 구체화하는 단계

 

 - 데이터 탐색 단계에서 변수별 분포, 변수 간 상관성, 이상치와 결측치, 변수 개수, 클래스 변수 분포 등을 확인하며, 이 탐색 결과는 데이터 전처리 및 모델 선택에 크게 영향을 미침

  . 데이터 크기 확인 -> 과적합 가능성 확인 및 특징 선택 고려

  . 특징별 기술 통계 -> 특징 변환 고려 및 이상치 제거 고려

  . 특징 간 상관성 -> 특징 삭제 및 주성분 분석 고려

  . 결측치 분포 -> 결측치 제거 및 추정 고려

  . 변수 개수 -> 차원 축소 기법 고려

  . 클래스 변수 분포 -> 비용민감 모델 및 재샘플링 고려

// 탐색결과를 모델링과 전처리에 반영을 한다고 보면 된다.

 

* 데이터 전처리

 - 원활한 모델링을 위해 데이터를 가공하는 단계로, 여기서 수행하는 대표적인 작업은 다음과 같다.

// 데이터를 가공하는 작업이라고 보면 된다.

 

* 모델링

// 모델선택+하이퍼 파라미터 설정은 하나의 단계로 봐도 무방하다.

 

 

* 모델평가

 - 분류 모델의 대표적인 지표

  . 정확도 (accuracy) : 전체 샘플 가운데 제대로 예측한 샘플의 비율

  . 정밀도 (precision) : 긍정 클래스라고 에측한 샘플 가운데 실제 긍정 클래스 샘플의 비율

  . 재현율 (recall) : 실제 긍정 클래스 샘플 가운데 제대로 예측된 샘플의 비율

  . F1 점수 (F1-score) : 정밀도와 재현율의 조화 평균

 

 - 에측 모델의 대표적인 지표

  . 평균 제곱 오차 (mean sqaured erro)

  . 평균 절대 오차 (mean absolute error)

  . 평균 절대 퍼센트 오차 (mean absolute percentage error)

// 평균 절대 퍼센트 오차는 실제로는 잘 안 쓰인다. 분모가 0이 되는 경우가 있다.

 

 - 잘못된 평가를 피하기 위해, 둘 이상의 평가 지표를 쓰는 것이 바람직하다.

 

* 결과보고서 작성

 - 지금까지의 분석 결과를 바탕으로 보고서를 작성하는 단계

 

 - 결과보고서의 통일된 구성은 없지만, 일반적으로 다음과 같이 구성된다.

  1) 분석 목적

  2) 데이터 탐색 및 전처리

  3) 분석 방법

  4) 분석 결과 및 활용 방안

// 어떻게 활용할 것인가가 중요하다.

 

* 부적절한 문제 정의

// 문제정의가 잘 못 되면 뒤에 결과까지 부적절한 영향을 주게 된다.

 

 - 부적절한 문제 정의의 가장 흔한 유형으로는 (1) 구체적이지 않은 문제 정의, (2) 부적절한 특징 정의, (3) 수집 불가한 데이터 정의가 있다.

// 3 번의 경우 입문자에게 많이 발생 한다.

 

 - 타이어 A사 사례

  . 문제 정의 : "타이어 생산 공정에서 발생하는 데이터를 바탕으로 공정을 최적화하고 싶다"

  . 제공 데이터 : 생산 공정에서 발생한 거의 모든 데이터

// 최적화라는 단어가 굉장히 모호한 단어이다. 추상적이다.

// 구체적으로 말할 수 있어야 한다.

// 타이어 생산 공정이라는 자체도 모호하다. 1단계만 이뤄진 것이 아니기 때문이다.

// column 에 대해서 데이터 설명서를 요청했지만 기업도 모른다고 답변을 했었다.

// 컬럼에 대한 정확한 정보를 알고 있어야 한다.

 

 - 카드 A사 사례

  . 문제 정의 : "일별 콜수요를 예측하고 싶다"

  . 특징 : (1) 상담원 수, (2) 상담원의 역량

// 일별로 상담원수가 바뀔 가능성이 거의 없다.

// 다시 말해서 1, 2번의 변수가 영향을 미치지 않는다.

// 역량을 측정하는 것 자체도 모호하다.

 

* 부적절한 데이터 수집

 - 부적절한 데이터 수집의 가장 흔한 유형으로 (1) 측정 오류 등으로 수집한 데이터가 실제 상황을 반영하지 못하는 경우, (2) 해결하고자 하는 문제와 무관한 데이터를 수집한 경우, (3) 특정 이벤트가 데이터에 누락된 경우가 있다.

// 데이터 수집이 잘 못 되면 어떤 방법을 쓰더라도 좋은 성능을 얻을 수가 없다.

 

 - 자동차 시트 A사 사례

  . 배경 : 자동차 시트 폼을 보관하는 과정에서 창고의 온도 및 습도 등에 따라, 폼이 수축하기도 이완하기도 한다.

  . 문제 정의 : 창고의 환경에 따른 폼의 수축 및 이완정도를 예측하고, 그 정도가 심할 것이라 판단되면 환경을 제어

  . 수집데이터 : 창고의 환경 조건과 폼의 수축 / 이완 정도 데이터 (수집 시기 : 2015년 6월 ~8월)

// 문제정의까지는 괜찮았던 정의 단계를 내렸지만...

// 수집데이터의 시기가 6~8월 정도로 이완 정도는 예측 할 수는 있지만, 수축 등의 데이터를 볼 수 없다.

// 통계적인 방향에서 보면 일어나지 않은.. 측정되지 않은 문제는 분석 할 수 없다는 것이다.

// 시기를 겨울철에도 모아서 다시 분석에 활용하였다.

 

* 부적절한 데이터 탐색

 - 피드백 루프를 발생시키는 핵심 원인이 부적절한 데이터 탐색 혹은 데이터 탐색 생략임

// 탐색을 대충하고, 대충 검정해보고 다시 이전으로 돌아가는 현상이 발생한다.

 

 - 데이터 탐색을 제대로 하지 않으면, 적절한 모델 선택 및 전처릴 할 수 없어, 모델 평가 단계에서 좋은 성능을 내는 것이 거의 불가능하다.

 

 - 자동차 A사 사례

  . 문제 정의 : 서비스 센터로 등록되는 클레임 가운데 안전 관련 클레임을 자동 검출하는 시스템 개발

  . 무적절한 탬색 내용 : 클레임에서 오탈자 및 비표준어가 굉장히 많았지만 빈발 단어의 분포 등 만 확인한다.

  . 결과 : 스펠링 교정 등의 전처리를 생략해서, 검출 성능이 매우 낮은 모델이 학습되어 다시 탐색 단계로 되돌아간다.

// 코드를 실행시키고 결과가 나온 시기가 1주일이 걸렸다. 그렇기 때문에 탐색을 꼼꼼히 해야만 된다.

 

* 부적절한 데이터 전처리

 - 데이터 전처리는 크게 모델 개발을 위해 필수적인 전처리와 모델 성능 향상을 위한 전처리로 구분된다.

 - 모통 모델 성능 향상을 위한 전처리를 생략해서 이전 단계로 되돌아가는 경우가 가장 흔하다.

// 필수적인 전처리를 반드시 해야 한다. Skip 할 수가 없다.

 

* 부적절한 모델링 및 모델 평가

 - 모델링에서는 주로 부적절한 모델 및 파라미터 선택으로 잘못되는 경우가 대부분이며, 모델링 자체가 잘못되는 경우는 매우 드물다.

 

 - 모델 평강가는 적절하지 않은 지표를 사용해서 잘못되는 경우가 대부분이며, 대표적인 사례로 단일 지표만 써서 부적절한 모델을 우수한 모델이라고 판단하는 경우가 있다.

// 실제 긍적의 재현율은 0 % 가 되어 버린다.

// 여러지표를 사용하는 것이 중요한 것이다.

// 클래스 분류형 문제가 있는 경우는 하나의 클래스로 치우쳐 발생되는 현상일 수 있다.


 

[03. Part 3) Ch 14. 이건 꼭 알아야 해 - 지도 학습 모델의 핵심 개념 - 03. 주요 모델의 구조 및 특성-1]

* 선형 회귀 모델과 정규화 회귀 모델

 - 모델 구조

// 샘플 또는 레코드라고 부른다.

 

- 비용 함수 : 오차제곱합

// 선형 -> 오차 제곱합

// 정규화 -> 계수에 대한 패널티를 추가 시킨다.

 

* 선형 회귀 모델과 정규화 회귀 모델

 - 특징과 라벨 간 비선형 관계가 무시될 수 있으므로, 특징 변환이 필요

- 특징 간 스케일 사이에 크게 영향을 받아, 예측 모델링을 할 때 스케일링이 필요하다.

 - 남다 와 max_iter에 따라 과적합 정도가 직접 결정된다.

// max_iter 는 언제까지 학습 시킬 것인가에 대해서 이야기 하는 것이다.

// 신경망 등에서 대해서 고의적으로 작게 잡아서 학습 시킨다. 과적화를 피하기 위해서 그렇게 하는 경우도 있다는 것이다.

 

* 실습 

// sklearn.linear_model.LinearRegression Documentation

scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html

class sklearn.linear_model.LinearRegression(*, fit_intercept=True, normalize=False, copy_X=True, n_jobs=None)

Ordinary least squares Linear Regression.

LinearRegression fits a linear model with coefficients w = (w1, …, wp) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation.

 

Parameters

fit_interceptbool, default=True

Whether to calculate the intercept for this model. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered).

normalizebool, default=False

This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use sklearn.preprocessing.StandardScaler before calling fit on an estimator with normalize=False.

copy_Xbool, default=True

If True, X will be copied; else, it may be overwritten.

n_jobsint, default=None

The number of jobs to use for the computation. This will only provide speedup for n_targets > 1 and sufficient large problems. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

Attributes

coef_array of shape (n_features, ) or (n_targets, n_features)

Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features.

rank_int

Rank of matrix X. Only available when X is dense.

singular_array of shape (min(X, y),)

Singular values of X. Only available when X is dense.

intercept_float or array of shape (n_targets,)

Independent term in the linear model. Set to 0.0 if fit_intercept = False.

 

 

// X는 1차원이어서 sklean 의 인풋 구조와 맞지 않아, reshape를 사용한다.

// 1차원일 경우에는 X=[recod1, record2, ...]

 

// 학습데이터와 평가 데이터를 나눠야지 정확한 결과가 도출 될 수가 있다.

 

// 모델링 할 때는 스켈링이 반드시 필요하다. 

 

* 로지스틱 회귀 모델

// 회귀 모델이지만 분류에 쓰이는 모델이라고 보면 된다.

 - 모델 구조

 

 - 비용 함수 : 크로스 엔트로피

 

 

* 로지스틱 회귀 모델

// 결과적으로는 선형식이라고 보면 된다.

// 선형적인 것들은 아래와 같은 특징을 가진다.

 - 특징의 구간별로 라벨의 분포가 달라지는 경우, 적절한 구간을 나타낼 수 있도록 특징 변환이 필요하다.

 

 

* 실습

 

 

// 원본을 다시 쓴다고 하면 copy 를 사용한다고 보면 된다.

 

// sklearn.linear_model.LogisticRegression Documentation

scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html

class sklearn.linear_model.LogisticRegression(penalty='l2', *, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)[source]

Logistic Regression (aka logit, MaxEnt) classifier.

In the multiclass case, the training algorithm uses the one-vs-rest (OvR) scheme if the ‘multi_class’ option is set to ‘ovr’, and uses the cross-entropy loss if the ‘multi_class’ option is set to ‘multinomial’. (Currently the ‘multinomial’ option is supported only by the ‘lbfgs’, ‘sag’, ‘saga’ and ‘newton-cg’ solvers.)

This class implements regularized logistic regression using the ‘liblinear’ library, ‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ solvers. Note that regularization is applied by default. It can handle both dense and sparse input. Use C-ordered arrays or CSR matrices containing 64-bit floats for optimal performance; any other input format will be converted (and copied).

The ‘newton-cg’, ‘sag’, and ‘lbfgs’ solvers support only L2 regularization with primal formulation, or no regularization. The ‘liblinear’ solver supports both L1 and L2 regularization, with a dual formulation only for the L2 penalty. The Elastic-Net regularization is only supported by the ‘saga’ solver.

Read more in the User Guide.

 

Parameters

penalty{‘l1’, ‘l2’, ‘elasticnet’, ‘none’}, default=’l2’

Used to specify the norm used in the penalization. The ‘newton-cg’, ‘sag’ and ‘lbfgs’ solvers support only l2 penalties. ‘elasticnet’ is only supported by the ‘saga’ solver. If ‘none’ (not supported by the liblinear solver), no regularization is applied.

New in version 0.19: l1 penalty with SAGA solver (allowing ‘multinomial’ + L1)

dualbool, default=False

Dual or primal formulation. Dual formulation is only implemented for l2 penalty with liblinear solver. Prefer dual=False when n_samples > n_features.

tolfloat, default=1e-4

Tolerance for stopping criteria.

Cfloat, default=1.0

Inverse of regularization strength; must be a positive float. Like in support vector machines, smaller values specify stronger regularization.

fit_interceptbool, default=True

Specifies if a constant (a.k.a. bias or intercept) should be added to the decision function.

intercept_scalingfloat, default=1

Useful only when the solver ‘liblinear’ is used and self.fit_intercept is set to True. In this case, x becomes [x, self.intercept_scaling], i.e. a “synthetic” feature with constant value equal to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic_feature_weight.

Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased.

class_weightdict or ‘balanced’, default=None

Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one.

The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)).

Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified.

New in version 0.17: class_weight=’balanced’

random_stateint, RandomState instance, default=None

Used when solver == ‘sag’, ‘saga’ or ‘liblinear’ to shuffle the data. See Glossary for details.

solver{‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, default=’lbfgs’

Algorithm to use in the optimization problem.

  • For small datasets, ‘liblinear’ is a good choice, whereas ‘sag’ and ‘saga’ are faster for large ones.

  • For multiclass problems, only ‘newton-cg’, ‘sag’, ‘saga’ and ‘lbfgs’ handle multinomial loss; ‘liblinear’ is limited to one-versus-rest schemes.

  • ‘newton-cg’, ‘lbfgs’, ‘sag’ and ‘saga’ handle L2 or no penalty

  • ‘liblinear’ and ‘saga’ also handle L1 penalty

  • ‘saga’ also supports ‘elasticnet’ penalty

  • ‘liblinear’ does not support setting penalty='none'

Note that ‘sag’ and ‘saga’ fast convergence is only guaranteed on features with approximately the same scale. You can preprocess the data with a scaler from sklearn.preprocessing.

New in version 0.17: Stochastic Average Gradient descent solver.

New in version 0.19: SAGA solver.

Changed in version 0.22: The default solver changed from ‘liblinear’ to ‘lbfgs’ in 0.22.

max_iterint, default=100

Maximum number of iterations taken for the solvers to converge.

multi_class{‘auto’, ‘ovr’, ‘multinomial’}, default=’auto’

If the option chosen is ‘ovr’, then a binary problem is fit for each label. For ‘multinomial’ the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. ‘multinomial’ is unavailable when solver=’liblinear’. ‘auto’ selects ‘ovr’ if the data is binary, or if solver=’liblinear’, and otherwise selects ‘multinomial’.

New in version 0.18: Stochastic Average Gradient descent solver for ‘multinomial’ case.

Changed in version 0.22: Default changed from ‘ovr’ to ‘auto’ in 0.22.

verboseint, default=0

For the liblinear and lbfgs solvers set verbose to any positive number for verbosity.

warm_startbool, default=False

When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. Useless for liblinear solver. See the Glossary.

New in version 0.17: warm_start to support lbfgs, newton-cg, sag, saga solvers.

n_jobsint, default=None

Number of CPU cores used when parallelizing over classes if multi_class=’ovr’”. This parameter is ignored when the solver is set to ‘liblinear’ regardless of whether ‘multi_class’ is specified or not. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.

l1_ratiofloat, default=None

The Elastic-Net mixing parameter, with 0 <= l1_ratio <= 1. Only used if penalty='elasticnet'. Setting l1_ratio=0 is equivalent to using penalty='l2', while setting l1_ratio=1 is equivalent to using penalty='l1'. For 0 < l1_ratio <1, the penalty is a combination of L1 and L2.

 

Attributes

classes_ndarray of shape (n_classes, )

A list of class labels known to the classifier.

coef_ndarray of shape (1, n_features) or (n_classes, n_features)

Coefficient of the features in the decision function.

coef_ is of shape (1, n_features) when the given problem is binary. In particular, when multi_class='multinomial', coef_ corresponds to outcome 1 (True) and -coef_ corresponds to outcome 0 (False).

intercept_ndarray of shape (1,) or (n_classes,)

Intercept (a.k.a. bias) added to the decision function.

If fit_intercept is set to False, the intercept is set to zero. intercept_ is of shape (1,) when the given problem is binary. In particular, when multi_class='multinomial', intercept_ corresponds to outcome 1 (True) and -intercept_ corresponds to outcome 0 (False).

n_iter_ndarray of shape (n_classes,) or (1, )

Actual number of iterations for all classes. If binary or multinomial, it returns only 1 element. For liblinear solver, only the maximum number of iteration across all classes is given.

Changed in version 0.20: In SciPy <= 1.0.0 the number of lbfgs iterations may exceed max_iter. n_iter_ will now report at most max_iter.

 

 

 


[03. Part 3) Ch 14. 이건 꼭 알아야 해 - 지도 학습 모델의 핵심 개념 - 03. 주요 모델의 구조 및 특성-2]

 

* k- 최근접 이웃 (k-Nearest Neighbors; kNN)

 - 모델 구조

 

 

 

* k - 최근접 이웃 (k-Nearest Neighbors ; kNN)

 - 주요 파라미터와 설정 방법

  . 이웃 수 (k) : 홀수로 설정하며, 특징 수 대비 샘플 수가 적은 경우에는 k를 작게 설정하는 것이 바람직하다.

// 홀수로 설정하는 이유는 동점을 방지하기 위해서이다.

// 샘플수가 작다는 것은 데이터가 밀도가 작다는 것이다.

 

  . 거리 및 유사도 척도

   .. 모든 변수가 서열형 혹은 정수인 경우 : 맨하탄 거리

   .. 방향성이 중요한 경우 (예 : 상품 추천 시스템) : 코사인 유사도

   .. 모든 변수가 이진형이면서 희소하지 않은 경우 : 매칭 유사도

   .. 모든 변수가 이진형이면서 희소한 경우 : 자카드 유사도

   .. 그 외 : 유클리디안 거리

// 희소하다는 것은 데이터 들이 0으로 이뤄져있다고 보면 된다. 텍스트 데이터가 그렇게 이뤄져 있다고 보면 된다.

 

 - 특징 추출이 어려우나 유사도 및 거리 계산만 가능한 경우 (예: 시퀀스 데이터) 에 주로 활용

 

 - 모든 특징이 연속형이고 샘플 수가 많지 않은 경우에 좋은 성능을 보인다고 알려져 있음

 

 - 특징 간 스케일 차이에 크게 영향을 받아, 스케일링이 반드시 필요함 (코사인 유사도를 사용하는 경우 제외)

 

 - 거리 및 유사도 계산에 문제가 없다면, 별다른 특징 변환이 필요하지 않다.

 

* 의사 결정 나무 (Decision tree)

 - 모델 구조

// 설명력이 굉장히 높다는 것이 이 의사결정나무의 핵심이라고 볼 수 있다.

 

 - 예측 과정을 잘 설명할 수 있다는 장점 덕분에 많은 프로젝트에서 활용

  . A 보험사 : 고객의 이탈 여부를 예측하고, 그 원인을 파악해달라

  . B 밸브사 : 밸브의 불량이 발생하는 공정 상의 원인을 파악해달라

  . C 홈쇼핑사 : 방송 조건에 따라 예측한 상품 매출액 기준으로 방송 편성표를 추천해주고, 그 근거를 설명해 달라

 

 - 선형 분류기라는 한계로 예측력이 좋은 편에 속하지는 못하나, 최근 각광 받고 있는 앙상블 모델 (예 : XGBoost, lightGBM) 의 기본 모형으로 사용된다.

// 예측력은 좋을지 몰라도 설명력이 떨어진다는 문제가 있다.

 

 - 주요 파라미터

  . max_depth : 최대 깊이로 그 크기가 클수록 모델이 복잡해진다.

  . min_samples_leaf : 잎 노드에 있어야 하는 최소 샘플 수로, 그 크기가 작을 수록 모델이 복잡해진다.

 

* 나이브 베이즈 (Navie Bayes)

 - 모델 구조

  . 베이즈 정리르 사용하고 특징 간 독립을 가정하여 사후 확률을 계산

  . 가능도는 조건부 분포를 가정하여 추정한다.

   .. 이진형 변수 : 베르누이 분포

   .. 범주형 변수 : 다항 분포

   .. 연속형 변수 : 가우시안 분포

 

 - 모델 특성

  . 특징 간 독립 가정이 실제로는 굉장히 비현실적이므로, 일반적으로 높은 성능을 기대하긴 어렵다.

// 특징 간 독립 가정이 통계학적으로는 많이 쓰이지만.. 높은 성능을 기대하긴 어렵다.

  . 설정한 분푸에 따라 성능 차이가 크므로, 특징의 타입이 서로 같은 경웨 사용하기 바람직하다.

  . 특징이 매우 많고 그 타입이 같은 문제 (예: 이진형 텍스트 분류)에 주로 사용된다.

  . 특징 간 독립 가정이 실제로는 굉장히 비현실적이므로, 일반적으로 높은 성능을 기대하긴 어렵다.

  . 설정한 분포에 따라 성능 차이가 크므로, 특징의 타입이 서로 같은 경우에 사용하기 바람직하다.

  . 특징이 매우 많고 그 타입이 같은 문제 (예: 이진형 텍스트 분류) 에 주로 사용된다.

 

* 서포트 벡터 머신 (Support Vector Machine; SVM)

 - 모델 구조

 

 - 최적화 모델

 - 오차를 최소화하면서 동시에 마진을 최대화하는 분류 모델로, 커널 트릭을 활용하여 저차원 공간을 고차원 공간으로 매핑한다.

 

 - 마진의 개념을 회귀에 활용한 모델을 서포트 벡터 회귀 (Support Vector Regression)이라 한다.

 

 - 주요 파라미터

  . kernel : 통상적으로 이진 변수가 많으면 linear 커널이, 연속 변수가 많으면 rbf 커널이 잘 맞는 다고 알려져 있다.

// 특징간 차이는 rbf, 특징간 곱 linear

  . C : 오차 패널티에 대한 계수로, 이 값이 작을 수록 마진 최대화에 클수록 학습 오차 최소화에 신경을 쓰며, 보통 10n 범위에서 튜닝한다.

  . r : rbf 커널의 파라미터로, 크면 클수록 데이터의 모양을 잡 잡아내지만 오차가 커질 위험이 있으며, C 가 증가하면 r도 증가하게 튜닝하는 것이 일반적이다.

 

 - 파라미터 튜닝이 까다로운 모델이지만, 튜닝만 잘하면 좋은 성능을 보장하는 모델이다.

// 학술에 관심이 있으면 VC 정리...를 확인해보면 좋다.

 

* 신경망 (Neural Network)

 - 모델 구조

 - 초기 가중치에 크게 영향을 받는 모델로, 세밀하게 random_state 와 max_iter 값을 조정해야 하다.

// 우연에 많이 기반한다는 의미이다. 데이터가 작으면 작을 수록 그런 경향이 크다.

 

 - 은닉 노드가 하나 추가되면 그에 따라 하나 이상의 가중치가 추가되어, 복잡도가 크게 증가할 수 있다.

 

 - 모든 변수 타입이 연속형인 경우에 성능이 잘 나오는 것으로 알려져 있으며, 은닉 층 구조에 따른 복잡도 조절이 파라미터 튜닝에서 고려해야 할 가장 중요한 요소임

 

 - 최근 딥러닝의 발전으로 크게 주목받는 모델이지만, 특정 주제 (예 : 시계열 예측, 이미지 분류, 객체 탐지 등) 를 제외하고는 깊은 층의 신경망은 과적합으로 인한 성능 이슈가 자주 발생한다.

 

 

* 트리 기반의 앙상블 모델

 - 최근 의사 결정나무를 기본 모형으로 하는 앙상블 모형이 캐글 등에서 자주 사용되며, 좋은 성능을 보인다.

 

 - 랜덤 포레스트 : 배깅(bagging) 방식으로 여러 트리를 학습하여 결합한 모델

 

 - XGboost & LightGBM : 부스팅 방식으로 여러 트리를 순차적으로 학습하여 결합한 모델

 

 - 랜덤 포레스트를 사용할 때는 트리의 개수와 나무의 최대 깊이를 조정해야 하며, XGboost 와 LightGBM 을 사용할 때는 트리의 개수, 나무의 최대 깊이, 학습률을 조정해야 한다.

  . 트리의 개수 : 통상적으로 트리의 개수가 많으면 많을 수록 좋은 성능을 내지만, 어느 수준 이상에서는 거의 큰 차일ㄹ 보이지 않는다.

  . 나무의 최대 깊이 : 4이하로 설정해주는 것이 과적합을 피할 수 있어, 바람직하다.

  . 학습률 : 이 값은 작으면 작을 수록 과소적합 위험이 있으며, 크면 클수록 과적합 위험이 있다. 통상적으로 0.1로 설정한다.


 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 모델 개발 프로세스에 대해서 배웠고, 지도학습에서는 선형회귀, 의사결정나무, 신경망 등에 대해서도 배워 볼 수 있었다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 20 회차 미션 시작]

* 복습

 - 홈페이지 분석을 위한 데이터 불러오기, 검정 방법, p-value 값에 대한 해석에 대해서 알아보았다.

 


[02. Part 2) Ch 13. 직접 해봐야 내것이 된다. - 02. 고객 세분화를 통한 마케팅 전략 수립 (실습)]

// 데이터 분할

// 각각의 Quantity 에서 음수를 구분해야 한다.

// 환불 데이터와, 주문 데이터를 각각 구분한다.

 

// 고객별 특징 추출

// 클러스터링을 위해서 데이터 초기화를 해야 한다.

// unique( ) 을 통해서 dataframe 을 만들어 준다.

// 주문 횟수 계산 및 부착을 한다.

// value_counts( ) 를 통해서.. 한 주문에서 여러개의 상품을 구매하기 때문에 CustomerID, InvoiceNo 로 분류 해준다.

// 시리즈로 만들어진 데이터를 to_dict( ) 로 바꾸어 준다. key 사전 id. value 주문횟수

// 주문 횟수가 0인 경우에는 replace 가 되지 않아 Customer ID 가 부착될 수 있다.

// 이러한 경우를 대비하기 위해서 0으로 변경한다.

 

// 반품 횟수에 대서 계산 및 부착

// 위와 동일 한 방법으로 주문횟수와 반품 횟수로 변경해준다.

 

// 주문량 계산 및 부착을 해준다.

// 주문 금액 합계 계산 및 부착

// Quantity 와 UnitPrice 로 주문금액을 만들어준다.

 

// 이 상태에서 최근 주문과 현재 시점까지의 거리를 부착해준다.

// to_datetime( ) 찾아보기

 

// pandas.to_datetime Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

pandas.to_datetime(arg: DatetimeScalar, errors: str = '...', dayfirst: bool = '...', yearfirst: bool = '...', utc: Optional[bool] = '...', format: Optional[str] = '...', exact: bool = '...', unit: Optional[str] = '...', infer_datetime_format: bool = '...', origin='...', cache: bool = '...') → Union[DatetimeScalar, ‘NaTType’]
pandas.to_datetime(arg: ‘Series’, errors: str = '...', dayfirst: bool = '...', yearfirst: bool = '...', utc: Optional[bool] = '...', format: Optional[str] = '...', exact: bool = '...', unit: Optional[str] = '...', infer_datetime_format: bool = '...', origin='...', cache: bool = '...') → ’Series’
pandas.to_datetime(arg: Union[List, Tuple], errors: str = '...', dayfirst: bool = '...', yearfirst: bool = '...', utc: Optional[bool] = '...', format: Optional[str] = '...', exact: bool = '...', unit: Optional[str] = '...', infer_datetime_format: bool = '...', origin='...', cache: bool = '...') → DatetimeIndex

Convert argument to datetime.

Parameters

argint, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like

The object to convert to a datetime.

errors{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

  • If ‘raise’, then invalid parsing will raise an exception.

  • If ‘coerce’, then invalid parsing will be set as NaT.

  • If ‘ignore’, then invalid parsing will return the input.

dayfirstbool, default False

Specify a date parse order if arg is str or its list-likes. If True, parses dates with the day first, eg 10/11/12 is parsed as 2012-11-10. Warning: dayfirst=True is not strict, but will prefer to parse with day first (this is a known bug, based on dateutil behavior).

yearfirstbool, default False

Specify a date parse order if arg is str or its list-likes.

  • If True parses dates with the year first, eg 10/11/12 is parsed as 2010-11-12.

  • If both dayfirst and yearfirst are True, yearfirst is preceded (same as dateutil).

Warning: yearfirst=True is not strict, but will prefer to parse with year first (this is a known bug, based on dateutil behavior).

utcbool, default None

Return UTC DatetimeIndex if True (converting any tz-aware datetime.datetime objects as well).

formatstr, default None

The strftime to parse time, eg “%d/%m/%Y”, note that “%f” will parse all the way up to nanoseconds. See strftime documentation for more information on choices: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.

exactbool, True by default

Behaves as: - If True, require an exact format match. - If False, allow the format to match anywhere in the target string.

unitstr, default ‘ns’

The unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit=’ms’ and origin=’unix’ (the default), this would calculate the number of milliseconds to the unix epoch start.

infer_datetime_formatbool, default False

If True and no format is given, attempt to infer the format of the datetime strings based on the first non-NaN element, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by ~5-10x.

originscalar, default ‘unix’

Define the reference date. The numeric values would be parsed as number of units (defined by unit) since this reference date.

  • If ‘unix’ (or POSIX) time; origin is set to 1970-01-01.

  • If ‘julian’, unit must be ‘D’, and origin is set to beginning of Julian Calendar. Julian day number 0 is assigned to the day starting at noon on January 1, 4713 BC.

  • If Timestamp convertible, origin is set to Timestamp identified by origin.

cachebool, default True

If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. The cache is only used when there are at least 50 values. The presence of out-of-bounds values will render the cache unusable and may slow down parsing.

New in version 0.23.0.

Changed in version 0.25.0: - changed default value from False to True.

Returns

datetime

If parsing succeeded. Return type depends on input:

  • list-like: DatetimeIndex

  • Series: Series of datetime64 dtype

  • scalar: Timestamp

In case when it is not possible to return designated types (e.g. when any element of input is before Timestamp.min or after Timestamp.max) return will have datetime.datetime type (or corresponding array/Series).

 

// recency 로 날짜를 처리한다.

// 하나의 element를 처리 한다는 것이다.

 

// keep = last 를 통해서, 계산량을 감소 시키는 것이다.

// keep 을 last 로 두는 이유는 맨 마지막 값을 두기 위한 것이다.

// CustomerID, Invoice 데이터를 가지고 오고.. 이건 최근성 이라는 column에 넣어준다.

 

// 각각의 스케일이 틀리기 때문에 유클리디안 거리등을 사용하기는 어렵다.

 

// 고객의 주문 특성에 따라서 군집화를 수행하다.

// 군집화 모델을 인스터스화 하고 학습을 시켜준다.

 

// 각각의 데이터를 보고 확인해 본다.

 

// 주요 상품에 대해서 확인을 해본다.

// TransactionEncdoer 를 통해서 나타내본다.

// 희소한지를 알아봐야 한다.

 

// 여기서 모든 것을 사용하는 것은 아니고 빈도가 100회 이상 나온 품목만 사용하면 된다.

// 차원을 줄여서 확인을 해 봐야 한다.

 


 

[02. Part 2) Ch 13. 직접 해봐야 내것이 된다. - 03. 이탈 고객의 고객 여정 탐색하기]

 

* 문제상황

 - 고객 로그 데이터를 바탕으로 이탈한 고객과 이탈하지 않은 고객이 보이는 주요 행동 패턴을 탐색하자!

  (1) 이탈 고객과 비이탈 고객 분리

  (2) 이탈 고객과 비이탈 고객 데이터 내 주요 행동 패턴 추출

  (3) 주요 행동 패턴의 등장 비율 비교

 

* 실습

// sort_values 를 통해서 고객ID, 날짜로 가져오고

// 행동을 unique 상태로 확인하고

// 다른 행동이 있을 수 있기 때문에 ~ not( churn_ID 에 속하지 않는 ID 를 찾아 본다.)

// isin 함수를 통해서 확인

// 이탈이든 아니든 고객ID 의 행동에 따라서 array 형태로 나타낸다.

// 비말 패턴 탐색에서 사용했던 함수들을 가지고 와서 빈말 패턴을 찾아 본다.

 

 


 

[03. Part 3) Ch 14. 이건 꼭 알아야 해 - 지도 학습 모델의 핵심 개념 - 01. 지도학습 개요]

// 기초적인 내용은 생략되어 있다.~

 

* 지도 학습

 - 컴퓨터에게 입력과 출력을 주고, 입력과 출력 간 관계를 학습하여 새로운 입력에 대해 적절한 출력을 내도록 하는 기계학습의 한 분야

 

 - 입력을 특징(feature) 혹은 특징 벡터 (featur vector)라고 하며, 출력을 라벨 (label)이라고 함

// 특징과 라벨간의 관계를 학습하는 거라고 보면 된다.

 - 라벨이 범주형 변수면 분류라고 하며, 연속형 변수면 예측 혹은 회귀라고 한다.

 

* 과적합

 - 지도학습 모델은 학습 데이터를 분류하고 예측하는 수준으로, 학습에 사용되지 않은 데이터도 정확히 분류하고 예측하리라 기대하며, 이러한 기대가 충족되는 경우 일반화 되었다고 한다.

 - 모델이 너무 족잡해서 학습 데이터에 대해서만 정확히 분류하고 예측하는 모델을 과적합되었다고 하며, 반대로 너무 단순해서 어떠한 데이터에 대해서도 부적합한 모델을 과소적합되었다고 한다.

// 적정적합은 오차가 조금씩 있고, 과적합은 오차가 전혀 없는 상태로 본다.

// 적정적합은 학습 데이터를 사용해서 학습을 했을 것이고.. 과적합은 너무 복잡하게 되어 있어서 데이터에 대해서만 과하게 적합이라고 보면 된다.

 

- 과적합과 과소적합에 영향을 끼치는 주요 인자로는 모델의 복잡도, 샘플 수, 차원의 크기 등이 있다.

// 샘플수는 이 모델을 지지하는 근거하는.. 수라고 보면 된다.

// 적으면 성급한 일반화가 되어 버릴 수가 있다.

 

* 데이터 분할

 - 과적합된 모델을 좋게 평가하는 것을 방지하기 위해서, 데이터를 학습 데이터와 평가 데이터로 분할한다.

// 객관적인 결과를 위해서 평가 데이터를 모르게 해야 한다.

 

 - 학습 데이터와 평가 데이터가 지나치게 유사하거나 특정 패턴을 갖지 않도록 분할 해야 한다.

 

* 파라미터와 하이퍼 파라미터

 - 하이퍼 파라미터(hyper parameter)는 일종의 사용자 옵션으로, 모델 성능에 직접적으로 영향을 끼치므로 자세한 데이터 탐색 결과를 바탕으로 선택해야 한다.

// 파라미터는 신경을 많이 쓰지 않는다고 보면 된다.

// 머신러닝에서 무조건 좋다는 것은 없다고 보면 된다. 경험으로 이것이 좀 더 나아 보인다고 생각하면 된다.

 

 

* 이진 분류 모델 평가 : 혼동 행렬

 - 이진 분류 : 클래스 변수의 상태 공간이 크기가 2인 분류

// 상태 공간은 값의 갯수로 보면 된다.

 - 혼동 행렬 : 분류 모델을 평가하는데 사용하는 표

  . Positive class : 분석의 관심 대상 (보통 1로 설정)

  . Negativ class : 분석 관심 대상 외 (보통 0이나 -1로 설정)

 

* 이진 분류 모델 평가 : 대표적인 지표

 - 각 지표의 한계 때문에, 가능한 여러 지표를 사용하여 모델을 평가해야 한다.

// 정확도 가 가장 많이 쓰이고, 공정하고

// F1 은 정확도랑 전혀 관계가 없다고 생각해야 한다.

 

* 다중 분류 모델 평가

 - 다중 분류 : 클래스 변수의 상태 공간이 크기가 3이상인 분류

 - 각 클래스를 긍정으로 간주하여 평가 지표를 계산한 뒤, 이들의 산술 평균이나 가중 평균으로 평가

// 산술 평균 marco average

// 가중 평균 weight average

 

* 예측 모델 평가

 - 대표적인 예측 모델 평가 지표로 루트 평균 제곱 오차 (root mean squared erro ;  RMSE) 와 평균 절대 오차 (mean absolute error ; MAE) 가 있으며, 두 지표 모두 값이 작을 수록 좋음

 

 - RMSE 와 MAE를 정확히 평가하려면, 해당 분야의 도메인 지식이나 클래스 변수의 스케일을 고려해야 한다.

  . 예를 들어, 코스피 지수를 예측하는 모델의 MAE 가 1010 이라면 무의미한 수준의 모델이지만, 전세계 인구 수를 예측하는 모델의 MAE 가 1010 이라면 매우 우수한 모델이다.

 


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 고객 데이터 활용 실습을 해보았고, 고객 이탈 여정에 대해서 간략하게 다른 주제로 살펴 볼 수 있었다. 지도 학습에 대한 주요 개념들을 배웠다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 19 회차 미션 시작]

* 복습

 - 빈발 패턴, 머신러닝에서의 활용, 어떤식을 구성을하면 소비자들이 더 머물고, 다른 전환율이 많이 발생할지에 대해서 알아보았다.

 


[02. Part 2) Ch 13. 직접 해봐야 내것이 된다. - 01. A-B 테스트 - 홈페이지 화면을 어떻게 구성할 것인가 - (실습 - Step 1 ~ 2)]

// %matplotlib inline 그래프 그리기 위한

// plt.rcParams 를 통해서 각각의 옵션을 정해서 나타낸다.

// 1년치 데이터라서 위치를 찾기 어렵기 때문에

// 월별 일 수 누적을 통한 매월 1일 인덱스 정의 (12월 제외) 했다.

// xtick_range = np.cumsum 을 통해서 확인함.

 

// 변동 자체는 그렇게 확 띄거나 변동성이 많이 없는 것 같다.

 

Step 2. 상품 배치와 상품 구매 금액에 따른 관계 분석

// index_col 을 사용해서 불러올때 부터 고객 ID 로 index 를 설정하는 것이다.

// 이런식으로 placement_A, placement_B, placement_C

// 원래는 같은 고객을 불러 오는 것이 더 좋을 수도 있다.

// 정확한 테스트를 위해서는 고객 ID 가 일치하는 것이 더 좋다.

// 현실적으로는 다른 고객들을 불러 온다.

 

// 구매금액이 0인 고객들을 제외하고 필터링

placement_A_without_zero = placement_Aloc[placement_A['구매금액'] != 0]['구매금액'].values

// ndarray 형태로 불러왔다. 뒤에 있는 scipy.stats 를 잘 사용하기 위해서 이런 형태로 불러 온것이다.

// 각 데이터가 정규 분포를 따름을 확인하는 과정

// scipy.stats 를 통해서 어떤 종류인지를 확인한다.

// 일원분산분석 수행을 한다.

// p-value 가 거의 -에 수렴 => A, B, C의 평균은 유의한 차이가 존재

// 이런 상태이기 때문에 사후 분석을 진행했다.

// from statsmodels.stats.multicomp import pairwise_tukeyhsd

// (A, C) ~ B 의 관계임을 확인한다.

// A, C 가 비슷하고 B 가 다르다는 것을 확인할 수 있다.

// 각 데이터가 정규분포를 따르는 것을 확인하고

// 다시 같은 방법으로 확인한다.

// A B 가 차이가 있고, A C, B C 가 차이가 없다.

// 이번에는 A ~ (B, C) 관계임을 확인 할 수 있다.

 

// 구매 여부와 상품 배치 간 관계 파악

// 각각의 데이터를 사용하기 위해서 데이터를 변환, index 가 겹칠 일이 없기 때문에 ignore_index = False 로 두었다.

// 0 이면 구매를 하지 않은것 구매 금액을 체크해서 그걸 boolean 을 다시 astype(int) 을 사용해서 0과 1로 변환한다.

// 데이터를 합친 이유는 범주형 을 분석. 즉, 카이제곱 검정을 하기 위해서 이렇게 사용하였다.

 

// p-value 가 0.06으로 구매여부와 상품배치에는 관계가 있다고 보기 힘들다.

 

[02. Part 2) Ch 13. 직접 해봐야 내것이 된다. - 01. A-B 테스트 - 홈페이지 화면을 어떻게 구성할 것인가 - (실습 - Step 3 ~ 6)]

 

// Step 3. 사이트맵 구성에 따른 체류 시간 차이 분석

// 각각의 sitemap 을 불러 오고, 이번에는 index_col 을 불러 오지 않는다.

// boxplot 함수를 사용해서 확인해본다.

// 하나의 box 는 1부터 시작한다. 그래서 plt.xtics 설정

// 정규 분포를 따르는지 우선 확인

// 거의 0 이다.

// 일원분산분석 : p-value 가 0 에 수렴 > A, B, C 가 거의 차이가 없음.

 

// Step 4. 할인 쿠폰의 효과 분석

// 발행후 구매횟수 에서 발행전 구매 횟수 차이를 구한다.

// .describe( ) 를 통해서 확인해본다.

// std 가 큰것은 이 값이 큰지를 안 큰지를 알 수가 없다. 분석이 필요하다.

 

// 통계량만 분석만 하면 기계적으로 분석할 위험이 있다. 그래서 그래프를 그려서 확인해본다.

 

// Step 5. 체류 시간과 구매 금액 간 관계분석

// 체류시간이 길어지면 구매 금액이 커지는지를 확인해본다.

// 이걸 보기 위해서 상황분석이 필요하다.

// 선형에서는 0.32 상관관계를.. 볼 수 있다.

 

// Step 6. 구매 버튼 배치에 따른 구매율 차이 분석

// fillna 는 결측을 바꾸는 함수이다.

 

// pandas.DataFrame.fillna Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)

Fill NA/NaN values using the specified method.

Parameters

valuescalar, dict, Series, or DataFrame

Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list.

method{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None

Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap.

axis{0 or ‘index’, 1 or ‘columns’}

Axis along which to fill missing values.

inplacebool, default False

If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame).

limitint, default None

If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.

downcastdict, default is None

A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible).

Returns

DataFrame or None

Object with missing values filled or None if inplace=True.


 

[02. Part 2) Ch 13. 직접 해봐야 내것이 된다. - 02 고객 세분화를 통한 마케팅 전략 수립 (문제)]

* 문제상황

 - 주문 내역 데이터를 바탕으로 고객들을 주문 특성과 주문 상품에 따라 그룹화 하고 싶다!

  . 주문 특성 기준 군집화

   -> 환불 데이터와 주문 데이터로 분할

   -> 특징 부착

   -> 코사인 유사도 기반의 계층 군집화 수행

  . 주문 상품 기준 군집화

   -> 판매 상위 100개 상품 출현 여부를 나타내는 데이터로 변환

   -> 자카드 유사도 기반의 계층 군집화 수행

 

* 주문 특성 기준 군집화 - 데이터 분할

 - 해당 데이터에는 주문 데이터와 환불 데이터가 동시에 포함되어 있다.

 - 환불 데이터는 주문 수량이 음수라는 특징이 있어, 데이터를 분할하는데 활용한다.

// 이런 특징을 이용해서 주문 데이터와 환불 데이터를 분류할 것이다.

 

* 주문 특성 기준 군집화 - 특징 추출

 1. 군집화 데이터를 유니크한 고객 ID 컬럼만 있는 데이터프레임으로 초기화

 2. 주문 / 반품 횟수 계산 및 부착 : 고객 ID 와 주문 ID 를 기준으로 중복을 제거 하는 방식으로 유니크한 (고객 ID, 주문 ID) 를 추출한 뒤, 추출한 데이터에서 고객 ID 의 수를 카운트하여 군집화 데이터에 부착

 3. 주문량 계산 및 부착 : 고객 ID에 따른 주문량의 합계를 계산하여 군집화 데이터에 부착

 4. 주문 금액 계산 및 부착 : 주문량과 단가를 곱하여 주문 금액을 계산한 뒤, 고객 ID에 따른 주문 금액의 합계를 계산하여 군집화 데이터에 부착

 5. 최근성 계산 및 부착 : 현재 날짜에서 주문 날짜의 차이를 뺀 뒤, 고객별 해당 값의 최소 값을 군집화 데이터에 부착

 

* 주문 특성 기준 군집화 - 코사인 유사도 기반의 계층 군집화 수행

 - 군집화 데이터에 (군집 개수 = 5, 군집간 거리 = 평균, 거리 척도 = 코사인 유사도)를 갖는 군집화 모델을 학습하여, 군집별 주요 특성을 파악

* 주문 상품 기준 군집화

 - 주문 횟수가 상위 100 등안에 드는 상품들을 기준으로 고객을 상품 구매 여부로 구성된 벡터로 표현

 - 이 데이터에 (군집 개수 = 5, 군집 간 거리 = 평균, 거리 척도 = 자카드 유사도)를 갖는 군집화 모델을 학습하여, 군집별 주요 특성을 파악한다.

// 희소한 데이터에 적절한 유사도 이기때문에 자카드 유사도를 사용했다.

 


 

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 홈페이지 분석을 위한 데이터 불러오기, 검정 방법, p-value 값에 대한 해석에 대해서 알아보았고, 새로운 실습 주제에 대해서 설명함.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 18 회차 미션 시작]

* 복습

 - 빈발 개념에 대해서 배웠으나 약간의 개념 정리가 필요한 것 같다. 어떤 sequence 를 이뤄서 나타내는 조건들에 대해서 분석을 해보고, 어똔 조건에서 어떠한 결과물을 내놓는 것에 대해서는 좀 더 연구가 필요하지 않나 싶다.

 


 

[02. Part 2) Ch 12. 어디서 많이 봤던 패턴이다 싶을 때 - 빈발 패턴 탐색 - 03. 빈발 시계열 패턴 탐색]

* 시계열 데이터란?

 - 시계열 데이터란 각 요소가 (시간, 값) 형태로 구성된 데이터로, 반드시 순서 및 시간을 고려해야 한다.

* 시계열과 시퀀스 데이터의 차이

 - 시계열 데이터와 시퀀스 데이터는 사용하는 인덱스와 값의 종류로 다음과 같이 구분할 수 있다.

 - 다만, 엄밀히 말해서 시계열 데이터도 시퀀스 데이터에 속한다.

// 시퀀스 데이터에 속하기는 하지만 표를 참고하는 것이 더 좋다.

 

 

* 시계열 패턴의 정의

 - 시계열의 패턴은 크게 모양, 변화에 의한 패턴과 값에 의한 패턴으로 구분할 수 있다.

 - 계절성 혹은 주기성이 있는 경우를 제외하면, 모양 패턴을 찾는 것은 거의 불가능에 가깝다.

 

* SAX : 시계열 -> 시퀀스

 - 시계열 데이터는 연속형이라는 특징 때문에 패턴을 찾으려면 이산화가 필요하며, SAX (symbolic aggregate approximatinon) 을 사용하면 시계열 데이터를 효과적으로 이산화할 수 있다.

// 범주화 하기 위한 방법이라고 보면 된다.

 

 - SAX 는 (1)원도우 분할, (2) 원도우별 대표값 계산, (3) 알파벳 시퀀스로 변환이라는 세 단계로 구성된다.

* 실습

// 날짜가 포함되어 있기 때문에 parse_date = True 로 두고 불러 온다.

// 인덱스가 날짜, 좀더 큰 범위로 시간이라고 보면 된다.

// 다별량 시계열은 하나의 시간에 더 많은 데이터가 붙어 있는 것이다.

// 하나만 있는 것은 단별량 시계열이라고 한다.

// 다별량 시계열의 경우가 더 분석하기 힘들다.

 

// segmentation 정의하기

// x : time seires sample, w : windows size, a : alphabe size

// 정상적으로 들어가는 window에 대해서만 처리 해주고...

// 행별 평균을 구한다. mean(axis =1 ) => 결과는 반드시 벡터 일 것이다.

 

// find_break_pints

// 구간의 범위의 기준선들을 의미한다.

// wmv : windows mean vector

 

// conversion_window 정의

// chr( ) 아시키 코드를 알파벳으로 바꿔주는 것이다.

 

// python 내장 함수 chr( )

docs.python.org/3/library/functions.html#chr

chr(i)

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

@classmethod

Transform a method into a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see Function definitions for details.

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section. For more information on class methods, see The standard type hierarchy.

Changed in version 3.9: Class methods can now wrap other descriptors such as property().

 

// 패턴 찾기

// 문자열로 변환 (하나의 리스트만 대상으로 하기에, 이렇게 하는 것이 더 수월)

// join 으로 각 alphabet 을 붙여줌.

 

// find_maximum_frequent_sequence_item 함수

 

// 각각의 신뢰도와 지지도를 확인해 볼 수 있다.

 

[02. Part 2) Ch 12. 어디서 많이 봤던 패턴이다 싶을 때 - 빈발 패턴 탐색 - 04. 머신러닝에서의 빈발 패턴 탐색]

* 추천 시스템

 - "상품 A 를 구매하면 상품 B 도 구매할 것이다" 라는 유의한 연관 규칙이 있다면, 상품 A 를 구매하고 상품 B 를 구매하지 않은 고객에게 상품 B 를 추천해주는 방법에 활용

// 가장 대표적인 것

 - (예시) 아마존의 도서 추천

 

* 시계열 및 시퀀스 데이터에서의 특징 추출

 - 시계열 및 시퀀스 분류 과제에서 특징을 추출하는데도 활용

// 원도우 크기를 정렬해줘야 한다.

// 지도 학습 또는 비지도 학습에 활용할 수 있다는 점이 있다.

 

[02. Part 2) Ch 13. 직접 해봐야 내것이 된다. - 01. A-B 테스트 - 홈페이지 화면을 어떻게 구성할 것인가 - (문제)]

* A/B 테스트란?

 - 임의로 나눈 둘 이상의 집단에 서로 다른 컨텐츠를 제시한 뒤, 통계적 가설 검정을 이용하여 어느 컨텐츠에 대한 반응이 더 효과적인지를 파악하는 방법

ko.wikipedia.org/wiki/A/B_%ED%85%8C%EC%8A%A4%ED%8A%B8

 

A/B 테스트 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 웹 사이트에서의 A/B 테스트 예제. 한 웹 사이트에서 한 개의 버튼 요소의 디자인만 다른 두 가지 버전을 무작위로 방문자에게 제공해, 두 디자인의 상대적인 효

ko.wikipedia.org

A/B 테스트

웹 사이트에서의 A/B 테스트 예제. 한 웹 사이트에서 한 개의 버튼 요소의 디자인만 다른 두 가지 버전을 무작위로 방문자에게 제공해, 두 디자인의 상대적인 효용성을 측정할 수 있다.

마케팅과 웹 분석에서, A/B 테스트(버킷 테스트 또는 분할-실행 테스트)는 두 개의 변형 A와 B를 사용하는 종합 대조 실험(controlled experiment)이다.[1] 통계 영역에서 사용되는 것과 같은 통계적 가설 검정 또는 "2-표본 가설 검정"의 한 형태다. 웹 디자인 (특히 사용자 경험 디자인)과 같은 온라인 영역에서, A/B 테스트의 목표는 관심 분야에 대한 결과를 늘리거나 극대화하는 웹 페이지에 대한 변경 사항이 무엇인지를 규명하는 것이다(예를 들어, 배너 광고의 클릭률(click-through rate)). 공식적으로 현재 웹 페이지에 null 가설과 연관이 있다. A/B 테스트는 변수 A에 비해 대상이 변수 B에 대해 보이는 응답을 테스트하고, 두 변수 중 어떤 것이 더 효과적인지를 판단함으로써 단일 변수에 대한 두 가지 버전을 비교하는 방법이다.[2]

이름에서 알 수 있듯이, 두 버전(A와 B)이 비교되는데 사용자의 행동에 영향을 미칠 수 있는 하나의 변형을 제외하면 동일하다. 버전 A는 현재 사용되는 버전(control)이라고 하는 반면, 버전 B의 일부 사항은 수정된다(treatment). 예를 들어, 전자상거래 웹사이트에서 구매 깔때기은 일반적으로 A/B 테스트하기 좋은 대상으로, 하락률에 있어 수익 한계선에 대한 개선이 판매에 있어 상당한 이익을 나타낼 수 있기 때문이다. 항상 그런 것은 아니지만, 때때로 텍스트, 레이아웃, 이미지 그리고 색상과 같은 요소들을 테스트함으로써 현저한 향상을 볼 수 있다.[3]

다변량 테스트 또는 다항 테스트가 A/B 테스트와 유사하지만, 동시에 두 개 이상의 버전을 테스트하거나 좀 더 많은 컨트롤들을 테스트할 수 있다. 두 개 이상의 버전 또는 동시에 더 많이 사용을 제어한다. 단순한 A/B 테스트는 설문 데이터, 오프라인 데이터 그리고 다른 좀 더 복잡한 현상과 같이, 실측, 유사 실험 또는 기타 비 실험 상황에서는 유효하지 않다.

A/B 테스트는 그 접근 방식이 다양한 연구 관례에서 일반적으로 사용되는, 피험자간 설계와 유사하긴 하지만, 특정 틈새 영역에서 철학과 사업 전략의 변화로 마케팅되었다.[4][5][6] 웹 개발 철학으로서의 A/B 테스트는 해당 영역을 증거 기반의 실천으로의 폭넓은 움직임으로 이끈다. 대부분의 마케팅 자동화 도구가 현재 일반적으로 A/B 테스트를 지속적으로 실행할 수 있는 기능과 함께 제공되고 있기 때문에, A/B 테스트가 거의 모든 영역에서 지속적으로 수행될 수 있는 것으로 간주되는 것이 A/B 테스트의 이점이다. 이로써 현재의 리소스를 사용해 웹 사이트와 다른 도구를 업데이트해 트렌드 변화를 유지할 수 있다.

 

// 버튼이 어떻게 배치되었을 때 클릭을 많이 하는지에 대해서

 

* 문제상황

 - 온라인 쇼핑몰 페이지 구성에 따른 다양한 실험 결과를 바탕으로 전환율이 최대가 되는 구성을 하고 싶다!

// 전환율은 어떤 상품을 구매율

 

 - 관련 데이터 : AB 테스트 폴더 내 모든 데이터

 

* Step 1. 현황 파악

 - 관련 데이터 : 일별현황데이터.csv

 

 - 분석 내용

  (1) 구매자수, 방문자수, 총 판매 금액에 대한 기술 통계

  (2) 일자별 방문자수 추이 파악

  (3) 일자별 구매자수 추이 파악

  (4) 일자별 총 판매 금액 추이 파악

 

* Step 2. 상품 배치와 상품 구매 금액에 따른 관계 분석

 - 관련 데이터

  . 상품배치_A.csv

  . 상품배치_B.csv

  . 상품배치_C.csv

 

 - 분석 내용

  (1) 일원분산분석을 이용한 상품 배치에 따른 상품 구매 금액 평균 차이 분석 (상품 구매 금액 0원 미포함)

  (2) 일원분산분석을 이용한 상품 배치에 따른 상품 구매 금액 평균 차이 분석 (상품 구매 금액 0원 포함)

  (3) 카이제곱 검정을 이용한 구매 여부와 상품 배치 간 독립성 파악

// 서로 독립적인지를 확인해 볼 것이다.

 

* Step 3. 사이트맵 구성에 따른 체류 시간 차이 분석

 - 관련 데이터

  . 사이트맵_A.csv

  . 사이트맵_B.csv

  . 사이트맵_C.csv

 

 - 분석 내용

  (1) 사이트맵별 체류시간 평균 계산

  (2) 일원분산분석을 이용한 사이트맵에 따른 체류 시간 평균 차이 분석 (박스 플롯 포함)

 

* Step 4. 할인 쿠폰의 효과 분석

 - 관련 데이터 : 할인쿠폰 발행효과.csv

 

 - 분석내용

  (1) 발행후와 전의 구매 횟수 차이에 대한 기술 통계

  (2) 발행전, 발행후의 구매 횟수에 대한 박스폴롯 시각화

  (3) 쌍체 표본 t - 검정을 이용한 차이 유의성 검정

// 유의하지 않다면 굳이 할인쿠폰을 발행할 필요가 없는 것이다.

 

* Step 5. 체류 시간과 구매 금액 간 관계 분석

 - 관련 데이터 : 체류시간_구매금액.csv

 - 분석 내용

  (1) 구매 금액과 체류 시간의 산점도 시각화

  (2) 구매 금액과 체류 시간 간 상관관계 분석

 

* Step 6. 구매 버튼 배치에 따른 구매율 차이 분석

 - 관련 데이터 : 구매버튼_버튼타입_통계.xlsx

 

 - 분석내용

  (1) 결측 대체

  (2) pivot table을 이용한 교차 테이블 생성

  (3) 카이제곱검정을 이용한 독립성 검정

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 시계열 데이터와 빈발 패턴, 그리고 머신러닝에서의 활용에 대해서 어떻게 활용할 것인가에 대해서 배웠다. 그리고, 새로운 프로젝트를 통해서 어떻게 이것을 분석하고 검정하는지에 대한 문제에 대해 알아보았다.

다음에는 실습을 통해서 어떤식으로 해결해 나갈지를 알 수 있을 것이다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 16 회차 미션 시작]

* 복습

 - 군집화 및 연관 규칙 탐색 이론에 대해서 배워 보았다.

 


 

[02. Part 2) 어디서 많이 봤던 패턴이다 싶을 때 - 빈발 패턴 탐색 - 01-2. 연관 규칙 탐색(실습)]

// value_counts 를 통해서 빈도를 item 에 대한 빈도를 보는 것이다.

 

// order_id 기준으로 product_id 를 apply(list) 를 통해서 list 형태로 정리를 하는 것이다.

 

// TransactionEncoder 로 instance 를 시켜서 fit 를 학습을 시키는 것이다. 거기에 transform 을 해줘야 한다.

// 결과는 ndarray 형태로 return 이 된다. ndarrray는 분석하기가 쉽지 않기 때문에 dataframe 화 시켜서 확인한다.

// False 는 0, True 1

// 매우 희소한 데이터 형태로 나왔다. (sparse) 하다고 볼 수 있다.

 

// apriori 함수로 원하는 데이터를 찾아 본다. min_support = 0.003 # 0.3% 구매한 상품만 대상으로 했다. 이것 또한 흔치 않는 데이터라고 보면 된다.

 

[02. Part 2) 어디서 많이 봤던 패턴이다 싶을 때 - 빈발 패턴 탐색 - 02-1. 빈발 시퀀스 탐색 (이론)]

* 시퀀스 데이터란?

 - 시퀀스 데이터란 각 요소가 (순서, 값) 형태로 구성된 데이터로, 분석 시에 반드시 순서를 고려해야 한다.

// 일종의 tuple, vector 형태로 된것

// 이벤트.. 즉 사건이 될 수도 있고..

 - 로그 데이터 대부분이 순서가 있는 시퀀스 데이터이다.

  . 고객 구매 기록

  . 고격 여정

  . 웹 서핑 기록

 

* 시퀀스 데이터에서의 빈발 패턴

 - 시퀀스 데이터에서의 빈발 패턴은 반드시 순서가 고려되어야 한다.

 

* 지지도와 신뢰도

 - 분석 목적에 따라, 특정 패턴의 등장 여부에 대한 정의가 필요하다.

 

 - 일반적으로, 윈도우 내 (크기 L) 에 특정 이벤트가 발생했는지를 기준으로 패턴의 등장 여부를 확인

 - 지지도와 신뢰도에 대한 정의는 일반 데이터에 대한 것과 같으나, 출현 횟수를 계산하는 방식이 다름

 

* 순서를 고려한 연관규칙 탐사

 - 시퀀스 데이터에 대한 연관규칙 탐사에 대해서는 A -> B와 B -> A 가 다른 지지도를 갖기 때문에, 같은 항목 집합으로부터 규칙을 생성할 수 없다.

 

 - 신뢰도에 대한 apriori 원리는 성립한다.

 

 - 따라서 개별 요소(이벤트)에 다른 요소를 추가하는 방식으로 규칙을 아래와 같이 직접 찾아 나가야 한다.

// 이벤트 목록 -> 빈발 이벤트 추출 -> 추가 및 지지도 계산 -> 집합탐색 -> 규칙 만들기

// 추출은 응용을 하는 것이라고 보면 된다.

// 신뢰도가 있기 때문에 가능한 것이다.

 

* 동적 프로그래밍

 - 원 문제를 작은 문제로 분할한 다음 점화식으로 만들어 재귀적인 형태로 원 문제를 해결하는 방식

// 동적 프로그래밍에 대해서는 좀더 조사가 필요하다.~

 - 시퀀스 데이터에 대한 연관 규칙 탐사 적용을 위한 동적 프로그래밍 구조

 

// Dynamic Programming 관련 괜찮은 사이트

towardsdatascience.com/beginners-guide-to-dynamic-programming-8eff07195667

What is Dynamic Programming?
Dynamic programming is a terrific approach that can be applied to a class of problems for obtaining an efficient and optimal solution.
In simple words, the concept behind dynamic programming is to break the problems into sub-problems and save the result for the future so that we will not have to compute that same problem again. Further optimization of sub-problems which optimizes the overall solution is known as optimal substructure property.
Two ways in which dynamic programming can be applied:
Top-Down:
In this method, the problem is broken down and if the problem is solved already then saved value is returned, otherwise, the value of the function is memoized i.e. it will be calculated for the first time; for every other time, the stored value will be called back. Memoization is a great way for computationally expensive programs. Don’t confuse memoization with memorize.

// memoization..으로 접근

Memoize != memorize

Bottom-Up:
This is an effective way of avoiding recursion by decreasing the time complexity that recursion builds up (i.e. memory cost because of recalculation of the same values). Here, the solutions to small problems are calculated which builds up the solution to the overall problem. (You will have more clarity on this with the examples explained later in the article).
Understanding Dynamic Programming With Examples

Let’s start with a basic example of the Fibonacci series.

Fibonacci series is a sequence of numbers in such a way that each number is the sum of the two preceding ones, starting from 0 and 1.

F(n) = F(n-1) + F(n-2)

 

  • Recursive method:
def r_fibo(n):
   if n <= 1:
       return n
   else:
       return(r_fibo(n-1) + r_fibo(n-2))
Here, the program will call itself, again and again, to calculate further values. The calculation of the time complexity of the recursion based approach is around O(2​^N). The space complexity of this approach is O(N) as recursion can go max to N.
For example-
F(4) = F(3) + F(2) = ((F(2) + F(1)) + F(2) = ((F(1) + F(0)) + F(1)) + (F(1) + F(0))
In this method values like F(2) are computed twice and calls for F(1) and F(0) are made multiple times. Imagine the number of repetitions if you have to calculate it F(100). This method is ineffective for large values.
  • Top-Down Method
def fibo(n, memo):
  if memo[n] != null:
    return memo[n]
  if n <= 1:
    return n
  else:
    res = fibo(n-1) + fibo(n+1)
    memo[n] = res
    return res
Here, the computation time is reduced significantly as the outputs produced after each recursion are stored in a list which can be reused later. This method is much more efficient than the previous one.
  • Bottom down
def fib(n):
  if n<=1:
    return n
  list_ = [0]*(n+1)
  list_[0] = 0
  list_[1] = 1 
  for i in range(2, n+1):
    list_[i] = list_[i-1] + list[i-2]
  return list_[n]
This code doesn’t use recursion at all. Here, we create an empty list of length (n+1) and set the base case of F(0) and F(1) at index positions 0 and 1. This list is created to store the corresponding calculated values using a for loop for index values 2 up to n.
Unlike in the recursive method, the time complexity of this code is linear and takes much less time to compute the solution, as the loop runs from 2 to n, i.e., it runs in O(n). This approach is the most efficient way to write a program.

Time complexity: O(n) <<< O(2​^N)

 

 

// Tablulation vs Memoization

www.geeksforgeeks.org/tabulation-vs-memoization/

 

There are following two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving DP problem:
    1. Tabulation: Bottom Up
    2. Memoization: Top Down
Before getting to the definitions of the above two terms consider the below statements:
  • Version 1: I will study the theory of Dynamic Programming from GeeksforGeeks, then I will practice some problems on classic DP and hence I will master Dynamic Programming.
  • Version 2: To Master Dynamic Programming, I would have to practice Dynamic problems and to practice problems – Firstly, I would have to study some theory of Dynamic Programming from GeeksforGeeks
Both the above versions say the same thing, just the difference lies in the way of conveying the message and that’s exactly what Bottom Up and Top Down DP do. Version 1 can be related to as Bottom Up DP and Version-2 can be related as Top Down Dp.
Tabulation Method – Bottom Up Dynamic Programming 
As the name itself suggests starting from the bottom and cumulating answers to the top. Let’s discuss in terms of state transition.
 
 
Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So,  we need to find the value of destination state i.e dp[n].
If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it Bottom Up approach as it is quite clear that we started our transition from the bottom base state and reached the top most desired state.
Now, Why do we call it tabulation method?
To know this let’s first write some code to calculate the factorial of a number using bottom up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x.
Now, it is quite obvious that dp[x+1] = dp[x] * (x+1)
// Tabulated version to find factorial x. int dp[MAXN]; // base case int dp[0] = 1; for (int i = 1; i< =n; i++) { dp[i] = dp[i-1] * i; }

 

The above code clearly follows the bottom-up approach as it starts its transition from the bottom-most base case dp[0] and reaches its destination state dp[n]. Here, we may notice that the dp table is being populated sequentially and we are directly accessing the calculated states from the table itself and hence, we call it tabulation method.
Memoization Method – Top Down Dynamic Programming 
Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP.
Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom most base state.
Once again, let’s write the code for the factorial problem in the top-down fashion
// Memoized version to find factorial x. // To speed up we store the values // of calculated states // initialized to -1 int dp[MAXN] // return fact x! int solve(int x) { if (x==0) return 1; if (dp[x]!=-1) return dp[x]; return (dp[x] = x * solve(x-1)); }
As we can see we are storing the most recent cache up to a limit so that if next time we got a call from the same state we simply return it from the memory. So, this is why we call it memoization as we are storing the most recent state values.
In this case the memory layout is linear that’s why it may seem that the memory is being filled in a sequential manner like the tabulation method, but you may consider any other top down DP having 2D memory layout like Min Cost Path, here the memory is not filled in a sequential manner.

This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

 

 

* 순서를 고려한 연관규칙 탐사 (예시 : L = 2, 최소 지지도 = 2)

 

* 순서를 고려한 연관규칙 탐사 (예시 : L = 2, 최소 지지도 = 3)


 

 

[02. Part 2) 어디서 많이 봤던 패턴이다 싶을 때 - 빈발 패턴 탐색 - 02-2. 빈발 시퀀스 탐색 (실습)]

// 만약에 순서가 없으면 순서를 만들면 된다.

 

// 순서가 중요한 데이터이기 때문에 고객ID, 순서를 정리를 해줘야 한다.

 

// unique () 찾아보기

// itertools.product() 함수에 대해서 알아보기

 

// pattern에 포함된 모든 아이템 집합이 recor에 포함된 아이템 집합에 속하지 않는지 체크

// 순서가 있기 때문에 반드시 존재했다고 볼 순 없다.

 

// 가능한 모든 조합에서 위치 간거리가 L이하면 True 를 반환

 

// find_maximum_frequent_sequence_item 함수를 만든다.

// 만들어진 함수들을 이용해서 원하는 프로젝트등에 활용해서 사용하면 된다.

 

// pandas.unique Documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.unique.html

pandas.unique(values)

Hash table-based unique. Uniques are returned in order of appearance. This does NOT sort.

Significantly faster than numpy.unique. Includes NA values.

Parametersvalues1d array-likeReturnsnumpy.ndarray or ExtensionArray

The return can be:

  • Index : when the input is an Index

  • Categorical : when the input is a Categorical dtype

  • ndarray : when the input is a Series/ndarray

Return numpy.ndarray or ExtensionArray.

The return can be:

  • Index : when the input is an Index

  • Categorical : when the input is a Categorical dtype

  • ndarray : when the input is a Series/ndarray

Return numpy.ndarray or ExtensionArray.

 

Index.unique

Return unique values from an Index.

Series.unique

Return unique values of Series object.

 

// itertools.product Documentation

docs.python.org/3/library/itertools.html#itertools.product

 

itertools.product(*iterables, repeat=1)

Cartesian product of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.

To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).

This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:

def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it only useful with finite inputs.


[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 빈발 개념에 대해서 배웠으나 약간의 개념 정리가 필요한 것 같다. 어떤 sequence 를 이뤄서 나타내는 조건들에 대해서 분석을 해보고, 어똔 조건에서 어떠한 결과물을 내놓는 것에 대해서는 좀 더 연구가 필요하지 않나 싶다.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 16 회차 미션 시작]

* 복습

 - 머신러닝에서의 상관관계 분석을 하였고, 군집화를 어떻게 해야 할 것인지에 대해서 개념 및 이론 수업에 대해서 들어보았다.

 


[02. Part 2) 탐색적 데이터 분석 Chapter 11. 비슷한 애들 모여라 - 군집화 - 02. 계층적 군집화 (실습)]

 

// set_index 는 컬럼을 인덱스화 시켜주는 것이다.

// fit 앞에것만 사용해서는 군집화가 진행되지 않는다. fit 을 통해서 학습시킨다고 봐야 한다.

 

// 이런 데이터는 더미화하기에는 좋은 데이터는 아니다.

 

* (Tip) Pandas.crosstab

 - 일반적인 거래 데이터를 교차 테이블 형태로 변환하는데 사용하는 함수

- 참고 : 카이제곱 검정

//이런식의 데이터를 얻게 된다.

 

// jaccard, average 를 통해서 작업을 진행

// fit 을 해줘야 한다. 물론.

 

[02. Part 2) 탐색적 데이터 분석 Chapter 11. 비슷한 애들 모여라 - 군집화 - 03. k-평균 군집화]

// 가장 대표적인 군집화라고 보면 된다.

 

* 기본 개념

 - (1) k개의 중심점 설정, (2) 샘플 할당, (3) 중심점 업데이트를 반복하는 방식으로 k개의 군집을 생성하는 알고리즘

// k 는 군집의 갯수

* k - 평균 군집화의 장단점

 - 장점 (1) 상대적으로 적은 계산량 O(n)

 - 장점 (2) 군집 개수 설정에 제약이 없고 쉽다.

// 가장 널리 쓰이는 군집화라고 보면 된다.

 

 - 단점 (1) 초기 중심 설정에 따른 수행할 때마다 다른 결과를 낼 가능성 존재 (임의성 존재 O)

// 초기점의 설정에 따라서 결과가 다를 수 있다는 임의성이 존재한다.

 - 단점 (2) 데이터 분포가 특이하거나 군집별 밀도 차이가 존재하면 좋은 성능을 내기 어렵다.

 - 단점 (3) 유클리디안 거리만 사용해야 한다.

 - 단점 (4) 수렴하지 않을 가능성 존재

 

* sklearn.cluster.KMeans

 - 주요입력

  . n_cluster : 군집 개수

  . max_iter : 최대 이터레이션 함수

 - 주요 메서드

  . fit(x) : 데이터 x에 대한 군집화 모델 학습

  . fit_predict(x) : 데이터 x에 대한 군집화 모델 학습 및 라벨 반환

 - 주요 속성

  . labels_ : fitting 한 데이터에 있는 샘플들이 속한 군집 정보 (ndarray)

  . cluster_center_: fitting 한 데이터에 있는 샘플들이 속한 군집 중심점 (ndarray)

 

// sklearn.cluster.KMeans Documentation

scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html

class sklearn.cluster.KMeans(n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='deprecated', verbose=0, random_state=None, copy_x=True, n_jobs='deprecated', algorithm='auto')

K-Means clustering.

Read more in the User Guide.

Parameters

n_clustersint, default=8

The number of clusters to form as well as the number of centroids to generate.

init{‘k-means++’, ‘random’, ndarray, callable}, default=’k-means++’

Method for initialization:

‘k-means++’ : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details.

‘random’: choose n_clusters observations (rows) at random from data for the initial centroids.

If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.

If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization.

n_initint, default=10

Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.

max_iterint, default=300

Maximum number of iterations of the k-means algorithm for a single run.

tolfloat, default=1e-4

Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence.

precompute_distances{‘auto’, True, False}, default=’auto’

Precompute distances (faster but takes more memory).

‘auto’ : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision.

True : always precompute distances.

False : never precompute distances.

Deprecated since version 0.23: ‘precompute_distances’ was deprecated in version 0.22 and will be removed in 0.25. It has no effect.

verboseint, default=0

Verbosity mode.

random_stateint, RandomState instance, default=None

Determines random number generation for centroid initialization. Use an int to make the randomness deterministic. See Glossary.

copy_xbool, default=True

When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True (default), then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. Note that if the original data is not C-contiguous, a copy will be made even if copy_x is False. If the original data is sparse, but not in CSR format, a copy will be made even if copy_x is False.

n_jobsint, default=None

The number of OpenMP threads to use for the computation. Parallelism is sample-wise on the main cython loop which assigns each sample to its closest center.

None or -1 means using all processors.

Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 0.25.

algorithm{“auto”, “full”, “elkan”}, default=”auto”

K-means algorithm to use. The classical EM-style algorithm is “full”. The “elkan” variation is more efficient on data with well-defined clusters, by using the triangle inequality. However it’s more memory intensive due to the allocation of an extra array of shape (n_samples, n_clusters).

For now “auto” (kept for backward compatibiliy) chooses “elkan” but it might change in the future for a better heuristic.

Changed in version 0.18: Added Elkan algorithm

 

Attributes

cluster_centers_ndarray of shape (n_clusters, n_features)

Coordinates of cluster centers. If the algorithm stops before fully converging (see tol and max_iter), these will not be consistent with labels_.

labels_ndarray of shape (n_samples,)

Labels of each point

inertia_float

Sum of squared distances of samples to their closest cluster center.

n_iter_int

Number of iterations run.

 

* 실습

// 결과가 아니라, 모델이라고 생각하면 된다.

 

[02. Part 2) 어디서 많이 봤던 패턴이다 싶을 때 - 빈발 패턴 탐색 - 01-1. 연관 규칙 탐색(이론)]

* 연관규칙이란?

 - "A가 발생하면 B도 발생하더라"라는 형태의 규칙으로, 트랜잭션 데이터를 탐색하는데 사용

  . A : 부모 아이템 집합 (antecedent)

  . B : 자식 아이템 집합 (consequent)

  . A 와 B 는 모두 공집합이 아닌 집합이며, A n B = 공집합 을 만족함 (즉, 공통되는 요소가 없다.)

 

 - 규칙 예시

 

* 연관규칙 탐색이란?

 - 트랜잭션 데이터에서 의미있는 연관규칙을 효율적으로 탐색하는 작업

// 연관규칙으로 만들 수 있는 경우의 수가 굉장히 많은데 그걸 효율적으로 탐색하는 작업이 필요하다.

 

* 연관규칙 탐색의 활용 사례 : 월마트

 - 월마트에서는 엄청나게 많은 영수증 데이터에 대해 연관규칙 탐색을 적용하여, 매출을 향상시킨다.

 

* 연관규칙의 평가 척도

 - 지지도 (supprot) : 아이템 집합이 전체 트랜잭션 데이터에서 발생한 비율

 - 신뢰도 (confidence) : 부모 아이템 집합이 등장한 트랜잭션 데이터에서 자식 아이템 집합이 발생한 비율

 

 - 지지도와 신뢰도가 높은 연관규칙을 좋은 규칙이라고 판단

 

* 연관규칙의 평가 척도 계산 예시

// 5 는 거래 ID 의 모든 수를 이야기 하고, 4 는 빵을 샀을 경우

 

* 아이템집합 격자

 - 아이템 집합과 그 관계를 한 눈에 보여주기 위한 그래프

 

* 지지도에 대한 Apriori 원리 : 개요

 - S (A -> B) 가 최소 지지도 (min supprot) 이상이면, 이 규칙을 빈발하다고 한다.

 - 아이템 집합의 지지도가 최소 지지도 이상이면, 이 집합을 빈발하다고 한다.

 - 지지도에 대한 Apriori 원리 : 어떤 아이템 집합이 빈발하면, 이 아이템의 부분 집합도 빈발한다.

 

* 지지도에 대한 Apriori 원리 : 작용

 

* 지지도에 대한 Apriori 원리 : 후보 규칙 생성

 - Apriori 원리를 사용하여 모든 최대 빈발 아이템 집합을 찾은 후, 후보 규칙을 모두 생성한다.

  . 최대 빈발 아이템 집합 : 최소 지지도 이상이면서, 이 집합의 모든 모집합이 빈발하지 않는 집합

// 모든 집합이라는 것은 부분 집합의 반대라고 생각하면 좋을 것 같다.

  . (예시) {A, B, C} 가 빈발한데, {A, B, C, D}, {A, B, C, E}등이빈발하지않으면, {A, B, C}를최대빈발아이템집합이라고한다.

 

 - 만약, {A, B, C} 가 최대 빈발아이템 집합이면, 생성 가능한 후보 규칙은 다음과 같다.

 

* 신뢰도에 대한 Apriori 원리

 - 동일한 아이템 집합으로 생성한 규칙 X1 -> Y1, X2 -> Y2 에 대해서, 다음이 성립한다.

// 동일한 아이템 집합이라는 것이 중요하다.

 

* 신뢰도에 대한 Apriori 원리 : 적용

 

* 관련 모듈 : mlxtend

 - apriori 함수를 이용한 빈발 아이템 집합 탐색과 association_rules 함수를 이용하여 연관규칙을 탐색하는 두 단계로 수행

 - mlxtend.frequent_patterns.apriori(df, min_support):

  . df : one hot encoding 형태의 데이터 프레임

  . min_support : 최소 지지도

 

 - mlxtend.frequent_patterns.association_rules(frequent_dataset, metric, min_threshod):

  . frequent_dataset 에서 찾은 연관 규칙을 데이터 프레임 형태로 반환

  . metric : 연관 규칙을 필터링하기 위한 유용성 척도 (default : confidence_

  . min_threshold : 지정한 metric 의 최소 기준치

 

* mlxtend.preprocessin.gTransactionEncoder

 - 연관 규칙 탐사에 적절하게 거래 데이터 구조를 바꾸기 위한 함수

 - 인스턴스 생성 후, fit(data).transform(data) 를 이용하여 data를 각 아이템의 출현 여부를 갖는 ndarray 및 DataFrame으로 변환

// 범주형 변수들을 처리 할때 OHE 을 사용한다.

 

// mlxtend.frequent_patterns.apriori 관련 사이트

rasbt.github.io/mlxtend/user_guide/frequent_patterns/apriori/

apriori(df, min_support=0.5, use_colnames=False, max_len=None, verbose=0, low_memory=False)

Get frequent itemsets from a one-hot DataFrame

Parameters

  • df : pandas DataFrame

    pandas DataFrame the encoded format. Also supports DataFrames with sparse data; for more info, please see (https://pandas.pydata.org/pandas-docs/stable/ user_guide/sparse.html#sparse-data-structures)

    Please note that the old pandas SparseDataFrame format is no longer supported in mlxtend >= 0.17.2.

    The allowed values are either 0/1 or True/False. For example,

Apple Bananas Beer Chicken Milk Rice 0 True False True True False True 1 True False True False False True 2 True False True False False False 3 True True False False False False 4 False False True True True True 5 False False True False True True 6 False False True False True False 7 True True False False False False

  • min_support : float (default: 0.5)

    A float between 0 and 1 for minumum support of the itemsets returned. The support is computed as the fraction transactions_where_item(s)_occur / total_transactions.

  • use_colnames : bool (default: False)

    If True, uses the DataFrames' column names in the returned DataFrame instead of column indices.

  • max_len : int (default: None)

    Maximum length of the itemsets generated. If None (default) all possible itemsets lengths (under the apriori condition) are evaluated.

  • verbose : int (default: 0)

    Shows the number of iterations if >= 1 and low_memory is True. If

    =1 and low_memory is False, shows the number of combinations.

  • low_memory : bool (default: False)

    If True, uses an iterator to search for combinations above min_support. Note that while low_memory=True should only be used for large dataset if memory resources are limited, because this implementation is approx. 3-6x slower than the default.

Returns

pandas DataFrame with columns ['support', 'itemsets'] of all itemsets that are >= min_support and < than max_len (if max_len is not None). Each itemset in the 'itemsets' column is of type frozenset, which is a Python built-in type that behaves similarly to sets except that it is immutable (For more info, see https://docs.python.org/3.6/library/stdtypes.html#frozenset).

 

Examples

For usage examples, please see http://rasbt.github.io/mlxtend/user_guide/frequent_patterns/apriori/

 

 

// mlxtend.frequent_patterns.association_rules 관련 사이트

rasbt.github.io/mlxtend/user_guide/frequent_patterns/association_rules/

association_rules(df, metric='confidence', min_threshold=0.8, support_only=False)

Generates a DataFrame of association rules including the metrics 'score', 'confidence', and 'lift'

Parameters

  • df : pandas DataFrame

    pandas DataFrame of frequent itemsets with columns ['support', 'itemsets']

  • metric : string (default: 'confidence')

    Metric to evaluate if a rule is of interest. Automatically set to 'support' if support_only=True. Otherwise, supported metrics are 'support', 'confidence', 'lift',

'leverage', and 'conviction' These metrics are computed as follows:

- support(A->C) = support(A+C) [aka 'support'], range: [0, 1] - confidence(A->C) = support(A+C) / support(A), range: [0, 1] - lift(A->C) = confidence(A->C) / support(C), range: [0, inf] - leverage(A->C) = support(A->C) - support(A)*support(C), range: [-1, 1] - conviction = [1 - support(C)] / [1 - confidence(A->C)], range: [0, inf]

  • min_threshold : float (default: 0.8)

    Minimal threshold for the evaluation metric, via the metric parameter, to decide whether a candidate rule is of interest.

  • support_only : bool (default: False)

    Only computes the rule support and fills the other metric columns with NaNs. This is useful if:

    a) the input DataFrame is incomplete, e.g., does not contain support values for all rule antecedents and consequents

    b) you simply want to speed up the computation because you don't need the other metrics.

Returns

pandas DataFrame with columns "antecedents" and "consequents" that store itemsets, plus the scoring metric columns: "antecedent support", "consequent support", "support", "confidence", "lift", "leverage", "conviction" of all rules for which metric(rule) >= min_threshold. Each entry in the "antecedents" and "consequents" columns are of type frozenset, which is a Python built-in type that behaves similarly to sets except that it is immutable (For more info, see https://docs.python.org/3.6/library/stdtypes.html#frozenset).

Examples

For usage examples, please see http://rasbt.github.io/mlxtend/user_guide/frequent_patterns/association_rules/

 

// mlxtend.preprocessin.gTransactionEncoder 관련 사이트

rasbt.github.io/mlxtend/user_guide/preprocessing/TransactionEncoder/

TransactionEncoder()

Encoder class for transaction data in Python lists

Parameters

None

Attributes

columns_: list List of unique names in the X input list of lists

Examples

For usage examples, please see http://rasbt.github.io/mlxtend/user_guide/preprocessing/TransactionEncoder/

Methods


fit(X)

Learn unique column names from transaction DataFrame

Parameters

  • X : list of lists

    A python list of lists, where the outer list stores the n transactions and the inner list stores the items in each transaction.

    For example, [['Apple', 'Beer', 'Rice', 'Chicken'], ['Apple', 'Beer', 'Rice'], ['Apple', 'Beer'], ['Apple', 'Bananas'], ['Milk', 'Beer', 'Rice', 'Chicken'], ['Milk', 'Beer', 'Rice'], ['Milk', 'Beer'], ['Apple', 'Bananas']]


fit_transform(X, sparse=False)

Fit a TransactionEncoder encoder and transform a dataset.


get_params(deep=True)

Get parameters for this estimator.

Parameters

  • deep : boolean, optional

    If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

  • params : mapping of string to any

    Parameter names mapped to their values.


inverse_transform(array)

Transforms an encoded NumPy array back into transactions.

Parameters

  • array : NumPy array [n_transactions, n_unique_items]

    The NumPy one-hot encoded boolean array of the input transactions, where the columns represent the unique items found in the input array in alphabetic order

    For example,

array([[True , False, True , True , False, True ], [True , False, True , False, False, True ], [True , False, True , False, False, False], [True , True , False, False, False, False], [False, False, True , True , True , True ], [False, False, True , False, True , True ], [False, False, True , False, True , False], [True , True , False, False, False, False]])

 

The corresponding column labels are available as self.columns_, e.g., ['Apple', 'Bananas', 'Beer', 'Chicken', 'Milk', 'Rice']

Returns

  • X : list of lists

    A python list of lists, where the outer list stores the n transactions and the inner list stores the items in each transaction.

    For example,

[['Apple', 'Beer', 'Rice', 'Chicken'], ['Apple', 'Beer', 'Rice'], ['Apple', 'Beer'], ['Apple', 'Bananas'], ['Milk', 'Beer', 'Rice', 'Chicken'], ['Milk', 'Beer', 'Rice'], ['Milk', 'Beer'], ['Apple', 'Bananas']]


set_params(params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form <component>__<parameter> so that it's possible to update each component of a nested object.

Returns

self


transform(X, sparse=False)

Transform transactions into a one-hot encoded NumPy array.

Parameters

  • X : list of lists

    A python list of lists, where the outer list stores the n transactions and the inner list stores the items in each transaction.

    For example, [['Apple', 'Beer', 'Rice', 'Chicken'], ['Apple', 'Beer', 'Rice'], ['Apple', 'Beer'], ['Apple', 'Bananas'], ['Milk', 'Beer', 'Rice', 'Chicken'], ['Milk', 'Beer', 'Rice'], ['Milk', 'Beer'], ['Apple', 'Bananas']]

    sparse: bool (default=False) If True, transform will return Compressed Sparse Row matrix instead of the regular one.

Returns

  • array : NumPy array [n_transactions, n_unique_items]

    if sparse=False (default). Compressed Sparse Row matrix otherwise The one-hot encoded boolean array of the input transactions, where the columns represent the unique items found in the input array in alphabetic order. Exact representation depends on the sparse argument

    For example, array([[True , False, True , True , False, True ], [True , False, True , False, False, True ], [True , False, True , False, False, False], [True , True , False, False, False, False], [False, False, True , True , True , True ], [False, False, True , False, True , True ], [False, False, True , False, True , False], [True , True , False, False, False, False]]) The corresponding column labels are available as self.columns_, e.g., ['Apple', 'Bananas', 'Beer', 'Chicken', 'Milk', 'Rice']

ython

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 군집화라는 개념도 어떠한 범주형 형태의 데이터 가공을 통해서 관련된 어떤 변수를 추천한다거나 분석하는 개념

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 15 회차 미션 시작]

* 복습

 - 일원분석, 상관분석, 카이제곱 검정에 대해서 알아보았다.

 

[02. Part 2) 탐색적 데이터 분석 Chapter 10. 둘 사이에는 무슨 관계가 있을까 - 가설 검정과 변수 간 관계 분석 - 06. 머신러닝에서의 가설 검정]

* 특징 정의 및 추출

 - 예측 및 분류에 효과적인 특징을 저으이하고 추출하는 과정은 다음과 같다.

 

- (예시) 아이스크림 판매량 예측

// 이 경우에는 처음으로 데이터를 모으는 경우에 많이 쓰이고, 다음에 나오는 것이 모아놓은 데이터를 활용해서 적용한다.

 

* 특징 선택

 - 특징 선택이란 예측 및 분류에 효과적인 특징을 선택하여 차원을 축소하는 기법이다.

 

 - 특징의 효과성(클래스 관련성)을 측정하기 위해 가설 검정에서 사용하는 통계량을 사용한다.

// x , y 가 모두 연속형 변수 이면 상관계수, x, y 가 범주형이면 카이제곱, 연속형 변수 범주형이면 아노바 검정을 쓸 수 있을 것이다.

// 시간대에 따라서 판매량 차이가 있느냐 없느냐, 아니면 어느 그룹과 비슷한 것인가를 나타낸다.

// 일원분석을 통해서. 24시간내에 있는 것을 검정하는 것이다.

 

 - 클래스 관련성 척도는 특징과 라벨의 유형에 따라 선택할 수 있다.

// 머신러닝에서는 범주형을 분석하는 경우가 거의 없기 때분에 이진형과 연속형만이 존재한다.

 

 

[02. Part 2) 탐색적 데이터 분석 Chapter 11. 비슷한 애들 모여라 - 군집화 - 01. 군집화 기본 개념]

 

* 군집화란?

 - 군집화 : 하나 이상의 특징을 바탕으로 유사한 샘플을 하나의 그룹으로 묶는 작업

// 각 군집마다 이름을 붙이는 작업은 무조건 수동으로 작업해야 한다.

// 컴퓨터는 크다, 작다 정도만 파악할 수 있다.

 

 - 군집화의 목적

  . 많은 샘플을 소수의 군집으로 묶어 각 군집의 특성을 파악하여 데이터의 특성을 이해하기 위함이다.

  . 군집의 특성을 바탕으로 각 군집에 속하는 샘플들에 대한 세분화된 의사결정을 수행하기 위함이다.

// 의사결정을 내리는 것이다.

 

*  군집화 활용 사례 : Code9

 - 신한카드에서는 카드 사용 패턴에 대한 군집화 결과를 바탕으로 고객을 총 18개의 군집으로 구분한다.

// 인구통계학적 특성도 군집화를 했다는 것을 알 수 있다.

// 각각의 마케팅을 달리해서 적용할 수 있다는 것이다.

 

 

* 거리와 유사도

// 거리와 유사도는 완벽하게 반대의 개념이라는 것을 알아야 한다.

 - 유사한 샘플을 하나의 군집으로 묶기 위해서는 거리 혹은 유사도의 개념이 필요

 

 - Tip. 대부분의 거리 척도와 유사도 척도는 수치형 변수에 대해서 정의되어 있으므로, 문자를 숫자로 바꿔주는 작업이 반드시 선행되어야 한다.

 

* 범주형 변수의 숫자화 : 더미화

 - 가장 일반적인 범주형 변수를 변환하는 방법으로, 범주형 변수가 특정 값을 취하는지 여부를 나타내는 더미 변수를 생성하는 방법

// 점선으로 된것은 사용하지 않는다는 것이다.

// 나머지 변수를 완벽하게 추론할 수 있기 때문에 있으나 마나한 변수를 없애는 것이다.

 

* 관련 함수 : Pandas.get_dummies

 - DataFrame 이나 Series 에 포함된 범주 변수를 더미화하는 함수

// 숫자인 변수를 인식하지 못한다.

 

 - 주요 입력

  . data : 더미화를 수행할 Data Frame 혹은 Series

  . drop_first : 첫 번째 더미 변수를 제거할지 여부 (특별한 경우를 제외하면 True 라고 설정)

 - 사용시 주의사항 : 숫자로 표현된 범주 변수 (예: 시간대, 월, 숫자로 코드화된 각종 문자)를 더미화하려면, 반드시 astype(str)을 이용하여 컬럼의 타입을 str 타입으로 변경해야 한다.

 

// pandas.get_dummies documenatation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html

pandas.get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)

Convert categorical variable into dummy/indicator variables.

Parameters

dataarray-like, Series, or DataFrame

Data of which to get dummy indicators.

prefixstr, list of str, or dict of str, default None

String to append DataFrame column names. Pass a list with length equal to the number of columns when calling get_dummies on a DataFrame. Alternatively, prefix can be a dictionary mapping column names to prefixes.

prefix_sepstr, default ‘_’

If appending prefix, separator/delimiter to use. Or pass a list or dictionary as with prefix.

dummy_nabool, default False

Add a column to indicate NaNs, if False NaNs are ignored.

columnslist-like, default None

Column names in the DataFrame to be encoded. If columns is None then all the columns with object or category dtype will be converted.

sparsebool, default False

Whether the dummy-encoded columns should be backed by a SparseArray (True) or a regular NumPy array (False).

drop_firstbool, default False

Whether to get k-1 dummies out of k categorical levels by removing the first level.

dtypedtype, default np.uint8

Data type for new columns. Only a single dtype is allowed.

New in version 0.23.0.

Returns

DataFrame

Dummy-coded data.

 

* 다양한 거리 / 유사도 척도 : (1) 유킬리디안 거리

 - 가장 흔하게 사용되는 거리 척도로 빛이 가는 거리로 정의된다.

// 벡터간 거리로 보면 된다.

// 특별한 제약이 있지는 않다. 가장 무난하게 쓸 수 있는 거리이다.

 

* 다양한 거리 / 유사도 척도 : (2) 맨하탄 거리

 - 정수형 데이터 (예: 리커트 척도)에 적합한 거리 척도로, 수직 / 수평으로만 이동한 거리의 합으로 정의된다.

// 빌딩숲에서 거리를 가는 것과 비슷하다고 해서 맨해튼 거리이다.

// 설문조사(리커트 척도)를 위한 것에 주로 쓰인다고 보면 된다.

 

* 다양한 거리 / 유사도 척도 : (3) 코사인 유사도

  - 스케일을 고려하지 않고 방향 유사도를 측정하는 상황(예: 상품 추천 시스템)에 주로 사용

// 핵심은 방향이 중요하다. 스케일은 전혀 중요하지 않다.

* 다양한 거리 /유사도 척도 : (4) 매칭 유사도

 - 이진형 데이터에 적합한 유사도 척도로 전체 특징 중 일치하는 비율을 고려한다.

 

 

* 다양한 거리 / 유사도 척도 : (5) 자카드 유사도

 - 이진형 데이터에 적합한 유사도 척도로 둘 중 하나라도 1을 가지는 특징 중 일치하는 비율을 고려한다.

 - 희소한 이진형 데이터에 적합한 유사도 척도임

// 희소하다는 것은 대부분 0을 가진다고 보면 된다. 텍스트, 상품 데이터가 대부분 0으로 보면 된다.

// 스포츠카를 가지고 있는 사람끼리는 유사하다. .. 우연히 같은 것을 배제하기 위한 척도라고 보면 된다.

 

 

 

 

[02. Part 2) 탐색적 데이터 분석 Chapter 11. 비슷한 애들 모여라 - 군집화 - 02. 계층적 군집화 (이론)]

* 기본 개념

 - 개별 샘플을 군집으로 간주하여, 거리가 가장 가까운 두 군집을 순차적으로 묶는 방식으로 큰 군집을 생성

// 최종적으로 하나의 군집으로 묶일때까지 묶다가 그중 하나를 선택해서 보는 것이다.

 

// 이전에 배웠던 것은 샘플간의 거리를 배웠다고 보면 된다.

* 군집 간 거리 : 최단 연결법

// 튀어나온 거리에 대해서 굉장히 민감하다고 볼 수 있다.

// 원래는 4 * 3 = 12 개의 계산량이 들어간다고 보면 된다.

 

* 군집 간 거리 : 최장 연결법

 

* 군집간 거리 : 평균 연결법

// 좀 더 직관적인 연결 방법

 

* 군집 간 거리 : 중심 연결법

// 다른 연결법과 달리 굉장히 많이 쓰이는 연결법이다.

 

* 군집 간 거리 : 와드 연결법

 

* 덴드로그램

 - 계층 군집화 과정을 트리 형태로 보여주는 그래프

 

* 덴드로그램의 현실

 - 덴드로그램은 샘플 수가 많은 경우에는 해석이 불가능할 정도로 복잡해진다는 문제가 있다.

// 100개 미만은 군집화가 필요 없을 것인데.. 샘플수가 7천개나되는 데이터가 위와 같다.

 

* 계층 군집화의 장단점

 - 장점 (1) 덴드로그램을 이용한 군집화 과정 확인 가능

// 실제로는 데이터가 크면 그것도 쉽지가 않다는 의미이다.

 - 장점 (2) 거리 / 유사도 행렬만 있으면 군집화 가능

 - 장점 (3) 다양한 거리 척도 활용 가능

 - 장점 (4) 수행할 때마다 같은 결과를 냄 (임의성 존재 x)

 

 - 단점 (1) 상대적으로 많은 계산량 O(n^3)

// 데이터가 크면 그만큼 시간이 오래 걸린다.

 - 단점 (2) 군집 개수 설정에 대한 제약 존재

 

* sklearn.cluster.AgglomerativeClustering

 - 주요 입력

  . n_clusters : 군집 개수

  . affinity : 거리 척도 {"Euclidean", "manhattan", "cosine", "precomputed"}

   .. linkage 가 ward 로 입력되면 "Euclidean"만 사용 가능함

// 그 이유는 각 군집마다 중심점을 필요로 하기 때문에 euclidean 은 중심을 표현하기 때문에 그런 것이다.

   .. "precomputed" 는 거리 혹은 유사도 행렬을 입력으로 하는 경우에 설정하는 값

// 데이터를 바탕으로 거리를 계산하는 것이 아니다.

// 생각보다 많이 쓰는 키워드 설정이다.

  . linkage : 군집 간 거리 { "ward", "complete", "average", "single"}

   .. complete: 최장 연결법

   .. average : 평균 연결법

   .. single : 최단 연결법

 

 - 주요 메서드

  . fix(x) : 데이터 x에 대한 군집화 모델 학습

  . fit_predict(x): 데이터 x 에 대한 군집화 모델 학습 및 라벨 반환

 

 - 주요 속성

  . labels_: fitting한 데이터에 있는 샘플들이 속한 군집 정보 (ndarray)

 

// skearn.cluster.AgglomeratevieClustering Documentation

scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html

class sklearn.cluster.AgglomerativeClustering(n_clusters=2, *, affinity='euclidean', memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', distance_threshold=None)

Agglomerative Clustering

Recursively merges the pair of clusters that minimally increases a given linkage distance.

Read more in the User Guide.

Parameters

n_clustersint or None, default=2

The number of clusters to find. It must be None if distance_threshold is not None.

affinitystr or callable, default=’euclidean’

Metric used to compute the linkage. Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”. If linkage is “ward”, only “euclidean” is accepted. If “precomputed”, a distance matrix (instead of a similarity matrix) is needed as input for the fit method.

memorystr or object with the joblib.Memory interface, default=None

Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory.

connectivityarray-like or callable, default=None

Connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. This can be a connectivity matrix itself or a callable that transforms the data into a connectivity matrix, such as derived from kneighbors_graph. Default is None, i.e, the hierarchical clustering algorithm is unstructured.

compute_full_tree‘auto’ or bool, default=’auto’

Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of samples. This option is useful only when specifying a connectivity matrix. Note also that when varying the number of clusters and using caching, it may be advantageous to compute the full tree. It must be True if distance_threshold is not None. By default compute_full_tree is “auto”, which is equivalent to True when distance_threshold is not None or that n_clusters is inferior to the maximum between 100 or 0.02 * n_samples. Otherwise, “auto” is equivalent to False.

linkage{“ward”, “complete”, “average”, “single”}, default=”ward”

Which linkage criterion to use. The linkage criterion determines which distance to use between sets of observation. The algorithm will merge the pairs of cluster that minimize this criterion.

  • ward minimizes the variance of the clusters being merged.

  • average uses the average of the distances of each observation of the two sets.

  • complete or maximum linkage uses the maximum distances between all observations of the two sets.

  • single uses the minimum of the distances between all observations of the two sets.

New in version 0.20: Added the ‘single’ option

distance_thresholdfloat, default=None

The linkage distance threshold above which, clusters will not be merged. If not None, n_clusters must be None and compute_full_tree must be True.

New in version 0.21.

Attributes

n_clusters_int

The number of clusters found by the algorithm. If distance_threshold=None, it will be equal to the given n_clusters.

labels_ndarray of shape (n_samples)

cluster labels for each point

n_leaves_int

Number of leaves in the hierarchical tree.

n_connected_components_int

The estimated number of connected components in the graph.

New in version 0.21: n_connected_components_ was added to replace n_components_.

children_array-like of shape (n_samples-1, 2)

The children of each non-leaf node. Values less than n_samples correspond to leaves of the tree which are the original samples. A node i greater than or equal to n_samples is a non-leaf node and has children children_[i - n_samples]. Alternatively at the i-th iteration, children[i][0] and children[i][1] are merged to form node n_samples + i

 

Methods

fit(X[, y])

Fit the hierarchical clustering from features, or distance matrix.

fit_predict(X[, y])

Fit the hierarchical clustering from features or distance matrix, and return cluster labels.

get_params([deep])

Get parameters for this estimator.

set_params(**params)

Set the parameters of this estimator.

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 머신러닝에 대해서는 추후에 머신러닝 프로젝트에서 다룰 것이라서 간단하게 코멘트만 하고 넘어 갔는데.. 군집화 범주형에 대해서 처리를 할때 필요한 것이긴 하지만.. 어렵다. ㅠ.ㅠ.. 역시 이론만 들어서는 너무 어렵군.

 

https://bit.ly/3m7bW22

 

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

[파이썬을 활용한 데이터 전처리 Level UP- 14 회차 미션 시작]

* 복습

 - 쌍체표본 t- 검정, 독립 표본 t- 검정, 단일 표본 t- 검정의 각각의 의미와 p-value를 통한 검증에 대한 결과에 대한 해석을 엿볼 수 있었다. 다만 아직까지는 좀 더 많은 실습과 경험이 필요한 것 같다.

 

[02. Part 2) 탐색적 데이터 분석 Chapter 10. 둘 사이에는 무슨 관계가 있을까 - 가설 검정과 변수 간 관계 분석 - 04. 일원분산분석]

 

 

// 독립검정 t-검정에 대해서 배워볼 수 있었다.

 

* 일원분산분석 개요

 - 목적 : 셋 이상의 그룹 간 차이가 존재하는지를 확인하기 위한 가설 검정 방법이다.

 

 - 영 가설과 대립 가설

 

 

- 가설 수립 예시 : 2020년 7월 한 달 간 지점 A, B, C 의 일별 판매량이 아래와 같다면, 지점별 7월 판매량 간 유의미한 차이가 있는가? 또한, 어느 지점 간에는 유의미한 판매량 차이가 존재하지 않는가?

 

 

 

* 독립 표본 검정 t 검정을 사용하면 안되는 이유

 - 일원분산분석은 독립 표본 t검정을 여러번 사용한 것과 같은 결과를 낼 것처럼 보인다.

 

 

- 독립 표본 t 검정에서 하나 이상의 영 가설이 기각되면, 자연스레 일원분산 분석의 영가설 역시 기각되므로, 기각된 원인까지 알 수 있으므로 일원분산분석이 필요하지 않아 보일 수 있다.

// p-value 를 기각했을때도 오류가 발생할 수가 있다.

 

 - 그러나 독립 표본 t 검정을 여러번 했을때, 아무리 높은 p-value 가 나오더라도 그 신뢰성에 문제가 생길 수 있어, 일원분산분석이 필요하다.

  . 각 가설의 p-value 가 0.95 이고, 그룹의 개수가 k일때 모든 영가설이 참일 확률 : 0.95^k

// k 승이 맞다는것은 점점 확률이 점점 떨어진다는 것을 의미하는 것이다.

  . 그룹의 개수가 3개만 되어도 그 확률이 0.857로 크게 감소하며, 그룹의 개수가 14개가 되면 그 확률이 0.5 미만으로 떨어진다.

 

* 일원분산분석의 선행 분석

// 독립 표본 t-검정과 비슷한 점이 있다.

 - 독립성 : 모든 그룹은 서로 독립적이어야 한다.

 

 - 정규성 : 모든 그룹의 데이터는 정규분포를 따라야 한다.

 . 그렇지 않으면 비모수적인 방법인 Kriskal-Wallis H Test 를 수행해야 한다.

 

 - 등분산성 : 모든 그룹에 데이터에 대한 분산이 같아야 한다.

 . 그렇지 않으면 비모수적인 방법인 Kruskal-Wallis H Test 를 수행해야 한다.

 

* 일원분산분석의 통계량

 

 

// F 통계량

// 집단 간의 차이가 크면 클 수록 값이 F 통계량이 커진다.

 

*  사후분석 : Tukey HSD test

 - Tukey HSD (honestly significant difference) test 는 일원분산분석에서 두 그룹 a와 b 간 차이가 유의한 지 파악하는 사후 분석 방법이다.

 

 

 

 

- 만약, HSD a,b 가 유의 수준보다 크면 두 차이가 유의하다고 간주

// 사후 분석을 통해서 어떤 그룹의 차이를 알 수 있다.

 

* 파이썬을 이용한 일원분산분석

 

 

// kstest 를 통해서 먼저 정규성을 검증을 먼저 한다.

// 사후분석과 일원분산분석은 구조가 다르다. scipy에는 없기때문에 다른 module에서 불러옴

 

// scipy.stas.f_oneway documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f_oneway.html

scipy.stats.f_oneway(*args, axis=0)

Perform one-way ANOVA.

The one-way ANOVA tests the null hypothesis that two or more groups have the same population mean. The test is applied to samples from two or more groups, possibly with differing sizes.

Parameters

sample1, sample2, …array_like

The sample measurements for each group. There must be at least two arguments. If the arrays are multidimensional, then all the dimensions of the array must be the same except for axis.

axisint, optional

Axis of the input arrays along which the test is applied. Default is 0.

Returns

statisticfloat

The computed F statistic of the test.

pvaluefloat

The associated p-value from the F distribution.

WarnsF_onewayConstantInputWarning

Raised if each of the input arrays is constant array. In this case the F statistic is either infinite or isn’t defined, so np.inf or np.nan is returned.

F_onewayBadInputSizesWarning

Raised if the length of any input array is 0, or if all the input arrays have length 1. np.nan is returned for the F statistic and the p-value in these cases.

 

// statsmodels.stats.multicomp.pairwise_tukeyhsd documentation

www.statsmodels.org/stable/generated/statsmodels.stats.multicomp.pairwise_tukeyhsd.html

statsmodels.stats.multicomp.pairwise_tukeyhsd(endog, groups, alpha=0.05)

Calculate all pairwise comparisons with TukeyHSD confidence intervals

Parameters

endogndarrayfloat, 1d

response variable

groupsndarray, 1d

array with groups, can be string or integers

alphafloat

significance level for the test

Returns

resultsTukeyHSDResults instance

A results class containing relevant data and some post-hoc calculations, including adjusted p-value

 

* 실습

// A, B, C 2차원 배열..ndarray

 

 

// C가 평균이 확실히 크다라고 생각 할 수 있고, 이 정도의 차이이면 아노바 검증을 할 필요가 없다.

// A, B 는 검증을 해야봐야 한다.

 

// 일원분산분석 수행 : p-value 가 거의 0에 수렴 => A, B, C의 평균은 유의한 차이가 존재하는지.

 

 

 

// False 는 둘의 차이가 없다라는 의미이다.

 


 

[02. Part 2) 탐색적 데이터 분석 Chapter 10. 둘 사이에는 무슨 관계가 있을까 - 가설 검정과 변수 간 관계 분석 - 04. 상관 분석]

 

 

// 연속 변수를 보는 상관분석과, 범주형 변수에서 볼수 있는 카이제곱검정이라고 보면 된다.

 

* 상관분석 개요

 - 목적 : 두 연속형 변수 간에 어떠한 선형 관계를 가지는지 파악

// x가 증가하면 y가 증가한다, 감소하면 감소한다가.. 선형 관계이다.

 

 - 영 가설과 대립 가설

 

 

- 시각화 방법 : 산점도 (scatter plot)

 

* 피어슨 상관 계수

 - 두 변수 모두 연속형 변수일 때 사용하는 상관 계수로 x와 y에 대한 상관 계수 p x,y 는 다음과 같이 정의된다.

 

 

 - 상관 계수가 1에 가까울수록 양의 상관관계가 강하다고 하며, -1에 가까울수록 음의 상관관계가 강하다고 한다. 또한, 0에 가까울수록 상관관계가 약하다고 한다.

 

* 피어슨 상관 계수

 

 

// 선형관계라는 것은 선으로 이어져 있는 것을 확인하는 것이라고도 볼 수 있다.

// 선으로 볼 수 없는 것들은 피어슨 상관관계로 볼 수 없다.

 

* 스피어만 상관 계수

 - 두 변수의 순위 사이의 단조 관련성을 측정하는 상관 계수로 x와 y에 대한 스피어만 상관 계수 S x,y 는 다음과 같이 정의된다.

 

 

 

* 파이썬을 이용한 상관분석

 

 

// 피어슨 상관계수에서 x, y 의 순서는 그렇게 중요하지 않다.

 

// scipy.stats.pearsonr documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html

scipy.stats.pearsonr(x, y)

Pearson correlation coefficient and p-value for testing non-correlation.

The Pearson correlation coefficient [1] measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. (See Kowalski [3] for a discussion of the effects of non-normality of the input on the distribution of the correlation coefficient.) Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.

The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.

Parameters

x(N,) array_like

Input array.

y(N,) array_like

Input array.

Returns

rfloat

Pearson’s correlation coefficient.

p-valuefloat

Two-tailed p-value.

Warns

PearsonRConstantInputWarning

Raised if an input is a constant array. The correlation coefficient is not defined in this case, so np.nan is returned.

PearsonRNearConstantInputWarning

Raised if an input is “nearly” constant. The array x is considered nearly constant if norm(x - mean(x)) < 1e-13 * abs(mean(x)). Numerical errors in the calculation x - mean(x) in this case might result in an inaccurate calculation of r.

 

 

// pandas.DataFrame.corr documentation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html

DataFrame.corr(method='pearson', min_periods=1)

Compute pairwise correlation of columns, excluding NA/null values.

Parameters

method{‘pearson’, ‘kendall’, ‘spearman’} or callable

Method of correlation:

  • pearson : standard correlation coefficient

  • kendall : Kendall Tau correlation coefficient

  • spearman : Spearman rank correlation

  • callable: callable with input two 1d ndarrays

    and returning a float. Note that the returned matrix from corr will have 1 along the diagonals and will be symmetric regardless of the callable’s behavior.

    New in version 0.24.0.

min_periodsint, optional

Minimum number of observations required per pair of columns to have a valid result. Currently only available for Pearson and Spearman correlation.

Returns

DataFrame

Correlation matrix.

 

 

* 실습

 

 

// 처음은 양의 값.. 같이 증가 한다는 의미이다.

 


 

[02. Part 2) 탐색적 데이터 분석 Chapter 10. 둘 사이에는 무슨 관계가 있을까 - 가설 검정과 변수 간 관계 분석 - 04. 카이제곱검정]

 

*  카이제곱 검정 개요

 - 목적 : 두 점부형 변수가 서로 독립적인지 검정

 

 - 영 가설과 대립 가설

 

 

 - 시각화 방법 : 교차 테이블

 

* 교차 테이블과 기대값

 - 교차 테이블(contingency table) 은 두 변수가 취할 수 있는 값의 조합의 출현 빈도를 나타낸다.

 

 - 예시 : 성별에 따른 강의 만족도 (카테고리 수 = 2 x 3 = 6)

 

 

// 빨간색은 기대값.

 

 

 

* 카이제곱 통계량

 - 카이제곱 검정에 사용하는 카이제곱 통계량은 기대값과 실제값의 차이를 바탕으로 정의된다.

 

 

 - 기대값과 실제값의 차이가 클수록 통계량이 커지며, 통계량이 커질수록 영 가설이 기각될 가능성이 높아진다. (즉, p-value 가 감소)

 

* 파이썬을 이용한 카이제곱 검정

 

 

// 시리즈이면서 범주형

// dof 자유도, expected 기대값

 

// pandas.crosstab documenation

pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html

pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False)

Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed.

Parameters

indexarray-like, Series, or list of arrays/Series

Values to group by in the rows.

columnsarray-like, Series, or list of arrays/Series

Values to group by in the columns.

valuesarray-like, optional

Array of values to aggregate according to the factors. Requires aggfunc be specified.

rownamessequence, default None

If passed, must match number of row arrays passed.

colnamessequence, default None

If passed, must match number of column arrays passed.

aggfuncfunction, optional

If specified, requires values be specified as well.

marginsbool, default False

Add row/column margins (subtotals).

margins_namestr, default ‘All’

Name of the row/column that will contain the totals when margins is True.

dropnabool, default True

Do not include columns whose entries are all NaN.

normalizebool, {‘all’, ‘index’, ‘columns’}, or {0,1}, default False

Normalize by dividing all values by the sum of values.

  • If passed ‘all’ or True, will normalize over all values.

  • If passed ‘index’ will normalize over each row.

  • If passed ‘columns’ will normalize over each column.

  • If margins is True, will also normalize margin values.

Returns

DataFrame

Cross tabulation of the data.

 

// scipy.stats.chi2_contingency documentation

docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html

scipy.stats.chi2_contingency(observed, correction=True, lambda_=None)

Chi-square test of independence of variables in a contingency table.

This function computes the chi-square statistic and p-value for the hypothesis test of independence of the observed frequencies in the contingency table [1] observed. The expected frequencies are computed based on the marginal sums under the assumption of independence; see scipy.stats.contingency.expected_freq. The number of degrees of freedom is (expressed using numpy functions and attributes):

dof = observed.size - sum(observed.shape) + observed.ndim - 1

Parameters

observedarray_like

The contingency table. The table contains the observed frequencies (i.e. number of occurrences) in each category. In the two-dimensional case, the table is often described as an “R x C table”.

correctionbool, optional

If True, and the degrees of freedom is 1, apply Yates’ correction for continuity. The effect of the correction is to adjust each observed value by 0.5 towards the corresponding expected value.

lambda_float or str, optional.

By default, the statistic computed in this test is Pearson’s chi-squared statistic [2]. lambda_ allows a statistic from the Cressie-Read power divergence family [3] to be used instead. See power_divergence for details.

Returns

chi2float

The test statistic.

pfloat

The p-value of the test

dofint

Degrees of freedom

expectedndarray, same shape as observed

The expected frequencies, based on the marginal sums of the table.

 

* 실습

// pvalue 0.0018 로 두 변수 간 독립이 아님을 확인할 수 있다. 서로 종속적이다라고 확인할 수 있다.

 

[파이썬을 활용한 데이터 전처리 Level UP-Comment]
- 일원분석.. 상관분석과 카이제곱 검정에서 대해서 알아봤다. 어렵다. 이론적인 배경 설명위주로 해서 그런지 넘 어렵게 느껴진다. ㅠ.ㅠ

 

https://bit.ly/3m7bW22

파이썬을 활용한 데이터 전처리 Level UP 올인원 패키지 Online. | 패스트캠퍼스

데이터 분석에 필요한 기초 전처리부터, 데이터의 품질 및 머신러닝 성능 향상을 위한 고급 스킬까지 완전 정복하는 데이터 전처리 트레이닝 온라인 강의입니다.

www.fastcampus.co.kr

 

728x90
반응형
:
Posted by 패치#노트