반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Elements of AI - Regression

2018. 6. 22. 03:58 | Posted by 솔웅


반응형


Elements of AI




III.Regression




Our main learning objective in this section is another nice example of supervised learning methods, and almost as simple as the nearest neighbor classifier too: linear regression. We'll introduce its close cousin, logistic regression as well.

이 섹션의 주요 학습 목표는 supervised learning 방법의 또 다른 좋은 예이며 가장 가까운 neighbor classifier 기준 인 선형 회귀 (linear regression)와 거의 비슷합니다. 또한 가까운 사촌 인 로지스틱 회귀(logistic regression)도 소개하겠습니다.



Note

The difference between classification and regression


There is a small but important difference in the kind of predictions that we should produce in different scenarios. While for example the nearest neighbor classifier chooses a class label for any item out of a given set of alternatives (like spam/ham, or 0,1,2,...,9), linear regression produces a numerical prediction that is not constrained to be an integer (a whole number as opposed to something like 3.14). So linear regression is better suited in situations where the output variable can be any number like the price of a product, the distance to an obstacle, the box-office revenue of the next Star Wars movie, and so on.


우리가 다른 시나리오에서 만들어야하는 예측의 종류에는 작지만 중요한 차이가 있습니다. 예를 들어 가장 가까운 neighbor classifier 프로그램이 주어진 대안 세트 (예 : 스팸 / 햄 또는 0,1,2, ..., 9)에서 어느 하나의 클래스 라벨을 선택하고 선형 회귀(linear regression)는 숫자로 된 예측을 만들어 냅니다. 이 숫자로 된 예측은 정수 (3.14와 같은 정수가 아닌 정수)로 제한되지 않습니다. 따라서 선형 회귀(linear regression)는 출력 변수가 제품 가격, 장애물까지의 거리, 다음 스타 워즈 영화의 흥행 수입 등과 같이 임의의 수일 수있는 상황에 더 적합합니다.



The basic idea in linear regression is to add up the effects of each of the feature variables to produce the predicted value. The technical term for the adding up process is linear combination. The idea is very straightforward, and it can be illustrated by your shopping bill.



선형 회귀(linear regression)의 기본 개념은 예측 값을 생성하기 위해 각 기능 변수(feature variables)별로 그 효과를 더하는 겁니다. 그 더하는 과정을 전문 용어로 선형 조합 (linear combination) 이라고 합니다. 이 아이디어는 매우 간단하며 쇼핑 청구서(shopping bill)예로 그 상황을 설명 할 수 있습니다.



Note

Thinking of linear regression as a shopping bill

Suppose you go to the grocery store and buy 2.5kg potatoes, 1.0kg carrots, and two bottles of milk. If the price of potatoes is 2€ per kg, the price of carrots is 4€ per kg, and a bottle of milk costs 3€, then the bill, calculated by the cashier, totals 2.5 × 2€ + 1.0 × 4€ + 2 × 3€ = 15€. In linear regression, the amount of potatoes, carrots, and milk are the inputs in the data. The output is the cost of your shopping, which clearly depends on both the price and how much of each product you buy.


당신이 식료품 가게에 가서 2.5kg의 감자, 1.0kg의 당근, 그리고 2 병의 우유를 사 먹는다 고 가정하십시오. 감자 가격이 kg 당 2 유로이고 당근 가격이 kg 당 4 유로이고 우유 한 병이 3 유로 인 경우 계산원이 계산 한 계산서는 총 2.5x2 + 1.0x4 + 2 × 3 € = 15 € 입니다. 선형 회귀 분석에서 감자, 당근 및 우유의 양은 데이터의 입력 값입니다. 산출량은 쇼핑 비용으로, 가격과 구입하는 제품의 양에 따라 다릅니다.




The word linear means that the increase in the output when one input feature is increased by some fixed amount is always the same. In other words, whenever you add, say, two kilos of carrots into your shopping basket, the bill goes up 8€. When you add another two kilos, the bill goes up another 8€, and if you add half as much, 1kg, the bill goes up exactly half as much, 4€.



linear라는 단어는 하나의 입력 특징이 일정량만큼 증가 될 때 출력의 증가가 항상 동일 함을 의미합니다. 즉, 쇼핑 바구니에 2kg의 당근을 추가하면 bill이 8 유로 씩 올라갑니다. 또 다른 2kg을 더하면 청구서가 8 € 올라가고, 1kg을 즉 절반 더 추가하면 계산서가 정확히 절반 인 4 € 올라갑니다.




Key terminology

Coefficients or weights


In linear regression terminology, the prices of the different products would be called coefficients or weights. (This may appear confusing since we measured the amount of potatoes and carrots by weight, but not let yourself be tricked by this!) One of the main advantages of linear regression is its easy interpretability: the learned weights may in fact be more interesting than the predictions of the outputs.


선형 회귀 (linear regression)라는 용어에서는 여러 제품의 가격을 coefficients (계수) 또는 weights (가중치) 라고합니다. (감자와 당근의 양을 무게로 측정했기 때문에 혼란 스러울 지 모르지만, 일부러 헛갈리게 한 것은 아니예요!) 선형 회귀(linear regression)의 주요 장점 중 하나는 쉽게 해석 할 수 있다는 것입니다. learned weights는 outputs 예측보다 더 흥미로운 것이 사실입니다.

