Kā darbojas naivie Bajes klasifikatori - ar Python koda piemēriem

Naivie Baiesa klasifikatori (NBC) ir vienkārši, bet jaudīgi mašīnmācīšanās algoritmi. Tie ir balstīti uz nosacītu varbūtību un Baiesa teorēmu.

Šajā amatā es izskaidroju "triku" aiz NBC un sniegšu jums piemēru, kuru mēs varam izmantot, lai atrisinātu klasifikācijas problēmu.

Nākamajās sadaļās es runāšu par matemātiku aiz NBC. Jūtieties brīvi izlaist šīs sadaļas un doties uz ieviešanas daļu, ja matemātika jūs neinteresē.

Ieviešanas sadaļā es parādīšu vienkāršu NBC algoritmu. Tad mēs to izmantosim, lai atrisinātu klasifikācijas problēmu. Uzdevums būs noteikt, vai kāds Titānika pasažieris izdzīvoja avārijā vai nē.

Nosacīta varbūtība

Pirms runājam par pašu algoritmu, parunāsim par vienkāršo matemātiku aiz tā. Mums jāsaprot, kāda ir nosacītā varbūtība un kā mēs varam izmantot Bajesa teorēmu, lai to aprēķinātu.

Padomājiet par godīgu mirst ar sešām pusēm. Kāda ir varbūtība iegūt sešinieku, ripinot matricu? Tas ir viegli, tas ir 1/6. Mums ir seši iespējamie un tikpat iespējamie rezultāti, bet mūs interesē tikai viens no tiem. Tātad, 1/6 tā ir.

Bet kas notiek, ja es jums saku, ka es jau esmu sarullējis matricu un rezultāts ir pāra skaitlis? Cik liela ir varbūtība, ka tagad esam ieguvuši sešinieku?

Šoreiz iespējamie rezultāti ir tikai trīs, jo uz matricas ir tikai trīs pāra skaitļi. Mūs joprojām interesē tikai viens no šiem rezultātiem, tāpēc varbūtība ir lielāka: 1/3. Kāda ir atšķirība starp abiem gadījumiem?

Pirmajā gadījumā mums nebija iepriekšējas informācijas par rezultātu. Tādējādi mums bija jāapsver katrs iespējamais rezultāts.

Otrajā gadījumā mums teica, ka iznākums ir pāra skaitlis, tāpēc mēs varētu samazināt iespējamo iznākumu atstarpi tikai līdz trim pāra skaitļiem, kas parādās parastajā sešpusē.

Kopumā, aprēķinot notikuma A varbūtību, ņemot vērā cita notikuma B rašanos, mēs sakām, ka mēs aprēķinām A nosacītās varbūtības B vai tikai A varbūtību B. Mēs to apzīmējam P(A|B).

Piemēram, varbūtība iegūt sešus ņemot vērā, ka numurs mēs esam ieguvuši, ir vēl: P(Six|Even) = 1/3. Šeit mēs ar Six atzīmējām notikumu, lai iegūtu sešinieku, un ar Even , ja iegūtu pāra skaitli.

Bet kā mēs aprēķinām nosacītās varbūtības? Vai ir kāda formula?

Kā aprēķināt nosacītās probes un Baiesa teorēmu

Tagad es jums iedošu pāris formulas, lai aprēķinātu nosacītās probas. Es apsolu, ka viņiem nebūs grūti, un tie ir svarīgi, ja vēlaties saprast ieskatus mašīnmācīšanās algoritmos, par kuriem mēs runāsim vēlāk.

Notikuma A varbūtību, ņemot vērā cita notikuma B rašanos, var aprēķināt šādi:

P(A|B) = P(A,B)/P(B) 

Kur P(A,B)apzīmē gan A, gan B vienlaicīgas rašanās varbūtību, gan B P(B)varbūtību.

Ievērojiet, ka mums P(B) > 0tas ir nepieciešams, jo nav jēgas runāt par A iespējamību B, ja B rašanās nav iespējama.

Mēs varam arī aprēķināt notikuma A varbūtību, ņemot vērā vairāku notikumu B1, B2, ..., Bn parādīšanos:

P(A|B1,B2,...,Bn) = P(A,B1,B2,...,Bn)/P(B1,B2,...,Bn) 

Ir vēl viens nosacīto zondu aprēķināšanas veids. Tādā veidā ir tā sauktā Bajesa teorēma.

