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个最近邻(最相似)的样本 ...
随机推荐
- 计蒜客 —— 字符串p型编码
给定一个完全由数字字符('0','1','2',…,'9')构成的字符串 strstr,请写出 strstr 的 pp 型编码串. 例如:字符串122344111可被描述为“1个 1.2 个 2.1 ...
- Unity3D热更新之LuaFramework篇[04]--自定义UI监听方法
时隔一个多月我又回来啦! 坚持真的是很难的一件事,其它事情稍忙,就很容易说服自己把写博客的计划给推迟了. 好在终于克服了自己的惰性,今天又开始了. 本篇继续我的Luaframework学习之路. 一. ...
- nodejs加解密
加密分类 可逆加密和不可逆加密 不可逆加密: 加密后不可解密,只能通过碰撞密文以极小的概率解密; 可逆加密: 加密后可以解密;包括对称加密与非对称加密; 对称加密双方采用共同密钥; 非对称加密: 这种 ...
- SpringCloud学习(五)路由网关(zuul)(Finchley版本)
在微服务架构中,需要几个基础的服务治理组件,包括服务注册与发现.服务消费.负载均衡.断路器.智能路由.配置管理等,由这几个基础组件相互协作,共同组建了一个简单的微服务系统.一个简单的微服务系统如下图: ...
- FTL方面综述
FTL 1.百度百科 http://baike.baidu.com/link?url=HJ94Rz2Td83V8OW-6dD_h_P8CZb9VFR6HznPDopY_SFdfXDaMriYcBm1X ...
- Python全栈开发之6、面向对象
一.创建类和对象 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类是一个模板,模板中包装了多个“函数”供使用(可以讲多函数中公用的变量封装到对象中) 对象,根据模板创建的实例 ...
- 【转帖】刘备三顾茅庐,请Elasticsearch出山
刘备三顾茅庐,请Elasticsearch出山 2019-08-08 18:31 https://www.sohu.com/a/332454886_463994?spm=smpc.author.fd- ...
- 2019年5月份最热门的JavaScript开源项目
五一假期后工作的第一天,不知道你们调整好状态没有呢? 1-libpku https://github.com/lib-pku/libpku Star 15820 该项目是由一名北大在读大学生整 ...
- 服务器:消息18456,级别16,状态1 用户‘sa’登录失败解决方法
无法连接到服务器**: 服务器:消息18456,级别16,状态1 [Microsoft][ODBC SQL Server Driver][Sql server] 用户 'sa ...
- jvm调试相关:jmap失效下找到alternatives神器
1.使用 jmap <pid>出现的错误日志:很明显是版本问题 Error attaching to process: sun.jvm.hotspot.runtime.VMVersionM ...