For example, when we use linear regression to predict the life expectancy, the weight of smoking (cigarettes per day) is about minus half a year, meaning that smoking one cigarette more per day takes you on the average half a year closer to termination. Likewise, the weight of vegetable consumption (handful of vegetables per day) has weight plus one year, so eating a handful of greens gives every day gives you on the average one more year.


예를 들어, 선형 회귀 (linear regression)을 사용하여 기대 수명을 예측할 때 이런식으로 계산할 수 있습니다. 예를 들어 흡연 (하루 한가치)은 약 반년을 마이너스 합니다.  즉 하루에 담배 하나 이상을 흡연하면 평균 반년 수명이 주는 겁니다. 마찬가지로, 야채 소비 (하루에 한웅큼의 야채)에는 가중치 1년을 더합니다. 즉 매일 야채를 한웅큼씩 먹으면 1년을 더 사는 것으로 계산하는 식입니다.




AWS DeepLens - Deep learning enabled video camera for developers





Exercise 16: Linear regression

Suppose that an extensive study is carried out, and it is found that in a particular country, the life expectancy (the average number of years that people live) among non-smoking women who don't eat any vegetables is 80 years. Suppose further that on the average, men live 5 years less. Also take the numbers mentioned above: every cigarette per day reduces the life expectancy by half a year, and a handful of veggies per day increases it by one year.



방대한 연구가 수행되어 특정 국가에서 야채를 먹지 않는 담배피는 여성들의 평균 기대 수명 이 80년이라고 가정합니다. 또한 남자는 평균적으로 여자보다 5년 적게 산다고 가정합시다. 그리고 위에서 언급했듯이 매일 한가치씩 흡연하면 기대 수명은 반년 줄어들고 매일 야채를 한웅큼 먹으면 수명이 1년 증가한다고 가정합니다. 



Calculate the life expectancies for the following example cases:


다음 예제의 기대 수명을 계산하세요



For example, the first case is a male (subtract 5 years), smokes 8 cigarettes per day (subtract 8 × 0.5 = 4 years), and eats two handfuls of veggies per day (add 2 × 1 = 2 years), so the predicted life expectancy is 73 years.



예를 들어, 첫 번째 경우는 남성 (5 년 감면), 하루 8 가치 담배를 피우고 (8 × 0.5 = 4 년 빼기) 하루에 2 웅큼의 채소를 먹습니다 (2 × 1 = 2 년 추가). 예상 수명은 73 세입니다.





Your task: Enter the correct value as an integer (whole number) for the missing sections A, B, and C above.






In the above exercise, the life expectancy of non-smoking, veggie-hating women, 80 years, was the starting point for the calculation. The technical term for the starting point is the intercept. We will return to this below when we discuss how to learn linear regression models from data.



위의 문제를 푸는 과저은 비 흡연자이고 채식을 하지 않는 여성들의 기대 수명은 80년이라는 기준에서 시작했습니다.  이것을 출발점이라고 할 때 이 출발점의 기술적 용어는 intercept입니다. 아래에서 데이터를 기반으로 선형 회귀 (linear regression) 모델을 어떻게 학습하는지에 대해 알아 보겠습니다.




Learning linear regression



Above, we discussed how predictions are obtained from linear regression when both the weights and the input features are known. So we are given the inputs and the weight, and we can produce the predicted output.



위에서 우리는 가중치(weights)와 입력 features가 모두 알려진 경우 예측이 선형 회귀(linear regression)로부터 어떻게 얻어지는 지에 대해 논의했습니다. 그렇게 함으로서 우리는 입력과 가중치가 주어지면 예측 된 결과를 산출 할 수 있습니다.



When we are given the inputs and the outputs for a number of items, we can find the weights such that the predicted output matches the actual output as well as possible. This is the task solved by machine learning.



많은 항목에 대한 입력과 출력이 주어지면 예상 출력이 가능한 실제 출력과 일치하도록 가중치를 찾을 수 있습니다. 이것은 기계 학습(machine learning)으로 해결되는 작업입니다.



Note

Example

Continuing the shopping analogy, suppose we were given the contents of a number of shopping baskets and the total bill for each of them, and we were asked to figure out the price of each of the products (potatoes, carrots, and so on). From one basket, say 1kg of sirloin steak, 2kg of carrots, and a bottle of Chianti, even if we knew that the total bill is 35€, we couldn't determine the prices because there are many sets of prices that will yield the same total bill. With many baskets, however, we will usually be able to solve the problem.


