K nearest neighbor cs229
vectorized code 带来的好处。
import numpy as np
from sklearn.datasets import fetch_mldata
import time
import matplotlib.pyplot as plt mnist = fetch_mldata('MNIST original') X = mnist.data.astype(float)
Y = mnist.target.astype(float) mask = np.random.permutation(range(np.shape(X)[0])) num_train = 10000
num_test = 500
K = 10 X_train = X[mask[:num_train]]
Y_train = Y[mask[:num_train]] X_mean = np.mean(X_train,axis = 0) X_train = (X_train-X_mean)/255 X_test = X[mask[num_train:num_train+num_test]] X_test = (X_test - X_mean)/255 Y_test = Y[mask[num_train:num_train+num_test]] print('X_train',X_train.shape)
print('Y_train',Y_train.shape)
print('X_test',X_test.shape)
print('Y_test',Y_test.shape) ex_image = (np.reshape(X_train[10,:]*255 + X_mean, (28, 28))).astype(np.uint8)
plt.imshow(ex_image, interpolation='nearest') # **Computing the distance matrix (num_test x num_train)** # Version 1 (Naive implementation using two for loops) start = time.time()
dists_1 = np.zeros((num_test,num_train))
for i in xrange(num_test):
for j in xrange(num_train):
dists_1[i,j] = np.sqrt(np.square(np.sum(X_test[i,:]-X_train[j,:]))) stop = time.time()
time_taken = stop-start
print('Time taken with two for loops: {}s'.format(time_taken)) # Version 2(Somewhat better implementation using one for loop) start = time.time()
dists_2 = np.zeros((num_test,num_train))
for i in xrange(num_test):
dists_2[i,:] = np.sqrt(np.square(np.sum(X_test[i,:]-X_train,axis = 1))) stop = time.time()
time_taken = stop-start
print('Time taken with just one for loop: {}s'.format(time_taken)) # Version 3 (Fully vectorized implementation with no for loop) start = time.time()
dists_3 = np.zeros((num_test,num_train))
A = np.sum(np.square(X_test),axis = 1)
B = np.sum(np.square(X_train),axis = 1)
C = np.dot(X_test,X_train.T) dists_3 = np.sqrt(A[:,np.newaxis]+B[np.newaxis,:]-2*C) stop = time.time()
time_taken = stop-start
print('Time taken with no for loops: {}s'.format(time_taken)) sorted_dist_indices = np.argsort(dists_3,axis = 1) closest_k = Y_train[sorted_dist_indices][:,:K].astype(int)
Y_pred = np.zeros_like(Y_test) for i in xrange(num_test):
Y_pred[i] = np.argmax(np.bincount(closest_k[i,:])) accuracy = (np.where(Y_test-Y_pred == 0)[0].size)/float(num_test)
print('Prediction accuracy: {}%'.format(accuracy*100))
K nearest neighbor cs229的更多相关文章
- K Nearest Neighbor 算法
文章出处:http://coolshell.cn/articles/8052.html K Nearest Neighbor算法又叫KNN算法,这个算法是机器学习里面一个比较经典的算法, 总体来说KN ...
- K NEAREST NEIGHBOR 算法(knn)
K Nearest Neighbor算法又叫KNN算法,这个算法是机器学习里面一个比较经典的算法, 总体来说KNN算法是相对比较容易理解的算法.其中的K表示最接近自己的K个数据样本.KNN算法和K-M ...
- K-Means和K Nearest Neighbor
来自酷壳: http://coolshell.cn/articles/7779.html http://coolshell.cn/articles/8052.html
- Nearest neighbor graph | 近邻图
最近在开发一套自己的单细胞分析方法,所以copy paste事业有所停顿. 实例: R eNetIt v0.1-1 data(ralu.site) # Saturated spatial graph ...
- 【cs231n】图像分类-Nearest Neighbor Classifier(最近邻分类器)【python3实现】
[学习自CS231n课程] 转载请注明出处:http://www.cnblogs.com/GraceSkyer/p/8735908.html 图像分类: 一张图像的表示:长度.宽度.通道(3个颜色通道 ...
- [机器学习系列] k-近邻算法(K–nearest neighbors)
C++ with Machine Learning -K–nearest neighbors 我本想写C++与人工智能,但是转念一想,人工智能范围太大了,我根本介绍不完也没能力介绍完,所以还是取了他的 ...
- Visualizing MNIST with t-SNE, MDS, Sammon’s Mapping and Nearest neighbor graph
MNIST 可视化 Visualizing MNIST: An Exploration of Dimensionality Reduction At some fundamental level, n ...
- Nearest Neighbor Search
## Nearest Neighbor Search ## Input file: standard input Output file: standard output Time limit: 1 ...
- K近邻(K Nearest Neighbor-KNN)原理讲解及实现
算法原理 K最近邻(k-Nearest Neighbor)算法是比较简单的机器学习算法.它采用测量不同特征值之间的距离方法进行分类.它的思想很简单:如果一个样本在特征空间中的k个最近邻(最相似)的样本 ...
随机推荐
- 综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ 四个分布式消息队列
来源:http://t.cn/RVDWcfe 一.资料文档 Kafka:中.有kafka作者自己写的书,网上资料也有一些.rabbitmq:多.有一些不错的书,网上资料多.zeromq:少.没有专门写 ...
- python-Re模块用法
主要函数:match().search().compile() re.compile compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 se ...
- POJ 3207 【2-SAT入门题 + 强连通分量】
这道题是我对于2-SAT问题的入门题:http://poj.org/problem?id=3207 一篇非常非常非常好的博客,很详细,认真看一遍差不多可以了解个大概:https://blog.csdn ...
- React + Antd开发模式下的Excel导入功能
具体js如下,配合的是antd里面的upload组件,使用的是xlsx插件 npm : npm install xlsx 插件链接: https://github.com/SheetJS/sheet ...
- 深入理解MySQL索引原理和实现——为什么索引可以加速查询?
说到索引,很多人都知道“索引是一个排序的列表,在这个列表中存储着索引的值和包含这个值的数据所在行的物理地址,在数据十分庞大的时候,索引可以大大加快查询的速度,这是因为使用索引后可以不用扫描全表来定位某 ...
- luoguP2664树上游戏(点分治)
题目链接:https://www.luogu.org/problem/P2664 题意:给定一颗带点权的树,结点数n<=1e5,点权<=1e5,用s(i,j)表示从i到j的路径上不同点权数 ...
- JS中的迭代
for each...in 使用一个变量迭代一个对象的所有属性值.对于每一个属性值,有一个指定的语句块被执行. 作为ECMA-357(E4X)标准的一部分,for each...in语句已被废弃,E4 ...
- layui 实现图片上传和预览
[学习笔记] 图片不自动上传并在表单提交时再上传,看代码. 附上表单页面 前台实现 <#--图片名--><input id="fileName" type=&qu ...
- matplotlib库的基本使用与折线图
matplotlib:最流行的Python底层绘图库,主要做数据可视化图表,名字取材于MATLAB,模仿MATLAB构建 基本使用: x和y的长度必须一致 figure()方法用来设置图片大小 x,y ...
- Jmeter入门(一)干货吐槽
前言:性能测试的基础是功能测试.性能测试的核心是业务场景,而这个业务场景是从功能测试的场景测试中提取出来的. 所以一个软件的测试顺序是:功能(接口)→性能N(接口)→自动化(接口) 接口测试则分布在每 ...