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

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

'2018/06/13'에 해당되는 글 1

  1. 2018.06.13 Elements of AI - Naive Bayes classification

Elements of AI - Naive Bayes classification

2018. 6. 13. 03:59 | Posted by 솔웅


반응형

Elements of AI



III.Naive Bayes classification




One of the most useful applications of the Bayes rule is the so-called naive Bayes classifier.

Bayes rule의 가장 유용한 어플리케이션 중 하나는 소위 순진한 Bayes classifier입니다.



The Bayes classifier is a machine learning technique that can be used to classify objects such as text documents into two or more classes. The classifier is trained by analysing a set of training data, for which the correct classes are given.




Bayes classifier는 텍스트 문서와 같은 객체를 두 개 이상의 클래스로 분류하는 데 사용할 수있는 machine learning 기술입니다. 분류자 (classifier)는 올바른 클래스들에 대한 일련의 training 데이터를 분석함으로써 훈련됩니다.




The naive Bayes classifier can be used to determine the probabilities of the classes given a number of different observations. The assumption in the model is that the feature variables are conditionally independent given the class. (We will not discuss the meaning of conditional independence in this course. For our purposes, it is enough to be able to exploit conditional independence in building the classifier.)



naive Bayes classifier는 여러 가지 관찰 결과에 따라 클래스의 확률을 결정하는 데 사용할 수 있습니다. 이 모델의 가정은 feature variables 특성 (기능) 변수들은 주어진 클래스에 조건부로 독립적이라는 것입니다. (우리는 이 과정에서 조건부 독립의 의미에 대해 논의하지 않을 것입니다. 우리의 목적을 이루기 위해서는, classifier를 만드는데에 대한 조건부 독립성을 활용할 수 있는 것만으로도 충분합니다.)







Real world application: spam filters



We will use a spam email filter as a running example for illustrating the idea of the naive Bayes classifier. Thus, the class variable indicates whether a message is spam (or “junk email”) or whether it is a legitimate message (also called “ham”). The words in the message correspond to the feature variables, so that the number of feature variables in the model is determined by the length of the message.



naive Bayes classifier의 개념을 설명하기 위해 스팸 메일 필터를 실행 예제로 사용하겠습니다. 따라서 클래스 변수는 메시지가 스팸 (또는 "junk email")인지 또는 정상적인 메시지인지 ( "햄"이라고도 함) 여부를 나타냅니다. 메시지의 단어는 feature variables 특성 (기능) 변수에 해당하므로 모델의 feature variables 특성 변수의 수는 메시지의 길이에 따라 결정됩니다.



Note

Why we call it “naive”


Using spam filters as an example, the idea is to think of the words as being produced by choosing one word after the other so that the choice of the word depends only on whether the message is spam or ham. This is a crude simplification of the process because it means that there is no dependency between adjacent words, and the order of the words has no significance. This is in fact why the method is called naive.


스팸 필터를 예제로 이용한다는 것은 다른 단어 다음에 오는 단어를 선택함으로서 생성되어지는 단어들에 대해 생각한다는 겁니다. 그렇게 해서 해당 단어에 대한 선택이 오직 그 메세지가 스팸인지 혹은 햄인지 에 대해 의존한다는 것입니다.

 이것은 인접한 단어 사이에 의존성이 없으며 단어 순서에 아무런 의미가 없다는 것을 의미하기 때문에 이 과정을 매우 단순하게 처리합니다. 이것은 사실상 그 방법이 순진 (naive)이라고 불리는 이유입니다.

 

 - 요약 : 이 방법은 단순히 단어와 이어진 단어의 관계가 별 관련이 없거나 의미가 없을 경우 스팸으로 처리하는 방법입니다. 아주 단순하게 작동되기 때문에 이 방법론 이름에 naive (순진) 라는 단어가 사용되었습니다. - 




The above idea is usually depicted using the following illustration where the class of the message (spam or ham) is the only factor that has an effect on the words.



위의 아이디어는 일반적으로 메시지 클래스 (스팸 또는 햄)가 단어에 영향을 미치는 유일한 요소인 다음 그림을 사용하여 설명될 수 있습니다.








Despite it’s naivete, the naive Bayes method tends to work very well in practice. This is a good example of what the common saying in statistics, “all models are wrong, but some are useful” means. (The aphorism is generally attributed to statistician George E.P. Box.)



그것이 순진함에도 불구하고 naive Bayes method는 실제로 꽤 잘 작동합니다. 이것은 통계에서 흔히 말하는 "모든 모델은 틀렸지만 어떤 것들은 유용하다"라는 것을 보여주는 좋은 예입니다. (격언은 일반적으로 통계 학자 George E.P. Box가 말했다고 알려져 있습니다.)





Estimating parameters


To get started, we need to specify the prior odds for spam (against ham). For simplicity assume this to be 1:1 which means that on the average half of the incoming messages are spam. (In reality, the amount of spam is probably much higher.)



