달력

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
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 패치#노트