Deep Learning/Fundamentals

C1W2 - Logistic Regression as a Neural Network

metamong 2023. 9. 6.

1. Binary Classification

Logistic Regression is an algorithm for binary classification

 

ex) an input of an image(represented in 3 RGB matrices: 3 x 64 x 64; if 64 x 64 pixels) → output 1 (cat) vs 0 (non cat)

 

 in binary classification, our goal is to learn a classifier(x → y), to predict whether this is a cat image or non-cat image(whether y is 1 or 0)

★ Notation:

① A single training example is represented by a pair (x, y) where x= N-dimensional feature vector and y is output {0,1}

 

② m is a number of training examples. {(x¹, y¹), (x², y²)…(xᵐ, yᵐ)} (entire training set)

(or to emphasize, m = $m_{train}$ / $m_{test}$is a number of test examples)

 

③ training examples can be shown in matrix

$X = \begin{bmatrix}
X^{(1)} & X^{(2)} & ... & ... & ... & X^{(m)} \\
\end{bmatrix}$

 

→ matrix X will have M columns (M is the number of train examples) / the height of the matrix: $n_x$

 

(+) without transpose, above matrix will make the implementation much easier(in NN)

$X\in \mathbb{R}^{n_x \times m}$

(X.shape will be ($n_x$,m) in python)

 

④ outputs y can be shown in matrix

$Y = \begin{bmatrix}
y^{(1)} & y^{(2)} & ... & ... & ... & y&{m} \\
\end{bmatrix}$

$Y \in \mathbb{R}^{1\times m}$

Y.shape = (1,m)

2. Logistic Regression

★ 0 또는 1을 분류하기 위해 사용되는 logistic regression은 0과 1사이의 범위를 갖는 sigmoid function으로 나타낼 수 있으며, sigmoid function 값으로 나타낸 y hat은 실제 y 값이 1이 될 확률이다. 

 

 our job is to try to learn parameters W and B so that Y hat becomes a good estimate of the chance of Y being equal to 1

3. Logistic Regression Cost Function

개별 training example y hat(denoted i)과 실제 y(denoted i)와의 discrepancy를 측정하는 방법은 위 연두색 칠한 식(log가 들어간)을 사용한다. 이를 loss function이라 하며, 위 loss function을 해석하면 실제 개별 y값이 1이라면 loss function을 최소화해야 하고, 이는 loss function 식에 의해 예측한 y hat(denoted i)가 실제로 1에 가까워야 한다는 결론을 내릴 수 있다 / 또한 실제 개별 y값이 0이라면 똑같이 loss function을 최소화하는 과정에서 예측한 y hat(denoted i)가 실제로 0에 가까워야 한다는 결론을 내릴 수 있다.

 

the loss function computes the error for a single training example; the cost function is the average of the loss functions of the entire training set

 

★ the cost function measures how well your parameters w & b are doing well on the training set

4. Gradient Descent

In the illustrated diagram, the horizontal axes represent w and b parameters and the axis above these horizontal axes represents the cost function. Our goal is to find the value of w and b such that the value of the cost function is minimum. (the height of the surface = the value of J at certain point)

 

★ what we want to do is find the value of w & b that corresponds to the minimum of the cost function J

The cost function J(w,b) which is used here is a convex function(this is why we use this particular cost function for logistic regression). Hence the gradient descent looks like a big bowl as opposed to several small local minima. (opposed to functions which has lots of different global optima)

 

A convex function always has multiple global optima (False)

 

★ (logistic regression), since it is a convex function, you should get to the same point no matter where you initialize. Normally, with logistic regression, the values are initialized to zero. Gradient Descent will start at an initial point and downhill towards the direction of the steepest descent as quickly as possible to reach the global minimum. It will take the value of w and b and update it as follows.

 

★ (alpha is a learning rate / w will be updated based on the learning rate & the derivative of w(change to w = the slope of w)

★ gradient descent 관점으로 해석하면, global optimum 오른쪽에 있는 점에서 intialization 진행 gradient descent 적용하면 dw의 부호는 현재 point의 slope 부호가 +이므로 +, learning rate 부호는 + → 따라서 gradient descent 식에 의해 w값이 감소 → global optimum을 향해 왼쪽으로 진행(learning rate에 따라 진행 정도 결정) / global optimum 왼쪽에 있는 점도 위와 마찬가지로 해석 가능

 

★ parameter b도 똑같이 적용

 

the actual equations

5. Computation Graph / Derivatives with a Computation Graph

★ a graph that organizes the computation from left to right (with the blue arrow below)

 

ex)