쇼핑 비유(hopping analogy)를 계속하면, 여러 쇼핑 바구니의 내용들과 각 쇼핑바구니에 대한 총 비용을 받았다고 가정합니다. 그리고 우리는 감자, 당근 등 각각의 품목들의 가격을 알아내야 합니다. 한 쇼핑 바구니에 등심 1키로, 당근 2키로, Chianti 1병이 있습니다. 이 바구니의 총 청구서는 35유로 입니다. 하지만 이것만 가지고는 각 품목들의 . 한 바구니에서, 등심 스테이크 1kg, 당근 2kg, Chianti 1 병이 담겼습니다, 그리고 총 청구액 35 유로입니다. 이 경우 총 청구액을 알았더라도 우리는 각 제품들의 가격을 산출 해 낼 수 없습니다. 왜냐하면 그 바구니 말고도 다른 많은 바구니가 있고 그 바구니들에 여러 품목들이 있을 테니까요. 이렇게 바구니가 많은 경우에 대한 문제 해결 방법도 있습니다. 




But the problem is made harder by the fact that in the real-world, the actual output isn’t always fully determined by the input, because of various factors that introduce uncertainty or “noise” into the process. You can think of shopping at a bazaar where the prices for any given product may vary from time to time, or a restaurant where the final damage includes a variable amount of tip. In such situations, we can estimate the prices but only with some limited accuracy.



그러나 현실 세계에서 실제 output은 프로세스에 불확실성 또는 "잡음 noise"을 초래하는 다양한 요소로 인해 입력에 의해 항상 완전히 결정되지는 않는다는 사실에 의해 문제가 더 커집니다. 어떤 제품에 대한 가격이 때때로 바뀔 수있는 바자회에서 쇼핑을 하거나, 여러 가변적인 팁이 포함 된 레스토랑의 식사 가격을 생각할 수 있습니다. 이러한 상황에서 우리는 가격을 예측할 수 있지만 제한된 정확도로 만 가능합니다.



Finding the weights that optimize the match between the predicted and the actual outputs in the training data is a classical statistical problem dating back to the 1800s, and it can be easily solved even for massive data sets.



training data에서 예측 된 결과와 실제 결과 간의 일치를 최적화하는 가중치를 찾는 것은 1800 년대로 거슬러 올라가는 고전적인 통계적 문제이며 이를 이용해 대용량 데이터 세트에서도 문제를 쉽게 해결할 수 있습니다.



We will not go into the details of the actual weight-finding algorithms, such as the classical least squares technique, simple as they are. However, you can get a feel of finding trends in data in the following exercises.



우리는 고전적인 최소 제곱 기법 (least squares technique)과 같은 실제 weight-finding algorithm의 세부 사항에 대해서는 자세히 설명하지 않겠습니다. 그러나 다음 연습문제를 통해서 데이터의 트렌드를 찾는 감을 잡을 수 있을 겁니다.



Visualising linear regression



A good way to get a feel for what linear regression can tell us is to draw a chart containing our data and our regression results. As a simple toy example our data set has one variable, the number of cups of coffee an employee drinks per day, and the number on lines of code written per day by that employee as the output. This is not a real data set as obviously there are other factors having an effect on the productivity of an employee other than coffee that interact in complex ways. The increase in productivity by increasing the amount of coffee will also hold only to a certain point after which the jitters distract too much.



선형 회귀 분석(linear regression)이 우리에게 무엇을 말할 수 있는가에 대한 감을 잡을 수 있는 좋은 방법은 데이터와 회귀결과 (regression results)를 가지고 있는 챠트를 그리는 겁니다.  간단한 장난감 예제를 들겠습니다. 우리의 데이터 세트는 한개의 변수를 가지고 있습니다. 한 직원이 하루에 마시는 커피의 컵 수 입니다. 그리고 그 직원이 하루에 작성한 코드 라인 수를 출력으로 받습니다. 이것은 실제 데이터 세트가 아닙니다. 분명히 커피 이외에 복잡한 상호 관계 속에서 직원의 생산성에 영향을 미치는 다른 요인들이 있을 겁니다. 커피의 양을 늘림으로써 생산성이 증가하는 것은 특정 시점까지만 유지 될 것입니다. 그 특정 시점 이후에는 불안하고 초조해 질 겁니다.





When we present our data in the chart above as points where one point represents one employee, we can see that there is obviously a trend that drinking more coffee results in more lines of code being written. (Recall that this is completely made-up data.) From this data set we can learn the coefficient, or the weight, related to coffee consumption, and by eye we can already say that it seems to be somewhere close to five, since for each cup of coffee consumed the number of lines programmed seems to go up rougly by five. For example, for employees who drink around two cups of coffee per day, they seem to produce around 15 lines of code per day, and similarly for four cups of coffee, the amount of lines produced is around 25.



위의 차트에있는 데이터를 보면 한 점이 한 직원을 나타냅니다.  더 많은 커피를 마시는 직원이 더 많은 코드 줄을 작성하는 경향이 있음을 알 수 있습니다. (이 데이터는 그냥 가상의 데이터 입니다.) 이 데이터 세트에서 우리는 커피 소비와 관련된 계수(coefficient) 또는 weight를 배울 수 있으며, 대충 눈 짐작으로 이 지점이 5 부근이라고 말할 수 있습니다. 커피 한잔 당 코드 라인 수는 약 5씩 증가 하는 것 같습니다. 예를 들어 어느 직원이 하루에 커피 두잔을 마신다면 이 직원은 대략 하루에 15줄의 코딩을 할 것입니다. 이런식으로 하면 4잔 마시는 직원은 대략 25줄의 코딩을 하겠죠. 



