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的更多相关文章

  1. K Nearest Neighbor 算法

    文章出处:http://coolshell.cn/articles/8052.html K Nearest Neighbor算法又叫KNN算法,这个算法是机器学习里面一个比较经典的算法, 总体来说KN ...

  2. K NEAREST NEIGHBOR 算法(knn)

    K Nearest Neighbor算法又叫KNN算法,这个算法是机器学习里面一个比较经典的算法, 总体来说KNN算法是相对比较容易理解的算法.其中的K表示最接近自己的K个数据样本.KNN算法和K-M ...

  3. K-Means和K Nearest Neighbor

    来自酷壳: http://coolshell.cn/articles/7779.html http://coolshell.cn/articles/8052.html

  4. Nearest neighbor graph | 近邻图

    最近在开发一套自己的单细胞分析方法,所以copy paste事业有所停顿. 实例: R eNetIt v0.1-1 data(ralu.site) # Saturated spatial graph ...

  5. 【cs231n】图像分类-Nearest Neighbor Classifier(最近邻分类器)【python3实现】

    [学习自CS231n课程] 转载请注明出处:http://www.cnblogs.com/GraceSkyer/p/8735908.html 图像分类: 一张图像的表示:长度.宽度.通道(3个颜色通道 ...

  6. [机器学习系列] k-近邻算法(K–nearest neighbors)

    C++ with Machine Learning -K–nearest neighbors 我本想写C++与人工智能,但是转念一想,人工智能范围太大了,我根本介绍不完也没能力介绍完,所以还是取了他的 ...

  7. 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 ...

  8. Nearest Neighbor Search

    ## Nearest Neighbor Search ## Input file: standard input Output file: standard output Time limit: 1 ...

  9. K近邻(K Nearest Neighbor-KNN)原理讲解及实现

    算法原理 K最近邻(k-Nearest Neighbor)算法是比较简单的机器学习算法.它采用测量不同特征值之间的距离方法进行分类.它的思想很简单:如果一个样本在特征空间中的k个最近邻(最相似)的样本 ...

随机推荐

  1. 安装heat

    在控制节点上执行 controller-heat(){mysql -uroot -p${MYSQL_PASSWD} << EOF DROP DATABASE IF EXISTS heat; ...

  2. Windows Server 2019远程桌面服务配置和授权激活

    参考Windows Server 2016远程桌面服务配置和授权激活方法可适用于Windows Server 2019     Server 2016默认远程桌面连接数是2个用户,如果多余两个用户进行 ...

  3. bert系列二:《BERT》论文解读

    论文<BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding> 以下陆续介绍ber ...

  4. 【VS开发】VSTO 学习笔记(十)Office 2010 Ribbon开发

    微软的Office系列办公套件从Office 2007开始首次引入了Ribbon导航菜单模式,其将一系列相关的功能集成在一个个Ribbon中,便于集中管理.操作.这种Ribbon是高度可定制的,用户可 ...

  5. phpstorm设置的快捷键突然失效了,提示: IdeaVim ...

    下班后,打开PHPstorm,突然感觉不对,经常用的快捷键突然用不了. 例如按了 Ctrl+F 快捷键后,提示:  IdeaVim! Using the Ctrl+F shortcut for Vim ...

  6. day36 joinablequeue、多线程理论、多线程的两种使用方式、守护线程、互斥锁、死锁、递归锁、信号量

    1.joinablequeue队列 joinablequeue与queue一样,也是一种队列,其继承自queue,也有queue中的put 与get 方法,但是在joinablequeue中有自己的 ...

  7. ucloud-monitor

    创建报警模板: 可以从现有模板导入: 设定指标: #通知人管理,可以设置报警短信通知人: #给主机绑定告警模板: 勾选要绑定的主机 点设置: #选择要添加的告警模板

  8. VirtualBox本地虚拟机常见问题

    SSH连接本地虚拟机配置 https://www.jianshu.com/p/d59ed9f226d1 开启双向复制https://blog.csdn.net/wcx1293296315/articl ...

  9. winform 中如何获取debug目录的路径

    项目中需要在debug启动目录创建文件夹,所以先获取debug路径: var debugPath = System.AppDomain.CurrentDomain.BaseDirectory;

  10. Qt 4.5发布(最大的变动是换用LGPL许可证,移植进了苹果的Cocoa框架。之前的Qt只支持Carbon框架,现在的Qt 4.5两者都支持。单一源代码创建出支持32位或64位字节的Intel或PowerPC Mac二进制文件)

            Nokia的开源Qt开发工具正式发布了4.5版.如前所述,Qt 4.5最大的变动是换用LGPL许可证,目前采用的三个许可证分别为LGPL/GPL和商业许可证.           新版 ...