Standalone Deep Learning

KAIST Idea Factory YouTube Lecture


Theory


Overfitting

  • Increasing the number of hyperparameters = As model capacity increases, the model can predict more complex phenomena, but at the same time the risk of overfitting increases.
  • When overfitting occurs, the empirical risk is small but the true risk is large.
  • The region where the generalization gap increases indicates that overfitting has occurred.

    Figure

⇒ Aim

  1. Cutting off training appropriately
  2. Finding an appropriate model capacity

Regularizations: Solving overfitting

L2 Regularization

💡

How does adding a regularization term solve overfitting?

: It has the effect of moving the weights toward the origin.

  • Reducing the number of features by lowering variable importance
  • Therefore, it has the effect of reducing the model’s complexity

💡

L1 Regularization vs L2 Regularization

  • L1 Regularization
    • Non-differentiable points occur
    • The regularized value is not unique
    • Feature selection process
    • When the prior distribution of the weights is a Laplace distribution
  • L2 Regularization
    • No non-differentiable points occur
    • The regularized value is unique
    • When the prior distribution of the weights is a Gaussian distribution

Dropout

  • A technique that randomly drops neurons with probability between 0 and 1
  • Model complexity decreases → Generalize

💡

The efficiency of using each individual neuron increases

: When a particular feature has the strongest correlation with the output value, without applying dropout, the weight of that feature is set to be the largest, causing a problem where the remaining features are not learned properly.

⇒ Through dropout, optimization is possible so that good outputs can be obtained even when learning excludes strongly correlated features.

  • A single model can be utilized like multiple models
  • Lab) Used only during the model’s training stage; in val./eval. mode it is automatically excluded and the model is tested accordingly

Gradient Vanishing

Figure

I had only understood the gradient vanishing part very intuitively, but understanding it through a computational graph like this made it easy to grasp! During backpropagation, a small input passing through \(\sigma\) inevitably produces a very small y, and since g = xy, when computing the partial derivative of f with respect to x, the partial derivative of g with respect to x is y, so the very small y value gets multiplied in and it becomes a very small value.

⇒ ReLU

Additional Activation Functions

Figure

Xavier Initialization

💡

Motivation

Suppose the weights are initialized to follow a standard Gaussian distribution and a sigmoid-family activation function is used. In this case, weights initialized with very small random numbers approach 0 as they pass through layers, converging (unstably), while conversely weights initialized with large random numbers saturate to 1 or -1 as they pass through layers, and the gradient vanishing problem occurs at the same time.

⇒ In this case, what if the weights are initialized so that the variance of the input data is preserved all the way to the output data? Wouldn’t the gradient vanishing problem then be solvable?

  • It is mainly an appropriate initialization method for sigmoid-family activation functions
  • For ReLU, HE Initialization is more appropriate

Batch Normalization

