brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Oct 10. 2020

앤드류 응의 머신러닝 (4-3) : 피처 스케일링

   온라인 강의 플랫폼 코세라의 창립자인 앤드류 응 (Andrew Ng) 교수는 인공지능 업계의 거장입니다. 그가 스탠퍼드 대학에서 머신 러닝 입문자에게 한 강의를 그대로 코세라 온라인 강의 (Coursera.org)에서 무료로 배울 수 있습니다. 이 강의는 머신러닝 입문자들의 필수코스입니다. 인공지능과 머신러닝을 혼자 공부하면서 자연스럽게 만나게 되는 강의입니다. 


Linear Regression with Mutiple Variables

다변수 선형회귀


Multivarate Linear Regression (다변수 선형 회귀) 


Gradient Descent in Practice I : Feature Scaling 

(경사 하강법 실습 I : 피쳐 스케일링)


   In this video and in the video after this one, I wanna tell you about some of the practical tricks for making gradient descent work well. In this video, I want to tell you about an idea called feature skill.


   이번 강의와 다음 강의에서, 경사 하강법을 잘 활용할 수 있는 실용적인 팁들을 설명합니다. 먼저 피처 스케일링(feature scaling)입니다.  



   Here's the idea. If you have a problem where you have multiple features, if you make sure that the features are on a similar scale, by which I mean make sure that the different features take on similar ranges of values, then gradient descents can converge more quickly.


   다수의 피처(Features)를 다룰 때 주의해야 할 점이 있습니다. 피처의 값의 범위가 비슷할 때 경사 하강법은 더 빠르게 최저값으로 수렴합니다. 


   Concretely let's say you have a problem with two features where X1 is the size of house and takes on values between say zero to two thousand and two is the number of bedrooms, and maybe that takes on values between one and five. If you plot the contours of the cost function J of theta, then the contours may look like this, where, let's see, J of theta is a function of parameters theta zero, theta one and theta two. I'm going to ignore theta zero, so let's about theta 0 and pretend as a function of only theta 1 and theta 2, but if x1 can take on them, you know, much larger range of values and x2 It turns out that the contours of the cause function J of theta can take on this very very skewed elliptical shape.  Except that with the so 2000 to 5 ratio, it can be even more secure. So, this is very, very tall and skinny ellipses, or these very tall skinny ovals, can form the contours of the cause function J of theta. And if you run gradient descents on this cos-function, your gradients may end up taking a long time and can oscillate back and forth and take a long time before it can finally find its way to the global minimum. In fact, you can imagine if these contours are exaggerated even more when you draw incredibly skinny, tall skinny contours, and it can be even more extreme than, then, gradient descent just have a much harder time taking it's way, meandering around, it can take a long time to find this way to the global minimum.


   여기 두 개의 피처가 있는 학습 알고리즘이 있습니다. x1은 주택 크기이고 값의 범위는 0 ~ 2,000 평방 피트 사이입니다. x2는 방의 개수이고 값의 범위는 1 ~ 5 개 사이입니다. 비용 함수 J(θ)를 그리면 등고선은 매우 길쭉한 모양입니다. 이 그림은 파라미터 θ0, θ1, θ2에 대한 비용 함수 J(θ)이고, θ0를 무시합니다.  비용 함수 J(θ)는 파라미터 θ1과 θ2에 대한 그래프입니다. 피처 x1 주택 크기의 값의 범위가 피처 x2 방의 개수의 값의 범위보다 너무 크다면 비용 함수 J(θ)의 등고선은 매우 매우 길쭉한 타원 모양입니다. 2000 : 5의 비율만 아니라면 안정된 모양을 그릴 수 있을 것입니다. 매우 뾰족하고 길쭉한 비용 함수 J(θ)에서 경사 하강 알고리즘은 오랜 시간 동안 앞뒤로 진동하면서 이동할 것이고 전역 최소값을 도달하는 데 오랜 시간이 걸립니다. 등고선들을 극단적으로 더 뾰족하고 길쭉하게 그린다면, 경사 하강 알고리즘은 더 오랜 시간 동안 더 구불구불하게 이동할 것입니다.



   In these settings, a useful thing to do is to scale the features. Concretely if you instead 

