码迷,mamicode.com
首页 > 编程语言 > 详细

cs231n(一) KNN 和一些python numpy 函数

时间:2016-05-10 23:27:54      阅读:3780      评论:0      收藏:0      [点我收藏+]

标签:

 

 

第一个作业的第一个问题,写KNN分类器,KNN的原理本身描述起来还是比较简单,

用到的一些函数:

(1)numpy.flatnonzero():

该函数输入一个矩阵,返回扁平化后矩阵中非零元素的位置(index)

这是官方文档给出的用法,非常正规,输入一个矩阵,返回了其中非零元素的位置

1 >>> x = np.arange(-2, 3)
2 >>> x
3 array([-2, -1,  0,  1,  2])
4 >>> np.flatnonzero(x)
5 array([0, 1, 3, 4])

这是在作业中给出的用法:不走寻常路,用来返回某个特定元素的位置

对向量元素的判断d==3返回了一个和向量等长的由0/1组成的矩阵,然后调用函数,返回的位置,就是对应要找的元素的位置。

d = np.array([1,2,3,4,4,3,5,3,6])
haa = np.flatnonzero(d == 3)
print haa

(2)matplotlib.pyplot.subplot(XXX):

该函数输入量为三个整数比如subplot(211),这样并不是很清楚,可以写成subplot(2,1,1)前两个数表示子图组成的矩阵的行列数,比如有6个子图,排列成3行2列,那就是subplot(3,2,X)。最后一个数表示要画第X个图了。作业中的用法:

# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
classes = [plane, car, bird, cat, deer, dog, frog, horse, ship, truck] #类别列表
num_classes = len(classes) #类别数目
samples_per_class = 7 # 每个类别采样个数
for y, cls in enumerate(classes): # 对列表的元素位置和元素进行循环,y表示元素位置(0,num_class),cls元素本身‘plane‘等
    idxs = np.flatnonzero(y_train == y) #找出标签中y类的位置
    idxs = np.random.choice(idxs, samples_per_class, replace=False) #从中选出我们所需的7个样本
    for i, idx in enumerate(idxs): #对所选的样本的位置和样本所对应的图片在训练集中的位置进行循环
        plt_idx = i * num_classes + y + 1 # 在子图中所占位置的计算
        plt.subplot(samples_per_class, num_classes, plt_idx) # 说明要画的子图的编号
        plt.imshow(X_train[idx].astype(uint8)) # 画图
        plt.axis(off)
        if i == 0:
            plt.title(cls) # 写上标题,也就是类别名
plt.show() # 显示

 

cs231n(一) KNN 和一些python numpy 函数

标签:

原文地址:http://www.cnblogs.com/lijiajun/p/5479523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!