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个最近邻(最相似)的样本 ...
随机推荐
- v-on可以监听多个方法吗?
原文地址 v-on可以监听多个方法 <template> <div class="about"> <button @click="mycli ...
- python3 速查参考- python基础 7 -> 函数编程之 装饰器、生成器
装饰器 1.速查笔记 #-- 函数装饰器:是它后边的函数的运行时的声明 由@符号以及后边紧跟的"元函数"(metafunction)组成 @staticmethod def sme ...
- 逻辑回归(Logistic Regression)二分类原理及python实现
本文目录: 1. sigmoid function (logistic function) 2. 逻辑回归二分类模型 3. 神经网络做二分类问题 4. python实现神经网络做二分类问题 1. si ...
- 支付宝网站即时支付开发,MD5加签名规则处理代码展示
一.如果传入进来的Object对象,最后生成制定格式的字符换 text: list拼接成字符串,map中的所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,list的元素之间用“| ...
- [CF544E]Remembering Strings_状压dp
E. Remembering Strings 题目大意: You have multiset of n strings of the same length, consisting of lowerc ...
- [转帖]【架构系列】龙芯loongson简介
[架构系列]龙芯loongson简介 https://blog.csdn.net/SoaringLee_fighting/article/details/97759305 2019年07月30日 10 ...
- Spring4学习回顾之路07- 通过工厂方法配置Bean
一:通过静态工厂配置Bean 建立Student.java package com.lql.srping04; /** * @author: lql * @date: 2019.10.28 * Des ...
- linux下安装anconda3
Liunx下安装anconda3其实特变简单,只需这几步骤 1. 首先要到网上下载一个ancoda3的安装包.然后在上传到linux上面即可 3. 是不是特别简单呢?哈哈
- 老贾的幸福生活day5 while循环 格式化 运算符 编码初识
while 循环 死循环 while 条件: print(结果) while 条件: print(结果) else: print(结果) break 终止当前循环 continue 跳出当前循环,进行 ...
- X86逆向14:常见的脱壳手法
本章节内容将介绍软件的脱壳技术.什么是加壳?加壳就是用来压缩或者保护软件不被非法修改破解的一种工具,而脱壳就是将已经加壳的程序从壳中剥离出来,既然能给程序进行加壳,那也就会有相应的脱壳方法,本节课我们 ...