机器学习入门教程-k-近邻
k-近邻算法原理
像之前提到的那样,机器学习的一个要点就是分类,对于分类来说有许多不同的算法,所谓的物以聚类,分以群分。我们非常的清楚,一个地域的人群,不管在生活习惯,还是在习俗上都是非常相似的,也就是我们说的一类人。每一类人都会形成自己的一个中心,越靠近这个中心的人越为相似。k近邻算法就是为了找到这个中心点,把这中心点当成这类关键点,在有新的数据需要分类的话,就看离哪个中心点近,那么就属于哪一类。
假设我们有这样的一组数据,他代表一个人的地理坐标位置:
| x坐标 | y坐标 | 哪省人 |
|---|---|---|
| 4.035615117 | 4.920529835 | 0 |
| 4.665299994 | 4.702897321 | 0 |
| 1.711128297 | 1.031989236 | 1 |
根据这坐标在图上绘出图形:

两个蓝色的点互相靠近,它们的属性应该是相似的,而红色的点,离这两个蓝色的点有一定的距离,可能属于另一个聚合。
在这里导入一组数据,这一组数据中有三个分类,每一个分类就是一个群,组成了三个中心,具体的数据和图如下:
import numpy as np
import random
import matplotlib.pyplot as plt
def read_clusters(clustersfile):
cl = []
tl = []
with open(clustersfile, 'r') as f:
for line in f:
line = line.strip()
if line != '':
line = line.split()
constraint = [float(line[0]), float(line[1])]
cl.append(constraint)
tl.append(int(line[2]))
return cl,tl
train_data,train_labels = read_clusters('clusters3.txt')
train_data = np.array(train_data)
key_name = {0:'red',1:'blue',2:'orange'}
for i in range(train_data.shape[0]):
plt.scatter(train_data[i:i + 1, 0:1], train_data[i:i + 1, 1:2], c=key_name[train_labels[i]], marker='o',s=20)
plt.savefig('clusters.png')

k-近邻算法步骤
k-近邻的一般步骤如下:
1.先随机的产生几个中心,中心点的确认来自于需要组建几个类群。
def _init_random_centroids(self, data):
n_samples, n_features = np.shape(data)
centroids = np.zeros((self.k, n_features))
for i in range(self.k):
centroid = data[np.random.choice(range(n_samples))]
centroids[i] = centroid
return centroids
2.接下来是把所有的数据点跟这几个中心点进行比较,数据点里哪个中心点近,那么这个点就属于哪个类群。
计算距离的公式如下:
def euclidean_distance(vec_1, vec_2):
if(len(vec_1) != len(vec_2)):
raise Exception("The two vectors do NOT have equal length")
distance = 0
for i in range(len(vec_1)):
distance += pow((vec_1[i] - vec_2[i]), 2)
return np.sqrt(distance)
根据距离查找属于哪个中心点。
def _closest_centroid(self, sample, centroids):
closest_i = None
closest_distance = float("inf")
for i, centroid in enumerate(centroids):
distance = ml_helpers.euclidean_distance(sample, centroid)
if distance < closest_distance:
closest_i = i
closest_distance = distance
return closest_i
3.通过中心点确定了类群,在通过类群更新中心点。中心点是这个类群所有点的均值点,计算均值更新中心点。
def _calculate_centroids(self, clusters, data):
n_features = np.shape(data)[1]
centroids = np.zeros((self.k, n_features))
for i, cluster in enumerate(clusters):
centroid = np.mean(data[cluster], axis=0)
centroids[i] = centroid
return centroids
4.不断的更新这一个过程,直到中心点不在变化。
整个过程如下:
import numpy as np
import random
import sys
import matplotlib.pyplot as plt
def euclidean_distance(vec_1, vec_2):
if(len(vec_1) != len(vec_2)):
raise Exception("The two vectors do NOT have equal length")
distance = 0
for i in range(len(vec_1)):
distance += pow((vec_1[i] - vec_2[i]), 2)
return np.sqrt(distance)
def read_clusters(clustersfile):
cl = []
tl = []
with open(clustersfile, 'r') as f:
for line in f:
line = line.strip()
if line != '':
line = line.split()
constraint = [float(line[0]), float(line[1])]
cl.append(constraint)
tl.append(int(line[2]))
return cl,tl
class KMeans():
def __init__(self, k=2, max_iterations=500):
self.k = k
self.max_iterations = max_iterations
self.kmeans_centroids = []
def _init_random_centroids(self, data):
n_samples, n_features = np.shape(data)
centroids = np.zeros((self.k, n_features))
for i in range(self.k):
centroid = data[np.random.choice(range(n_samples))]
centroids[i] = centroid
return centroids
def _closest_centroid(self, sample, centroids):
closest_i = None
closest_distance = float("inf")
for i, centroid in enumerate(centroids):
distance = euclidean_distance(sample, centroid)
if distance < closest_distance:
closest_i = i
closest_distance = distance
return closest_i
def _create_clusters(self, centroids, data):
n_samples = np.shape(data)[0]
clusters = [[] for _ in range(self.k)]
for sample_i, sample in enumerate(data):
centroid_i = self._closest_centroid(sample, centroids)
clusters[centroid_i].append(sample_i)
return clusters
def _calculate_centroids(self, clusters, data):
n_features = np.shape(data)[1]
centroids = np.zeros((self.k, n_features))
for i, cluster in enumerate(clusters):
centroid = np.mean(data[cluster], axis=0)
centroids[i] = centroid
return centroids
def _get_cluster_labels(self, clusters, data):
y_pred = np.zeros(np.shape(data)[0])
for cluster_i, cluster in enumerate(clusters):
for sample_i in cluster:
y_pred[sample_i] = cluster_i
return y_pred
def fit(self, data):
centroids = self._init_random_centroids(data)
for iteration in range(self.max_iterations):
clusters = self._create_clusters(centroids, data)
prev_centroids = centroids
centroids = self._calculate_centroids(clusters, data)
diff = centroids - prev_centroids
if not diff.any():
break
self.kmeans_centroids = centroids
return centroids
def predict(self, data):
if not self.kmeans_centroids.any():
raise Exception("K-Means centroids have not yet been determined.\nRun the K-Means 'fit' function first.")
clusters = self._create_clusters(self.kmeans_centroids, data)
predicted_labels = self._get_cluster_labels(clusters, data)
return predicted_labels
key_name = {0:'red',1:'blue',2:'orange'}
clf = KMeans(k=3, max_iterations=3000)
train_data,train_labels = read_clusters('clusters3.txt')
train_data = np.array(train_data)
centroids = clf.fit(train_data)
print centroids
中心点不断更新的过程如下:

