‘Deep Learning with Python’ 세미나 6, 4장. Fundamentals of machine learning

실습할 내용이 없기 때문에 빠르게 읽을 수 있는 장입니다. 번역본을 가지고 쭉 읽어나갑니다. 이해가 잘 되지 않는 부분만 체크합니다. 이해가 잘 되지 않는 부분에 대해서 원서를 읽어봅니다. 그리고 아래 정리된 내용을 읽어봅니다.

4.1 Four branches of machine learning

머신러닝은 학습 방법에 따라 지도 학습, 비지도 학습, 자기 지도 학습, 강화 학습으로 구분할 수 있습니다.

지도 학습은 지도를 받고 학습하는 것입니다. 학습해야 할 데이터에 그 데이터를 통해 얻고자 하는 답을 표시해서 지도합니다.

비지도 학습은 답 없이 데이터만 가지고 학습하는 것입니다. 이렇게 하는 이유는 데이터에서 어떤 답을 도출할 수 있을지 모르기 때문입니다. 아직 데이터 분석이 안 되었다는 거죠. 학습을 통해 데이터에서 끌어낼 수 있는 흥미로운 변환을 찾아내려는 겁니다. 이러한 이유로 비지도 학습은 종종 지도 학습 문제를 풀기 전에 데이터셋을 잘 이해하기 위한 단계로 사용됩니다.

자기 지도 학습은 훈련 과정에서 스스로 데이터에서 답을 찾아내 학습합니다.

강화 학습에 대해서는 참고 자료 [1]을 추천합니다.

Classification and regression glossary

다음 용어들에 대해서 익숙해 지도록 합니다.

  • Sample or input – One data point that goes into your model.
  • Prediction or output – What comes out of your model.
  • Target – The truth. What your model should ideally have predicted, according to an external source of data.
  • Prediction error or loss value – A measure of the distance between your model’s prediction and the target.
  • Classes – A set of possible labels to choose from in a classification problem.
  • Label – A specific instance of a class annotation in a classification problem.
  • Ground-truth or annotations – All targets for a dataset, typically collected by humans.
  • Binary classification – A classification task where each input sample should be categorized into two exclusive categories.
  • Multiclass classification – A classification task where each input sample should be categorized into more than two categories.
  • Multilabel classification – A classification task where each input sample can be assigned multiple labels.
  • Scalar regression – A task where the target is a continuous scalar value.
  • Vector regression – A task where the target is a set of continuous values.
  • Mini-batch or batch – A small set of samples (typically between 8 and 128) that are processed simultaneously by the model. The number of samples is often a power of 2, to facilitate memory allocation on GPU. When training, a mini-batch is used to compute a single gradient-descent update applied to the weights of the model.

4.2 Evaluating machine-learning models

The fundamental issue in machine learning is the tension between optimization and generalization. Optimization refers to the process of adjusting a model to get the best performance possible on the training data (the learning in machine learning), whereas generalization refers to how well the trained model performs on data it has never seen before. The goal of the game is to get good generalization, of course, but you don’t control generalization; you can only adjust the model based on its training data.

먼저 이 부분을 분명하게 이해하고 넘어가는 것이 좋겠다고 판단되어, 4.4절의 일부 내용을 앞으로 옮겨 왔습니다. 위 문장을 10번 정도 읽어 봅니다.

4.2.1 Training, validation, and test sets

You train on the training data and evaluate your model on the validation data. Once your model is ready for prime time, you test it one final time on the test data.

검증셋을 두는 이유는? 처음부터 목표에 최적화된 모델을 구성할 수 있다면 검증셋은 필요 없습니다. 모델이 학습하는 것처럼 우리도 어떻게 모델을 구성할지에 대해 학습하는 것입니다. 모델의 학습 과정을 보면서 모델을 개선해 나갑니다. 훈련셋으로 학습한 것에 검증셋을 적용한 결과를 보면서 모델을 개선해 나갑니다.

모델 학습 결과는 가중치 값 변경으로 반영됩니다. 모델 구성 학습 결과는 모델 구성을 위한 설정(하이퍼 파라미터) 값으로 반영됩니다. 층을 몇 개로 할 것인지, 층의 units는 몇 개로 할 것인지 등의 결정이 모델 구성 학습의 결과입니다.

