- 각 변수에 들어있는 숫자 데이터의 상대적 크기 차이 때문에 머신러닝 분석결과가 달라질 수 있다.
- ex) A변수는 0~1000 범위를 갖고, B 변수는 0~1 범위를 갖는다고 할때, 이 경우 상대적으로 큰 숫자 값으 갖는 A변수의 영향이 더 커진다.
따라서, 숫자데이터의 상대적 크기차이를 제거할 필요가 있다.
각 열(변수)에 속하는 데이터 값을 동일한 크기 기준으로 나눈 비율로 나타내는 것을 정규화(Normalization)이라고 한다.
정규화를 거친 데이터의 범위는 0~1 또는 -1~1이된다.
# -*- coding: utf-8 -*-
# 라이브러리 불러오기
import pandas as pd
import numpy as np
# read_csv() 함수로 df 생성
df = pd.read_csv('./auto-mpg.csv', header=None)
# 열 이름을 지정
df.columns = ['mpg','cylinders','displacement','horsepower','weight',
'acceleration','model year','origin','name']
# horsepower 열의 누락 데이터('?') 삭제하고 실수형으로 변환
df['horsepower'].replace('?', np.nan, inplace=True) # '?'을 np.nan으로 변경
df.dropna(subset=['horsepower'], axis=0, inplace=True) # 누락데이터 행을 삭제
df['horsepower'] = df['horsepower'].astype('float') # 문자열을 실수형으로 변환
# horsepower 열의 통계 요약정보로 최대값(max)과 최소값(min)을 확인
print(df.horsepower.describe())
print('\n')
# horsepower 열의 최대값의 절대값으로 모든 데이터를 나눠서 저장
min_x = df.horsepower - df.horsepower.min()
min_max = df.horsepower.max() - df.horsepower.min()
df.horsepower = min_x / min_max
print(df.horsepower.head())
print('\n')
print(df.horsepower.describe())
count 392.000000
mean 104.469388
std 38.491160
min 46.000000
25% 75.000000
50% 93.500000
75% 126.000000
max 230.000000
Name: horsepower, dtype: float64
0 0.565217
1 0.717391
2 0.652174
3 0.652174
4 0.608696
Name: horsepower, dtype: float64
count 392.000000
mean 0.454215
std 0.167353
min 0.200000
25% 0.326087
50% 0.406522
75% 0.547826
max 1.000000