It can also be noted that employees who do not drink coffee at all also produce code, and is shown by the graph to be about ten lines. This number is the intercept term that we mentioned earlier. The intercept is another parameter in the model just like the weights are, that can be learned from the data. Just as in the life expectancy example it can be thought of as the starting point of our calculations before we have added in the effects of the input variable, or variables if we have more than one, be it coffee cups in this example, or cigarettes and vegetables in the previous one.



또한 커피를 전혀 마시지 않는 직원도 코드를 생성하며 그래프를 보면 대략 10 줄 정도 코딩하는 것 같습니다. 이 숫자는 앞서 언급 한 intercept 용어입니다. intercept는 이 모델에서 또다른 파라미터 입니다. weights 처럼요. 이는 데이터로부터 나옵니다.  기대 수명 예와 마찬가지로, 입력 변수의 효과를 추가하기 전이나 혹은 한개 이상의 변수가 있을 때 (이 예에서는 커피컵의 수가 되고 이전의 예에서는 담배나 야채 등이 되겠죠.) 를 계산의 출발점이라고 생각할 수 있습니다. 



The line in the chart represents our predicted outcome, where we have estimated the intercept and the coefficient by using an actual linear regression technique called least squares. This line can be used to predict the number of lines produced when the input is the number of cups of coffee. Note that we can obtain a prediction even if we allow only partial cups (like half, 1/4 cups, and so on).



차트의 선은 우리가 예측 한 outcome을 나타냅니다. 위에서 우리는 least squares 이라는 실제 linear regression technique을 사용하여 intercept과 coefficient를 추정했습니다. 이 선은 입력이 커피 잔 수일 때 생산되는 줄 수를 예측하는 데 사용할 수 있습니다.  반컵이나 1/4컵일 때도 예측할 수 있다는 부분을 기억해 두세요. 









Exercise 17: Life expectancy and education (part 1 of 2)

Let's study the link between the total number of years spent in school (including everything between preschool and university) and life expectancy. Here is data from three different countries displayed in a figure represented by dots:



학교에서 보낸 총 연수 (유치원과 대학 간의 모든 것을 포함)와 기대 수명 사이의 연관성을 연구합시다. 다음은 점으로 표시된 세개의 다른 나라에 대한 데이터가 있습니다. 





We have one country where the average number of years in school is 10 and life expectancy is 57 years, another country where the average number of years in school is 13 and life expectancy is 53 years, and a third country where the average number of years in school is 20 and life expectancy is 80 years.



학교에 다닌 평균 년 수가 10년이고 평균 수명이 57 세 인 다른 나라와 학교에 다닌 평균 연수가 13 년이고 평균 수명이 53 세인 국가와 학교에서 다닌 평균 기간이 20년이고 평균 수명은 80 세인 국가가 있습니다.



You can drag the end points of the solid line to position the line in such a way that it follows the trend of the data points. Note that you will not be able to get the line fit perfectly with the data points, and this is fine: some of the data points will lie above the line, and some below it. The most important part is that the line describes the overall trend. After you have positioned the line you can use it to predict the life expectancy.



실선의 끝점을 드래그하여 데이터 점의 추세를 따르는 방식으로 선의 위치를 지정할 수 있습니다. 데이터 요소에 맞게 선을 완벽하게 맞출 수는 없으므로 일부 데이터 요소는 선 위에 있고 일부는 아래에 위치합니다. 가장 중요한 부분은이 라인이 전반적인 경향을 설명한다는 것입니다. 선을 배치 한 후에는 이를 사용하여 평균 수명을 예측할 수 있습니다.



Given the data, what can you tell about the life expectancy of people who have 15 years of education?


데이터를 감안할 때, 15 년간 교육을받은 사람들의 평균 수명은 어떻다고 말할 수 있습니까?


보기


1. It is exactly 64 years

2. It is certainly between 60 and 70 years

3. It is certainly 70 years or less

4. It is probably less than 90





Exercise 18: Life expectancy and education (part 2 of 2)


In the previous exercise, we only had data from three countries. The full data set consists of data from 14 different countries, presented here in a graph:



이전 연습문제에서는 세 국가의 데이터 만 있었습니다. 아래 예제의 전체 데이터 세트는 14 개국의 데이터로 구성되어 있습니다.






Based on this data, would your prediction about the life expectancy of people with 15 years of education change? If so, why?

Which of the following options would best match your estimate of the life expectancy for people with 15 years of education?



이 데이터를 바탕으로, 15 년간 교육을받은 사람들의 기대 수명에 대한 귀하의 예측은 바뀌 었습니까? 그렇다면 왜 그렇습니까?


다음 중 15 년간 교육을받은 사람들의 평균 기대 수명과 가장 유사한 보기는 무엇입니까?


1. Between 45 and 50 years

2. Between 60 and 80 years

3. Between 69 and 71 years

