编写k_nearest_neighbor.py这个utils文件:
import numpy as np
class KNearestNeighbor(object):
def __init__(self):
pass
def train(self, X, y):
Train the classifier.
def predict(self, X, k=1, num_loops=0):
Predict labels for test data using this classifier.
return ...
def time_function(f, *args):
"""
Call a function f with args and return the time (in seconds) that it took to execute.
"""
import time
tic = time.time()
f(*args)
toc = time.time()
return toc - tic
import Matplotlib.pyplot as plt
plt.imshow(X)
plt.show()
其中,X的shape:(n,m) 或者(n,m,3) 或者(n,m,4)
第二种情况下,可以是float(在0.0和1.0之间,其实就是int/255)或者int(0到255之间)。
>>> x = np.arange(-2, 3)
>>> x
array([-2, -1, 0, 1, 2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
>>>d = np.array([1,2,3,4,4,3,5,3,6])
>>>haa = np.flatnonzero(d == 3)
>>>print(haa)
array([2 5 7])
返回数组a中非零元素的索引值数组。
>>>a = np.array([[0,0,3],[0,0,0],[0,0,9]])
>>>b = np.nonzero(a)
>>>print(b)
(array([0, 2]), array([2, 2]))
>>>print(np.transpose(b))
array([[0, 2],
[2, 2]])
说明:
numpy.where() 有两种用法:
>>> aa = np.arange(10)
>>> np.where(aa,1,-1)
array([-1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # 0为False,所以第一个输出-1
>>> np.where(aa > 5,1,-1)
array([-1, -1, -1, -1, -1, -1, 1, 1, 1, 1])
>>> np.where([[True,False], [True,True]], # 官网上的例子
[[1,2], [3,4]],
[[9,8], [7,6]])
array([[1, 8],
[3, 4]])
>>> a = np.array([2,4,6,8,10])
>>> np.where(a > 5) # 返回索引
(array([2, 3, 4]),)
>>> a[np.where(a > 5)] # 等价于 a[a>5]
array([ 6, 8, 10])
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
上面这个例子条件中[[0,1],[1,0]]### 的真值为两个1,各自的第一维坐标为[0,1]### ,第二维坐标为[1,0]### 。
>>> b = (1,2)
>>> np.array(b)
array([1, 2])
>>> b = (np.array([1,2]),np.array([3,4]))
>>> np.array(b) #把最外层的tuple换成array
array([[1, 2],
[3, 4]])
>>> np.transpose(b)
array([[1, 3],
[2, 4]])
>>> b2 = np.array([1,2])
>>> tuple(b2)
(1, 2)
>>> b2 = np.array([[1,2],[3,4],[5,6]])
>>> tuple(b2) #把最外层的array去掉,换成tuple表达形式
(array([1, 2]), array([3, 4]), array([5, 6]))
>>> b = [1,2]
>>> np.array(b)
array([1, 2])
>>> b2 = np.array([[1,2],[3,4],[5,6]])
>>> [b2] #直接添加为新的list一部分,没有转换的意思
[array([[1, 2],
[3, 4],
[5, 6]])]
>>> list(b2) #将最外层的array去掉,换成list表达形式
[array([1, 2]), array([3, 4]), array([5, 6])]
>>>
>>> b
[1, 2]
>>> tuple(b)
(1, 2)
>>> list(tuple(b))
[1, 2]
>>>
>>> a = np.array([1,2,3])
>>> a.shape
(3,) #一维矩阵
>>> b = np.array([[1,2,3]])
>>> b.shape
(1, 3) #二维矩阵
>>> c = np.array([[[1,2,3]]])
>>> c.shape
(1, 1, 3) #三维矩阵
#Mlliu/CS231n/Assignment1