CNN for Visual Recognition (assignment1_Q1)

参考:http://cs231n.github.io/assignment1/

Q1: k-Nearest Neighbor classifier (30 points)

  1 import numpy as np
  2 from matplotlib.cbook import todate
  3 
  4 class KNearestNeighbor:
  5   """ a kNN classifier with L2 distance """
  6 
  7   def __init__(self):
  8     pass
  9 
 10   def train(self, X, y):
 11     """
 12     Train the classifier. For k-nearest neighbors this is just 
 13     memorizing the training data.
 14 
 15     Input:
 16     X - A num_train x dimension array where each row is a training point.
 17     y - A vector of length num_train, where y[i] is the label for X[i, :]
 18     """
 19     self.X_train = X
 20     self.y_train = y
 21     
 22   def predict(self, X, k=1, num_loops=0):
 23     """
 24     Predict labels for test data using this classifier.
 25 
 26     Input:
 27     X - A num_test x dimension array where each row is a test point.
 28     k - The number of nearest neighbors that vote for predicted label
 29     num_loops - Determines which method to use to compute distances
 30                 between training points and test points.
 31 
 32     Output:
 33     y - A vector of length num_test, where y[i] is the predicted label for the
 34         test point X[i, :].
 35     """
 36     if num_loops == 0:
 37       dists = self.compute_distances_no_loops(X)
 38     elif num_loops == 1:
 39       dists = self.compute_distances_one_loop(X)
 40     elif num_loops == 2:
 41       dists = self.compute_distances_two_loops(X)
 42     else:
 43       raise ValueError('Invalid value %d for num_loops' % num_loops)
 44 
 45     return self.predict_labels(dists, k=k)
 46 
 47   def compute_distances_two_loops(self, X):
 48     """
 49     Compute the distance between each test point in X and each training point
 50     in self.X_train using a nested loop over both the training data and the 
 51     test data.
 52 
 53     Input:
 54     X - An num_test x dimension array where each row is a test point.
 55 
 56     Output:
 57     dists - A num_test x num_train array where dists[i, j] is the distance
 58             between the ith test point and the jth training point.
 59     """
 60     num_test = X.shape[0]
 61     num_train = self.X_train.shape[0]
 62     dists = np.zeros((num_test, num_train))
 63     for i in xrange(num_test):
 64       for j in xrange(num_train):
 65         #####################################################################
 66         # TODO:                                                             #
 67         # Compute the l2 distance between the ith test point and the jth    #
 68         # training point, and store the result in dists[i, j]               #
 69         #####################################################################
 70         dists[i,j] = np.sqrt(np.sum(np.square(X[i,:] - self.X_train[j,:])))
 71         #####################################################################
 72         #                       END OF YOUR CODE                            #
 73         #####################################################################
 74     return dists
 75 
 76   def compute_distances_one_loop(self, X):
 77     """
 78     Compute the distance between each test point in X and each training point
 79     in self.X_train using a single loop over the test data.
 80 
 81     Input / Output: Same as compute_distances_two_loops
 82     """
 83     num_test = X.shape[0]
 84     num_train = self.X_train.shape[0]
 85     dists = np.zeros((num_test, num_train))
 86     for i in xrange(num_test):
 87       #######################################################################
 88       # TODO:                                                               #
 89       # Compute the l2 distance between the ith test point and all training #
 90       # points, and store the result in dists[i, :].                        #
 91       #######################################################################
 92       dists[i, :] = np.sqrt(np.sum(np.square(self.X_train - X[i,:]), axis=1))
 93       #######################################################################
 94       #                         END OF YOUR CODE                            #
 95       #######################################################################
 96     return dists
 97 
 98   def compute_distances_no_loops(self, X):
 99     """
100     Compute the distance between each test point in X and each training point
101     in self.X_train using no explicit loops.
102 
103     Input / Output: Same as compute_distances_two_loops
104     """
105     num_test = X.shape[0]
106     num_train = self.X_train.shape[0]
107     dists = np.zeros((num_test, num_train)) 
108     #########################################################################
109     # TODO:                                                                 #
110     # Compute the l2 distance between all test points and all training      #
111     # points without using any explicit loops, and store the result in      #
112     # dists.                                                                #
113     # HINT: Try to formulate the l2 distance using matrix multiplication    #
114     #       and two broadcast sums.                                         #
115     #########################################################################
116     tDot = np.multiply(np.dot(X, self.X_train.T), -2)
117     t1 = np.sum(np.square(X), axis=1, keepdims=True)
118     t2 = np.sum(np.square(self.X_train), axis=1)
119     tDot = np.add(t1, tDot)
120     tDot = np.add(tDot, t2)
121     dists = np.sqrt(tDot)
122     #########################################################################
123     #                         END OF YOUR CODE                              #
124     #########################################################################
125     return dists
126 
127   def predict_labels(self, dists, k=1):
128     """
129     Given a matrix of distances between test points and training points,
130     predict a label for each test point.
131 
132     Input:
133     dists - A num_test x num_train array where dists[i, j] gives the distance
134             between the ith test point and the jth training point.
135 
136     Output:
137     y - A vector of length num_test where y[i] is the predicted label for the
138         ith test point.
139     """
140     num_test = dists.shape[0]
141     y_pred = np.zeros(num_test)
142     for i in xrange(num_test):
143       # A list of length k storing the labels of the k nearest neighbors to
144       # the ith test point.
145       closest_y = []
146       #########################################################################
147       # TODO:                                                                 #
148       # Use the distance matrix to find the k nearest neighbors of the ith    #
149       # training point, and use self.y_train to find the labels of these      #
150       # neighbors. Store these labels in closest_y.                           #
151       # Hint: Look up the function numpy.argsort.                             #
152       #########################################################################
153       # pass
154       closest_y = self.y_train[np.argsort(dists[i, :])[:k]]
155       #########################################################################
156       # TODO:                                                                 #
157       # Now that you have found the labels of the k nearest neighbors, you    #
158       # need to find the most common label in the list closest_y of labels.   #
159       # Store this label in y_pred[i]. Break ties by choosing the smaller     #
160       # label.                                                                #
161       #########################################################################
162       
163       y_pred[i] = np.argmax(np.bincount(closest_y))
164       #########################################################################
165       #                           END OF YOUR CODE                            # 
166       #########################################################################
167 
168     return y_pred

 