4. Between 30 and 100 years



It should be pointed out that studies like those used in the above exercises cannot identify causal relationships. In other words, from this data alone, it is impossible to say whether studying actually increases life expectancy through better informed and healthier life-style or other mechanisms, or whether the apparent association between life expectancy and education is due to underlying factors that affects both. It is likely that, for example, in countries where people tend to be highly educated, nutrition, healtcare, and safety are also better, which increases life expectancy. With this kind of simple analysis, we can only identify associations, which can nevertheless be useful for prediction.



위의 연습문제에서 사용한 것과 같은 studies는 인과관계(causal relationships)를 식별 할 수 없다는 점을 밝혀두어야 겠습니다. 즉,이 데이터만으로는 공부가 더 나은 정보를 제공하고 건강한 생활습관을 갖게 하는 등의 역할을 해서 기대 수명을 증가시킨다라고 말 할 수 없다는 겁니다. 더 나은 정보와 건강 스타일 또는 기타 메커니즘을 통해 실제로 공부하는 것이 기대 수명을 증가시키는 지 여부 또는 평균 수명과 교육 간의 명백한 연관성이 둘 다 영향을 미치는 근본적인 요인에 의한 것인지 여부를 말할 수 없습니다 . 예를 들어, 사람들이 고학력 인 경향이있는 국가에서 영양, 건강 관리, 안전이 더 좋으며 이로 인해 기대 수명이 늘어날 가능성이 있습니다. 이러한 종류의 간단한 분석을 통해 연관성을 식별 할 수는 있지만 그럼에도 불구하고 예측에 유용 할 수 있습니다.




Machine learning applications of linear regression



Linear regression is truly the workhorse of many AI and data science applications. It has its limits but they are often compensated by its simplicity, interpretability and efficiency. Linear regression has been successfully used in the following problems to give a few examples:



선형 회귀(Linear regression)는 정말 많은 AI 및 데이터 과학 응용 프로그램의 핵심 요소입니다. 한계가 있지만 단순함, 해석 가능성 및 효율성으로 인해 종종 그 보상을 받습니다. 선형 회귀(Linear regression) 는 다음과 같은 문제에서 성공적으로 사용된 예들이 있습니다.



  • prediction of click rates in online advertising
  • prediction of retail demand for products
  • prediction of box-office revenue of Hollywood movies
  • prediction of software cost
  • prediction of insurance cost
  • prediction of crime rates
  • prediction of real estate prices



Could we use regression to predict labels?



As we discussed above, linear regression and the nearest neighbor method produce different kinds of predictions. Linear regression outputs numerical outputs while the nearest neighbor method produces labels from a fixed set of alternatives (“classes”).



위에서 설명한 것처럼 선형 회귀(linear regression)와 nearest neighbor method은 다른 종류의 예측을 생성합니다. 선형 회귀 분석은 수치를 출력하지만 nearest neighbor method은 고정 된 대체 세트 ( "classes")에서 라벨을 생성합니다.




Where linear regression excels compared to nearest neighbors, is interpretability. What do we mean by this? You could say that in a way, the nearest neighbor method and any single prediction that it produces are easy to interpret: it’s just the nearest training data element! This is true, but when it comes to the interpretability of the learned model, there is a clear difference. Interpreting the trained model in nearest neighbors in a similar fashion as the weights in linear regression is impossible: the learned model is basically the whole data, and it is usually way too big and complex to provide us with much insight. So what if we’d like to have a method that produces the same kind of outputs as the nearest neighbor, labels, but is interpretable like linear regression?



linear regression가 nearest neighbors에 비해 우수하다고 해석이 가능합니다. 이게 무슨 소리냐 하면? nearest neighbors 방법과 그것이 생성하는 어떤 단일 예측은 쉽게 해석 할 수 있습니다. nearest training data element 일뿐입니다! 이것은 사실이지만, 학습 된 모델의 해석 가능성과 관련해서는 그 두가지 방법이 뚜렷한 차이가 있습니다. linear regression 분석에서의 가중치와 유사한 방식으로 nearest neighbors에 trained model을 해석하는 것은 불가능합니다. trained model은 기본적으로 전체 데이터이며, 우리가 분석하기에는 대개 너무 크고 복잡합니다. 그렇다면 nearest neighbor, 레이블과 같은 종류의 산출물을 생산하는 방법을 원한다면linear regression 처럼 해석 하는 것이 가능할까요?




Logistic regression to the rescue


Well there are good news for you: we can turn the linear regression method’s outputs into predictions about labels. The technique for doing this is called logistic regression. We will not go into the technicalities, suffice to say that in the simplest case, we take the output from linear regression, which is a number, and predict one label A if the label is more than zero, and another label B if the label is less than or equal to zero. Actually, instead of just predicting one class or another, logistic regression can also give us a measure of uncertainty of the prediction. So if we are predicting whether a customer will buy a new smartphone this year, we can get a prediction that customer A will buy a phone with probability 90%, but for another, less predictable customer, we can get a prediction that they will not buy a phone with 55% probability (or in other words, that they will buy one with 45% probability).