시작하려면 스팸 (햄에 대한)에 대한 prior odds을 지정해야합니다. 간단히  1 : 1이라고 가정합시다. 이는 수신 메시지의 평균 절반이 스팸임을 의미합니다. 실제로 스팸의 양은 훨씬 더 많습니다.



To get our likelihood ratios, we need two different probabilities for any word occurring: one in spam messages and another one in ham messages.



likelihood ratios 를 얻으려면 단어들에 대한 두가지 다른 probabilities가 필요합니다. 하나는 스팸 메세지이고 다른 하나는 햄 메세지 입니다.



The word distributions for the two classes are best estimated from actual training data that contains some spam messages as well as legitimate messages. The simplest way is to count how many times each word, abacus, acacia, ..., zurg, appears in the data and divide the number by the total word count.



두 클래스의 단어 분포는 약간의 스팸 메시지와 정상적인 메시지가 포함 된 실제 training 데이터에서 가장 잘 예측할 수 있습니다. 가장 간단한 방법은 데이터에 얼마나 많은 abacus, acacia, ..., zurg, 단어들이 나타났느냐와 그 숫자를 총 단어 숫자로 나누는 겁니다. 



To illustrate the idea, let’s assume that we have at our disposal some spam and some ham. You can easily obtain such data by saving a batch of your emails in two files.



아이디어를 설명하기 위해 disposal에 약간의 스팸과 약간의 햄이 있다고 가정해 봅시다. 두개의 파일을 여러분의 이메일들의 batch를 저장함으로서 그러한 데이터를 쉽게 얻을 수 있습니다. 



Assume that we have calculated the number of occurrences of the following words (along with all other words) in the two classes of messages:



두 가지 메시지 클래스에서 다음 단어 (다른 단어와 함께)의 발생 횟수를 계산했다고 가정 해 보겠습니다.




We can now estimate that the probability that a word in a spam message is million, for example, is about 156 out of 95791, which is roughly the same as 1 in 614. Likewise, we get the estimate that 98 out of 306438 words, which is about the same as 1 in 3127, in a ham message are million. Both of these probability estimates are small, less than 1 in 500, but more importantly, the former is higher than the latter: 1 in 614 is higher than 1 in 3127. This means that the likelihood ratio, which is the first ratio divided by the second ratio, is more than one. To be more precise, the ratio is (1/614) / (1/3127) = 3127/614 = 5.1 (rounded to one decimal digit).



이제 우리는 스팸 메세지에 있는 단어가 million인 경우의 probability를 알아 낼 수 있습니다. 예를 들어 95791 개중 156개 즉 대략 614개 중 1개 라는 식으로 말이죠. 그리고 306438 단어 중 98개의 단어도 계산해 날 수 있습니다. 대략 3127 개중 1개 꼴입니다. 이 두개의 확률 계산은 500개중 1개 보다 작은 겁니다. 그리고 더 중요한 것은 첫번 째 것이 두번 째 것보다 높다는 겁니다. (614개 중 1개가 3127개중 1개 보다 더 높죠). 이 의미는 첫번 째 ratio 나누기 두번 째 ratio 인 likelihood ratio가 1보다 크다는 겁니다. 좀 더 자세히 살펴 보면 그 (1/614) / (1/3127) = 3127/614 = 5.1 (rounded to one decimal digit) 입니다.



Recall that if you have any trouble at all with following the math in this section, you should refresh the arithmetics with fractions using the pointers we gave earlier (see the part about Odds in section Odds and Probability).



이 단원의 수학 문제를 푸는데 어려움이 있다면 이전에 알려드렸던 것들을 사용해서 포인터를 사용하여 arithmetics with fractions를 refresh 해야 합니다. (see the part about Odds in section Odds and Probability).





Note

Zero means trouble


One problem with estimating the probabilities directly from the counts is that the zero counts lead to zero estimates. This can be quite harmful for the performance of the classifier - it easily leads to situations where the posterior odds is 0/0, which is nonsense. The simplest solution is to use a small lower bound for all probability estimates. The value 1/100000, for instance, does the job.


카운트에서 직접 확률을 추정 할 때의 한 가지 문제점은 제로 카운트가 0으로 계산된다는 것입니다. 이것은 classifier의 performance에 부정적인 영향을 미칠 수 있습니다. - 그것은 posterior odds이 0/0 인 상황으로 쉽게 이어집니다. 이것은 말도 안되는 상황이죠. 가장 간단한 해결책은 모든 probability 추정치에 대해 작은 하한을 사용하는 것입니다. 예를 들어 값 1/100000으로 작업을 수행하는 것이죠.



Using the above logic, we can determine the likelihood ratio for all possible words without having to use zero, giving us the following likelihood ratios:



위의 논리를 사용하여 0을 사용하지 않고 모든 가능한 단어에 대한 likelihood ratio 우도 비율을 결정할 수 있으며 다음 likelihood ratio 우도 비율을 얻을 수 있습니다.





