728x90
반응형
데이터 전처리(preprocessing) 클링징 : 수정, 결손값 처리 :nullnan 처리(제거, 평균, 추가코드부여).
인코딩(ml은 숫자만 인식해서 2진수(01), 문자를 숫자로 표현),
스케일링(정규화, 표준화 // 키, 몸무게 단위가 다른경우),
이상치 제거,
feature 적절한 선택,
추출가공
데이터 인코딩
- 레이블 인코딩(Label encoding) : 1개 col으로 해결 상품이름을 상품코드번호로 maping하는 경우(냉장고 => 코드번호 13)
from sklearn.preprocessing import LabelEncoder
items=['TV','냉장고','전자렌지','컴퓨터','선풍기','선풍기','믹서','믹서']
# LabelEncoder를 객체로 생성한 후 , fit( ) 과 transform( ) 으로 label 인코딩 수행.
encoder = LabelEncoder() # 객체생성
encoder.fit(items) # 형태 맞추기
labels = encoder.transform(items)
print('인코딩 변환값:',labels) # 실제 값 변환
# 인코딩 변환값: [0 1 4 5 3 3 2 2]
print('인코딩 클래스:',encoder.classes_)
# 인코딩 클래스: ['TV' '냉장고' '믹서' '선풍기' '전자렌지' '컴퓨터']
print('디코딩 원본 값:',encoder.inverse_transform([4, 5, 2, 0, 1, 1, 3, 3])) # 원본값을 보고싶을때
# 디코딩 원본 값: ['전자렌지' '컴퓨터' '믹서' 'TV' '냉장고' '냉장고' '선풍기' '선풍기']
- 원-핫 인코딩(One-Hot encoding) : 차원분류 상품수만큼 col 부여 해당시 1 값 지정 특징 상품이름은 서로 연관이 없음 => 숫자라서 원치않는 방향으로 알고리즘 코딩될 수 있음 => 원핫인코딩 해결 pd get_dummies(인자) 손쉽게 가능
from sklearn.preprocessing import OneHotEncoder
import numpy as np
items=['TV','냉장고','전자렌지','컴퓨터','선풍기','선풍기','믹서','믹서']
# 먼저 숫자값으로 변환을 위해 LabelEncoder로 변환합니다. 비지도학습인 경우 fit transform 데이터 변환
encoder = LabelEncoder() # 객체생성
encoder.fit(items) # 와꾸 맞추기
labels = encoder.transform(items) # 실제 값 변환
# 1차원 레이블 추가작업
# 2차원 데이터로 변환합니다.
labels = labels.reshape(-1,1) # col은 하나.행은 동쪽으로
# 원-핫 인코딩을 적용합니다.
oh_encoder = OneHotEncoder()
oh_encoder.fit(labels)
oh_labels = oh_encoder.transform(labels)
print('원-핫 인코딩 데이터')
print(oh_labels.toarray())
print('원-핫 인코딩 데이터 차원')
print(oh_labels.shape)
# 이 복잡한 과정을 get_dummies로 형식, 고유값문제까지 해결해서 더 깔끔하게 해결
원-핫 인코딩 데이터
[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 1.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]]
원-핫 인코딩 데이터 차원
(8, 6)
import pandas as pd
df = pd.DataFrame({'item':['TV','냉장고','전자렌지','컴퓨터','선풍기','선풍기','믹서','믹서'] })
df
item
0 TV
1 냉장고
2 전자렌지
3 컴퓨터
4 선풍기
5 선풍기
6 믹서
7 믹서
pd.get_dummies(df)
item_TV item_냉장고 item_믹서 item_선풍기 item_전자렌지 item_컴퓨터
0 1 0 0 0 0 0
1 0 1 0 0 0 0
2 0 0 0 0 1 0
3 0 0 0 0 0 1
4 0 0 0 1 0 0
5 0 0 0 1 0 0
6 0 0 1 0 0 0
7 0 0 1 0 0 0
피처 스케일링과 정규화
표준화 : feature 각각을 평균 0이고 분산 1인 가우시안 정규분포를 가진 값으로 변환 정규화 : 서로다른 피처의 크기를 통일 크기변환
- StandardScaler : 평균 0, 분산 1인 정규분포형태 변환
from sklearn.datasets import load_iris
import pandas as pd
# 붓꽃 데이터 셋을 로딩하고 DataFrame으로 변환합니다.
iris = load_iris()
iris_data = iris.data
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_nam es)
print('feature 들의 평균 값')
print(iris_df.mean())
print('\nfeature 들의 분산 값')
print(iris_df.var())
feature 들의 평균 값
sepal length (cm) 5.843333
sepal width (cm) 3.054000
petal length (cm) 3.758667
petal width (cm) 1.198667
dtype: float64
feature 들의 분산 값
sepal length (cm) 0.685694
sepal width (cm) 0.188004
petal length (cm) 3.113179
petal width (cm) 0.582414
dtype: float64
from sklearn.preprocessing import StandardScaler
# StandardScaler객체 생성
scaler = StandardScaler()
# StandardScaler 로 데이터 셋 변환. fit( ) 과 transform( ) 호출.
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)
#transform( )시 scale 변환된 데이터 셋이 numpy ndarry로 반환되어 이를 DataFrame으로 변환
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
print('feature 들의 평균 값')
print(iris_df_scaled.mean())
print('\nfeature 들의 분산 값')
print(iris_df_scaled.var())
feature 들의 평균 값
sepal length (cm) -1.690315e-15
sepal width (cm) -1.637024e-15
petal length (cm) -1.482518e-15
petal width (cm) -1.623146e-15
dtype: float64
feature 들의 분산 값
sepal length (cm) 1.006711
sepal width (cm) 1.006711
petal length (cm) 1.006711
petal width (cm) 1.006711
dtype: float64
- MinMaxScaler : 데이터값을 0 ~ 1 사이의 범위값으로 변환(음수 값있으면 -1 ~ 1 변환)
from sklearn.preprocessing import MinMaxScaler
# MinMaxScaler객체 생성
scaler = MinMaxScaler()
# MinMaxScaler 로 데이터 셋 변환. fit() 과 transform() 호출.
scaler.fit(iris_df)
iris_scaled = scaler.transform(iris_df)
# transform()시 scale 변환된 데이터 셋이 numpy ndarry로 반환되어 이를 DataFrame으로 변환
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
print('feature들의 최소 값')
print(iris_df_scaled.min())
print('\nfeature들의 최대 값')
print(iris_df_scaled.max())
feature들의 최소 값
sepal length (cm) 0.0
sepal width (cm) 0.0
petal length (cm) 0.0
petal width (cm) 0.0
dtype: float64
feature들의 최대 값
sepal length (cm) 1.0
sepal width (cm) 1.0
petal length (cm) 1.0
petal width (cm) 1.0
dtype: float64
반응형
'Data_Science > ML_Perfect_Guide' 카테고리의 다른 글
3-1. Accuracy || 평가지표 (0) | 2021.12.22 |
---|---|
2-5. titanic || sklearn (0) | 2021.12.22 |
2-3. model selection || sklearn (0) | 2021.12.22 |
2-2. sklearn 내장 데이터 || iris (0) | 2021.12.22 |
2-1. iris || sklearn (0) | 2021.12.22 |