define the feature x1 to be the size of the house divided by two thousand, and define x2 to be maybe the number of bedrooms divided by five, then the count well as of the cost function J can become much more, much less skewed so the contours may look more like circles. And if you run gradient descent on a cost function like this, then gradient descent, you can show mathematically, you can find a much more direct path to the global minimum rather than taking a much more convoluted path where you're sort of trying to follow a much more complicated trajectory to get to the global minimum.So, by scaling the features so that there are, the consumer ranges of values. In this example, we end up with both features, x1 and x2 t, between zero and one. You can wind up with an implementation of gradient descent. They can convert much faster.


   이 문제를 해결하는 유용한 방법은 피처의 값의 범위를 조정하는 피처 스케일링(Feature Scaling)을 이용하는 것입니다. 구체적으로 피처 x1 주택 크기는 최대값 2,000으로 나눈 값으로 정의하고, 피처 x2 방의 개수는 최대값 5로 나눈 값으로 정의합니다. 비용 함수 J(θ)가 그린 등고선 모양은 뾰족하지 않은 원에 가까운 모양을 만들 수 있습니다. 비용 함수 J(θ)에서 경사 하강 알고리즘은 전역 최소값을 정확하게 똑바르게 찾는 경로를 이동합니다. 난해하고 복잡한 경로를 그리거나 구불구불하게 가지 않습니다. 그래서, 머선 러닝에서 피처의 값의 범위를 조정하는 피처 스케일링을 합니다. 이 예제에서 x1과 x2의 값의 범위는 0과 1 사이의 값입니다. 따라서, 더 빠르게 최소값에 수렴하는 경사 하강법을 구현할 수 있습니다. 



   More generally, when we're performing feature scaling, what we often want to do is get every feature into approximately a -1 to +1 range and concretely, your feature x0 is always equal to 1. So, that's already in that range, but you may end up dividing other features by different numbers to get them to this range. The numbers -1 and +1 aren't too important. So, if you have a feature, x1 that winds up being between zero and three, that's not a problem. If you end up having a different feature that winds being between -2 and + 0.5, again, this is close enough to minus one and plus one that, you know, that's fine, and that's fine. It's only if you have a different feature, say X 3 that is between, that ranges from -100 to +100, then, this is a very different values than minus 1 and plus 1. So, this might be a less well-skilled feature and similarly, if your features take on a very, very small range of values so if X 4 takes on values between minus 0.0001 and positive 0.0001, then again this takes on a much smaller range of values than the minus one to plus one range. And again I would consider this feature poorly scaled.   So you want the range of values, you know, can be bigger than plus or smaller than plus one, but just not much bigger, like plus 100 here, or too much smaller like 0.0001 one over there. Different people have different rules of thumb. But the one that I use is that if a feature takes on the range of values from say minus three the plus 3 how you should think that should be just fine, but maybe it takes on much larger values than plus 3 or minus 3 unless not to worry and if it takes on values from say minus one-third to one-third. You know, I think that's fine too or 0 to one-third or minus one-third to 0. I guess that's typical range of value sector 0 okay. But it will take on a much tinier range of values like x4 here than gain on mine not to worry. 


   보통 피쳐 스케일링(feature scaling)은 모든 피쳐 값의 범위가 대략 '-1 <= xi <= 1'에 있는 것이 좋습니다. x0는 항상 1 이므로 이미 범위에 있습니다. 하지만 다른 피처들은 다른 수로 나누어서 이 범위로 만들 수 있습니다.  '-1 <= xi <= 1'라는 숫자가 중요한 것은 아닙니다. 만일 '0 <= x1 <= 3' 이면 문제없습니다. 만일 '-2 <= x2 <= 0.5'이면 충분히 -1과 1에 가깝습니다. 좋습니다. 만일 '-100 <= x3 <= 100' 이면 -1과 1과는 완전 다른 값의 범위입니다. 이것은 피처의 좋은 범위가 아닙니다. 만일 '-0.0001 <= x1 <= 0.0001' 이면 -1과 1에 비해 매우 작은 값의 범위입니다. 피처의 스케일링이 잘못된 것입니다. 그래서 값의 범위는 1보다 크거나 작을 수 있지만 100처럼 엄청 크거나 0.0001처럼 엄청 작으면 안 됩니다.  사람들마다 규칙이 다릅니다. 피처의 범위가 -3과 3 사이의 범위라면 괜찮습니다. 하지만, +3에서 -3의 범위보다 크다면 한 번 생각해 봐야 합니다. -1/3과 1/3 사이의 범위라면 괜찮습니다. 보통 0 근처의 범위면 좋습니다. 하지만, x4의 범위만큼 작다면 문제가 있습니다.



   So, the take-home message is don't worry if your features are not exactly on the same scale or exactly in the same range of values. But so long as they're all close enough to this gradient descent it should work okay. In addition to dividing by so that the maximum value when performing feature scaling sometimes, people will also do what's called mean normalization. And what I mean by that is that you want to take a feature Xi and replace it with Xi minus mu i to make your features have approximately 0 mean. And obviously we want to apply this to the future x zero, because the future x zero is always equal to one, so it cannot have an average value of zero. But it concretely for other features if the range of sizes of the house takes on values between 0 to 2000 and if you know, the average size of a house is equal to 1000 then you might use this formula. Size, set the feature x1 to the size minus the average value divided by 2000 and similarly, on average if your houses have one to five bedrooms and if on average a house has two bedrooms then you might use this formula to mean normalize your second feature x2.


    피처의 범위가 같은 크기나 정확히 똑같은 범위가 아니어도 상관없습니다. 경사 하강법이 잘 동작하는 것이 목적입니다. 피처 스케일(Feature Scaling)을 할 때 최대값으로 나누고 평균 정규화(mean normalization)를 합니다. 평균 정규화는 값들이 평균이 0이 되도록 스케일링하는 것입니다. 피처 스케일링의 정규화 다음과 같습니다. 



   xi는 피처의 값이고, μi는 피처 xi 값들의 평균입니다. x0는 항상 1 이므로 정규화를 할 필요가 없습니다. 


   다른 피처는 가능합니다. 주택 크기의 범위는 0 ~ 2,000 사이고 집의 크기의 평균이 1,000 이면, 이 공식을 적용할 수 있습니다. 주택 크기 피처 x1 = (Size -  μi) / 최대값 = (Size- 1000)/2000입니다. 집은 1개에 5개 사이의 침실이 있고, 평균은 2 개이면, 정규화를 위해 이 공식을 적용할 수 있습니다. 



   In both of these cases, you therefore wind up with features x1 and x2. They can take on values roughly between minus 5 and positive 5. Exactly not true - x2 can actually be slightly larger than 5 but, close enough. And the more general rule is that you might take a feature x1 and replace it with x1 minus mu1 over S1 where to define these terms mu1 is the average value of x1 in the training sets and S1 is the range of values of that feature and by range, I 

