반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

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

 

2.2. Data Preprocessing — Dive into Deep Learning 1.0.3 documentation

 

d2l.ai

2.2. Data Preprocessing

 

So far, we have been working with synthetic data that arrived in ready-made tensors. However, to apply deep learning in the wild we must extract messy data stored in arbitrary formats, and preprocess it to suit our needs. Fortunately, the pandas library can do much of the heavy lifting. This section, while no substitute for a proper pandas tutorial, will give you a crash course on some of the most common routines.

 

지금까지 우리는 ready-made tensors 에 도착한 synthetic data 를 사용해 작업해 왔습니다. 그러나 실제 딥러닝을 적용하려면 임의의 형식으로 저장된 지저분한 데이터를 추출하고 필요에 맞게 전처리해야 합니다. 다행스럽게도 pandas 라이브러리는 많은 무거운 작업을 수행할 수 있습니다. 이 섹션은 적절한 Pandas 튜토리얼을 대체할 수는 없지만 가장 일반적인 루틴 중 일부에 대한 단기 집중 강좌를 제공합니다.

 

2.2.1. Reading the Dataset

Comma-separated values (CSV) files are ubiquitous for the storing of tabular (spreadsheet-like) data. In them, each line corresponds to one record and consists of several (comma-separated) fields, e.g., “Albert Einstein,March 14 1879,Ulm,Federal polytechnic school,field of gravitational physics”. To demonstrate how to load CSV files with pandas, we create a CSV file below ../data/house_tiny.csv. This file represents a dataset of homes, where each row corresponds to a distinct home and the columns correspond to the number of rooms (NumRooms), the roof type (RoofType), and the price (Price).

 