좋은 소식이 하나 있습니다. linear regression 방법의 결과를 라벨에 대한 예측으로 바꿀 수 있습니다. 이를 수행하는 기술을 로지스틱 회귀 (logistic regression)라고합니다. 우리는 이에대한 기술적인 부분을 다루지는 않겠지만, 


가장 간단한 경우에는 선형 회귀 (linear regression)의 결과를 숫자로 취하고 레이블이 0보다 크면 하나의 레이블 A를 예측하고 레이블이 0보다 작거나 같으면 레이블 A를 취합니다. 실제로, 한 클래스 또는 다른 클래스를 예측하는 대신, 로지스틱 회귀는 예측의 불확실성을 측정 할 수 있습니다. 따라서 고객이 올해 새로운 스마트 폰을 구입할 것인지 예측할 경우 고객 A가 구매할 확률이 90 % 이고 예측이 어려운 다른 고객의 전화 구매하지 않을 확률은 55%라는 식으로 예측할 수 있습니다. (즉, 구매할 확률은 45 % 가 되는 것이죠.)



It is also possible to use the same trick to obtain predictions over more than two possible labels, so instead of always predicting either yes or no (buy a new phone or not, fake news or real news, and so forth), we can use logistic regression to identify, for example, handwritten digits, in which case there are ten possible labels.



동일한 트릭을 사용하여 두개 이상의 가능한 레이블에 대해 예측을 얻을 수도 있으므로 예 또는 아니요 (새 전화를 사지 않겠습니까, 가짜 뉴스 또는 실제 뉴스를 사는지 등)를 예측하는 대신 로지스틱 회귀 (logistic regression)를 사용할 수 있습니다. 예를 들어 손으로 쓴 글자 같은 경우 10개의 가능한 레이블이 있는 겁니다. 



An example of logistic regression



Let’s suppose that we collect data of students taking an introductory course in cookery. In addition to the basic information such as the student id, name, and so on, we also ask the students to report how many hours they studied for the exam (however you study for a cookery exam, probably cooking?) - and hope that they are more or less honest in their reports. After the exam, we will know whether each student passed the course or not. Some data points are presented below:



조리 과정에 입문 과정을 수강하는 학생들의 데이터를 수집한다고 가정 해 봅시다. 학생 ID, 이름 등과 같은 기본 정보 외에도 학생들은 시험을 위해 몇 시간 공부했는지 알려달라고 요청합니다 (그러나 요리를 배우기는하지만 아마도 요리를 배우려고합니다). 그들은 그들의 보고서에서 다소 정직합니다. 시험이 끝나면 각 학생이 과목을 통과했는지 여부를 알 수 있습니다. 일부 데이터 포인트는 다음과 같습니다.





Based on the table, what kind of conclusion could you draw between the hours studied and passing the exam? We could think that if we have data from hundreds of students, maybe we could see the amount needed to study in order to pass the course. We can present this data in a chart as you can see below.



이 표를 기초로, 공부 한 시간과 시험을 통과하는 사이에 어떤 결론을 이끌어 낼 수 있습니까? 수백 명의 학생들로부터 얻은 데이터가 있다면 과정을 통과하기 위해 공부하는데 필요한 시간을 생각할 수 있겠죠. 아래에서 볼 수 있듯이이 데이터를 차트로 표시 할 수 있습니다.






Exercise 19: Logistic regression



Each dot on the figure corresponds to one student. On the bottom of the figure we have the scale for how many hours the student studied for the exam, and the students who passed the exam are shown as dots at the top of the chart, and the ones who failed are shown at the bottom. We'll use the scale on the left to indicate the predicted probability of passing, which we'll get from the logistic regression model as we explain just below. Based on this figure, you can see roughly that students who spent longer studying had better chances of passing the course. Especially the extreme cases are intuitive: with less than an hour’s work, it is very hard to pass the course, but with a lot of work, most will be successful. But what about those that spend time studying somewhere inbetween the extremes? If you study for 6 hours, what are your chances of passing?



그림의 각 점은 한 학생을 의미합니다. 그림의 맨 아래에는 학생이 시험을 위해 몇 시간 동안 공부했는지에 대한 척도가 있고 시험에 합격 한 학생은 차트 상단에 점으로 표시되고 실패한 학생은 아래쪽에 표시됩니다. 예상되는 확률을 나타 내기 위해 왼쪽의 눈금을 사용합니다. 아래에서 설명하는대로 logistic regression model을 사용해서 이를 얻어낼 수 있습니다. 이 수치를 토대로, 당신은 대략 오래 공부하는 학생들이 코스를 통과 할 가능성이 더 높다는 것을 알 수 있습니다. Especially the extreme cases are intuitive. 1 시간 미만의 공부로 코스를 통과하는 것은 매우 어렵습니다, 그리고 많은 노력을 기울이면 대부분 합격할 것입니다. 그러나 extremes 사이에서 공부하면서 시간을 보내는 사람들은 어떨까요? 6 시간 동안 공부하면 통과 할 확률은 얼마입니까?