\[\begin{aligned} &\textbf{Input: } x \text{ over a mini-batch: } \mathcal{B} = \{x_{1 \ldots m}\}; \\ &\qquad\quad \text{parameters to be learned: } \gamma, \beta \\ &\textbf{Output: } \{ y_i = \mathrm{BN}_{\gamma,\beta}(x_i) \} \\[6pt] &\mu_\mathcal{B} \leftarrow \frac{1}{m} \sum_{i=1}^{m} x_i && \text{// mini-batch mean} \\ &\sigma_\mathcal{B}^2 \leftarrow \frac{1}{m} \sum_{i=1}^{m} (x_i - \mu_\mathcal{B})^2 && \text{// mini-batch variance} \\ &\hat{x}_i \leftarrow \frac{x_i - \mu_\mathcal{B}}{\sqrt{\sigma_\mathcal{B}^2 + \epsilon}} && \text{// normalize} \\ &y_i \leftarrow \gamma \hat{x}_i + \beta \equiv \mathrm{BN}_{\gamma,\beta}(x_i) && \text{// scale and shift} \end{aligned}\]

Batch Normalization Algorithm

  • Normalization over mini-batches
  • Terminology
    • Initial Covariate Shift: refers to the phenomenon where data is distorted by unseen factors
  • Steps
    1. For an n-dimensional input, compute n empirical means and variances per dimension
    2. Normalize the data to the standard Gaussian distribution N(0,1) across all layers
    3. Then restore the data distribution again (the original data’s mean and standard deviation are obtained through learning)

    ⇒ Solving the gradient vanishing problem, reducing dependence on initialization

💡

The difference between Batch, Iteration, and Epoch

  • Epoch: the state of having completed learning over the entire dataset once
  • Iteration: the number of times a dataset of batch size has been learned once
  • Batch: the number of data used in one training step

Being iterative = requiring multiple optimization processes to produce a result

Practice


Problems to be solved…

  • The inconvenience of changing hyperparameters such as the number of hidden layers and hidden units in the model

    💡

    Solution

    • nn.ModuleList
    • Argparse
    • Turning into functions
  • The problem where the same code produces different results each time it is run

    💡

    Solution

    • Fixing the seed : Xavier Initialization
  • The problem of experiments taking a long time to run

    💡

    Solution

    • Using GPU
  • Utilizing the Train-Validation-Test Set and improving model performance

    💡

    Solution

    • Hyperparameter Tuning
  • And… solving overfitting

How to Parameterize DL Code

: Parameterize “Hyperparameters”

loss.backward() and optimizer.step()

loss.backward()

Figure

  • The process of computing gradients via backpropagation

optimizer.step()

Figure

  • Updating parameters based on the computed gradients

Hyperparameter?

  • Hyperparameter vs. Parameter
    • Hyperparameter: usually non-trainable
    • Parameter: trainable
  • Types
    • Determining a Model
    • Optimizer Related
    • Training, Evaluation Process Related
    • Device Related
    • Saving Exp Result

Argparse

: Dictionary like obj

  • Makes it easy to manage hyperparameters
  • Usage

     import argparse
       
     parser = argparse.ArgumentParser()
     args = parser.parse_args("")
       
     args.num_layer = 5 
     args.in_dim = 100
       
     linears = [i for i in range(args.num_layer)] # 바로 int 값으로 활용 가능하다
       
     d = vars(args) # args -> dict 변환
       
     print(args)
     print(linears)
     print(d, type(d))
    
  • Result

    Figure

Pytorch GPU

  • The originally familiar usage of GPUs: “graphics” processors. Ray tracing, etc.. often used in rendering. In other words, a design optimized for matrix operations.

    ⇒ Since parallel computation is possible in DL computations, the speed is much faster.

How to use GPU with Pytorch

model = MLPModel(784, 10, [1000])
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model.to(device) # GPU가 사용가능하다면 모델을 CPU -> GPU로

# --- data의 이동 --- #
input_X = input_X.squeeze()
input_X = input_X.view(-1, 784)
...
input_X = input_X.to(device)
true_y = true_y.to(device)

# true_y까지 데이터를 모두 GPU로 옮겼으므로, loss 계산도 GPU에서 가능해진다
pred_y = model(input_X) 

train_loss += loss.detach().numpy() # loss 계산을 GPU에서 했으면 cpu로 옮겨서 numpy로 변환하라는 오류가 뜬다
# .item() 사용
train_loss += loss.item()

Hyperparameter Tuning

Tuning Options

  • Model Related
    • Num of hidden layers
      • Flexible
      • MLP: 1-10
      • CNN: ~152, ~1000
    • Num of hidden units
      • Flexible
      • 10-1024 unit/layer
    • Activation Function
      • ReLU is the most commonly used trend
      • Other ReLU-family, LeakyReLU, GeLU, ELU…
  • Optimization Related
    • Type of Optimizer
      • SGD, RMSProp, ADAM, AdaDelta…
    • Learning Rate, L2 coefficient
      • Search both on a log scale → then search linearly within an appropriate range
        • LR: 1e-5 ~ 1e-1
        • L2 coef: 1e-5 ~ 1e5
      • L2 Coef: how to set the importance of the weights?
    • Dropout Rate
      • 0.1 ~ 0.5
      • Up to 0.7 when test data is severely lacking
    • Batch Size
      • Increase the batch size until OOM occurs → reduce it when overfitting is severe
    • Epoch
      • Early Stopping

Ways of Tuning

Figure

Human Bias During Tuning Process

  • Avoid continuously checking Test Acc during the tuning process

    ⇒ Check Val Acc instead

: To prevent the human from becoming trained on the Test Set

CIFAR 10 Practice Code

  1. Data Generation
    • transforms.Normalize(mean, std, inplace=Falce): Normalize a tensor image with mean and standard deviation.
    • The output of torchvision datasets are PILImage images of range [0, 1]
    • transforms.Compose(): Composes several transforms together (parameters: list of transforms to compose)
    • transforms.ToTensor(): Convert img or numpy.ndarray to tensor
    transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((.5, .5, .5), (.5, .5, .5))])
                                    # for R, G, B three channels, pixel value - mean / std ->  normalized range [-1, 1].
    
    • PIL: a representative library for image processing in Python
  2. Train the Model
    • .view(): For reshaping data (but of same num of elements)
  3. Experiment with Argparse