학습은 답이 정해진 입력을 가지고, 정해진 답을 구할 수 있는 확률이 최대가 되도록 최적화하는 것입니다. 학습이 이런 것이기에 학습한 데이터에 최적화되는 것입니다. 학습이 이러한 것이다보니, 새로운 데이터를 만났을 때 모델이 원하는 결과를 내 놓지 못할 수 있다는 것입니다. 이런 문제를 과적합이라고 합니다. 훈련셋과 검증셋을 분리하고 훈련셋으로 훈련한 결과가 과적합 되었는지를 검증셋으로 검증할 수 있습니다. 과적합된 경우 모델을 개선합니다.

검증셋을 사용한다고 모든 문제가 사라지는 것은 아닙니다. 검증셋을 사용해서 모델을 개선하기 때문에, 모델 개선을 수차례 하다보면 모델이 검증셋에 과적합되는 문제가 생길 수 있습니다. 검증셋에 과적합된 모델은 새로운 데이터를 만났을 대 원하는 결과를 내 놓지 못할 수 있습니다. 검증셋에 과적합 되었는지를 확인하기 위해 테스트셋을 사용합니다. 테스트셋을 사용해서 테스트 했을 때 원하는 결과가 나오지 않는다면 검증셋에 과적합된 것입니다.

Splitting your data into training, validation, and test sets may seem straightforward, but there are a few advanced ways to do it that can come in handy when little data is available. Let’s review three classic evaluation recipes: simple hold-out validation, Kfold validation, and iterated K-fold validation with shuffling.

데이터가 적은 경우에는 데이터셋을 이렇게 나누는 것 자체가 문제가 될 수 있습니다. 안 그래도 데이터가 적은데.

데이터가 아무리 적다고 해도 테스트셋을 모델 학습에 사용할 수는 없습니다. 무조건 테스트셋은 떼어놓아야 합니다. 테스트셋을 뺀 나머지 데이터를 가지고, 훈련셋과 검증셋으로 최대한 활용하기 위한 방법들(simple hold-out validation, Kfold validation, iterated K-fold validation with shuffling)이 있습니다.

4.2.2 Things to keep in mind
  • Data representativeness – You want both your training set and test set to be representative of the data at hand. 예) MNIST에서 데이터가 숫자 순으로 정렬되어 있다면. For this reason, you usually should randomly shuffle your data before splitting it into training and test sets.
  • The arrow of time – If you’re trying to predict the future given the past (for example, tomorrow’s weather, stock movements, and so on), you should not randomly shuffle your data before splitting it.
  • Redundancy in your data- If some data points in your data appear twice (fairly common with real-world data), then shuffling the data and splitting it into a training set and a validation set will result in redundancy between the training and validation sets.

4.3 Data preprocessing, feature engineering, and feature learning

4.3.1 Data preprocessing for neural networks

All inputs and targets in a neural network must be tensors of floating-point data (or, in specific cases, tensors of integers). Whatever data you need to process—sound, images, text—you must first turn into tensors, a step called data vectorization.

모든 입력과 출력을 숫자 값(대부분의 경우 float 타입)을 갖는 텐서가 되도록 해야 합니다.(벡터화)

모든 특성이 대체로 비슷한 범위 값을 갖도록, 작은 값을 취하도록(일반적으로 대부분의 값이 0~1 범위 값을 갖도록), 각 특성별 평균이 0이 되도록, 각 특성별 표준편차가 1이 되도록. (정규화)

누락된 값을 다루어야 합니다.

4.3.2 Feature engineering

That’s the essence of feature engineering: making a problem easier by expressing it in a simpler way. It usually requires understanding the problem in depth. Before deep learning, feature engineering used to be critical, because classical shallow algorithms didn’t have hypothesis spaces rich enough to learn useful features by themselves. Fortunately, modern deep learning removes the need for most feature engineering, because neural networks are capable of automatically extracting useful features from raw data.

그래도 feature engineering을 하는 것은 도움이 된다.

  • Good features still allow you to solve problems more elegantly while using fewer resources.
  • Good features let you solve a problem with far less data.

4.4 Overfitting and underfitting

모델은 학습을 통해 사용된 데이터에 최적화 됩니다. 학습 초기에는 훈련셋에 대해서도 검증셋에 대해서도 답을 제대로 맞추지 못할 것입니다. 이를 과소적합(underfitting)이라고 합니다.