输出:

Two loop version took 55.817642 seconds
One loop version took 49.692089 seconds
No loop version took 1.267753 seconds

转载于:https://www.cnblogs.com/JackOne/p/4222320.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/398602.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

深度学习修炼(四)——补充知识

文章目录致谢4 补充知识4.1 微积分4.1.1 导数和微分4.1.2 偏导数4.1.3 梯度4.1.4 链式求导4.2 Hub模块致谢 导数与微分到底有什么区别? - 知乎 (zhihu.com) 4 补充知识 在这一小节的学习中,我们会对上一小节的知识点做一个补充,并且拓展一个…

java使用POI jar包读写xls文件

主要使用poi jar来操作excel文件。代码中用到的数据库表信息见ORACLE之表。使用public ArrayList<Person> getPersonAllRecords()获得所有的记录。 1 public class PersonXLS {2 3 public static void main(String[] args) throws IOException {4 5 …

U-boot 打补丁,编译,设置环境变量,

&#xff08;1&#xff09;U-boot 的最终目的是&#xff1a; 启动内核 U-boot 从Flash上读取内核&#xff0c;把内核放到SDRAM上&#xff0c;运行内核 设置环境变量 print  显示出环境变量 set bootdelay 10 save reset  重启转载于:https://www.cnblogs.com/bkyysd/p/42…

深度学习修炼(五)——基于pytorch神经网络模型进行气温预测

文章目录5 基于pytorch神经网络模型进行气温预测5.1 实现前的知识补充5.1.1 神经网络的表示5.1.2 隐藏层5.1.3 线性模型出错5.1.4 在网络中加入隐藏层5.1.5 激活函数5.1.6 小批量随机梯度下降5.2 实现的过程5.2.1 预处理5.2.2 搭建网络模型5.3 简化实现5.4 评估模型5 基于pytor…

Android 应用程序集成FaceBook 登录及二次封装

1、首先在Facebook 开发者平台注册一个账号 https://developers.facebook.com/ 开发者后台 https://developers.facebook.com/apps 2、创建账号并且获得 APP ID 图一 图二 图三 图四 图五 3、获取app签名的Key Hashes 值&#xff08;两种方式&#xff09; 3.1方法1&#xff1…

IKAnalyzer进行中文分词和去停用词

最近学习主题模型pLSA、LDA&#xff0c;就想拿来试试中文。首先就是找文本进行切词、去停用词等预处理&#xff0c;这里我找了开源工具IKAnalyzer2012&#xff0c;下载地址&#xff1a;(&#xff1a;(注意&#xff1a;这里尽量下载最新版本&#xff0c;我这里用的IKAnalyzer201…

C++从0到1的入门级教学(六)——函数

文章目录6 函数6.1 概述6.2 函数的定义6.3 函数的调用6.4 值传递6.5 函数的常见形式6.6 函数的声明6.7 函数的分文件编写6 函数 6.1 概述 作用&#xff1a;将一段经常使用的代码封装起来&#xff0c;减少重复代码。 一个较大的程序&#xff0c;一般分为若干个程序块&#xf…

PC实用手册

为什么80%的码农都做不了架构师&#xff1f;>>> ##Win10除了Edge/IE&#xff0c;其他浏览器打开和载入速度都很慢 解决办法&#xff1a;以管理员身份运行cmd&#xff0c;输入netsh winsock reset重置winsock&#xff0c;然后重启电脑即可 转载于:https://my.oschin…

MySQL之表的约束

一 介绍 约束条件与数据类型的宽度一样&#xff0c;都是可选参数 作用&#xff1a;用于保证数据的完整性和一致性主要分为&#xff1a; PRIMARY KEY (PK) 标识该字段为该表的主键&#xff0c;可以唯一的标识记录 FOREIGN KEY (FK) 标识该字段为该表的外键 NOT NULL 标…

eclipse静态部署tomcat

转载于:https://www.cnblogs.com/sprinng/p/4223798.html

jvm fastdebug

背景 RednaxelaFX 写道agapple 写道还有一个问题&#xff0c;就是在验证一些逃逸优化时&#xff0c;有些jvm参数用不了&#xff0c;比如-XX:printInlining&#xff0c;-XX:printAssembly&#xff0c;jdk用的是1.6.11和jdk1.6.18-XX:PrintInlining在product build的Sun JDK上可以…

设计模式杂谈(一)——设计模式概述

文章目录1 设计模式概述1.1 软件设计模式的产生背景1.2 软件设计模式的概念1.3 设计模式的必要性1.4 设计模式分类1 设计模式概述 1.1 软件设计模式的产生背景 设计模式最初并不是在软件设计中&#xff0c;而是被用于建筑领域的设计中。 1977年美国著名建筑大师、加利福尼亚…

hmailserver批量添加用户

2019独角兽企业重金招聘Python工程师标准>>> 将内容复制到txt文件中后缀改为vbs 将用户名密码替换为自己的 脚本内容如下: Option Explicit On Error resume nextDim obBaseApp Dim objFSO Dim objTextFile Dim strNewAlias,iDim scrreport Dim failed Dim added fa…

云说的到底对不对,京东到底行不行?

摘要&#xff1a;马云吐槽京东被引爆以来&#xff0c;似乎就没人去关注马云说的对不对&#xff0c;有没有价值&#xff0c;大家更多的是在关注马云攻击了京东&#xff0c;京东回击了马云&#xff0c;马云被偷录了&#xff0c;再和人说话要去澡堂了…但&#xff0c;马云说的到底…

JS-随机生成的密码

randPassword(size) >{ //数组 let seed new Array(A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z, a,b,c,d,e,f,g,h,i,j,k,m,n,p,Q,r,s,t,u,v,w,x,y,z, 2,3,4,5,6,7,8,9 ) //数组长度 seedlength seed.length; let creatPassword[]; for (i0;i<size;i) { j Mat…

数据库杂谈(九)——事务管理

文章目录9 事务管理9.1 恢复机制9.2 事务和日志9.2.1 事务9.2.2 运行记录的结构9.2.2.1 活动事务表9.2.2.2 提交事务表9.2.2.3 日志9.2.3 提交规则和先记后写规则9.2.3.1 提交规则9.2.3.2 先记后写规则9.3 更新策略以及故障后的恢复9 事务管理 9.1 恢复机制 数据对一个单位是…

CSS邮件相关

转载于:https://blog.51cto.com/8465917/1758775

MySql 错误 Err [Imp] 1153 - Got a packet bigger than 'max_allowed_packet' bytes

今天在用Navicat导入SQL文件时报错&#xff1a;MySql 错误 Err [Imp] 1153 - Got a packet bigger than max_allowed_packet bytes 查了一下&#xff0c;原来是MySQL默认读取执行的SQL文件最大为16M&#xff0c;我这个SQL文件260M&#xff0c;所以执行不过去 解决方法&#xff…

沙箱模式以及其使用到的IIFE

//沙箱//与外界隔绝的一个环境&#xff0c;外界无法修改该环境内任何信息&#xff0c;沙箱内的东西单独属于一个世界//360沙箱模式//将软件和操作系统进行隔离&#xff0c;以达到安全的目的//苹果手的app使用的就是沙箱模式去运行//隔离app的空间&#xff0c;每个app独立运行//…

C++从0到1的入门级教学(十)——类和对象

文章目录10 类和对象10.1 封装10.1.1 封装的意义10.1.2 struct和class的区别10.1.3 成员属性设置为私有10.2 对象的初始化和清理10.2.1 构造函数和析构函数10.2.2 构造函数的分类及调用10.2.3 关于拷贝构造函数调用时机10.2.4 构造函数调用规则10.2.5 深拷贝和浅拷贝10.2.6 初始…