: 위의 예시처럼 왼쪽부터 먼저 계산해가는 과정을 그림으로 표현한 그래프가 Computation Graph. 상단에서 배운 logistic regression을 여기서 적용하자면, cost function J 값을 계산하기 위해 오른쪽으로 진행 / 그 반대로 J의 각 parameter별 derivative 값을 계산하기 위해서는 right to left computation: backward propagation 진행

 

※ One step of Backward propagation on a computation graph yields derivative of final output variable

 

★ chain-rule (backward propagation)

 

: right to left computation 연산을 진행하면서 각각의 variable derivative를 구할 수 있다. 즉, 아래와 같이 da, db, dc를 chain-rule로 구할 수 있다. (위 computation graph 예시에서는 da = 3, db = 6, dc = 9)

: 위 da, db, dc를 coding convention으로 $d_var$라고 하며, 이는 the derivative of a final output with respect to various intermediate quntities

6. Logistic Regression Gradient Descent

★ logistic regression(1 training example)

feature 개수가 2개라면 $z = w_1x_1 + w_2x+2 + b$의 식으로 나타낼 수 있다.

② z를 sigmoid function의 input으로 받고 출력한 output인 1개의 $\hat{y}$이자 a는 예측값

③ 그리고 실제 값 1개의 a와의 Loss function값을 구하기

 

★ 위 logistic regression을 computational graph로 나타내면 아래와 같다.

: 각 feature의 가중치 $w_1, w_2$와 parameter b를 modify해서 loss를 최소화해야 한다.

 

★ bacward-propagation(derivative 사용)

① loss function을 a에 대해서 미분 → da = $\frac{\mathrm{d} L(a,y)}{\mathrm{d} a} = -\frac{y}{a} + \frac{1-y}{1-a}$

② loss function의 z에 대한 미분 결과 → chain-rule에 의거해 위 ①과 a를 z에 대해 미분한 결과와의 곱 → a를 z에 대해 미분하면 a에 관해 나타낼 수 있고, 이는 a(1-a)가 되며 최종 곱은 a - y가 나온다.

최종적으로 알아야 할 건, modify할 수 있는 parameter w와 b를 얼마나 바꿔야 할 지, w와 b가 최종 L에 얼마나 기여하는 지를 알아야 한다. 

즉, 최종적으로 구한 $dw_1, dw_2, db$를 통해 앞서 구한 gradient descent 식을 아래와 같이 나타낼 수 있다.

 

$w_1 := w_1 - \alpha\times dw_1$ 

$w_2 := w_2 - \alpha\times dw_2$

$b := b - \alpha\times db$

7. Gradient Descent on m examples

★ 앞서 6.에서 backward-propgation으로 구한 logistic regression의 각 parameter derivative는 단 1개의 training example에 대한 결괏값이다.

 

★ 이제 m개의 training example에 대한 logistic regression Loss function을 최소화해보자

: 원리는 간단. 각 parameter별로 나온 각각의 training example의 derivative를 쭉 더한 다음, 전체 개수로 나눈, 평균값. 그 다음 평균값을 gradient descent식에 대입해주면 됨

 

★ pseudo-code(two-features에 한정. 만약 2개보다 더 많은 feature가 존재한다면 dw3, dw4,.. dwt 이렇게 많아짐

	J = 0; dw1 = 0; dw2 =0; db = 0;                 # Devs.
	w1 = 0; w2 = 0; b=0;							# Weights
	for i = 1 to m
		# Forward pass
		z(i) = W1*x1(i) + W2*x2(i) + b
		a(i) = Sigmoid(z(i))
		J += (Y(i)*log(a(i)) + (1-Y(i))*log(1-a(i)))

		# Backward pass
		dz(i) = a(i) - Y(i)
		dw1 += dz(i) * x1(i)
		dw2 += dz(i) * x2(i)
		db  += dz(i)
	J /= m
	dw1/= m
	dw2/= m
	db/= m

	# Gradient descent
	w1 = w1 - alpha * dw1
	w2 = w2 - alpha * dw2
	b = b - alpha * db

 

★ 즉, feature의 개수가 많아질수록 for-loop time complexity는 증가하므로(time complexity: O(n)), less efficiency. 따라서, vectorization technique(for loop 없애기)으로 코드의 효율성을 높일 수 있다. (vectorization technique은 다음 포스팅에)


☆ source1) Coursera <Deep Learning Specialization> (Neural Networks and Deep Learning)

☆ source2) Course Note from GH

 

 

댓글