We can quantify the probability of passing using logistic regression. The curve in the figure can be interpreted as the probability of passing: for example, after studying for five hours, the probability of passing is a little over 20%. We will not go into the details on how to obtain the curve, but it will be similar to how we learn the weights in linear regression.



우리는 logistic regression를 사용하여 통과 할 확률을 정량화 할 수 있습니다. 그림의 곡선은 합격할 확률로 해석 할 수 있습니다. 예를 들어 5 시간 동안 공부 한 후 합격할 확률은 20 %를 약간 넘습니다. 곡선을 얻는 방법에 대해서는 자세히 설명하지 않겠지 만 linear regression에서 가중치(weights)를 배우는 것과 비슷합니다.



If you wanted to have an 80% chance of passing a university exam, based on the above figure, how many hours should you approximately study for?



위의 그림을 토대로 대학교 시험에 합격 할 확률이 80 %가 되려면 대략 몇 시간 동안 공부해야합니까?



1. 6-7 hours

2. 7-8 hours

3. 8-9 hours

4. 10-11 hours



Logistic regression is also used in a great variety of real-world AI applications such predicting financial risks, medical studies, and so on. However, like linear regression, it is also constrained by the linearity property and we need many other methods in our toolbox. We will return to the linearity issue later when we discuss neural networks.



Logistic regression는 financial risks, 의학 연구 등을 예측하는 등 실제 AI 응용 프로그램의 다양한 분야에서 사용됩니다. 그러나 linear regression와 마찬가지로 linearity property에 의해 제약을 받기 때문에 우리 주머니 안에는 다른 방법론들도 준비해 두어야 할 겁니다. 나중에 neural networks에 대해 논의 할 때 linearity 문제를 다룰 겁니다



The limits of machine learning


To summarize, machine learning is a very powerful tool for building AI applications. In addition to the nearest neighbor method, linear regression, and logistic regression, there are literally hundreds, if not thousands, different machine learning techniques, but they all boil down to the same thing: trying to extract patterns and dependencies from data and using them either to gain understanding of a phenomenon or to predict future outcomes.



요약하면, machine learning은 AI 애플리케이션을 구축하기 위한 매우 강력한 도구입니다. nearest neighbor method, linear regression 및 logistic regression 이외에도 수 백 가지의 기계 학습 기술이 있지만 모두 똑같은 것으로 요약됩니다. 데이터에서 패턴과 dependencies을 추출하고 그것을 이용해 어떤 현상을 이해하거나 미래의 결과를 예측하는 겁니다.



Machine learning can be a very hard problem and we can’t usually achieve a perfect method that would always produce the correct label. However, in most cases, a good but not perfect prediction is still better than none. Sometimes we may be able to produce better predictions by ourselves but we may still prefer to use machine learning because the machine will make its predictions faster and it will also keep churning out predictions without getting tired. Good examples are recommendation systems that need to predict what music, what videos, or what ads are more likely to be of interest to you.



Machine learning은 매우 어려운 문제 일 수 있으며 항상 정확한 label을 생성 할 수있는 완벽한 방법을 얻을 수는 없습니다. 그러나 대부분의 경우, 좋지만 완벽하지는 않은 예측은 아무런 예측도 할 수 없는 것 보다는 낫습니다. 때로는 우리 인간이 더 나은 예측을 내는 경우도 있을 겁니다. 하지만 우리는 machine learning 사용하는 것을 더 선호합니다. 왜냐하면 기계는 그 예측을 훨씬 더 빠르게 할 수 있고 지치지 않고 그 예측을 대량으로 진행시킬 수 있기 때문이죠. 그 좋은 예로는 어떤 음악, 어떤 동영상 또는 어떤 광고가 관심을 가질지를 예측해야하는 추천 시스템을 들 수 있습니다.



The factors that affect how good a result we can achieve include:

  • The hardness of the task: in handwritten digit recognition, if the digits are written very sloppily, even a human can’t always guess correctly what the writer intended
  • The machine learning method: some methods are far better for a particular task than others
  • The amount of training data: from only a few examples, it is impossible to obtain a good classifier
  • The quality of the data



우리가 달성 할 수있는 결과에 영향을 미치는 요인은 다음과 같습니다.


- 작업의 경도 (어려움의 정도) : 손으로 작성한 숫자를 인식하는 것에서 숫자가 매우 불투명하게 작성된 경우에는 사람이라도 항상 작가의 의도를 정확하게 추측 할 수 있는 것은 아닙니다.

- 기계 학습 방법 : 일부 방법은 특정 작업에 대해 다른 것보다 훨씬 낫습니다.

- training data의 양 : 단지 몇 가지의 예를 통해 좋은 classifier를 얻는 것은 불가능합니다.

- 데이터의 품질




Note

Data quality matters

In the beginning of this Chapter, we emphasized the importance of having enough data and the risks of overfitting. Another equally important factor is the quality of the data. In order to build a model that generalises well to data outside of the training data, the training data needs to contain enough information that is relevant to the problem at hand. For example, if you create an image classifier that tells you what the image given to the algorithm is about, and you have trained it only on pictures of dogs and cats, it will assign everything it sees as either a dog or a cat. This would make sense if the algorithm is used in an environment where it will only see cats and dogs, but not if it is expected to see boats, cars, and flowers as well.