훈련을 거듭할 수록 적합도는 높아갈 것입니다. 훈련이란 것이 적합도를 높혀가는 것이니까요. 훈련을 계속하다보면 어느 순간 훈련셋의 적합도는 높아지는데 검증셋에 대한 적합도는 낮아지는 경우가 발생합니다. 훈련셋에 과적합된 것입니다. 모델을 개선해야 하는 시점이 된 것입니다.

과적합을 피할 만큼 데이터가 많다면 좋겠죠. 하지만 현실에서 그 만큼 데이터를 수집하는 것은 쉽지 않은 일입니다.

4.4.1 Reducing the network’s size

과적합을 피하기 위한 가장 단순한 방법은 네트워크 크기를 줄이는 것입니다. 즉 가중치 개수를 줄이는 것입니다. 가중치는 모델의 기억 용량으로 비유할 수 있습니다. 기억 용량이 작아도 문제지만, 문제에 비해 너무 커도 문제입니다. 문제는 단순한데 기억 용량이 큰 경우, 입력을 출력으로 변환하기 위한 표현을 발견하기 보다 단순 기억으로 문제를 해결할 수 있습니다. 기억해서 하는 방법의 문제는 이미 기억한 데이터들에 대해서는 문제를 잘 해결하지만 새로운 데이터를 만나면 문제를 잘 해결하지 못한다는 것입니다. 너무 작지도 너무 크지도 않은 기억 용량을 설정해야 합니다.

4.4.2 Adding weight regularization

A common way to mitigate overfitting is to put constraints on the complexity of a network by forcing its weights to take only small values, which makes the distribution of weight values more regular. This is called weight regularization, and it’s done by adding to the loss function of the network a cost associated with having large weights.

과적합을 피하기 위한 또 다른 방법은 regularization입니다.

모델 훈련은 손실 점수를 줄이는 쪽으로 진행합니다. 가중치의 절대값이나 제곱의 합을 손실 점수에 더하게 되면, 손실 함수를 줄이려고 하는 입장에서는 값이 큰 가중치의 값을 줄여야 합니다. 절대값 보다는 제곱의 합을 구해서 더하는 방식이 더 확실하겠죠. 이렇게 함으로  특별히 튀는 것 없이 고만 고만한 가중치들을 갖도록 할 수 있습니다.

케라스에서는 층을 생성할 때 kernel_regularizer 값으로 작성합니다.

model.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.001), activation=’relu’))

4.4.3 Adding dropout

dropoup은 과적합을 피하기 위한 가장 효과적인 방법입니다. 이름 그대로 일정 비율로 층의 일부 출력을 제외하는 것입니다.

At test time, no units are dropped out; instead, the layer’s output values are scaled down by a factor equal to the dropout rate, to balance for the fact that more units are active than at training time.

drop은 훈련을 위한 것으로, 테스트 시에는 drop하지 않습니다. 테스트 시에 drop하지 않기 때문에 출력 계산에 사용된 unit은 훈련 시에 사용된 unit보다 drop 비율 만큼 많게 됩니다. 따라서 출력 값을 drop 비율 만큼 줄여줘야 합니다. drop 비율은 보통 0.2에서 0.5의 소수 값을 갖기 때문에 출력 값에 drop 비율을 곱해주면 됩니다.

케라스에서는 층의 출력 바로 뒤에 Dropout 층을 추가합니다.

model.add(layers.Dense(16, activation=’relu’))
model.add(layers.Dropout(0.5))

4.5 The universal workflow of machine learning

4.5.1 Defining the problem and assembling a dataset

딥러닝 또한 문제 해결이기 때문에 먼저 문제를 이해해야 합니다.

What type of problem are you facing? Is it binary classification? Multiclass classification? Scalar regression? Vector regression? Multiclass, multilabel classification? Something else, like clustering, generation, or reinforcement learning? Identifying the problem type will guide your choice of model architecture, loss function, and so on.

어떤 문제 유형에 속하는지를 알게 되면 모델의 구조와 손실 함수 등을 선택하는데 도움이 됩니다.

