[CS231n] Lecture 3 ์ •๋ฆฌ (Loss Functions and Optimization)

suyeonยท2024๋…„ 12์›” 24์ผ

CV

๋ชฉ๋ก ๋ณด๊ธฐ
3/17

๐Ÿ”Ž Stanford CS231n ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ๊ธฐ๋ก์šฉ๋„๋กœ ์ •๋ฆฌํ•˜๋Š” ๊ฒŒ์‹œ๊ธ€์ž…๋‹ˆ๋‹ค.

  • ์ €๋ฒˆ ์‹œ๊ฐ„์— W๋ฅผ ์–ด๋–ป๊ฒŒ ์„ ํƒํ• ์ง€์— ๋Œ€ํ•ด ์–˜๊ธฐํ•˜์ง€ ์•Š์Œ
  • ์‹ค์ œ๋กœ ์–ด๋–ค W๊ฐ’์ด ์ตœ์„ ์ผ์ง€์— ๋Œ€ํ•ด, ๋˜ training data๋ฅผ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š”์ง€์— ๋Œ€ํ•ด

  • in this case, cat is not correctly classified, car is, but frog score is wrong

Loss Function

  • ์ด classifier๊ฐ€ ์–ผ๋งˆ๋‚˜ ์ž˜ ์ž‘๋™ํ•˜๋Š”์ง€๋ฅผ ์•Œ๋ ค์ฃผ๋Š” ํ•จ์ˆ˜
    • given a dataset of examples (xi,yi)i=1N{(x_i, y_i)}_{i=1}^N, where xix_i is image, yiy_i is (integer, in this case, it's score) label
    • L=1Nโˆ‘iLi(f(xi,W),yi)\displaystyle L = \frac{1}{N}\sum_iL_i(f(x_i, W), y_i)
    • LiL_i is loss function
      • input: predicted score from function f, true target label y
      • output: quantative value for how bad the predictions are for the training example
    • LL is average of losses

Multiclass SVM loss

  • unlike SVM, it handles multiple classes
  • sums over all of the categories (YY) except for the true category YiY_i
    Li=โˆ‘jโ‰ yi{0ifย syi>sj+1sjโˆ’syi+1otherwise=โˆ‘jโ‰ yimax(0,sjโˆ’syi+1)\displaystyle \begin{aligned}L_i & = \sum_{j \neq y_i} \begin {cases} 0 & \text{if }s_{y_i} \gt s_j + 1 \\ s_j-s_{y_i}+1 & \text{otherwise} \end{cases} \\ & = \sum_{j \neq y_i} max(0, s_j-s_{y_i}+1)\end{aligned}
    • compare the score of the correct category and the incorrect category
      • if score for the correct category > score for the incorrect category โ†’ loss=0loss = 0
        โ‡’ sum these up over all incorrect categories
  • scores vector: s=f(xi,W)s = f(x_i, W), SVM loss form is the following:

  • ์–ด๋–ค ๊ฐ’๊ณผ 0 ์‚ฌ์ด์˜ max๊ฐ’์„ ์ทจํ•˜๋Š” ํ˜•์‹์˜ loss function์€ hinge loss์ž„
  • x์ถ•: syis_{y_i} = score for true category
  • y์ถ•: lossloss
  • syis_{y_i}๊ฐ€ ์ฆ๊ฐ€ํ• ์ˆ˜๋ก, ์–ด๋–ค safety margin์— ๋„๋‹ฌํ•˜๊ธฐ๊นŒ์ง€ loss๊ฐ€ ์„ ํ˜•์ ์œผ๋กœ ๊ฐ์†Œํ•˜๊ณ , ๊ทธ ์ดํ›„์—๋Š” correctly classifiedํ–ˆ์œผ๋ฏ€๋กœ loss=0loss = 0
  • ์ด loss๊ฐ’์ด ๊ถ๊ทน์ ์œผ๋กœ ๋งํ•ด์ฃผ๋Š” ๊ฒƒ์€ ์ •๋‹ต์ธ ์นดํ…Œ๊ณ ๋ฆฌ์— ๋Œ€ํ•œ ์ ์ˆ˜๊ฐ€ ๋‹ค๋ฅธ ์ ์ˆ˜๋“ค๋ณด๋‹ค ํฌ๋ฉด happyํ•˜๋‹ค๋Š” ๊ฒƒ์ž„

Calculating Multiclass SVM loss for those 3 examples




  • ๊ฒฐ๊ณผ์ ์œผ๋กœ, ์—ฌ๊ธฐ์—์„œ ์‚ฌ์šฉํ•œ classifier๋Š” ์ด data set์— ๋Œ€ํ•ด 5.3๋งŒํผ์ด๋‚˜ ์ข‹์ง€ ์•Š์Œ

Q: How do you choose "plus one"?
A: We don't actually care about the "absolute" values of the scores in this loss function, only care about the relative differences between the scores, only care that the correct score is much greater than the incorrect score. So, the choice of 1 doesn't matter. Later on, the "1" is canceled with the overall setting of the scale in WW.

Some Questions

  1. If car scores change a bit, what happens to loss?
    • Nothing.
    • SVM loss only cares about getting the correct score to be greater than one more than the incorrect scores
    • But in this case, the car score is already quite a bit larger than the others, and this margin of the '1' will still be retained, so the loss will not change.
  2. What is the min/max possible loss?
    • minimum loss = 0 (if our correct scores were much larger, all of the loss will be 0)
    • maximum loss = โˆž\infty (if the correct score goes very negative, we could incur potentially infinite loss)
  3. At initialization, W is small, so all s is approximately 0. What is the loss?
    • number of classes - 1
    • We're looping over C-1 classes, the two SSs will be about the same, which means max(0,1)=1max(0, 1) = 1 โ†’ so we'll get C-1

โ‡’ this is useful debugging strategy. when you start training, you should think about what you expect your loss to be, and if the loss you actually see at the start of training at that first iteration is not equal to C-1, means you probably have a bug

  1. What if the sum was over all classes? (including j=yij = y_i)
    • (originally, SVM sums up scores over the incorrect scores)
    • loss increases by 1
  2. What if we used mean instead of sum?
    • nothing changes; number of classes is fixed ahead of time, so that's just rescaling the whole loss function by a constant, so it doesn't really matter
  3. What if we change the loss formulation to Li=โˆ‘jโ‰ yimax(0,sjโˆ’syi+1)2L_i = \sum_{j\neq y_i} max(0, s_j-s_{y_i}+1)^2
    • this would be a different classification algorithm
    • here, we're changing the trade-offs between good and badness in kind of a nonlinear way, so we'll end up computing a different loss function
    • this method gets used sometimes in practice. it means that things that are bad gets squared bad = even more bad โ†’ whereas, if you're using hinge loss, we don't care being a little bit wrong and a lot wrong.

Multiclass SVM Loss: Example Code

def L_i_vectorized(x, y, W):
	scores = W.dot(x)
    margins = np.maximum(0, scores - scores[y] + 1)
    margins[y] = 0
    loss_i = np.sum(margins)
    return loss_i

Is a W that makes L = 0 unique?

  • no. there are other WWs.
  • 2W2W also makes L=0L = 0. it's because margins between the correct and incorrect scores will also double = all these margins were already greater than 1 and we double them, it'll be still greater than 1, so we still get 0 loss.

Regularization

Why do we need it

  • the loss function above makes the classifier "fit" the training data
    • however, we don't actually care about training data performance, we care about performance on test data
  • if we have the new data(green) come in, the blue line is going to be totally wrong
  • what we would have preferred the classifier to do was the strict green line
    • rather than blue line that perfectly fits the training data
  • this is a core fundamental problem in machine learning, and we solve it by regularization

Regularization

  • add an additional term to the loss function
  • in addition to data loss(which will tell our classifier that it should fit training data), we'll add another term which encourages the model to somehow pick the simpler WW. ("simple" depends on the task and the model)
  • whole idea is from Occam's Razor
    -"Among competing hypotheses, the simplest is the best"

  • standard loss function has two terms; data loss, regularization loss, hyper-parameter(lambda - trades off between the two)

Types of Regularization

1. L2 Regularization(Weight Decay)

  • euclidean norm of WW(weight vector)
  • penalizing the euclidean norm of this weight vector
    • we're considering two different possibilities for W
    • when we're doing linear classification, we're doing dot products between our xx and WW, these two WWs are the same b/c they give out the same result when dot producted with xx
    • which one would L2 regression prefer? โ†’ W2W2, b/c it has a smaller norm(๋ฒกํ„ฐ์˜ ๊ธธ์ด)
    • L2 regression measures complexity of the classifier in a relatively coarse(๊ฑฐ์นœ) way
    • L.C has interpretation of how much the value of the vector xx corresponds to the output class, so the L2 regularization is saying that it prefers to spread that influence across all the different values in xx

2. L1 Regularization

  • penzalizing the L1 norm of the weight vector
  • has properties that encourage sparsity(ํฌ๋ฐ•, ์„ฑ๊น€, ํฌ์†Œ) in WW
  • opposite interpretation compared to L2 regularization
    • would prefer W1 over W2
      • bc L1 reg has different notion of complexity
        • saying that maybe the model is less complex if the weight vector has less 0s, so the question of how do we measure complexity and how does L2 measure complexity is problem dependent, so you have to think about the particualr setup and data, and think about how the complexity should be measure on this task
          - (์œ„์˜ ๊ฒฝ์šฐ L1 = L2์ด๊ธด ํ•˜์ง€๋งŒ)
  1. Elastic net(L1 + L2)
  2. Max norm regularization
  3. Dropout
  4. Batch normalization, stocahstic depth
  • whole idea of regularization is that any thing that you do to your model that penalizes somehow the complexity of the model rather than explicitly trying to fit the train data

Softmax loss (Multinomial Logistic Regression)

  • another popular choice for loss function in DL

  • in Multiclass SVM, we didn't have interpretation for the scores

  • for multinomial logistic regression, endow(๊ธฐ๋ถ€ํ•˜๋‹ค) scores with some additional meaning, and use the scores to compute probability distribution over classes

    • scores = unnormalized log probabilities of the classes
  • we use softmax function

    • take all of our scores,
    • exponentiate them(become positive),
    • re-normalize them by the sum of those exponents
  • send scores to the softmax function, end up with this probability distribution, and we have probabilites over our classes, and the sum of probabilities across all the classes sum to 1
    P(Y=kโˆฃX=xi)=eskโˆ‘jesjย whereย s=f(xi,W)\displaystyle P(Y=k|X=x_i) = \frac{e^{s_k}}{\sum_je^{s_j}} \ \text{where} \ s = f(x_i,W)

  • the interpretation is that we want to compare the computed probability distribution implied by scores and the target(true probability distribution)

  • want to encourage the computed probability distribution from softmax function to match the target probability distribution that has all the mass on the correct class(e.g. if it's cat, we want probability for cat to be 1)

    • softmax ๊ณ„์‚ฐ ๊ฒฐ๊ณผ ๋‚˜์˜จ ํ™•๋ฅ  ๋ถ„ํฌ๊ฐ€ ์ •๋‹ต์˜ ํ™•๋ฅ  ๋ถ„ํฌ๋ฅผ ๋”ฐ๋ฅด๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ?
  • What we want is the probability of the true class to be high and as close to 1

  • loss will be the negative log of the probability of the true class
    Li=โˆ’logP(Y=yiโˆฃX=xi)L_i = -logP(Y=y_i|X=x_i)

    • ๋กœ๊ทธ๋ฅผ ์“ฐ๋Š” ์ด์œ ๋Š” ์›๋ž˜ ๊ฐ’ (raw probability)๋ณด๋‹ค ๋กœ๊ทธ ๊ฐ’์„ ์ตœ๋Œ€ํ™”ํ•˜๋Š” ๊ฒƒ์ด ์ˆ˜ํ•™์ ์œผ๋กœ ์‰ฝ๊ธฐ ๋•Œ๋ฌธ์ž„
    • ๋กœ๊ทธ๋Š” ์ฆ๊ฐ€๋งŒ ํ•จ(monotonic) โ†’ ์ •๋‹ต์ผ ํ™•๋ฅ ์˜ log๊ฐ’์„ ์ตœ๋Œ€ํ™”ํ•œ๋‹ค = badness๋ฅผ ์ธก์ •ํ•˜๋Š” ๊ฐ’์„ ์ตœ๋Œ€ํ™”ํ•œ๋‹ค โ†’ ์•ž์— - ๋ฅผ ๋ถ™์ž„
  • in summary, Li=โˆ’log(esyiโˆ‘jesj)\displaystyle L_i = -log(\frac{e^{s_{y_i}}}{\sum_je^{s_j}})

Example

  • 3 scores that came out of our linear classifier = exactly the way that they were in the context of SVM loss
  • rather than taking these scores and putting them directly into the loss function, exponentiate all of them(so that they're all positive) โ†’ normalize them(to make sure they all sum to 1) โ†’ loss will the minus log of each value
  1. What is the min/max value of the softmax loss?
    • min = 0 (theoretically)
      • probability distribution that we want is 1 on the correct class, 0 on the incorrect classes
      • if that were the case, inside the log will be 1 and โˆ’logโก1=0-\log1 = 0, loss would be 0
      • in order to get the thing totally right, our scores would have to look like infinity score for the correct class, -infinity score for all the incorrect classes (b/c we do exponentiation and normalization)
      • but computers don't deal with infinities, so in practice you'll never get 0 loss
    • max = โˆž\infty
      • suppose that we have 0 probability on the correct class, โˆ’logโก0=โˆž-\log0 = \infty
      • but, you'll never get here b/c the only way you can get this probability to be 0 is..
        • if ecorrectย classย score=0e^{\text{correct class score}} = 0, and it can only happen if the correct class score is โˆ’โˆž-\infty
  2. Usually at initialiation W is small, so all s is approximately 0. What is the loss?
    • logโกC\log C

Comparing the two loss functions

  • linear classification

    • WW gets multiplied against our input to produce scores
  • difference = how we choose to interpret those scores to quantitatively measure the badness afterwards

    • SVM - look at the margins between the scores of the correct class and incorrect classes
    • softmax - compute a probability distribution, and look at the -log probability of the correct class
  • in multi-class SVM loss, when the car score was much better than all the incorrect scores, jiggling the scores for that car image didn't change the loss at all

    • b/c the only thing that SVM loss cares about is getting that correct score to be greater than a margin above the incorrect scores
  • BUT softmax is different

    • always wants the probability mass all the way to 1
    • so even if you're giving high score to correct score, softmax will want to continue pushing that score of the correct class up toward โˆž\infty, and the score of the incorrect classes down toward โˆ’โˆž-\infty

Recap

Optimization

  • In practice, once your prediction function ff, loss function, regularizer gets big and complex, there's not much hope in trying to write down an explicit analytic solution that takes you directly to the minima
  • In practice, we use iterative methods where we start with some solution and gradually improve it over time
  • Take a bunch of WW sampled randomly, throw them into loss function and see how well they do

  • really bad algorithm, should not use this

  • random chance is 10%, and if we did random trials, some setting WW got 15% accuracy โ†’ better than random, but state of the art is 95%, got a gap to close

Strategy 2. Follow the slope

  • using the local geometry of this landscape

  • you can determine which way would take you a little down the hill

  • repeat, and hope that you'll end up at the bottom of the valley eventually

  • tends to work really well in practice

    • generally the strategy when training linear classifier, neural network and other things
  • in 1-D, slope = derivative(๋ฏธ๋ถ„, ๋„ํ•จ์ˆ˜) of this function
    = df(x)dx=limโกhโ†’0f(x+h)โˆ’f(x)h\displaystyle\frac{df(x)}{dx} = \displaystyle\lim_{h\rarr0}\frac{f(x+h)-f(x)}{h}

Gradient

  • gradient is the vector of (ํŽธ๋ฏธ๋ถ„) along each dimension
    • generalization of derivative in multi variable setting
    • each element of the gradient tells us what the slope of the function ff is, if we move in that coordinate direction
      • = how much the loss will change if we move a tiny amount in that coordinate direction
    • gradients point in the direction of greatest increase of the function
      • if you look at the negative gradient direction, it gives you the direction of the greatest decrease of the function
    • generally, slope of the landscape in any direction = the dot product of the gradient with the unit vector describing that direction
  • a lot of DL is about computing gradients of your functions, and using those gradients to iteratively update your parameter vector

Evaluating gradient

  • using the method of finite differences(going back to the limit definition of gradient)

  • ex) increment the first element of WW by a small value hh and recompute the loss

    • loss would decrease a little bit

    • then, use the limit definition to come up with the finite differences approximation to the gradient in this first dimension

    • repeat the procedure in the second dimension,

  • this is a terrible idea b/c it's very slow

Evaluating gradient on a computer

  • โˆ‡WL\nabla_WL์€ WW๋ฅผ ๋ณ€ํ™”์‹œ์ผฐ์„ ๋•Œ LL์ด ์–ผ๋งˆ๋‚˜ ๋ณ€ํ•˜๋Š”์ง€์— ๋Œ€ํ•œ ๊ฐ’์ž„
    • LL์„ WW์— ๋Œ€ํ•ด ํŽธ๋ฏธ๋ถ„ํ•œ ๊ฒƒ

  • write the expression for our loss and an expression for what this gradient should be (using calculus)
    • more efficient that trying to compute it analytically via finite differences
  • figure ahead of time what the analytic expression for the gradient is, and go directly from the WW and compute the dWdW or the gradient in one step

Summary so far

  • Numerical gradient - approximate, simple, slow, easy to write
    • but a very useful debugging tool
  • Analytic gradient - exact, fast, error-prone
  • In practice, always use analytic gradient, but check implementation with numerical gradient = gradient check

Gradient Descent

  • once we know how to compute the gradient, it leads us to a simple algorithm but heart of how we train these very biggest, complex algorithms
# Vanilla Gradient Descent

while True:
	weights_grad = evaluate_gradient(loss_fun, data, weights)
    weights += - step_size * weights_grad  # perform parameter update
  • after initializing WW with some random thing, while True, compute loss in our gradients and update weights in the opposite of the gradient direction

    • why opposite? โ†’ gradient is pointing in the direction of greatest increase of the function
      • ๋ฏธ๋ถ„๊ฐ’์ด + ์ด๋ฉด ๋ฐ˜๋Œ€๋กœ ๊ฐ€์•ผ ์ตœ์†Ÿ๊ฐ’์— ๋„๋‹ฌํ•  ์ˆ˜๊ฐ€ ์žˆ์Œ
      • ๋ฐ˜๋Œ€๋กœ -์ด๋ฉด +๋กœ ๊ฐ€์•ผ (๋ฐ˜๋Œ€๋ฐฉํ–ฅ์œผ๋กœ) ์ตœ์†Ÿ๊ฐ’์— ๋„๋‹ฌ ๊ฐ€๋Šฅ
  • step size = learning rate is hyperparameter

    • how far do we step in that direction at every update
  • 2D example

    • bowl = showing loss function (red = low loss = we want to get here)
    • start WW at a random point in space, and compute the negative gradient direction, repeat, and hopefully it'll get to the exact minima

Stochastic Gradient Descent (SGD)

  • we defined...
    • a loss as computing how bad a classifier is doing at any single training example
    • a full loss as average loss across the entire training set
  • NN(๋ฐ์ดํ„ฐ ๊ฐœ์ˆ˜) could be very large in practice
    • ex) image data set โ†’ N = 1.3 million
      • computing this loss is very expensive and requires a lot of computing โ†’ could be very slow
    • gradient is a linear operator
      • the gradient of the loss is the sum of gradient of the losses for each of the individual terms
    • so, if we want to compute the gradient again, it requires to iterate over the entire training data set, if N = million โ†’ very slow
    • In practice, we use SGD
  • rather than computing the loss and gradient over the training set, every iteration, we sample some small set of training example called minibatch (32, 64, 128 are common numbers)
    • use minibatch to estimate the full sum, estimate the true gradient
  • this is stochastic(ํ™•๋ฅ ์ )
    • b/c you can view this as Monte Carlo estimate of some expectation of the true value
      • Monte Carlo - ๋ฐ˜๋ณต๋œ ๋ฌด์ž‘์œ„ ์ถ”์ถœ์„ ์ด์šฉํ•˜์—ฌ ํ•จ์ˆ˜์˜ ๊ฐ’์„ ์ˆ˜๋ฆฌ์ ์œผ๋กœ ๊ทผ์‚ฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜ (์ถ”์ •ํ•˜๊ณ  ์‹ถ์€ ๊ฐ’์„ random sampling์„ ํ†ตํ•ด ๊ทผ์‚ฌํ•˜๋Š” ๊ฒƒ)
# Vanilla Minibatch Gradient Descent
while True:
	data_batch = sample_training_data(data, 256)  # sample 256 examples
    weights_grad = evaluate_gradient(loss_fun, data_batch, weights)
    weights += - step_size * weights_grad  # perform parameter update
  • sample some random minibatch of data โ†’ evaluate loss and gradient on the minibatch โ†’ make an update of the parameter based on the estimate of the gradient

Aside: Image Features

  • input raw pixel values into linear classifier = not work so well
  • before the dominance of deep neural network, using 2-stage apporach was common
    • compute various feature representations of input image
    • concatenate these different feature vectors to get feature representation of the image
      • this feature representation of the image is the input to a linear classifier, rather than the raw pixel values

Motivation

  • training data set on the left
    • no way that we can draw a linear decision boundary to separate blue and red points
  • but if we use a clever feature transform (in this case transforming to polar coordinates)
    • after doing the feature trasnform, this complex data might become linearly separable
    • and could be classified by a linear classifier
  • now, figure out what the right feature transform that is computing the right quantities for the problem is
    • ex) images - converting pixels to polar coordinates doesn't make sense, but you can try to write down feature representations of images that might make sense and might do better than putting raw pixels in the classifier

Example: Color Histogram

  • take hue color spectrum and divide into buckets
  • for every pixel, map it into one of the color buckets and count how many pixels fall into each buckets
  • this is an example of a simple feature vector

Example: Histogram of Oriented Gradients (HoG)

  • oriented edges are important in the human visual system (Hubel and Wiesel)
  • this histogram tries to capture the same intuition and measure the local orientation of edges on the image
    • divide the image into 8x8 pixel regions
    • within each region, compute what the dominant edge direction is
    • quantize those edge directions into several buckets
    • within each region, compute a histogram over these different edge orientations
  • full-feature vector would be bucketed histograms of edge orientations across all the different 8x8 regions

Example: Bag of Words

  • a way to represent a paragraph might be counting up the occurrences of different words โ†’ apply it into images someway
  • so, we need to define our own "vocabulary" of visual words โ†’ 2-stage approach
    • get a bunch of images, sample a group of tiny random crops from those images
    • cluster them using K-means
      • to come up with different cluster centers that might be representing different types of visual words in the images

Summary (image features vc convnets)

  • way that the image classification pipeline might have looked like 5-10 years ago, would be compute the different feature representations of the image(ex. bag of words) โ†’ concatenate a whole bunch of feature together, feed this feature extractor down into linear classifier
    โ‡’ after extracting the feature, this feature extractor would be a fixed block that would not be updated during training. during training, only linear classifier that's working on top of features would be updated.
  • BUT in ConvNets, rather than writing down the feature ahead of time, we're going to learn the features directly from the data
    • train this entire weights for this entire network rather than just the weights of the linear classifier on the top
profile
๋‚‘๋‚‘์Šจ....

0๊ฐœ์˜ ๋Œ“๊ธ€