P(A|B) = P(B|A)P(A)/P(B) P(A|B1,B2,...,Bn) = P(B1,B2,...,Bn|A)P(A)/P(B1,B2,...,Bn) 

Ievērojiet, ka mēs aprēķinām notikuma A varbūtību, ņemot vērā notikumu B, apgriežot notikumu rašanās kārtību.

Tagad mēs pieņemam, ka notikums A ir noticis, un mēs vēlamies aprēķināt notikuma B problēmu (vai notikumus B1, B2, ..., Bn otrajā un vispārīgākajā piemērā).

Svarīgs fakts, ko var iegūt no šīs teorēmas, ir aprēķina formula P(B1,B2,...,Bn,A). To sauc par varbūtības ķēdes likumu.

P(B1,B2,...,Bn,A) = P(B1 | B2, B3, ..., Bn, A)P(B2,B3,...,Bn,A) = P(B1 | B2, B3, ..., Bn, A)P(B2 | B3, B4, ..., Bn, A)P(B3, B4, ..., Bn, A) = P(B1 | B2, B3, ..., Bn, A)P(B2 | B3, B4, ..., Bn, A)...P(Bn | A)P(A) 

Tā ir neglīta formula, vai ne? Bet dažos apstākļos mēs varam novērst un izvairīties no tā.

Parunāsim par pēdējo jēdzienu, kas mums jāzina, lai saprastu algoritmus.

Neatkarība

Pēdējā koncepcija, par kuru mēs runāsim, ir neatkarība. Mēs sakām, ka notikumi A un B ir neatkarīgi, ja

P(A|B) = P(A) 

Tas nozīmē, ka notikuma B rašanos neietekmē notikuma A iespējamība. Tiešas sekas ir tādas P(A,B) = P(A)P(B).

Vienkāršā angļu valodā tas nozīmē, ka gan A, gan B rašanās iespējamība vienlaikus ir vienāda ar A un B notikumu zondu reizinājumu, kas notiek atsevišķi.

Ja A un B ir neatkarīgi, tas arī uzskata, ka:

P(A,B|C) = P(A|C)P(B|C) 

Tagad mēs esam gatavi runāt par Naive Bayes klasifikatoriem!

Naivie Bajes klasifikatori

Pieņemsim, ka mums ir n pazīmju vektors X , un mēs vēlamies noteikt šī vektora klasi no k klases y1, y2, ..., yk kopas . Piemēram, ja mēs vēlamies noteikt, vai šodien līs lietus vai ne.

Mums ir divas iespējamās klases ( k = 2 ): lietus , nevis lietus , un pazīmju vektora garums varētu būt 3 ( n = 3 ).

Pirmā iezīme varētu būt mākoņaina vai saulaina, otra iezīme - vai augsts vai zems mitrums, bet trešā - vai augsta, vidēja vai zema temperatūra.

Tātad, tie varētu būt iespējamie iezīmju vektori.

Mūsu uzdevums ir noteikt, vai līs, ņemot vērā laika apstākļu īpašības.

Uzzinot par nosacītām varbūtībām, šķiet dabiski pieiet problēmai, mēģinot aprēķināt lietus varbūtību, ņemot vērā funkcijas:

R = P(Rain | Cloudy, H_High, T_Low) NR = P(NotRain | Cloudy, H_High, T_Low) 

Ja R > NRatbildam, ka līs, citādi sakām, ka nelīs.

Kopumā, ja mums ir k klases y1, y2, ..., yk un n pazīmju vektors X = , mēs vēlamies atrast klasi yi, kas maksimizē

P(yi | X1, X2, ..., Xn) = P(X1, X2,..., Xn, yi)/P(X1, X2, ..., Xn) 

Ievērojiet, ka saucējs ir nemainīgs un tas nav atkarīgs no klases yi . Tātad, mēs varam to ignorēt un koncentrēties tikai uz skaitītāju.

In a previous section, we saw how to calculate P(X1, X2,..., Xn, yi) by decomposing it in a product of conditional probabilities (the ugly formula):

P(X1, X2,..., Xn, yi) = P(X1 | X2,..., Xn, yi)P(X2 | X3,..., Xn, yi)...P(Xn | yi)P(yi) 

Assuming all the features Xi are independent and using Bayes's Theorem, we can calculate the conditional probability as follows:

P(yi | X1, X2,..., Xn) = P(X1, X2,..., Xn | yi)P(yi)/P(X1, X2, ..., Xn) = P(X1 | yi)P(X2 | yi)...P(Xn | yi)P(yi)/P(X1, X2, ..., Xn) 