mean let's say the maximum value minus the minimum value or for those of you that understand the deviation of the variable is setting S1 to be the standard deviation of the variable would be fine, too. But taking, you know, this max minus min would be fine.


   두 가지 경우 모두 피처 x1과 x2가 대략 -0.5에서 +0.5 사이의 값의 범위에 있습니다. 엄밀하게 x2는 0.5보다 약간 크게 되지만 거의 근접합니다. 일반적인 공식은' x1 := (x1- μ1)/S1'입니다. μ1은 학습 데이터 셋의 피처 x1의 평균값이고, S1은 피처 값의 범위로 최대값에서 최소값을 뺀 값이 될 수도 있고, 표준 편차일 수도 있습니다. 최대값에서 최소값을 뺀 값도 괜찮습니다. 


   And similarly for the second feature, x2, you replace x2 with this sort of subtract the mean of the feature and divide it by the range of values meaning the max minus min. And this sort of formula will get your features, you know, maybe not exactly, but maybe roughly into these sorts of ranges, and by the way, for those of you that are being super careful technically if we're taking the range as max minus min this five here will actually become a four. So if max is 5 minus 1 then the range of their own values is actually equal to 4, but all of these are approximate and any value that gets the features into anything close to these sorts of ranges will do fine. And the feature scaling doesn't have to be too exact, in order to get gradient descent to run quite a lot faster. 


   비슷하게 두 번째 피처' x2 := (x2- μ2)/(최대값 - 최소값)' 공식으로 하면 대략 -0.5에서 +0.5 사이의 값의 범위가 나옵니다. 엄밀히 계산하면, 최대값에서 최소값을 빼면 4입니다. 5-1 = 4이지만, 여기서 대부분 근사값이고, 피처의 범위와 거의 차이가 없기 때문에 괜찮습니다. 경사 하강법이 더 빨리 실행될 수 있기 때문에 너무 정확하지 않아도 됩니다. 


   So, now you know about feature scaling and if you apply this simple trick, it and make gradient descent run much faster and converge in a lot fewer other iterations.  That was feature scaling. In the next video, I'll tell you about another trick to make gradient descent work well in practice.


   피처 스케일링 (feature scaling)은 경사 하강 알고리즘은 더 빨리 동작할 수 있게 도와줍니다. 즉, 더 적은 반복으로 최소값에 수렴할 것입니다. 여기까지가 feature scaling입니다. 다음 강의에서는 강사 하강 알고리즘을 효율적으로 다루는 다른 방법을 배울 것입니다.



정리하며

    피처 스케일링은 경사 하강 알고리즘이 더 적은 반복으로 전역 최소값에 도달하기 위해 피처 값의  범위를 조정하는 것입니다. 피처 스케일링한 값의 범위는 0을 기준으로 '-1 <= xi <= 1' 사이에 있는 것이 가장 좋습니다. 단순하게 각 피처의 최대값으로 나누는 것도 좋습니다. x0는 항상 1이기 때문에 정규화를 하지 않습니다.



문제 풀이


   다음의 문제를 풉니다. 도시의 집값을 예측하는 학습 알고리즘입니다. 피처 xi 중에 하나는 집의 나이입니다. 훈련용 데이터 셋에 집의 나이는 30에서 50년 사이이고 평균 나이는 38년입니다. 다음 중에 피쳐 스케일링과 정규화를 올바르게 사용한 식은 무엇인가요?


   정답은 네 번째입니다. 



매거진의 이전글 앤드류 응의 머신러닝 (4-2) : 다변수의 경사 하강
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari