Pipeline - 연속된 변환을 일괄적으로 처리하기 위해서 사용된다.

파이프라인을 이용하면 전처리과정과 학습, 예측의 전과정을 통합가능하다.

하지만 뒤에 있을 모델 세부튜닝을 위해 전처리만 적용하려한다.

 

사용 데이터는 iris 데이터이다.

 

기본적인 구조는 다음과 같다.

from sklearn.pipeline import Pipeline

new_pipeline = Pipeline([
    ('Name', tool),('Name', tool)
])

 

이를 토대로 간단한 파이프라인을 작성하겠다.

sklearn의 SimpleImputer와 StandardScaler를 적용한 예시이다.

from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer

new_pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy = 'mean')),('std_scaler', StandardScaler())
])

결과는 다음과 같다.

 

통합적인 변환 이외에도 각각의 열에 대해서 변환을 적용시켜야하는 경우가 생긴다.

이 경우 ColumnTransformer를 이용한다.

 

- Columntransformer

예시)

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

num_att = ['col3']
cat_att = ['col1','col2']

col_pipeline = ColumnTransformer([
    ('num',new_pipeline,num_att),
    ('cat',OneHotEncoder(),cat_att)
])

df_prepared = col_pipeline.fit_transform(my_df)

결과.

 

이번 포스팅은 'Hands-On Machine Learning with Scikit-Learn, Keras & TensorFlow 2판' 을 참고하였습니다.

'Others > Data Science' 카테고리의 다른 글

Preprocessing (4) Scaling  (0) 2022.07.19
Preprocessing (3) Encoding  (0) 2022.07.18
Preprocessing (2) 누락된 값의 처리(Null)  (0) 2022.07.15
Pandas - DataFrame (3) 조회(loc/iloc)  (0) 2022.07.15
Pandas - DataFrame (2) 삭제  (0) 2022.07.14
스케일링: 특성의 범위를 같게 만들어주는 방법.

 

Standardization - 표준화

: 평균이 0, 분산이 1인 정규분포로 변환하는 과정이다.

Normalization - 정규화

: 값들을 0~1 사이의 값으로 변환하는 과정이다.

 

※ 정규화는 이상치의 영향을 많이 받는다. 따라서 이상값이 많은 경우 표준화를 적용한다.

 

우선 Iris 데이터를 이용해서 데이터를 알아보겠습니다.

from sklearn.datasets import load_iris
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)

iris 데이터의 꽃받침의 길이와 넓이를 가져옵니다.

sepal_length = df[['sepal length (cm)']]
sepal_width = df[['sepal width (cm)']]

sns.distplot(sepal_length)
sns.distplot(sepal_width)

 

이제 scikit learn의 Scaler들을 하나씩 사용해보겠습니다.

Standardization - 표준화

1. StandardScaler: 평균을 0, 분산을 1로 스케일링합니다.

from sklearn.preprocessing import StandardScaler
Standardsc = StandardScaler()

#변환
Standardsc.fit(sepal_length)
sepal_length_scaled=Standardsc.transform(sepal_length)

Standardsc.fit(sepal_width)
sepal_width_scaled=Standardsc.transform(sepal_width)

평균이 0 으로 잘 스케일링됨을 알 수 있습니다.

 

2. RobustScaler: 중앙값과 사분위수를 기준으로 스케일링합니다. (IQR)

from sklearn.preprocessing import RobustScaler
Robustsc = RobustScaler()

Robustsc.fit(sepal_length)
sepal_length_Rscaled=Robustsc.transform(sepal_length)

Robustsc.fit(sepal_width)
sepal_width_Rscaled=Robustsc.transform(sepal_width)

 

Normalization - 정규화

1.MinMaxScaler : 0~1사이의 값으로 스케일링

from sklearn.preprocessing import MinMaxScaler
MinMax = MinMaxScaler()

MinMax.fit(sepal_length)
sepal_length_minmax = MinMax.transform(sepal_length)

MinMax.fit(sepal_width)
sepal_width_minmax = MinMax.transform(sepal_width)

값들이 0~1사이에 분포하고 있음을 알 수 있습니다.

 

2. MaxAbsScaler : -1 ~ 1 사이에 값들이 분포하도록 스케일링합니다.

from sklearn.preprocessing import MaxAbsScaler
Mabs = MaxAbsScaler()

Mabs.fit(sepal_length)
sepal_length_abs = Mabs.transform(sepal_length)

Mabs.fit(sepal_width)
sepal_width_abs = Mabs.transform(sepal_width)

 

참고.

https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing

 

API Reference

This is the class and function reference of scikit-learn. Please refer to the full user guide for further details, as the class and function raw specifications may not be enough to give full guidel...

scikit-learn.org

 

'Others > Data Science' 카테고리의 다른 글

Preprocessing (5) Pipeline  (0) 2022.07.25
Preprocessing (3) Encoding  (0) 2022.07.18
Preprocessing (2) 누락된 값의 처리(Null)  (0) 2022.07.15
Pandas - DataFrame (3) 조회(loc/iloc)  (0) 2022.07.15
Pandas - DataFrame (2) 삭제  (0) 2022.07.14

텍스트로 이루어진 값들은 대부분의 머신러닝 알고리즘을 사용하기 어렵습니다.

따라서 해당 값들을 숫자형태로 변환하는 과정을 거쳐야 합니다.  이것을 인코딩이라 부릅니다.

싸이킷런에서 제공하는 인코더들을 실습하려합니다.

 

실습에 앞서 인코딩을 위한 데이터프레임을 생성합니다.

 

1. Label Encoder & Ordinal Encoder

두 인코더가 하는 일은 같습니다. 데이터의 값들을 0부터 n-1의 숫자로 변환하여 표시합니다.

우선 Label Encoder입니다.

from sklearn.preprocessing import LabelEncoder
Le = LabelEncoder()
Le.fit(df.col2)

변환은 다음과 같이 사용합니다.

Le.transform(df.col2)

다음 코드로 역변환도 가능합니다.

Le.inverse_transform(Le.transform(df.col2))

이제는 Ordinal Encoder에 대해 살펴보겠습니다.

from sklearn.preprocessing import OrdinalEncoder
Od= OrdinalEncoder()
Od.fit(df)

마찬가지로 transfrom을 사용하여 변환합니다.

Od.transform(df)

 

각각의 목록은 categories_를 사용하여 볼 수 있습니다.

Od.categories_

 

간단하게 두 encoder를 살펴보았습니다. 하는 역할은 비슷합니다. 그러나 차이점이 분명히 존재합니다.

Label Encoder의 경우에는 1차원 데이터를 다루고있습니다.

그러나 Ordinal Encoder의 경우는 2차원데이터를 다룹니다. 그렇다면 서로 역할을 바꾸어보면 어떨까요?

- Label Encoder로 2차원데이터를 변환시키려 해봅니다.

Le.transform(df)

 - Ordinal Encoder로 1차원 데이터를 변환.

Od.transform(df.col2)

이런식으로 두 Encoder 모두 에러가 뜨게됩니다.

 

정리.
Label Encoder - 1D
Ordinal Encoder -2D

 

2. OneHotEncoder

각 카테고리를 이진화하여 인코딩하는 방법입니다.

간단하게 변환을 수행해보겠습니다.

from sklearn.preprocessing import OneHotEncoder
onehot = OneHotEncoder()
col1_onehot = onehot.fit_transform(df[['col2']])
col1_onehot

이런식으로 출력됨을 알 수 있습니다.

하지만 보고싶은것은 배열의 형태임으로 다음과 같이 사용합니다.

col1_onehot.toarray()

또는 이런식으로도 사용 가능합니다.

onehot2 = OneHotEncoder(sparse=False)
col1_onehot2 = onehot2.fit_transform(df[['col2']])
col1_onehot2

scikit learn의 OneHotEncoding 을 할 때 주의할 점은 백터를 사용할 수 없다는 것입니다.

