# 2.1.13.1.KNN Theory

## 1.K Nearest Neighbor

* 找和新數據最近的K個鄰居, 這些鄰居是什麼分類, 那麼新數據就是什麼樣的分類 (Choosing a K will affect what class a new point is assigned to)

![](https://github.com/jenhsuan/python/tree/8fc9c0b8df4ccd709d3078c2d8842af0932de09d/assets/螢幕快照%202018-06-24%20下午3.37.55.png)

* Training algorithm
  * Store all the data
* Prediction algorithm
  1. Calculate the distance from x to all points in your data
  2. Sort the points in your data by increasing distance from x
  3. Predict the majority label of the "k" closet points

## 2.Pros and cons

* Pros
  1. Very simple
  2. Training is trivial
  3. Works with any number of classes
  4. Easy to add more data
  5. Few parameters
     * K
     * Distance metric
* Cons
  1. High prediction cost (worse for large data sets)
  2. Not good with high dimensional data
  3. Categorical features do not work well


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jen-hsuan-hsieh.gitbook.io/python/chapter-2courses/21python-for-data-science-and-machine-learning-bootcamp/sd/21131knn-theory.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