算法误差估计
检验算法的好坏,简单的办法是把一部分的数据用来训练,一部分的数据用来检验,查看算法的结果跟预计的数据相差多少?
下面是算法的效果估计:
Accuracy = 0
for index in range(len(train_labels)):
# Cluster the data using K-Means
current_label = train_labels[index]
predicted_label = predicted_labels[index]
if current_label == int(predicted_label):
Accuracy += 1
Accuracy /= len(train_labels)
print Accuracy
输出的结果为
1
准确率达到100%。
sklearn 下的k-近邻算法
在学习算法的时候知道了原理,通过自己的代码对算法的原理进行编写,通常来讲这很方便学习,在知道了如何编写算法以后,可以直接使用现成的开源库,直接使用该算法,sklearn 就非常方便使用。
clf = cluster.KMeans(n_clusters=3, max_iter=3000, n_init=10)
kmeans = clf.fit(train_data)
Accuracy = 0
for index in range(len(train_labels)):
# Cluster the data using K-Means
current_sample = train_data[index].reshape(1,-1)
current_label = train_labels[index]
predicted_label = kmeans.predict(current_sample)
if current_label == predicted_label:
Accuracy += 1
Accuracy /= len(train_labels)
算法的应用
k-近邻算法用来找到中心点,同时算法也可以用来进行去重,把重复的附近的点都把他近似为中心点。
转载请标明来之:http://www.bugingcode.com/
更多教程:阿猫学编程
机器学习入门教程-k-近邻的更多相关文章
- 机器学习03:K近邻算法
本文来自同步博客. P.S. 不知道怎么显示数学公式以及排版文章.所以如果觉得文章下面格式乱的话请自行跳转到上述链接.后续我将不再对数学公式进行截图,毕竟行内公式截图的话排版会很乱.看原博客地址会有更 ...
- 机器学习 Python实践-K近邻算法
机器学习K近邻算法的实现主要是参考<机器学习实战>这本书. 一.K近邻(KNN)算法 K最近邻(k-Nearest Neighbour,KNN)分类算法,理解的思路是:如果一个样本在特征空 ...
- 机器学习实战python3 K近邻(KNN)算法实现
台大机器技法跟基石都看完了,但是没有编程一直,现在打算结合周志华的<机器学习>,撸一遍机器学习实战, 原书是python2 的,但是本人感觉python3更好用一些,所以打算用python ...
- 02机器学习实战之K近邻算法
第2章 k-近邻算法 KNN 概述 k-近邻(kNN, k-NearestNeighbor)算法是一种基本分类与回归方法,我们这里只讨论分类问题中的 k-近邻算法. 一句话总结:近朱者赤近墨者黑! k ...
- 机器学习算法之K近邻算法
0x00 概述 K近邻算法是机器学习中非常重要的分类算法.可利用K近邻基于不同的特征提取方式来检测异常操作,比如使用K近邻检测Rootkit,使用K近邻检测webshell等. 0x01 原理 ...
- 机器学习实战笔记--k近邻算法
#encoding:utf-8 from numpy import * import operator import matplotlib import matplotlib.pyplot as pl ...
- 机器学习PR:k近邻法分类
k近邻法是一种基本分类与回归方法.本章只讨论k近邻分类,回归方法将在随后专题中进行. 它可以进行多类分类,分类时根据在样本集合中其k个最近邻点的类别,通过多数表决等方式进行预测,因此不具有显式的学习过 ...
- 机器学习随笔01 - k近邻算法
算法名称: k近邻算法 (kNN: k-Nearest Neighbor) 问题提出: 根据已有对象的归类数据,给新对象(事物)归类. 核心思想: 将对象分解为特征,因为对象的特征决定了事对象的分类. ...
- 机器学习-- 入门demo1 k临近算法
1.k-近邻法简介 k近邻法(k-nearest neighbor, k-NN)是1967年由Cover T和Hart P提出的一种基本分类与回归方法. 它的工作原理是:存在一个样本数据集合,也称作为 ...
随机推荐
- 01 语言基础+高级:1-5 常用API第二部分_day01.【Object类、常用API: Date类、System类、StringBuilder类】
day01[Object类.常用API] 主要内容 Object类 Date类 DateFormat类 Calendar类 System类 StringBuilder类 包装类 java.lang.O ...
- 面向对象 part7 class
类的定义 类实际上是个“特殊的函数“,就像能够定义函数表达式和函数声明一样,类语法 有两个组成部分:类表达式和类声明式 类声明 类声明没有提升 静态方法 只有构造函数名可以调用,实例无法使用.常用于应 ...
- 小白学习之pytorch框架(5)-多层感知机(MLP)-(tensor、variable、计算图、ReLU()、sigmoid()、tanh())
先记录一下一开始学习torch时未曾记录(也未好好弄懂哈)导致又忘记了的tensor.variable.计算图 计算图 计算图直白的来说,就是数学公式(也叫模型)用图表示,这个图即计算图.借用 htt ...
- 小白学习之pytorch框架(4)-softmax回归(torch.gather()、torch.argmax()、torch.nn.CrossEntropyLoss())
学习pytorch路程之动手学深度学习-3.4-3.7 置信度.置信区间参考:https://cloud.tencent.com/developer/news/452418 本人感觉还是挺好理解的 交 ...
- 二、Shell脚本高级编程实战第二部
一.什么是变量? 变量就是一个固定的字符串替代更多更复杂的内容,当然内容里面可能还有变量.路径.字符串等等内容,最大的特点就是方便,更好开展工作 1.变量有环境变量(全局变量)和局部变量 环境变量就是 ...
- 吴裕雄--天生自然python Google深度学习框架:图像识别与卷积神经网络
- rare alleles
I.4 Where the rare alleles are found p是基因A的频率,N是个体数目(也就是基因型个数,所以基因个数是2n,所以全部个体的基因A的个数是2np),p方是PAA,np ...
- linux4.11内核设备编译时出现的问题(参考博客并更改的)
AllWinnerH3 linux4.11版本的bsp下载: https://pan.baidu.com/s/1mhU4a8K 密码: b375 H3-linux4.11_bsp目录就是所需的源码及编 ...
- druid+mybaits简单集成
在前面的文章中,我们对springboot开发中一些常用的框架进行了集成,但是发现还是存在一些问题,比如druid还需要比较长的固有配置,实际上druid官方是提供了相关的starters包的,内部采 ...
- ionic3 打开相机与相册,并实现图片上传
安装依赖项等: $ ionic cordova plugin add cordova-plugin-camera $ npm install --save @ionic-native/camera 创 ...