2.2. Data Preprocessing

Eunjin Kim·2022년 4월 21일
0

Dive into Deep Learning

목록 보기
5/14

강의 : https://d2l.ai/chapter_preliminaries/pandas.html

2.2. Data Preprocessing

지금까지 우리는 이미 tensors에 저장된 데이터를 다루는 다양한 기술을 소개했다. 딥러닝을 적용해서 실제 문제를 해결하기 위해서는, tensor 형식으로 깔끔하게 준비된 데이터가 아닌, raw data를 전처리 하는것부터 시작해야한다. 유명한 Python의 데이터 분석 툴 중에, pandas 가 tensor와 같이 사용된다. 그래서, 우리는 pandas로 원시 데이터를 전처리하고 텐서 형식으로 변환하는 단계를 간략히 살펴볼 것이다. 이후 챕터에서는 더 많은 데이터 전처리 기술에 대해 다룰 것이다.

2.2.1. Reading the Dataset

예시로, 우리는 csv(comma-separated values) 파일 ../data/house_tiny.csv에 저장된 인공 데이터 세트를 생성하는 것으로 시작한다. 다른 형식으로 저장된 데이터는 유사한 방식으로 처리될 수 있다.

아래에서는 데이터 세트를 csv 파일에 한 행씩 기록합니다.

import os

os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
    f.write('NumRooms,Alley,Price\n')  # Column names
    f.write('NA,Pave,127500\n')  # Each row represents a data example
    f.write('2,NA,106000\n')
    f.write('4,NA,178100\n')
    f.write('NA,NA,140000\n')

생성된 CSV 파일에서 원시 데이터 세트를 로드하려면, pandas 패키지를 import 하고 read_csv 함수를 호출한다. 이 데이터셋은 4개의 행과 3개의 열을 가지고 있다.(각 행은 number of rooms (“NumRooms”), the alley type (“Alley”), the price (“Price”) 설명)

# If pandas is not installed, just uncomment the following line:
# !pip install pandas
import pandas as pd

data = pd.read_csv(data_file)
print(data)

# Output
   NumRooms Alley   Price
0       NaN  Pave  127500
1       2.0   NaN  106000
2       4.0   NaN  178100
3       NaN   NaN  140000

2.2.2. Handling Missing Data

"NaN" 항목은 누락된 값이다. 누락된 데이터를 처리하는 대표적인 방법으로는 imputation 및 deletion가 있는데, imputation은 누락된 값을 대체한 값으로 대체하는 반면, deletion는 누락된 값을 무시한다. 여기서 우리는 imputation을 볼 것이다.

정수 위치 기반 인덱싱(integer-location based indexing - iloc)을 통해 데이터를 입력과 출력으로 분할하며, 여기서 전자는 처음 두 열을 사용하고 후자는 마지막 열만 유지한다. 누락된 입력의 숫자 값에 대해 "NaN" 항목을 동일한 열의 평균 값으로 대체한다.

inputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = inputs.fillna(inputs.mean())
print(inputs)

# Output
   NumRooms Alley
0       3.0  Pave
1       2.0   NaN
2       4.0   NaN
3       3.0   NaN

inputs이 범주형 또는 이산형 값의 경우, "NaN"을 class로 간주한다. "Alley" 열은 "Pave"와 "NaN" 두 가지 유형의 범주 값만 사용하기 때문에, pandas는 이 열을 "Alley_Pave"와 "Alley_nan" 두 개의 열로 자동 변환할 수 있다. 골목 유형이 "Pave"인 행은 "Alley_Pave" 및 "Alley_nan" 값을 1과 0으로 설정한다. 결측 골목 유형이 있는 행은 해당 값을 0과 1로 설정한다.

inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)

# Output
   NumRooms  Alley_Pave  Alley_nan
0       3.0           1          0
1       2.0           0          1
2       4.0           0          1
3       3.0           0          1

2.2.3. Conversion to the Tensor Format

이제 inputs와 ouputs의 모든 입력이 수치화 되었고, 텐서 형식으로 변환될 수 있다. 데이터가 이 형식이 되면 섹션 2.1에서 소개한 텐서 기능을 사용하여 데이터를 추가로 조작할 수 있다.

import torch

X, y = torch.tensor(inputs.values), torch.tensor(outputs.values)
X, y

# Output
(tensor([[3., 1., 0.],
         [2., 0., 1.],
         [4., 0., 1.],
         [3., 0., 1.]], dtype=torch.float64),
 tensor([127500, 106000, 178100, 140000]))

2.2.4. Summary

  • Like many other extension packages in the vast ecosystem of Python, pandas can work together with tensors.
  • Imputation and deletion can be used to handle missing data.

2.2.5. Exercises

Create a raw dataset with more rows and columns.

  1. Delete the column with the most missing values.
  2. Convert the preprocessed dataset to the tensor format.
profile
ALL IS WELL🌻

0개의 댓글