We are now ready to apply the method to classify new messages.


이제 새 메시지를 분류하는 방법을 적용 할 준비가되었습니다.



Example: is it spam or ham?


Once we have the prior odds and the likelihood ratios calculated, we are ready to apply the Bayes rule, which we already practiced in the medical diagnosis case as our example. The reasoning goes just like it did before: we update the odds of spam by multiplying it by the likelihood ratio. To remind ourselves of the procedure, let's try a message with a single message to begin with. For the prior odds, as agreed above, you should use odds 1:1.



우리가 prior odds과 likelihood ratios 우도 비율을 계산하고 나면 이제 Bayes rule을 적용할 준비가 된 것입니다. medical diagnosis 예제에서 한번 다뤘었죠. reasoning은 이전에 했던 것과 같습니다. likelihood ratio에 스팸의 odds를 곱함으로서 odds를 업데이트 합니다. 다시 한번 그 과정을 상기해 보죠. 하나의 메세지로 시작하는 메세지를 예로 들어 보겠습니다. prior odds는 위에서 얘기한 대로 odds 1:1을 사용하시면 됩니다.






Exercise 12: One word spam filter

Let's start with a message that only has one word in it: “million”.


Your task: Calculate the posterior odds for spam given this word using the table above. Keep in mind that the odds is not the same as the probability, which we would usually express as a percentage.


Give your answer in the form of a single decimal number x.x using the dot '.' as the decimal separator.




한 단어 만 들어있는 메시지, “million”부터 시작해 보겠습니다.


과제 : 위의 표를 사용하여 이 단어가 주어진 스팸에 대한 posterior odds을 계산하십시오. odds는 우리가 일반적으로 백분율로 표현하는 probability과 같지 않습니다.


소수점 구분 기호로 점 '.'을 사용하여 x.x 형식으로 소수점 한자리로 답을 제공하세요. 



To handle the rest of the words in a message, we can use exactly the same procedure. The posterior odds after one word, which you calculated in the previous exercise, will become the prior odds for the next word, and so on.



메시지의 나머지 단어를 처리하기 위해 똑같은 절차를 사용할 수 있습니다. 이전 실습에서 계산 한 한 단어 뒤의 posterior odds은 다음 단어에 대한 prior odds이됩니다.




Exercise 13: Full spam filter


Now use the naive Bayes method to calculate the posterior odds for spam given the message “million dollars adclick conferences”.


You should again start with the prior odds 1:1, and then multiply the odds repeatedly by the likelihood ratios for each of the four words. Notice that the likelihood ratios are tabulated above for your reference (these are the numbers 5.1, 0.8, and so on).


Your task: Express the result as posterior odds without any rounding of the result. You may take a look at the solution of the previous exercise for help.



이제 naive Bayes 방법을 사용하여 “million dollars adclick conferences”라는 메시지가 주어졌을 때의 스팸에 대한 posterior odds을 계산하세요.


이전 확률 1 : 1로 다시 시작한 다음 네 개의 단어 각각에 대한 likelihood ratios 우도 비율로 반복하여 odds을 곱하십시오. likelihood ratios 우도 비율은 참조 용으로 위에 요약되어 있습니다 (숫자 5.1, 0.8 등).


과제 : 결과를 반올림하지 않고 posterior odds로 결과를 표현하십시오. 이전 연습 문제의 해결 방법을 살펴보면 도움이 될 겁니다.




Hooray! You have now mastered a powerful technique used every day in a wide range of real-world AI applications, the naive Bayes classifier. Even if you had to skip some of the technicalities, you should try to make sure you understood the basic principles of applying probabilities to update beliefs. As we discussed in the beginning of this Chapter, the main advantage of probabilistic reasoning is the ability to handle uncertain and conflicting evidence. Using examples in medical diagnosis and spam filtering, we demonstrated how this work is practice.



야호~~~! 이제 실제 AI 어플리케이션, 즉 naive Bayes classifier에서 항상 사용되는 강력한 기술을 익혔습니다. 만약 여러분이 특정 테크니컬한 부분을 건너 뛰었더라도 beliefs를 업데이트 하기 위해 probabilities를 적용하는 가장 기초적이고 핵심적인 부분은 꼭 이해하셔야 합니다. 이 장의 시작 부분에서 논의했듯이 probabilistic reasoning 확률론적 추론의 주된 이점은 불확실하고 모순되는 증거를 처리 할 수있는 능력입니다. 의료 진단 및 스팸 필터링의 예제를 사용하여이 작업이 실제로 어떻게 수행되는지를 보여주었습니다.






After completing Chapter 3 you should be able to:




  • Express probabilities in terms of natural frequencies
  • Apply the Bayes rule to infer risks in simple scenarios
  • Explain the base-rate fallacy and avoid it by applying Bayesian reasoning




반응형
이전 1 다음