Comma-separated values (CSV) 파일은 표 형식(스프레드시트와 같은) 데이터를 저장하는 데 널리 사용됩니다. 여기에서 각 행은 하나의 레코드에 해당하며 여러(쉼표로 구분된) 필드로 구성됩니다(예: "Albert Einstein, March 14 1879, Ulm, Federal Polytechnic school, field of gravitational 물리"). Pandas로 CSV 파일을 로드하는 방법을 보여주기 위해 ../data/house_tiny.csv 아래에 CSV 파일을 만듭니다. 이 파일은 주택의 데이터세트를 나타냅니다. 여기서 각 행은 고유한 주택에 해당하고 열은 방 수(NumRooms), 지붕 유형(RoofType) 및 가격(Price)에 해당합니다.

 

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,RoofType,Price
NA,NA,127500
2,NA,106000
4,Slate,178100
NA,NA,140000''')

 

주어진 코드는 Python을 사용하여 디렉토리를 생성하고 CSV 파일을 만드는 작업을 수행하는 코드입니다. 아래는 코드의 설명입니다:

  1. import os: os 모듈을 가져옵니다. 이 모듈은 운영체제와 상호작용하여 파일 및 디렉토리를 다룰 때 유용합니다.
  2. os.makedirs(os.path.join('..', 'data'), exist_ok=True): 이 부분은 상위 디렉토리에서 "data" 디렉토리를 생성합니다. os.path.join() 함수는 경로를 조합하는 데 사용되며, exist_ok=True를 설정하여 디렉토리가 이미 존재하면 오류를 발생시키지 않고 계속 진행합니다.
  3. data_file = os.path.join('..', 'data', 'house_tiny.csv'): 이 부분은 CSV 파일의 경로를 생성하여 data_file 변수에 저장합니다.
  4. with open(data_file, 'w') as f:: data_file 경로로 파일을 열고 쓰기 모드('w')로 열기 시작합니다. with 문을 사용하면 파일이 올바르게 닫히도록 보장됩니다.
  5. f.write('''NumRooms,RoofType,Price\nNA,NA,127500\n2,NA,106000\n4,Slate,178100\nNA,NA,140000'''): 이 부분은 CSV 파일에 데이터를 씁니다. 여기서는 간단한 데이터를 작성하고 있으며, 각 줄은 쉼표로 구분된 값(NumRooms, RoofType, Price)으로 구성되어 있습니다. 이 데이터는 주택 정보를 나타내는 것으로 보입니다.

코드를 실행하면 "data" 디렉토리가 생성되고 그 안에 "house_tiny.csv" 파일이 작성됩니다. 이 CSV 파일은 주택 정보를 담고 있으며, 데이터 과학 또는 머신 러닝 작업에서 사용될 수 있습니다.

 

Now let’s import pandas and load the dataset with read_csv.

 

이제 pandas를 가져오고 read_csv를 사용하여 데이터 세트를 로드해 보겠습니다.

 

import pandas as pd

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

주어진 코드는 Python의 Pandas 라이브러리를 사용하여 CSV 파일을 읽고 데이터를 DataFrame으로 표시하는 작업을 수행하는 코드입니다. 아래는 코드의 설명입니다:

  1. import pandas as pd: Pandas 라이브러리를 가져오고, 일반적으로 Pandas를 pd라는 별칭으로 사용합니다.
  2. data = pd.read_csv(data_file): 이 부분은 data_file 경로에 있는 CSV 파일을 읽어와 데이터를 DataFrame으로 저장합니다. pd.read_csv() 함수는 CSV 파일을 읽고 그 내용을 DataFrame 형태로 반환합니다. 이 DataFrame은 표 형태로 데이터를 저장하고 다루기 용이합니다.
  3. print(data): 읽어온 데이터를 출력합니다. 이 코드는 DataFrame의 내용을 표시하며, CSV 파일에 저장된 주택 정보 데이터를 출력합니다.

결과적으로, 코드를 실행하면 CSV 파일에 있는 데이터가 Pandas DataFrame으로 읽어와지고, 그 데이터가 화면에 출력됩니다. 이를 통해 데이터를 쉽게 검토하고 분석할 수 있습니다.

 

   NumRooms RoofType   Price
0       NaN      NaN  127500
1       2.0      NaN  106000
2       4.0    Slate  178100
3       NaN      NaN  140000

2.2.2. Data Preparation

In supervised learning, we train models to predict a designated target value, given some set of input values. Our first step in processing the dataset is to separate out columns corresponding to input versus target values. We can select columns either by name or via integer-location based indexing (iloc).

 

지도 학습에서는 일부 입력 값 세트가 주어지면 지정된 목표 값을 예측하도록 모델을 훈련합니다. 데이터 세트 처리의 첫 번째 단계는 입력 값과 목표 값에 해당하는 열을 분리하는 것입니다. 이름이나 정수 위치 기반 인덱싱(iloc)을 통해 열을 선택할 수 있습니다.

 

You might have noticed that pandas replaced all CSV entries with value NA with a special NaN (not a number) value. This can also happen whenever an entry is empty, e.g., “3,,,270000”. These are called missing values and they are the “bed bugs” of data science, a persistent menace that you will confront throughout your career. Depending upon the context, missing values might be handled either via imputation or deletion. Imputation replaces missing values with estimates of their values while deletion simply discards either those rows or those columns that contain missing values.

 

pandas가 값 NA가 있는 모든 CSV 항목을 특수 NaN(숫자 아님) 값으로 바꾼 것을 눈치챘을 것입니다. 이는 항목이 비어 있을 때마다(예: "3,,,270000") 발생할 수도 있습니다. 이를 누락된 값이라고 하며 데이터 과학의 " bed bugs "이며, 경력 전반에 걸쳐 직면하게 될 지속적인 위협입니다. 컨텍스트에 따라 누락된 값은 대치 또는 삭제를 통해 처리될 수 있습니다. 대치에서는 누락된 값을 예상 값으로 바꾸는 반면, 삭제에서는 누락된 값이 포함된 행이나 열을 삭제합니다.

 

Here are some common imputation heuristics. For categorical input fields, we can treat NaN as a category. Since the RoofType column takes values Slate and NaN, pandas can convert this column into two columns RoofType_Slate and RoofType_nan. A row whose roof type is Slate will set values of RoofType_Slate and RoofType_nan to 1 and 0, respectively. The converse holds for a row with a missing RoofType value.

 

다음은 몇 가지 일반적인 대치 휴리스틱입니다. 범주형 입력 필드의 경우 NaN을 범주로 처리할 수 있습니다. RoofType 열은 Slate 및 NaN 값을 사용하므로 Pandas는 이 열을 RoofType_Slate 및 RoofType_nan의 두 열로 변환할 수 있습니다. 지붕 유형이 슬레이트인 행은 RoofType_Slate 및 RoofType_nan 값을 각각 1과 0으로 설정합니다. RoofType 값이 누락된 행에는 반대의 경우가 적용됩니다.

 

inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)

주어진 코드는 Python의 Pandas 라이브러리를 사용하여 데이터를 전처리하는 작업을 수행하는 코드입니다. 아래는 코드의 설명입니다:

  1. inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]: 이 부분에서 데이터를 입력과 타겟으로 나누고 있습니다. data.iloc[:, 0:2]는 DataFrame data의 모든 행(:)과 0부터 1번 열(0:2)까지의 데이터를 선택하여 inputs로 저장합니다. data.iloc[:, 2]는 DataFrame data의 모든 행과 2번 열의 데이터를 선택하여 targets로 저장합니다. 이렇게 하면 입력 데이터와 타겟 데이터가 나누어집니다.
  2. inputs = pd.get_dummies(inputs, dummy_na=True): 이 부분에서는 입력 데이터를 전처리합니다. pd.get_dummies() 함수를 사용하여 범주형 변수를 더미 변수로 변환합니다. dummy_na=True를 설정하면 결측치를 나타내는 더미 변수도 생성됩니다. 이렇게 하면 범주형 변수가 숫자로 인코딩되고 모델 학습에 사용할 수 있는 형태로 변환됩니다.
  3. print(inputs): 전처리된 입력 데이터를 출력합니다. 이 코드는 더미 변수로 변환된 입력 데이터를 화면에 출력하여 확인할 수 있습니다.

결과적으로, 이 코드는 입력 데이터와 타겟 데이터를 분리하고, 입력 데이터를 범주형 변수를 더미 변수로 변환하여 전처리하는 작업을 수행합니다. 이렇게 전처리된 데이터는 머신 러닝 모델에 입력으로 사용될 수 있습니다.

 

   NumRooms  RoofType_Slate  RoofType_nan
0       NaN           False          True
1       2.0           False          True
2       4.0            True         False
3       NaN           False          True
inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)
print(targets)
   NumRooms  RoofType_Slate  RoofType_nan
0       NaN               0             1
1       2.0               0             1
2       4.0               1             0
3       NaN               0             1

0    127500
1    106000
2    178100
3    140000
Name: Price, dtype: int64

For missing numerical values, one common heuristic is to replace the NaN entries with the mean value of the corresponding column.

 

누락된 숫자 값의 경우 일반적인 경험적 방법 중 하나는 NaN 항목을 해당 열의 평균 값으로 바꾸는 것입니다.

 

inputs = inputs.fillna(inputs.mean())
print(inputs)

주어진 코드는 Python의 Pandas 라이브러리를 사용하여 결측치(누락된 데이터)를 해당 열의 평균 값으로 대체하는 작업을 수행하는 코드입니다. 아래는 코드의 설명입니다:

  1. inputs = inputs.fillna(inputs.mean()): 이 부분에서는 inputs DataFrame의 결측치를 대체하는 작업을 수행합니다. fillna() 함수는 DataFrame에서 결측치를 대체할 때 사용됩니다. 여기서는 inputs.mean()을 사용하여 각 열의 평균 값을 계산하고, 이 평균 값으로 해당 열의 결측치를 대체합니다. 즉, 각 열에 대해 결측치가 있는 경우 그 열의 평균 값으로 결측치를 채웁니다.
  2. print(inputs): 결측치가 대체된 후의 inputs DataFrame을 출력합니다. 이 코드는 결측치가 대체된 데이터를 화면에 출력하여 확인할 수 있습니다.

결과적으로, 이 코드는 결측치를 해당 열의 평균 값으로 대체하여 데이터를 전처리하는 작업을 수행합니다. 이렇게 하면 모델 학습에 결측치가 없는 데이터로 사용할 수 있습니다.

 

교재

   NumRooms  RoofType_Slate  RoofType_nan
0       3.0           False          True
1       2.0           False          True
2       4.0            True         False
3       3.0           False          True

CoLab

   NumRooms  RoofType_Slate  RoofType_nan
0       3.0               0             1
1       2.0               0             1
2       4.0               1             0
3       3.0               0             1

2.2.3. Conversion to the Tensor Format

Now that all the entries in inputs and targets are numerical, we can load them into a tensor (recall Section 2.1).

 

이제 입력과 목표의 모든 항목이 숫자이므로 이를 텐서에 로드할 수 있습니다(섹션 2.1을 기억하세요).

 

import torch

X = torch.tensor(inputs.to_numpy(dtype=float))
y = torch.tensor(targets.to_numpy(dtype=float))
X, y

주어진 코드는 Python에서 PyTorch 라이브러리를 사용하여 데이터를 텐서로 변환하는 작업을 수행하는 코드입니다. 아래는 코드의 설명입니다:

  1. import torch: PyTorch 라이브러리를 가져옵니다. PyTorch는 딥러닝 및 텐서 연산을 위한 라이브러리입니다.
  2. X = torch.tensor(inputs.to_numpy(dtype=float)): 입력 데이터인 inputs를 PyTorch 텐서로 변환합니다. 먼저 inputs를 NumPy 배열로 변환하기 위해 to_numpy() 함수를 사용하고, 이후에 torch.tensor() 함수를 사용하여 NumPy 배열을 PyTorch 텐서로 변환합니다. dtype=float를 사용하여 텐서의 데이터 타입을 부동소수점으로 설정합니다.
  3. y = torch.tensor(targets.to_numpy(dtype=float)): 타겟 데이터인 targets를 PyTorch 텐서로 변환합니다. 위와 같은 방식으로 NumPy 배열로 변환한 후, PyTorch 텐서로 변환합니다.
  4. X, y: 변환된 입력 데이터와 타겟 데이터를 출력합니다. 이 코드는 데이터를 NumPy 배열에서 PyTorch 텐서로 변환한 후, 그 결과를 확인하기 위해 화면에 출력합니다.

결과적으로, 이 코드는 입력 데이터와 타겟 데이터를 PyTorch 텐서로 변환하여 딥러닝 모델 또는 텐서 연산을 수행할 준비를 마칩니다. PyTorch를 사용하면 이러한 텐서를 활용하여 모델을 학습하고 예측하는 등의 다양한 머신 러닝 작업을 수행할 수 있습니다.

 

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

 

2.2.4. Discussion

 

You now know how to partition data columns, impute missing variables, and load pandas data into tensors. In Section 5.7, you will pick up some more data processing skills. While this crash course kept things simple, data processing can get hairy. For example, rather than arriving in a single CSV file, our dataset might be spread across multiple files extracted from a relational database. For instance, in an e-commerce application, customer addresses might live in one table and purchase data in another. Moreover, practitioners face myriad data types beyond categorical and numeric, for example, text strings, images, audio data, and point clouds. Oftentimes, advanced tools and efficient algorithms are required in order to prevent data processing from becoming the biggest bottleneck in the machine learning pipeline. These problems will arise when we get to computer vision and natural language processing. Finally, we must pay attention to data quality. Real-world datasets are often plagued by outliers, faulty measurements from sensors, and recording errors, which must be addressed before feeding the data into any model. Data visualization tools such as seaborn, Bokeh, or matplotlib can help you to manually inspect the data and develop intuitions about the type of problems you may need to address.

 

이제 데이터 열을 분할하고, 누락된 변수를 대치하고, Pandas 데이터를 텐서에 로드하는 방법을 알았습니다. 섹션 5.7에서는 데이터 처리 기술을 더 배우게 됩니다. 이 단기 집중 강좌에서는 작업을 단순하게 유지했지만 데이터 처리가 까다로울 수 있습니다. 예를 들어 단일 CSV 파일로 도착하는 대신 데이터 세트가 관계형 데이터베이스에서 추출된 여러 파일에 분산될 수 있습니다. 예를 들어 전자 상거래 애플리케이션에서 고객 주소는 한 테이블에 있고 구매 데이터는 다른 테이블에 있을 수 있습니다. 더욱이 실무자는 텍스트 문자열, 이미지, 오디오 데이터, 포인트 클라우드 등 범주형 및 숫자형을 넘어서는 수많은 데이터 유형에 직면합니다. 데이터 처리가 기계 학습 파이프라인에서 가장 큰 병목 현상이 되는 것을 방지하려면 고급 도구와 효율적인 알고리즘이 필요한 경우가 많습니다. 이러한 문제는 컴퓨터 비전과 자연어 처리에 접근할 때 발생합니다. 마지막으로 데이터 품질에 주의를 기울여야 합니다. 실제 데이터 세트는 종종 이상치, 센서의 잘못된 측정, 기록 오류로 인해 어려움을 겪습니다. 이러한 문제는 데이터를 모델에 공급하기 전에 해결해야 합니다. seaborn, Bokeh 또는 matplotlib와 같은 데이터 시각화 도구를 사용하면 데이터를 수동으로 검사하고 해결해야 할 문제 유형에 대한 직관을 개발하는 데 도움이 될 수 있습니다.

 

2.2.5. Exercises

  1. Try loading datasets, e.g., Abalone from the UCI Machine Learning Repository and inspect their properties. What fraction of them has missing values? What fraction of the variables is numerical, categorical, or text?

    UCI Machine Learning Repository에서 Abalone과 같은 데이터세트를 로드하고 해당 속성을 검사해 보세요. 그 중 누락된 값이 있는 부분은 얼마나 됩니까? 변수 중 숫자형, 범주형 또는 텍스트형 변수는 얼마나 됩니까?

  2. Try indexing and selecting data columns by name rather than by column number. The pandas documentation on indexing has further details on how to do this.

    열 번호 대신 이름으로 데이터 열을 인덱싱하고 선택해 보세요. 인덱싱에 대한 팬더 문서에는 이 작업을 수행하는 방법에 대한 자세한 내용이 나와 있습니다.

  3. How large a dataset do you think you could load this way? What might be the limitations? Hint: consider the time to read the data, representation, processing, and memory footprint. Try this out on your laptop. What happens if you try it out on a server?

    이 방법으로 얼마나 큰 데이터 세트를 로드할 수 있다고 생각하시나요? 한계는 무엇입니까? 힌트: 데이터, 표현, 처리 및 메모리 공간을 읽는 데 걸리는 시간을 고려하세요. 노트북에서 사용해 보세요. 서버에서 시험해 보면 어떻게 되나요?

  4. How would you deal with data that has a very large number of categories? What if the category labels are all unique? Should you include the latter?

    카테고리 수가 매우 많은 데이터를 어떻게 처리하시겠습니까? 카테고리 라벨이 모두 고유하면 어떻게 되나요? 후자를 포함해야 할까요?

  5. What alternatives to pandas can you think of? How about loading NumPy tensors from a file? Check out Pillow, the Python Imaging Library.

    팬더에 대한 어떤 대안을 생각할 수 있나요? 파일에서 NumPy 텐서를 로드하는 것은 어떻습니까? Python 이미징 라이브러리인 Pillow를 확인해 보세요.

 

 

 

반응형