따라서 reshape(-1,1)를 사용하거나 다음과 같이 사용합니다.

df[['col2']].shape

 

참고.

https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing

 

API Reference

This is the class and function reference of scikit-learn. Please refer to the full user guide for further details, as the class and function raw specifications may not be enough to give full guidel...

scikit-learn.org

 

'Others > Data Science' 카테고리의 다른 글

Preprocessing (5) Pipeline  (0) 2022.07.25
Preprocessing (4) Scaling  (0) 2022.07.19
Preprocessing (2) 누락된 값의 처리(Null)  (0) 2022.07.15
Pandas - DataFrame (3) 조회(loc/iloc)  (0) 2022.07.15
Pandas - DataFrame (2) 삭제  (0) 2022.07.14

우선 비어있는 값인 Null 이 포함된 데이터 프레임을 생성합니다.

df = pd.DataFrame({'col1':[0,1,2,3,6],'col2':pd.Series([1,2,3],index=[1,2,3]), 
		'col3': ['A','B','C','D','E'],'col4':pd.Series([1,3],index=[0,2])},index=[0,1,2,3,4])
df

우선 NaN값에 대해서 drop하는 방법은 따로 설명하지않고 이전 포스팅의 링크를 올립니다.

 

Pandas - DataFrame (2) 삭제

우선 데이터프레임을 생성합니다. my_dictionary = {"col1":[0,1,2,3], "col2": pd.Series([1,2,3],index=[1,2,3])} df=pd.DataFrame(data=my_dictionary, index=[0,1,2,3]) df Drop 명령어를 사용해서 행,열을..

itpori.tistory.com

 

이제 남은 방식은 dropna()와 fillna()를 사용하는 방법입니다.

1. dropna()

간단하게 NaN값이 들어있는 행이나 열을 제거시킵니다. 기본적으로 행을 삭제하며, axis=1 를 사용하면 열도 가능합니다.

df.dropna()

df.dropna(axis=1)

 

 

2.fillna()

기본적인 구조는 다음과 같습니다.

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

사용 예시들입니다.

0으로 채우고 싶다면 괄호안에 0을 넣으면됩니다.

df.fillna(0)

null값의 앞이나 뒤의 값으로 채우고싶다면 method를 설정해주어야합니다.

- 앞의 값으로 채우기

df.fillna(method='ffill')

- 뒤의 값으로 채우기

df.fillna(method='backfill')

※ 앞 뒤에 값이 없는 경우 채워지지 않습니다.

 

참고.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html

 

pandas.DataFrame.fillna — pandas 1.4.3 documentation

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 t

pandas.pydata.org


scikit learn의 SimpleImputer를 사용하는 방법도 있습니다. 이 방법은 수치형 데이터에만 사용가능합니다.

기본 구성은 다음과 같습니다.

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

strategy의 값을 변경하면 되는데, 'mean','median','most_frequent', 'constant' 의 값을 적용 가능합니다.

'mean' 값으로 치환하는 예제 코드입니다.

우선 앞의 데이터프레임에서 문자 데이터인 'col3' 를 제거하고 수치형 데이터만 남기겠습니다.

df.drop('col3',inplace=True,axis=1)
df

그다음 SimpleImputer를 설정,학습합니다.

Im = SimpleImputer(strategy= "mean")
Im.fit(df)

계산된 값들을 살펴보기 위해 다음과 같이 작성합니다.

Im.statistics_

계산한 값들을 토대로 원래의 데이터프레임 형식으로 되돌립니다.

X=Im.transform(df)
pd.DataFrame(X,columns=df.columns,index=df.index)

결과

 

'Others > Data Science' 카테고리의 다른 글

Preprocessing (4) Scaling  (0) 2022.07.19
Preprocessing (3) Encoding  (0) 2022.07.18
Pandas - DataFrame (3) 조회(loc/iloc)  (0) 2022.07.15
Pandas - DataFrame (2) 삭제  (0) 2022.07.14
Preprocessing (1) train_test_split  (0) 2022.07.14

+ Recent posts