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

第一个作业的第一个问题,写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() # 显示

(3)np.random.choice(x,x,x):

可以从一个int数字或1维array里随机选取内容,并将选取结果放入n维array中返回。
>>> np.random.choice(5, 3)
array([0, 3, 4])

>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])

>>> np.random.choice(5, 3, replace=False)
array([3,1,0])

>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([2, 3, 0])

>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']

>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],

# 参数意思分别 是从a 中以概率P,随机选择3个, p没有指定的时候相当于是一致的分布
a1 = np.random.choice(a=5, size=3, replace=False, p=None)
print(a1)
# 非一致的分布,会以多少的概率提出来
a2 = np.random.choice(a=5, size=3, replace=False, p=[0.2, 0.1, 0.3, 0.4, 0.0])
print(a2)
# replacement 代表的意思是抽样之后还放不放回去,如果是False的话,那么出来的三个数都不一样,如果是
True的话, 有可能会出现重复的,因为前面的抽的放回去了。

猜你喜欢

转载自blog.csdn.net/a417197457/article/details/80806135