문제를 정의할 때 여러분은 두 가지 가설을 갖고 있을 것입니다. ‘주어진 입력으로 출력을 예측할 수 있고, 가용한 데이터에 입력과 출력 사이의 관계를 학습하는 데 충분한 정보가 있다.’ 이런 가설 없다면 시작할 수 조차 없습니다.

모델을 구성하고 훈련을 통해 가설을 검증해 나가는 것입니다.

4.5.2 Choosing a measure of success

가설이 올바른지 그른지를 검증하려면 측정할 수 있는 지표가 있어야 합니다. 지표는 관찰 가능해야 합니다.

4.5.3 Deciding on an evaluation protocol

훈련의 진척 사항을 평가할 방법이 필요합니다. 한 번의 훈련으로 진척 사항을 평가할 것인지, 여러 번의 훈련으로 진척 사항을 측정할 것인지를 결정합니다. 여러 번의 훈련으로 진척 사항을 측정한다면 얼마나 많은 훈련을 어떻게 할 것인지를 정해야 합니다.

다음과 같은 세 가지 방식 중 하나를 선택해서 사용할 수 있습니다.

  • Maintaining a hold-out validation set- The way to go when you have plenty of data
  • Doing K-fold cross-validation – The right choice when you have too few samples for hold-out validation to be reliable
  • Doing iterated K-fold validation – For performing highly accurate model evaluation when little data is available
4.5.4 Preparing your data

입력 데이터와 출력 데이터의 텐서를 준비합니다.

데이터는 텐서 형태이고, 작은 값으로 스케일이 조정되어 있어야 합니다. 특성마다 범위가 다르면 정규화 되어 있어야 합니다. 데이터가 적은 경우에는 특성 공학을 수행했어야 합니다.

4.5.5 Developing a model that does better than a baseline

훈련된 모델을 통한 예측은 무작위 예측보다는 나아야 합니다. 손으로 쓴 숫자 이미지를 가지고 숫자를 맞춘다면, 훈련된 모델은 10% 이상의 확률로 맞출 수 있어야 합니다.

표 4.1을 참조해서 첫 번째 모델을 구성합니다.

4.5.6 Scaling up: developing a model that overfits

Remember that the universal tension in machine learning is between optimization and generalization; the ideal model is one that stands right at the border between underfitting and overfitting; between undercapacity and overcapacity. To figure out where this border lies, first you must cross it.

층을 추가하고, units의 수를 키우고, 더 많은 epochs 동안 훈련하도록 해서 과적합 모델에서 시작합니다.

Always monitor the training loss and validation loss, as well as the training and validation values for any metrics you care about. When you see that the model’s performance on the validation data begins to degrade, you’ve achieved overfitting.

훈련 지표와 검증 지표 뿐만 아니라 훈련 손실과 검증 손실을 항상 모니터링 합니다. 검증셋을 사용하는 모델 성능이 감소하기 시작할 때가 과적합에 도달한 때 입니다.

4.5.7 Regularizing your model and tuning your hyperparameters

과적합이 일어나면 모델을 개선합니다.

  •  Add dropout.
  • Try different architectures: add or remove layers.
  • Add L1 and/or L2 regularization.
  • Try different hyperparameters (such as the number of units per layer or the learning rate of the optimizer) to find the optimal configuration.
  • Optionally, iterate on feature engineering: add new features, or remove features that don’t seem to be informative.

Once you’ve developed a satisfactory model configuration, you can train your final production model on all the available data (training and validation) and evaluate it one last time on the test set. If it turns out that performance on the test set is significantly worse than the performance measured on the validation data, this may mean either that your validation procedure wasn’t reliable after all, or that you began overfitting to the validation data while tuning the parameters of the model. In this case, you may want to switch to a more reliable evaluation protocol (such as iterated K-fold validation).

만족할 만한 모델 성능을 얻었다면, 가용한 모든 데이터를 사용해서 최종 모델을 훈련하고, 테스트셋으로 딱 한 번 테스트합니다. 테스트 성능이 훈련 결과보다 나쁘다면 검증셋에 과적합 되었을 수 있습니다. 이러한 경우에는 iterated K-fold validation과 같은 평가 방법으로 바꾸는 것이 좋습니다.

About the Author
(주)뉴테크프라임 대표 김현남입니다. 저에 대해 좀 더 알기를 원하시는 분은 아래 링크를 참조하세요. http://www.umlcert.com/kimhn/

Leave a Reply

*