We'll return to potential problems caused by ”biased” data.


이 장의 시작 부분에서 우리는 충분한 데이터를 갖는 것의 중요성과 overfitting의 위험성을 강조했다. 이외에 또다른 중요한 요소는 데이터의 품질입니다. training data 외부의 (이외의) 데이터에 잘 적용되는 모델을 구축하려면 training data는 당면한 문제와 연관되어 있는 충분한 정보를 가지고 있어야 합니다. 예를 들어, 개와 고양이의 그림에만 훈련시킨 이미지 분류기를 만들면 개 또는 고양이로 보이는 모든 것을 판단합니다. 이것은 알고리즘이 고양이와 개만 볼 수있는 환경에서 사용될 수는 있겠지만 보트, 자동차 및 꽃을 볼 것으로 예상되는 경우에는 사용하지 않는 것이 좋습니다.


이제 "편향된 biased"데이터로 인한 잠재적 문제로 되돌아갑니다.




It is also important to emphasize that different machine learning methods are suitable for different tasks. Thus, there is no single best method for all problems (“one algorithm to rule them all...”). Fortunately, one can try out a large number of different methods and see which one of them works best in the problem at hand.



각기 다른 machine learning 방법들은 각기 다른 업무에 적합하다는 점을 강조하는 것도 중요합니다. 따라서 모든 문제에 대해 유일한 최선의 방법은 없습니다 ( "하나의 알고리즘으로 모든 문제를 해결할 수 있는 방법은 없습니다."). 다행스럽게도 많은 수의 다양한 방법을 시도해 볼 수 있으며 그 중 어느 것이 해당 문제에 가장 좋은 방법인지 파악할 수 있습니다.



This leads us to a point that is very important but often overlooked in practice: what it means to work better. In the digit recognition task, a good method would of course produce the correct label most of the time. We can measure this by the classification error: the fraction of cases where our classifier outputs the wrong class. In predicting apartment prices, the quality measure is typically something like the difference between the predicted price and the final price for which the apartment is sold. In many real-life applications, it is also worse to err in one direction than in another: setting the price too high may delay the process by months, but setting the price too low will mean less money for the seller. And to take yet another example, failing to detect a pedestrian in front of a car is a far worse error than falsely detecting one when there is none.



이는 우리를 매우 중요하지만 실제로 종종 간과되는 지점으로 이끕니다. 숫자 인식 작업에서 좋은 방법은 물론 대부분의 시도에서 맞는 레이블을 생성하는 겁니다. 우리는 classification error로 이것을 측정 할 수 있습니다. 분류기 classifier가 잘못된 클래스를 출력하는 경우의 비율입니다. 아파트 가격을 예측할 때, 품질 측정은 전형적으로 아파트가 판매되는 예상 가격과 최종 가격의 차이를 가지고 할 수 있겠죠. 많은 실제 생활에서 사용되는 애플리케이션에서 어떤 한 방향으로  잘못 해석하는 것이 다른 방향으로 잘 못 해석하는 것 보다 더 나쁠 수가 있습니다. 가격을 너무 높게 설정하면 프로세스를 몇 개월 지연 시키는데 그치지만 가격을 너무 낮게 설정하면 판매자에게는 더 적은 돈을 손에 쥐게 만듭니다. 그리고 또 다른 예를 들자면, 자동차 앞에서 보행자가 있는데 감지 못하는 것은 보행자가 없는데 감지하는 오류보다 훨씬 더 나쁜 오류입니다.



As mentioned above, we can’t usually achieve zero error, but perhaps we will be happy with error less than 1 in 100 (or 1%). This too depends on the application: you wouldn’t be happy to have only 99% safe cars on the streets, but being able to predict whether you’ll like a new song with that accuracy may be more than enough for a pleasant listening experience. Keeping the actual goal in mind at all times helps us make sure that we create actual added value.



위에서 언급했듯이 일반적으로 오류를 0으로 만들 수는 없지만 100%에서 1% 모자란 오류 정도에는 만족할 것입니다. 이것 역시 application에 달려 있습니다. 도로에서 99 %의 안전만 보장하는 차량이 있으면 행복하지 않을 것입니다. 하지만 그 정도의 정확도로 새 노래를 좋아할지를 예측할 수 있다면 쾌적한 청취 경험을 위해서는 충분할 것입니다. 실제 목표를 항상 염두에두면 실제 부가가치를 창출 할 수 있습니다.



After completing Chapter 4 you should be able to:

  • Explain why machine learning techniques are used
  • Distinguish between unsupervised and supervised machine learning scenarios
  • Explain the principles of three supervised classification methods: the nearest neighbor method, linear regression, and logistic regression



- machine learning 기술이 사용되는 이유를 설명하는 것.

- unsupervised 와  supervised machine learning 시나리오를 구분하는 것

- 3 가지 supervised classification 방법의 원리를 설명하는 것 : the nearest neighbor method, linear regression, and logistic regression





반응형