And we just need to focus on the numerator.

By finding the class yi that maximizes the previous expression, we are classifying the input vector. But, how can we get all those probabilities?

How to calculate the probabilities

When solving these kind of problems we need to have a set of previously classified examples.

For instance, in the problem of guessing whether it'll rain or not, we need to have several examples of feature vectors and their classifications that they would be obtained from past weather forecasts.

So, we would have something like this:

...  -> Rain  -> Not Rain  -> Not Rain ... 

Suppose we need to classify a new vector . We need to calculate:

P(Rain | Cloudy, H_Low, T_Low) = P(Cloudy | H_Low, T_Low, Rain)P(H_Low | T_Low, Rain)P(T_Low | Rain)P(Rain)/P(Cloudy, H_Low, T_Low) 

We get the previous expression by applying the definition of conditional probability and the chain rule. Remember we only need to focus on the numerator so we can drop the denominator.

We also need to calculate the prob for NotRain, but we can do this in a similar way.

We can find P(Rain) = # Rain/Total. That means counting the entries in the dataset that are classified with Rain and dividing that number by the size of the dataset.

To calculate P(Cloudy | H_Low, T_Low, Rain) we need to count all the entries that have the features H_Low, T_Low and Cloudy. Those entries also need to be classified as Rain. Then, that number is divided by the total amount of data. We calculate the rest of the factors of the formula in a similar fashion.

Making those computations for every possible class is very expensive and slow. So we need to make assumptions about the problem that simplify the calculations.

Naive Bayes Classifiers assume that all the features are independent from each other. So we can rewrite our formula applying Bayes's Theorem and assuming independence between every pair of features:

P(Rain | Cloudy, H_Low, T_Low) = P(Cloudy | Rain)P(H_Low | Rain)P(T_Low | Rain)P(Rain)/P(Cloudy, H_Low, T_Low) 

Now we calculate P(Cloudy | Rain) counting the number of entries that are classified as Rain and were Cloudy.

The algorithm is called Naive because of this independence assumption. There are dependencies between the features most of the time. We can't say that in real life there isn't a dependency between the humidity and the temperature, for example. Naive Bayes Classifiers are also called Independence Bayes, or Simple Bayes.

The general formula would be:

P(yi | X1, X2, ..., Xn) = P(X1 | yi)P(X2 | yi)...P(Xn | yi)P(yi)/P(X1, X2, ..., Xn) 

Remember you can get rid of the denominator. We only calculate the numerator and answer the class that maximizes it.

Now, let's implement our NBC and let's use it in a problem.

Let's code!

I will show you an implementation of a simple NBC and then we'll see it in practice.

The problem we are going to solve is determining whether a passenger on the Titanic survived or not, given some features like their gender and their age.

Here you can see the implementation of a very simple NBC:

class NaiveBayesClassifier: def __init__(self, X, y): ''' X and y denotes the features and the target labels respectively ''' self.X, self.y = X, y self.N = len(self.X) # Length of the training set self.dim = len(self.X[0]) # Dimension of the vector of features self.attrs = [[] for _ in range(self.dim)] # Here we'll store the columns of the training set self.output_dom = {} # Output classes with the number of ocurrences in the training set. In this case we have only 2 classes self.data = [] # To store every row [Xi, yi] for i in range(len(self.X)): for j in range(self.dim): # if we have never seen this value for this attr before, # then we add it to the attrs array in the corresponding position if not self.X[i][j] in self.attrs[j]: self.attrs[j].append(self.X[i][j]) # if we have never seen this output class before, # then we add it to the output_dom and count one occurrence for now if not self.y[i] in self.output_dom.keys(): self.output_dom[self.y[i]] = 1 # otherwise, we increment the occurrence of this output in the training set by 1 else: self.output_dom[self.y[i]] += 1 # store the row self.data.append([self.X[i], self.y[i]]) def classify(self, entry): solve = None # Final result max_arg = -1 # partial maximum for y in self.output_dom.keys(): prob = self.output_dom[y]/self.N # P(y) for i in range(self.dim): cases = [x for x in self.data if x[0][i] == entry[i] and x[1] == y] # all rows with Xi = xi n = len(cases) prob *= n/self.N # P *= P(Xi = xi) # if we have a greater prob for this output than the partial maximum... if prob > max_arg: max_arg = prob solve = y return solve 

Here, we assume every feature has a discrete domain. That means they take a value from a finite set of possible values.