Defining exmeriment function
def experiment(args):
    model = MLP(args.in_dim, args.out_dim, args.hid_dim, args.n_layers, args.act)
    model.cuda()
    
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.mm)

    for epoch in range(args.epoch):

        # ===== Train ===== #
        running_loss = 0.0
        train_loss = 0.0
        for i, data in enumerate(trainloader, 0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data # inputs.shape: [4,3,32,32]
            inputs = inputs.view(-1, 3072) # .view()로 차원 맞추기. For reshaping data (but of same num of elements)
            inputs, labels = inputs.cuda(), labels.cuda()

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            outputs = model(inputs) # 3072 X 100 shape
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.item()
            train_loss += loss.item()
            if i % 2000 == 1999:    # print every 2000 mini-batches
                print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
                running_loss = 0.0
                
        # ===== Validation ===== #
        correct = 0
        total = 0
        val_loss = 0
        loss = 0.0
        # since we're not training, we don't need to calculate the gradients for our outputs
        with torch.no_grad():
            for data in valloader:
                images, labels = data
                images = images.view(-1, 3072)
                # calculate outputs by running images through the network
                images, labels = images.cuda(), labels.cuda()
                outputs = model(images)
                # the class with the highest energy is what we choose as prediction
                loss = criterion(outputs,labels) # loss for each batch
                val_loss += loss.item()
                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()
            
            val_loss /= len(valloader)
            val_acc = 100 * correct // total

        print(f'Epoch: {epoch + 1} / Train Loss: {train_loss:.3f} / Validation Loss: {val_loss:.3f}')
        print(f'Validation accuracy: {val_acc:.3f}')

    # ===== Evaluation ===== #
    correct = 0
    total = 0
    # since we're not training, we don't need to calculate the gradients for our outputs
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            # calculate outputs by running images through the network
            images, labels = images.view(-1, 3072).cuda(), labels.cuda()
            outputs = model(images)
            # the class with the highest energy is what we choose as prediction
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
        test_acc = 100 * correct // total

        print(f'Evaluation accuracy: {test_acc:.3f}')
Using argparse to parmaeterize hyperparameters
import argparse

# seed: random.rand() process to be deterministic
seed =123
np.random.seed(seed)
torch.manual_seed(seed)

parser = argparse.ArgumentParser()
args = parser.parse_args("")

args.n_layers = 5
args.in_dim = 3072
args.out_dim = 10
args.hid_dim = 100
args.act = nn.ReLU()

args.lr = 0.001
args.mm = 0.9

args.epoch = 2

list_var1 = [4, 5, 6]
list_var2 = [50, 100, 150]

for var1 in list_var1:
    for var2 in list_var2:
        args.n_layers = var1
        args.hid_dim = var2
        result = experiment(args)
        print(result)