sources:
https://www.kaggle.com/code/ryanholbrook/stochastic-gradient-descent
Stochastic Gradient Descent
Explore and run machine learning code with Kaggle Notebooks | Using data from DL Course Data
www.kaggle.com
Introduction
In the first two lessons, we learned how to build fully-connected networks out of stacks of dense layers. When first created, all of the network's weights are set randomly -- the network doesn't "know" anything yet. In this lesson we're going to see how to train a neural network; we're going to see how neural networks learn.
이번 에는 어떻게 덴스 레이어를 쌓아서 어떻게 Fully-connected network 완전연결된 신경망을 구성하는지 배울 것이다.
일단 신경망을 구성하면 모든 네트워크상의 가중치는 무작위로 (랜덤하게) 설정된다. 즉 학습전의 네트워크는 아직 무엇이 어떻게 이루어질지 모르는 상태다.
여기서는 어떻게 신경망을 학습시키는지 보자.
As with all machine learning tasks, we begin with a set of training data. Each example in the training data consists of some features (the inputs) together with an expected target (the output). Training the network means adjusting its weights in such a way that it can transform the features into the target. In the 80 Cereals dataset, for instance, we want a network that can take each cereal's 'sugar', 'fiber', and 'protein' content and produce a prediction for that cereal's 'calories'. If we can successfully train a network to do that, its weights must represent in some way the relationship between those features and that target as expressed in the training data.
다른 머신 러닝 사례처럼 일단 데이터 셋에서 트레이닝 데이터를 분리한다. 트레이닝데이터는 몇가지의 입력값 (features)과 출력값을 가지고 있다.
신경망을 학습시킨다는 의미는 입력값을 출력값으로 변환(transform) 시킬 수 있는 가중치를 조정해 나간다는 것을 의미한다.
예를 들어 80 Cereals 데이터에서 우리는 sugar, fiber, proten의 feature 값을 가지고 calories 항목을 예측하고자 한다. 만약 우리가 신경망을 잘 훈련시킨다면 신경망 모델이 갖는 가중치들은 트레이닝 데이터 상에 있는 입력값과 출력값간의 관계를 잘 설명해줄 수 있는 값을 가지고 있다고 할 수 있다.
In addition to the training data, we need two more things:
그리고 트레이닝 데이터에서 2가지 더 알아야할 것은
A "loss function" that measures how good the network's predictions are.
로스 펑션 (loss function; 손실함수) 은 신경망의 예측이 얼마나 좋은가를 나타낸다.
An "optimizer" that can tell the network how to change its weights.
Optimizer는 신경망이 가중치를 어떻게 바꿀 것인지 알려준다.
The Loss Function
손실함수
We've seen how to design an architecture for a network, but we haven't seen how to tell a network what problem to solve. This is the job of the loss function.
우리는 네트워크 구조에 대해서는 봤지만 어떻게 문제를 풀게 할 것인지에 대해서는 보지 않았다. 이것이 loss function 이 하는 일이다.
The loss function measures the disparity between the the target's true value and the value the model predicts.
로스 펑션은 목표 실제값(rue value)와 예측값(predicted value)간의 차이를 나타낸다.
Different problems call for different loss functions. We have been looking at regression problems, where the task is to predict some numerical value -- calories in 80 Cereals, rating in Red Wine Quality. Other regression tasks might be predicting the price of a house or the fuel efficiency of a car.
문제마다 각각 다른 로스 펑션이 호출된다. 우리가 살펴본 회귀문제에서 목표는 어떤 숫자값을 예측하는 일이었고 80 Cereals 문제에서는 calories 값이고 Red Wine Quality 문제에서는 rating 값이었다.
기타 회귀 문제로 집값을 예측하거나 차량 연비를 예측하는 문제가 있었다.
A common loss function for regression problems is the mean absolute error or MAE. For each prediction y_pred, MAE measures the disparity from the true target y_true by an absolute difference abs(y_true - y_pred).
회귀 문제에서 사용되는 대표적인 손실함수는 Mean Absolute Error (MAE)가 있다.
각각의 예측된 출력값 y_pred 에 대해서 MAE는 실제 데이터 값 y_true 값과의 절대값 차이 평균을 나타낸다.
mean(abs(y_true - y_pred))
에서 abs는 absolute의 약자로 절대값 기호를 대신한 것이고 mean은 평균값을 의미
The total MAE loss on a dataset is the mean of all these absolute differences.
전체 MAE 값은 이러한 절대값의 평균을 의미한다.
The mean absolute error is the average length between the fitted curve and the data points.
Besides MAE, other loss functions you might see for regression problems are the mean-squared error (MSE) or the Huber loss (both available in Keras).
위 그래프에서 MAE값은 피팅된 커브라인(직선처럼 보이지만)과 실제 데이터 값(점)간의 y축 거리 (이것이 abs(y_pred - y_true)를 취합한 평균값이다.
이외에서 회귀 문제에서 MSE(Mean Squared Error )나 Huber loss 와 같은 손실 함수가 사용되기도 한다.
During training, the model will use the loss function as a guide for finding the correct values of its weights (lower loss is better). In other words, the loss function tells the network its objective.
트레이닝을 시키는 과정에서 모델은 이 손실함수를 이용하여 각 가중치 값을 조정하는 기준으로 사용한다. 즉 손실함수 값을 최소화하는 방향으로 가중치를 조절하게 된다. 다시 말하면 이 손실함수가 신경망 모델의 학습 목표를 알려주고 있다고 말할 수 있다.
The Optimizer - Stochastic Gradient Descent
옵티마이져 - 확률 경사 하강법 (스토케이스틱 그라디언트 디센트)
We've described the problem we want the network to solve, but now we need to say how to solve it. This is the job of the optimizer. The optimizer is an algorithm that adjusts the weights to minimize the loss.
우리는 이제 신경망이 풀어야 하는 문제를 알려 주었고 어떻게 풀지를 알려 줘야 한다.
이게 옵티마이져가 하는 역할인데 옵티마이져는 바로 손실함수를 어떻게 줄일 수 있는지를 알려주는 알고리즘이다.
Virtually all of the optimization algorithms used in deep learning belong to a family called stochastic gradient descent. They are iterative algorithms that train a network in steps. One step of training goes like this:
딥러닝에 속하는 알고리즘에서 옵티마이져 알고리즘은 대부분 이 확률적 경사 하강법 Stochastic gradient descent에 속한다고 말할 수 있다. 이 방법은 신경망을 반복적인 스텝을 거쳐 원하는 값에 이르고자 하며 하나의 스텝을 고찰하자면 다음과 같다.
Sample some training data and run it through the network to make predictions.
우선 트레이닝 데이터에서 샘플을 얻어 이를 모델에 넣어 예측값을 구한다.
Measure the loss between the predictions and the true values.
예측값과 실제값을 이용하여 로스값을 구한다.
Finally, adjust the weights in a direction that makes the loss smaller.
마지막으로 로스를 더 작게 만들수 있는 방향으로 가중치값을 조정한다.
Then just do this over and over until the loss is as small as you like (or until it won't decrease any further.)
이것을 반복해서 더이상 로스값이 작아지지 않는 상태에 이르도록 하면 최소 로스값을 갖는 모델이 된다.
.
Each iteration's sample of training data is called a minibatch (or often just "batch"), while a complete round of the training data is called an epoch. The number of epochs you train for is how many times the network will see each training example.
트레이닝 데이터 샘플을 넣어 얻은 하나의 스텝을 미니배치 또는 배치 (mini-batch or batch)라고 하고 준비된 트레이닝 데이터셋을 한 라운드 다 넣었다면 이것을 에포크 (epoch)라고 한다. 각 네트워크가 트레이닝 샘플 전체를 얼마나 많이 트레이닝했는가 하는 값이 에포크(epoch)로 나타나는 것.
The animation shows the linear model from Lesson 1 being trained with SGD. The pale red dots depict the entire training set, while the solid red dots are the minibatches. Every time SGD sees a new minibatch, it will shift the weights (w the slope and b the y-intercept) toward their correct values on that batch. Batch after batch, the line eventually converges to its best fit. You can see that the loss gets smaller as the weights get closer to their true values.
#SGD stochastic gradient descent 확률 경사하강
위의 애니메이션에서 희미한 빨간점은 전체 트레이닝 세이고 짙은 빨간점은 batch 배치다. 이 모델이 매번 미니배치를 수행할때마다 가중치를 조정하며 (가중치는 w기울기와 b의 y절편) 배치가 거듭될 수록 최적의 피팅으로 수렴하게 된다.
그리고 가중치에 의해 예측값이 실제값에 가까워질수록 손실함수값이 줄어드는 것을 볼 수 있다.
Learning Rate and Batch Size
학습빈도 (러닝레이트)와 배치 크기(Batch Size)
Notice that the line only makes a small shift in the direction of each batch (instead of moving all the way). The size of these shifts is determined by the learning rate. A smaller learning rate means the network needs to see more minibatches before its weights converge to their best values.
애니메이션에서 라인이 각 배치 방향으로 조금씩만 움직이는 것을 볼 수 있다. 이 움직임은 러닝레이트(학습율)에 의해 결정되는데 학습률이 작을수록 신경망은 더 많은 미니배치를 확인한 뒤 가중치를 조정하게 된다.
The learning rate and the size of the minibatches are the two parameters that have the largest effect on how the SGD training proceeds. Their interaction is often subtle and the right choice for these parameters isn't always obvious. (We'll explore these effects in the exercise.)
러닝레이트와 배치 사이즈는 SGD에서 학습 진행방향에 큰 영향을 주는 2개의 파라미터이다.
하지만 이 둘의 상호작용이 항상 명료한 것은 아니다.이 파라미터를 조정하는 것이 파라미터 튜닝이다. 이에 대해서는 나중에 논의하겠다.
Fortunately, for most work it won't be necessary to do an extensive hyperparameter search to get satisfactory results. Adam is an SGD algorithm that has an adaptive learning rate that makes it suitable for most problems without any parameter tuning (it is "self tuning", in a sense). Adam is a great general-purpose optimizer.
다행히 대부분의 작업에서는 추가적인 하이퍼 파라미터를 구축해서 결과를 찾을 필요가 없다. Adam은 SGD 알고리즘 중 하나인데 이것은 adaptive learning rate (적응형 학습률)를 적용하고 있고 대부분 별도의 파라미터 튜닝 없이 스스로 튜닝값을 정한다. (이를 셀프 튜닝이라고 함.) Adam이 가장 일반적인 옵티마이져로 사용된다.
Adding the Loss and Optimizer
손실함수와 옵티마이져를 더하자.
After defining a model, you can add a loss function and optimizer with the model's compile method:
모델을 정의한 뒤 로스 함수와 옵티마이져를 정할 수 있다.
#파이썬코딩
model.compile(
optimizer="adam",
loss="mae",
)
Notice that we are able to specify the loss and optimizer with just a string. You can also access these directly through the Keras API -- if you wanted to tune parameters, for instance -- but for us, the defaults will work fine.
여기서는 로스 함수와 옵티마이져를 단순히 이름으로만 지정했다. 만약 Keras API의 해당 함수에 직접 억세스하여 파라미터 튜닝을 직접할 수도 있겠지만, 앞서 이야기한대로 우리가 다루는 문제는 대부분의 경우 그대로 디폴트 값을 사용해도 무방하다.
What's In a Name?
The gradient is a vector that tells us in what direction the weights need to go. More precisely, it tells us how to change the weights to make the loss change fastest. We call our process gradient descent because it uses the gradient to descend the loss curve towards a minimum. Stochastic means "determined by chance." Our training is stochastic because the minibatches are random samples from the dataset. And that's why it's called SGD!
경사는 벡터 기울기를 의미하는데 이는 가중치 변화방향을 나타내는 것이다. 경사값을 어떻게 조정해서 로스를 가장 빠르게 최소화할 수 있냐는 것이다. 경사 하강이라고 부르는 이유는 로스 함수의 그래프 곡선 (또는 곡면이든)에서 점진적으로 그래프 아래로 하강하면서 최소값을 찾아 나가기 때문이다.
자 이제 경사하강 앞에 확률 (stochastic)을 붙인 이유는 미니배치가 데이터셋에서 샘플을 가져올때 무작위로 (랜덤하게) 가져오기 때문이다.
(이하 생략)
...
#파이썬코딩
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(512, activation='relu', input_shape=[11]),
layers.Dense(512, activation='relu'),
layers.Dense(512, activation='relu'),
layers.Dense(1),
])
Deciding the architecture of your model should be part of a process. Start simple and use the validation loss as your guide. You'll learn more about model development in the exercises.
모델 정의부분은 연습창에서 좀더 배울 것.
After defining the model, we compile in the optimizer and loss function.
모델을 정의하고 나서 로스 펑션과 옵티마이져를 컴파일한다. (여기서는 디폴트값이므로 파라미터 튜닝없이 string 값으로 adam, mae 바로 적음.)
#파이썬 코딩
model.compile(
optimizer='adam',
loss='mae',
)
Now we're ready to start the training! We've told Keras to feed the optimizer 256 rows of the training data at a time (the batch_size) and to do that 10 times all the way through the dataset (the epochs).
자 이제 트레이닝을 할 준비가 되었다.
우리는 Keras에 옵티마이져(adam)에 한번에 256개 데이터를 무작위 추출하여 전달하도록 요청할 거고, 이게 배치 사이즈(batch_size)이고 데이터셋 전체를 10번 반복하도록 요청할 거다 -- 이게 에포크(epoch)다. 아래 코딩이 해당 모델을 트레이닝 데이터에 피팅하기 위한 코딩이다.
자 앞과 연결하자면,
1. 모델을 정의했다. 신경망 모델이다.
2. 모델의 로스 펑션과 옵티마이져를 컴파일했다. (파라미터 튜닝은 디폴트)
3. 해당 모델에 트레이닝 데이터 셋을 넣어 트레이닝 하는데, 여기서 배치 사이즈와 에포크를 정해줬다.
출력결과에서 에포크가 카운트 되는 모습을 볼 수 있다.
#코딩
history = model.fit(
X_train, y_train,
validation_data=(X_valid, y_valid),
batch_size=256,
epochs=10,
)
#출력
Epoch 1/10
5/5 [==============================] - 1s 66ms/step - loss: 0.2470 - val_loss: 0.1357
Epoch 2/10
5/5 [==============================] - 0s 21ms/step - loss: 0.1349 - val_loss: 0.1231
Epoch 3/10
5/5 [==============================] - 0s 23ms/step - loss: 0.1181 - val_loss: 0.1173
Epoch 4/10
5/5 [==============================] - 0s 21ms/step - loss: 0.1117 - val_loss: 0.1066
Epoch 5/10
5/5 [==============================] - 0s 22ms/step - loss: 0.1071 - val_loss: 0.1028
Epoch 6/10
5/5 [==============================] - 0s 20ms/step - loss: 0.1049 - val_loss: 0.1050
Epoch 7/10
5/5 [==============================] - 0s 20ms/step - loss: 0.1035 - val_loss: 0.1009
Epoch 8/10
5/5 [==============================] - 0s 20ms/step - loss: 0.1019 - val_loss: 0.1043
Epoch 9/10
5/5 [==============================] - 0s 19ms/step - loss: 0.1005 - val_loss: 0.1035
Epoch 10/10
5/5 [==============================] - 0s 20ms/step - loss: 0.1011 - val_loss: 0.0977
You can see that Keras will keep you updated on the loss as the model trains.
계속해서 손실함수값이 업데이트 되고 있다.
Often, a better way to view the loss though is to plot it. The fit method in fact keeps a record of the loss produced during training in a History object. We'll convert the data to a Pandas dataframe, which makes the plotting easy.
손실함수값을 직접 보는 가장 좋은 방법은 그래프로 보는 것이다. 모델을 피팅하는 과정에서도 로스펑션값은 계속해서 저장이된다. (History 오브젝트) 이것을 데이터프레임으로 전환하면 그래프를 손쉽게 그릴 수 있다.
아래 코딩 참조
#코딩
import pandas as pd
# convert the training history to a dataframe
history_df = pd.DataFrame(history.history)
# use Pandas native plot method
history_df['loss'].plot();
Notice how the loss levels off as the epochs go by. When the loss curve becomes horizontal like that, it means the model has learned all it can and there would be no reason continue for additional epochs.
에포크가 회차를 거듭하면서 어떻게 로스값이 변하는지 확인해라.
로스 커브가 평평해지면 (기울기가 0에 가까워지면) 모델이 학습을 끝마쳐간다는 것이고 추가적인 에포크를 거듭할 필요가 없다는 것이다.
이하 실습할 것.
<끝>
[딥러닝초급] Drop out and Batch Normalization (0) | 2025.02.18 |
---|---|
[딥러닝초급] Overfitting and Underfitting (0) | 2025.02.10 |
[딥러닝초급]Deep Neural Networks (0) | 2025.02.04 |
[딥러닝초급] A Single Neuron (0) | 2025.02.03 |
[머신러닝중급]Cross-Validation + XGBoost (0) | 2025.01.23 |