机器学习: KNN--python
今天介绍机器学习中比较常见的一种分类算法,K-NN,NN 就是 Nearest Neighbors, 也就是最近邻的意思,这是一种有监督的分类算法,给定一个 test sample, 计算这个 test sample 与 training set
里每个 training sample 的距离,选择离 test sample 最近的 K 个,然后通过投票选择这 K 个样本中,属于哪类的最多,那么这个 test sample 就属于哪类。K-NN 比较简单直观,也很好理解,一般需要考虑的就是设置 K 的大小,以及如何计算样本之间的距离,比较常用的是欧式距离。下面给出一段简单的代码,说明这个算法的使用。
from sklearn import datasets
import numpy as np
import operator
def Knn_Classify (x, Train_data, labels, k):
N_sample = Train_data.shape[0]
diff_mat = np.tile(x, (N_sample, 1)) - Train_data
Sq_diffmat = diff_mat **2
Sq_dis = Sq_diffmat.sum(axis = 1)
Dis = Sq_dis ** 0.5
Index = Dis.argsort()
C_count = {}
for i in range (k):
votelabel = labels[Index[i]]
C_count[votelabel] = C_count.get(votelabel, 0) + 1
Sort_K = sorted(C_count.iteritems(),
key = operator.itemgetter(1), reverse=True)
return Sort_K
iris = datasets.load_iris()
x_data = iris.data
y_label = iris.target
class_name = iris.target_names
n_sample = len(x_data)
np.random.seed(0)
index = np.random.permutation(n_sample)
x_data = x_data[index]
y_label = y_label[index]
ratio = 0.8
train_x = x_data[ : int(ratio * n_sample)]
train_y = y_label[ : int(ratio * n_sample)]
test_x = x_data[int(ratio * n_sample) :]
test_y = y_label[int(ratio * n_sample) : ]
n_test = len(test_x)
p_label = np.zeros((len(test_y)))
for i in range (n_test):
in_x = test_x [i, :]
target_label = test_y [i]
predict_value = Knn_Classify(in_x, train_x, train_y, 5)
p_label[i] = predict_value[0][0]
# print "the predict label is: ", predict_value
# print "the target_label is: ", target_label
t = (p_label == test_y)
acc = t.sum()*1.0/len(test_y)
print "the accuracy is: ", acc
机器学习: KNN--python的更多相关文章
- 可能是史上最全的机器学习和Python(包括数学)速查表
新手学习机器学习很难,就是收集资料也很费劲.所幸Robbie Allen从不同来源收集了目前最全的有关机器学习.Python和相关数学知识的速查表大全.强烈建议收藏! 机器学习有很多方面. 当我开始刷 ...
- KNN Python实现
KNN Python实现 ''' k近邻(kNN)算法的工作机制比较简单,根据某种距离测度找出距离给定待测样本距离最小的k个训练样本,根据k个训练样本进行预测. 分类问题:k个点中出现频率最高的类别作 ...
- 机器学习之python: kNN
################################################## # kNN : k Nearest Neighbour # Author : Monne # Da ...
- 《机器学习实战》之一:knn(python代码)
数据 标称型和数值型 算法 归一化处理:防止数值较大的特征对距离产生较大影响 计算欧式距离:测试样本与训练集 排序:选取前k个距离,统计频数(出现次数)最多的类别 def classify0(inX, ...
- 吴裕雄 python 机器学习——KNN回归KNeighborsRegressor模型
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...
- 吴裕雄 python 机器学习——KNN分类KNeighborsClassifier模型
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...
- 吴裕雄 python 机器学习-KNN(2)
import matplotlib import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import ...
- 吴裕雄 python 机器学习-KNN算法(1)
import numpy as np import operator as op from os import listdir def classify0(inX, dataSet, labels, ...
- [机器学习] ——KNN K-最邻近算法
KNN分类算法,是理论上比较成熟的方法,也是最简单的机器学习算法之一. 该方法的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别 ...
- 机器学习常用Python扩展包
在Ubuntu下安装Python模块通常有3种方法:1)使用apt-get:2)使用pip命令(推荐);3)easy_instal 可安装方法参考:[转]linux和windows下安装python集 ...
随机推荐
- Run-time Settings--General--Run Logic
LR单用户,重复操作日志 案例:假如你想在一个脚本中,实现登录执行1次,查询执行2次,插入执行3次,怎么办?录3个脚本?每个事务分别在脚本中复制N次? 当然不用,LR早就想到了你的需求,下面让我们隆重 ...
- Dream City(线性DP)
描述 JAVAMAN is visiting Dream City and he sees a yard of gold coin trees. There are n trees in the ya ...
- hihoCoder#1105 题外话·堆
原题地址 有没有更优雅地堆模板啊,总感觉我写的有些啰嗦 代码: #include <iostream> using namespace std; #define MAX_NODE 1000 ...
- springboot注释详解
1.属性注入 @ConfigurationProperties(prefix="...") spring会从classpath下的/config目录或者classpath的根目录查 ...
- PHP字符串的替换(preg_replace)
/* 正则表达式 preg_replace() */ $str = array( "如果没有一些http://www.abc.com特殊的<b>替换</b>需5求( ...
- WebService流行框架CXF
CXF官方网址:http://cxf.apache.org/ CXF官方网址:官网学习地址:http://cxf.apache.org/docs/index.html 官网下载cxf压缩文件: ...
- POJ1256 Anagram
Time Limit: 1000MS Memory Limit: 10000KB 64bit IO Format: %lld & %llu Submit Status Descript ...
- SQL SERVER 2012 第三章 使用INSERT语句添加数据
INSERT [TOP (<expression>) [PERCENT] [INTO] <tabular object>[(column list)][OUTPUT <o ...
- UVAlive 3026 KMP 最小循环节
KMP算法: 一:next数组:next[i]就是前面长度为i的字符串前缀和后缀相等的最大长度,也即索引为i的字符失配时的前缀函数. 二:KMP模板 /* pku3461(Oulipo), hdu17 ...
- P1918 保龄球 洛谷
https://www.luogu.org/problem/show?pid=1918 题目描述 DL 算缘分算得很烦闷,所以常常到体育馆去打保龄球解闷.因为他保龄球已经打了几十年了,所以技术上不成问 ...