Chapter 2 - Classifying with k-N

2018-06-28  本文已影响0人  mofii

Classifying with distance measurements

k-Nearest Neighbors

  • Pros: High accuracy, insensitive to outliers, no assumptions about data
  • Cons: Computationally expensive, requires a lot of memory
  • Works with: Numeric values, nominal values

The first machine-learning algorithm is k-Nearest Neighbors (kNN). When given a new piece of data, we compare the new piece of data with our training set. We look at the k most similar pieces of data and take a majority vote from the k pieces of data, and the majority is the new class we assign to the data we were asked to classify.

Prepare: importing data with Python

Putting the kNN classification algorithm into action

How to test a classifier

Calculate error rate using test set.

Example: improving matches from a dating site with kNN

Prepare: parsing data from a text file

Analyze: creating scatter plot with Matplotlib

Visualizing Data

Prepare: normalizing numeric values

When dealing with values that lie in different ranges, it's common to normalize them. Common ranges to normalize them to are 0 to 1 or -1 to 1.

Test: testing the classifier as a whole program

To test the accuracy of the algorithm, we take 90% of the existing data to train the classifier. Then we take the remaining 10% to test the classifier and see how accurate it is. The 10% should be randomly selected. Our data isn't stored in a specific sequence, so you can take the first 10%.

Use: putting together a useful system

Now that we've tested the classifier on our data, it's time to use it to actually classify people for Hellen. Hellen will find someone on the dating site and enter his information. The program predicts how much she'll like this person.

Example: a handwriting recognition system

Prepare: converting images into test vectors

We'll take the 32x32 matrix that is each binary image and make it a 1x1024 vector. After this, we can apply it to the existing classifier.

Test: kNN on handwriting digits

So many calculations make this algorithm pretty slow. This is a modification to kNN, called kD-trees, that allow us to reduce the number of calculations.

Summary

The k-Nearest Neighbors algorithm is a simple and effective way to classify data. kNN is an example of instance-based learning, where you need to have instances of data close at hand to perform the machine learning algorithm. In addition, you need to calculate the distance measurement for every piece of data in the database, and this can be cumbersome.

And additional drawback is that kNN doesn't give you any idea of the underlying structure of the data; you have no idea what an "average" or "examplar" instance from each class looks like. In the next chapter, we'll address this issue by exploring ways in which probability measurements can help you do classification.

上一篇下一篇

猜你喜欢

热点阅读