Book Image

Artificial Intelligence with Python

Book Image

Artificial Intelligence with Python

Overview of this book

Artificial Intelligence is becoming increasingly relevant in the modern world. By harnessing the power of algorithms, you can create apps which intelligently interact with the world around you, building intelligent recommender systems, automatic speech recognition systems and more. Starting with AI basics you'll move on to learn how to develop building blocks using data mining techniques. Discover how to make informed decisions about which algorithms to use, and how to apply them to real-world scenarios. This practical book covers a range of topics including predictive analytics and deep learning.
Table of Contents (23 chapters)
Artificial Intelligence with Python
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Building a K-Nearest Neighbors classifier


A K-Nearest Neighbors classifier is a classification model that uses the nearest neighbors algorithm to classify a given data point. The algorithm finds the K closest data points in the training dataset to identify the category of the input data point. It will then assign a class to this data point based on a majority vote. From the list of those K data points, we look at the corresponding classes and pick the one with the highest number of votes. Let's see how to build a classifier using this model. The value of K depends on the problem at hand.

Create a new Python file and import the following packages:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.cm as cm 
from sklearn import neighbors, datasets 

Load the input data from data.txt. Each line contains comma-separated values and the data contains four classes:

# Load input data 
input_file = 'data.txt' 
data = np.loadtxt(input_file, delimiter=...