The same happens with classes. Notice that we store some data in the __init__ method so we don't need to repeat some operations. The classification of a new entry is carried on in the classify method.

This is a simple example of an implementation. In real world applications you don't need (and is better if you don't make) your own implementation. For example, the sklearn library in Python contains several good implementations of NBC's.

Notice how easy it is to implement it!

Now, let's apply our new classifier to solve a problem. We have a dataset with the description of 887 passengers on the Titanic. We also can see whether a given passenger survived the tragedy or not.

So our task is to determine if another passenger that is not included in the training set made it or not.

In this example, I'll be using the pandas library to read and process the data. I don't use any other tool.

The data is stored in a file called titanic.csv, so the first step is to read the data and get an overview of it.

import pandas as pd data = pd.read_csv('titanic.csv') print(data.head()) 

The output is:

Survived Pclass Name \ 0 0 3 Mr. Owen Harris Braund 1 1 1 Mrs. John Bradley (Florence Briggs Thayer) Cum... 2 1 3 Miss. Laina Heikkinen 3 1 1 Mrs. Jacques Heath (Lily May Peel) Futrelle 4 0 3 Mr. William Henry Allen Sex Age Siblings/Spouses Aboard Parents/Children Aboard Fare 0 male 22.0 1 0 7.2500 1 female 38.0 1 0 71.2833 2 female 26.0 0 0 7.9250 3 female 35.0 1 0 53.1000 4 male 35.0 0 0 8.0500 

Notice we have the Name of each passenger. We won't use that feature for our classifier because it is not significant for our problem. We'll also get rid of the Fare feature because it is continuous and our features need to be discrete.

There are Naive Bayes Classifiers that support continuous features. For example, the Gaussian Naive Bayes Classifier.

y = list(map(lambda v: 'yes' if v == 1 else 'no', data['Survived'].values)) # target values as string # We won't use the 'Name' nor the 'Fare' field X = data[['Pclass', 'Sex', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard']].values # features values 

Then, we need to separate our data set in a training set and a validation set. The later is used to validate how well our algorithm is doing.

print(len(y)) # >> 887 # We'll take 600 examples to train and the rest to the validation process y_train = y[:600] y_val = y[600:] X_train = X[:600] X_val = X[600:] 

We create our NBC with the training set and then classify every entry in the validation set.

We measure the accuracy of our algorithm by dividing the number of entries it correctly classified by the total number of entries in the validation set.

## Creating the Naive Bayes Classifier instance with the training data nbc = NaiveBayesClassifier(X_train, y_train) total_cases = len(y_val) # size of validation set # Well classified examples and bad classified examples good = 0 bad = 0 for i in range(total_cases): predict = nbc.classify(X_val[i]) # print(y_val[i] + ' --------------- ' + predict) if y_val[i] == predict: good += 1 else: bad += 1 print('TOTAL EXAMPLES:', total_cases) print('RIGHT:', good) print('WRONG:', bad) print('ACCURACY:', good/total_cases) 

The output:

TOTAL EXAMPLES: 287 RIGHT: 200 WRONG: 87 ACCURACY: 0.6968641114982579 

It's not great but it's something. We can get about a 10% accuracy improvement if we get rid of other features like Siblings/Spouses Aboard and Parents/Children Aboard.

You can see a notebook with the code and the dataset here

Conclusions

Today, we have neural networks and other complex and expensive ML algorithms all over the place.

NBCs are very simple algorithms that let us achieve good results in some classification problems without needing a lot of resources. They also scale very well, which means we can add a lot more features and the algorithm will still be fast and reliable.

Even in a case where NBCs were not a good fit for the problem we were trying to solve, they might be very useful as a baseline.

We could first try to solve the problem using an NBC with a few lines of code and little effort. Then we could try to achieve better results with more complex and expensive algorithms.

This process can save us a lot of time and gives us an immediate feedback about whether complex algorithms are really worth it for our task.

Šajā rakstā jūs lasāt par nosacītām varbūtībām, neatkarību un Baiesa teorēmu. Tie ir matemātiskie jēdzieni, kas ir Naive Bayes klasifikatoru pamatā.

Pēc tam mēs redzējām vienkāršu NBC ieviešanu un atrisinājām problēmu, nosakot, vai Titānika pasažieris izdzīvoja avārijā.

Es ceru, ka šis raksts jums šķita noderīgs. Jūs varat lasīt par datorzinātnēm saistītām tēmām manā personīgajā emuārā un sekojot man Twitter.