Data Preprocessing
To apply deep learning in real-world scenarios, we often need to preprocess and extract valuable information from raw data. The pandas library provides powerful tools for data manipulation and preprocessing. Here, we will focus on loading CSV files and performing basic operations using pandas.
실제 상황에서 딥러닝을 적용하기 위해서는 원시 데이터에서 가치 있는 정보를 추출하고 전처리하는 작업이 필요합니다. pandas 라이브러리는 데이터 조작과 전처리를 위한 강력한 도구를 제공합니다. 여기에서는 CSV 파일을 로드하고 pandas를 사용하여 기본 작업을 수행하는 방법에 초점을 맞출 것입니다.
Reading the Dataset
One of the most common formats for storing tabular data is the Comma-Separated Values (CSV) format. Each line in a CSV file represents a record, and the fields within a record are separated by commas. To demonstrate how to load CSV files using pandas, we will create a sample dataset file called house_tiny.csv. This dataset contains information about homes, including the number of rooms, roof type, and price.
테이블 형식 데이터를 저장하는 가장 일반적인 형식 중 하나는 CSV(쉼표로 구분된 값) 형식입니다. CSV 파일의 각 줄은 레코드를 나타내며 레코드 내의 필드는 쉼표로 구분됩니다. pandas를 사용하여 CSV 파일을 로드하는 방법을 시연하기 위해 house_tiny.csv라는 샘플 데이터 세트 파일을 생성합니다. 이 데이터 세트에는 방 수, 지붕 유형 및 가격을 포함하여 주택에 대한 정보가 포함되어 있습니다.
Here is the code to create the house_tiny.csv file:
다음은 house_tiny.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,RoofType,Price
NA,NA,127500
2,NA,106000
4,Slate,178100
NA,NA,140000''')
Once we have the dataset file, we can use the read_csv function in pandas to load the data into a DataFrame:
데이터셋 파일을 준비했으면 pandas의 read_csv 함수를 사용하여 데이터를 DataFrame으로 로드할 수 있습니다:
import pandas as pd
data = pd.read_csv(data_file)
print(data)
실행결과
NumRooms RoofType Price
0 NaN NaN 127500
1 2.0 NaN 106000
2 4.0 Slate 178100
3 NaN NaN 140000
The read_csv function reads the CSV file and creates a DataFrame, which is a tabular data structure provided by pandas. We can then perform various operations on the DataFrame to preprocess the data further.
read_csv 함수는 CSV 파일을 읽어와 DataFrame이라는 테이블 형태의 데이터 구조로 만듭니다. 이후에는 DataFrame에서 추가적인 데이터 전처리 작업을 수행할 수 있습니다.
Data Preparation
In supervised learning, we train models to predict a target value based on input values. The first step in processing the dataset is to separate the columns for input and target values. This can be done by selecting columns by name or index using iloc.
지도 학습에서는 입력 값에 기반하여 지정된 목표(target) 값을 예측하는 모델을 훈련합니다. 데이터셋을 처리하는 첫 번째 단계는 입력과 목표 값을 나타내는 열을 분리하는 것입니다. 열은 이름이나 정수 기반의 위치 인덱싱(iloc)을 사용하여 선택할 수 있습니다.
Missing values are common in data science and are often represented as NA or empty entries. They can be handled through imputation or deletion. Imputation replaces missing values with estimates, while deletion removes rows or columns containing missing values.
결측값은 데이터 과학에서 흔하게 발생하며, NA나 빈 엔트리로 표시될 수 있습니다. 결측값은 대체(imputation) 또는 삭제(deletion)를 통해 처리할 수 있습니다. 대체는 결측값을 추정치로 대체하는 것이고, 삭제는 결측값을 포함하는 행이나 열을 제거하는 것입니다.
For categorical input fields, NaN can be treated as a separate category. For example, the RoofType column can be split into RoofType_Slate and RoofType_nan columns. Rows with Slate as the roof type will have RoofType_Slate set to 1 and RoofType_nan set to 0, while rows with missing RoofType values will have the opposite values.
범주형 입력 필드의 경우, NaN은 별도의 범주로 처리할 수 있습니다. 예를 들어, RoofType 열은 RoofType_Slate와 RoofType_nan 열로 분리할 수 있습니다. Slate인 경우 RoofType_Slate는 1이 되고 RoofType_nan은 0이 됩니다. 반면, RoofType 값이 결측값인 행은 그 반대의 값을 가지게 됩니다.
inputs, targets = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)
실행결과
NumRooms RoofType_Slate RoofType_nan
0 NaN 0 1
1 2.0 0 1
2 4.0 1 0
3 NaN 0 1
For missing numerical values, a common approach is to replace them with the mean value of the corresponding column.
숫자형 결측값의 경우, 일반적인 방법은 해당 열의 평균값으로 결측값을 대체하는 것입니다.
inputs = inputs.fillna(inputs.mean())
print(inputs)
실행결과
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
Data preparation is an important step in training deep learning models, where missing values need to be handled appropriately.
데이터 준비는 결측값을 적절히 처리해야 하는 딥러닝 모델 훈련의 중요한 단계입니다.
Conversion to the Tensor Format
Now that [all the entries in inputs
and targets
are numerical, we can load them into a tensor]
이제 입력 및 대상의 모든 항목이 숫자이므로 텐서에 로드할 수 있습니다.
import torch
X, y = torch.tensor(inputs.values), torch.tensor(targets.values)
X, y
실행결과
(tensor([[3., 0., 1.],
[2., 0., 1.],
[4., 1., 0.],
[3., 0., 1.]], dtype=torch.float64),
tensor([127500, 106000, 178100, 140000]))
Discussion
Data Processing Complexity: Data may span multiple files and tables, making processing complex.
데이터 처리의 복잡성: 데이터는 여러 파일과 테이블에 걸쳐 있을 수 있어 처리가 복잡해질 수 있습니다.
Data Types Variety: Data comes in many forms such as text, images, and audio, not just categorical and numeric.
다양한 데이터 유형: 데이터는 범주형과 수치형뿐만 아니라 텍스트, 이미지, 오디오 등 다양한 형태로 제공됩니다.
Advanced Tools Requirement: Advanced tools and algorithms are necessary to prevent data processing from becoming a bottleneck in machine learning.
고급 도구의 필요성: 데이터 처리가 머신 러닝에서 병목이 되지 않도록 하기 위해 고급 도구와 알고리즘이 필요합니다.
Data Quality: Attention must be paid to real-world data issues like outliers, faulty measurements, and recording errors.
데이터 품질: 이상치, 잘못된 측정값, 기록 오류 등과 같은 실제 데이터 문제에 주의를 기울여야 합니다.
Data Visualization Tools: Tools like seaborn, Bokeh, and matplotlib aid in inspecting data and identifying potential problems.
데이터 시각화 도구: seaborn, Bokeh, matplotlib과 같은 도구를 사용하여 데이터를 검사하고 잠재적인 문제를 식별할 수 있습니다.
Linear Algebra(선형대수학)
By now, we can load datasets into tensors and manipulate these tensors with basic mathematical operations. To start building sophisticated models, we will also need a few tools from linear algebra.
이제 데이터 세트를 텐서에 로드하고 기본 수학 연산으로 이러한 텐서를 조작할 수 있습니다. 정교한 모델 구축을 시작하려면 선형 대수학의 몇 가지 도구도 필요합니다.
Scalars
In mathematics, scalars are individual real numbers without direction. They are used in everyday computations, such as converting temperatures. Scalars are often denoted by lower-case letters and are considered members of the real number space, denoted by $\mathbb{R}$. For instance, the variables in the equation $c = \frac{5}{9}(f - 32)$ are all scalars. In programming, scalars can be implemented as tensors containing just one element.
수학에서 스칼라는 방향을 가지지 않는 개별 실수를 의미합니다. 이들은 온도 변환 같은 일상적인 계산에 사용됩니다. 스칼라는 종종 소문자로 표현되며, 실수 공간인 $\mathbb{R}$의 구성원으로 간주됩니다. 예를 들어, 방정식 $c = \frac{5}{9}(f - 32)$의 변수들은 모두 스칼라입니다. 프로그래밍에서는 스칼라를 하나의 요소만을 포함하는 텐서로 구현할 수 있습니다.
x = torch.tensor(3.0)
y = torch.tensor(2.0)
x + y, x * y, x / y, x**y
실행결과
(tensor(5.), tensor(6.), tensor(1.5000), tensor(9.))
Here, it's creating two scalar tensors x and y with the values 3.0 and 2.0 respectively. Then, it performs standard mathematical operations on these tensors:
여기서는 값이 각각 3.0과 2.0인 두 개의 스칼라 텐서 x와 y를 생성합니다. 그런 다음 다음 텐서에서 표준 수학 연산을 수행합니다.
When this code is run, the output is a tuple of four elements, each of which is a result of the corresponding operation: (5.0, 6.0, 1.5, 9.0). This indicates that x + y is 5.0, x * y is 6.0, x / y is 1.5, and x raised to the power y (or x**y) is 9.0.
이 코드가 실행되면 출력은 4개 요소의 튜플이며 각 요소는 해당 작업의 결과입니다: (5.0, 6.0, 1.5, 9.0). 이는 x + y가 5.0, x * y가 6.0, x / y가 1.5이고 x의 y승(또는 x**y)이 9.0임을 나타냅니다.
벡터
A vector is a tuple consisting of one or more scalar values. It can be denoted in various ways:
벡터는 하나 이상의 스칼라 값으로 구성된 튜플입니다. 이는 다양한 방식으로 표현될 수 있습니다.
$$v = (a_1, a_2, a_3) = [a_1, a_2, a_3]$$ $$or$$ $$v = \begin{pmatrix}
a_1 \\
a_2 \\
a_3 \end{pmatrix} = \begin{bmatrix}
a_1\\
a_2\\
a_3\end{bmatrix}$$
Vectors have distinct mathematical operations, including the dot product and the cross product. The dot product of two vectors, $u$ and $v$, produces a scalar and is computed as $u \cdot v = |u||v|cos\theta$, where $\theta$ is the angle between the two vectors.
벡터는 내적과 외적이라는 고유한 수학적 연산을 가지고 있습니다. 두 벡터 $u$와 $v$의 내적은 스칼라를 생성하며, 이는 $u \cdot v = |u||v|cos\theta$로 계산됩니다. 여기서 $\theta$는 두 벡터 사이의 각입니다.
On the other hand, the cross product, denoted as $u\times v$, results in a new vector. Its direction is perpendicular to both $u$ and $v$, and its magnitude is $|u||v|sin\theta$, signifying the area of the parallelogram with $u$ and $v$ as sides.
반면에, 외적은 $u\times v$로 표시되며, 새로운 벡터를 생성합니다. 그 방향은 $u$와 $v$ 모두에게 수직이며, 그 크기는 $|u||v|sin\theta$로, 이는 $u$와 $v$가 변인 평행사변형의 넓이를 의미합니다.
x = torch.arange(3)
x
실행결과
tensor([0, 1, 2])
We can refer to an element of a vector by using a subscript. For example, $x_2$ denotes the second element of $\mathbf{x}$. Since $x_2$ is a scalar, we do not bold it. By default, we visualize vectors by stacking their elements vertically.
벡터의 요소는 첨자(subscript)를 사용하여 나타낼 수 있습니다. 예를 들어, $x_2$는 $\mathbf{x}$의 두 번째 요소를 나타냅니다. $x_2$는 스칼라이므로 굵게 표시하지 않습니다. 기본적으로, 우리는 벡터를 요소를 세로로 쌓아서 시각화합니다.
$$\mathbf{x} =\begin{bmatrix}
x_{1} \\
\vdots \\
x_{n}\end{bmatrix},$$
Here $x_1, \ldots, x_n$ are elements of the vector. Later on, we will distinguish between such column vectors and row vectors whose elements are stacked horizontally. Recall that [we access a tensor's elements via indexing.]
여기서 $x_1, \ldots, x_n$은 벡터의 요소입니다. 나중에는 이러한 열 벡터와 가로로 쌓인 행 벡터를 구분할 것입니다. 기억해주세요. [텐서의 요소에는 색인(indexing)을 통해 접근합니다.]
x[2]
실행결과
tensor(2)
To indicate that a vector contains $n$ elements, we write $\mathbf{x} \in \mathbb{R}^n$. Formally, we call $n$ the dimensionality of the vector.
벡터가 $n$개의 요소를 포함한다는 것을 나타내기 위해 $\mathbf{x} \in \mathbb{R}^n$와 같이 표기합니다. 형식적으로, 우리는 $n$을 벡터의 차원이라고 부릅니다.
len(x)
실행결과
3
We can also access the length via the shape attribute. The shape is a tuple that indicates a tensor's length along each axis.
또한 shape 속성을 통해 길이에 액세스할 수도 있습니다. shape은 텐서의 각 축에 따른 길이를 나타내는 튜플입니다.
x.shape
실행결과
torch.Size([3])
Matrices
Matrices are 2nd-order tensors, denoted by bold capital letters (e.g., $\mathbf{X}$, $\mathbf{Y}$, $\mathbf{Z}$). In code, matrices are represented as tensors with two axes. A matrix $\mathbf{A} \in \mathbb{R}^{m \times n}$ contains $m \times n$ real-valued scalars arranged in $m$ rows and $n$ columns. If $m = n$, the matrix is called square.
행렬은 2차 텐서로, 굵은 대문자로 표기됩니다 (예: $\mathbf{X}$, $\mathbf{Y}$, $\mathbf{Z}$). 코드에서는 행렬을 두 개의 축을 가진 텐서로 표현합니다. 행렬 $\mathbf{A} \in \mathbb{R}^{m \times n}$은 $m$개의 행과 $n$개의 열로 구성된 $m \times n$개의 실수값을 포함합니다. 만약 $m = n$이라면, 해당 행렬은 "정사각 행렬"이라고 합니다.
Individual elements in a matrix are referred to using subscripts for row and column indices. For example, $a_{ij}$ represents the value in the $i^{\mathrm{th}}$ row and $j^{\mathrm{th}}$ column of matrix $\mathbf{A}$.
행렬의 개별 요소는 행과 열 인덱스의 하위 첨자(subscript)를 사용하여 표기합니다. 예를 들어, $a_{ij}$는 행렬 $\mathbf{A}$의 $i$번째 행과 $j$번째 열에 위치한 값을 나타냅니다.
$$\mathbf{A}=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \\ \end{bmatrix}.$$
In code, a matrix $\mathbf{A} \in \mathbb{R}^{m \times n}$ is represented as a 2nd-order tensor with shape ($m$, $n$). To convert a tensor of size $m \times n$ to a matrix, we can use the reshape function with the desired shape ($m$, $n$).
코드에서 행렬 $\mathbf{A} \in \mathbb{R}^{m \times n}$은 ($m$, $n$) 모양의 2차 텐서로 표현됩니다. $m \times n$ 크기의 텐서를 행렬로 변환하기 위해서는 reshape 함수를 사용하면 됩니다.
A = torch.arange(6).reshape(3, 2)
A
실행결과
tensor([[0, 1],
[2, 3],
[4, 5]])
Sometimes, we want to flip the axes. When we exchange a matrix's rows and columns, the result is called its transpose. Formally, we signify a matrix $\mathbf{A}$'s transpose by $\mathbf{A}^\top$ and if $\mathbf{B} = \mathbf{A}^\top$, then $b_{ij} = a_{ji}$ for all $i$ and $j$. Thus, the transpose of an $m \times n$ matrix is an $n \times m$ matrix:
때로는 축을 뒤집고 싶을 때가 있습니다. 행렬의 행과 열을 교환하여 얻는 결과를 전치(transpose)라고 합니다. 수식적으로 행렬 $\mathbf{A}$의 전치는 $\mathbf{A}^\top$로 표기하며, 만약 $\mathbf{B} = \mathbf{A}^\top$이라면, 모든 $i$와 $j$에 대해 $b_{ij} = a_{ji}$입니다. 따라서 $m \times n$ 행렬의 전치는 $n \times m$ 행렬이 됩니다:
$$
\mathbf{A}^\top =
\begin{bmatrix}
a_{11} & a_{21} & \dots & a_{m1} \\
a_{12} & a_{22} & \dots & a_{m2} \\
\vdots & \vdots & \ddots & \vdots \\
a_{1n} & a_{2n} & \dots & a_{mn}
\end{bmatrix}.
$$
In code, we can access any (matrix's transpose) as follows:
코드에서는 (행렬의 전치)를 다음과 같이 얻을 수 있습니다.
A.T
실행결과
tensor([[0, 2, 4],
[1, 3, 5]])
[Symmetric matrices are the subset of square matrices that are equal to their own transposes: $\mathbf{A} = \mathbf{A}^\top$.] The following matrix is symmetric:
[대칭 행렬은 자신의 전치와 같은 정사각 행렬의 하위 집합입니다: $\mathbf{A} = \mathbf{A}^\top$.] 다음 행렬은 대칭 행렬입니다:
A = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
A == A.T
실행결과
tensor([[True, True, True],
[True, True, True],
[True, True, True]])
Matrices are useful for representing datasets. Typically, rows correspond to individual records and columns correspond to distinct attributes.
행렬은 데이터셋을 표현하는 데 유용합니다. 일반적으로 행은 개별 레코드를 나타내고 열은 서로 다른 속성을 나타냅니다.
Tensors
Tensors are higher-order arrays that provide a way to describe extensions beyond scalars, vectors, and matrices. In machine learning, tensors are represented by software objects of the tensor class, allowing for arbitrary numbers of axes. Tensors are denoted by capital letters with a special font face and can be indexed using a similar mechanism as matrices.
텐서는 스칼라, 벡터 및 행렬을 넘어서는 확장을 설명하는 데 사용되는 고차원 배열입니다. 머신 러닝에서 텐서는 텐서 클래스의 소프트웨어 객체로 표현되며 임의의 축 수를 지원합니다. 텐서는 특별한 글꼴로 대문자로 표시되며 행렬과 유사한 방식으로 인덱싱될 수 있습니다.
Tensors become particularly important when working with images. Images are represented as 3rd-order tensors, with axes corresponding to height, width, and channels (such as red, green, and blue). Collections of images are represented by 4th-order tensors, with distinct images indexed along the first axis. Higher-order tensors are constructed by increasing the number of shape components.
이미지 처리에서 텐서는 특히 중요합니다. 이미지는 3차원 텐서로 표현되며 높이, 너비 및 채널 (예: 빨강, 초록, 파랑)에 해당하는 축을 가지고 있습니다. 이미지의 모음은 4차원 텐서로 표현되며 각각의 이미지는 첫 번째 축을 따라 인덱싱됩니다. 고차원 텐서는 모양 구성 요소의 수를 증가시킴으로써 생성됩니다.
torch.arange(24).reshape(2, 3, 4)
실행결과
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Basic Properties of Tensor Arithmetic(텐서 산술의 기본 속성)
Scalars, vectors, matrices, and higher-order tensors all have some handy properties. For example, lementwise operations produce outputs that have the same shape as their operands.
스칼라, 벡터, 행렬 및 고차원 텐서는 유용한 몇 가지 특성을 갖고 있습니다. 예를 들어, 요소별 연산은 출력 결과가 피연산자와 동일한 형태를 갖습니다.
A = torch.arange(6, dtype=torch.float32).reshape(2, 3)
B = A.clone() # Assign a copy of A to B by allocating new memory
A, A + B
실행결과
(tensor([[0., 1., 2.],
[3., 4., 5.]]),
tensor([[ 0., 2., 4.],
[ 6., 8., 10.]]))
The [elementwise product of two matrices is called their Hadamard product] (denoted $\odot$). Below, we spell out the entries of the Hadamard product of two matrices $\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times n}$:
스칼라, 벡터, 행렬 및 고차원 텐서는 모두 일부 유용한 특성을 갖고 있습니다. 예를 들어, 요소별 연산은 출력이 피연산자와 동일한 모양을 갖습니다. 두 행렬의 요소별 곱셈을 Hadamard 곱셈이라고하며 (기호 $\odot$로 표시됨), 아래에는 두 행렬 $\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times n}$의 Hadamard 곱셈의 항목을 구체적으로 나열합니다.
$$
\mathbf{A} \odot \mathbf{B} =
\begin{bmatrix}
a_{11} b_{11} & a_{12} b_{12} & \dots & a_{1n} b_{1n} \\
a_{21} b_{21} & a_{22} b_{22} & \dots & a_{2n} b_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
a_{m1} b_{m1} & a_{m2} b_{m2} & \dots & a_{mn} b_{mn}
\end{bmatrix}.
$$
A * B
실행결과
tensor([[ 0., 1., 4.],
[ 9., 16., 25.]])
[Adding or multiplying a scalar and a tensor] produces a result with the same shape as the original tensor. Here, each element of the tensor is added to (or multiplied by) the scalar.
스칼라와 텐서의 덧셈 또는 곱셈은 원래 텐서와 동일한 형태의 결과를 생성합니다. 여기서 텐서의 각 요소는 스칼라와 더해지거나 (또는 곱해지는) 값입니다.
a = 2
X = torch.arange(24).reshape(2, 3, 4)
a + X, (a * X).shape
실행결과
(tensor([[[ 2, 3, 4, 5],
[ 6, 7, 8, 9],
[10, 11, 12, 13]],
[[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]]]),
torch.Size([2, 3, 4]))