深度学习cs231n之knn学习的一些记录(1)

很糟糕, 这篇文章本来应该在周二晚上就发布的,但是我在周3早上又写了一篇,导致对周二晚上的那篇产生了覆盖。这里就当复习一遍。

首先是需要下载数据集,下载到cs231n里面。数据下载地址

下载之后,放到对应的位置。就可以看一下图片是怎么样的。

完成之后,进行一个reshape的操作, 把四维张量转换为2维矩阵。
4维张量为(5000*32*32*3)5000张图片,每个图片大小为32*32,因为每个像素有三种颜色。所以乘以3.
reshape之后的训练集的大小为5000*3072
这里面有很重要的一段在knn.ipynb box7里面。

open cs231n/classifiers/k_nearest_neighbor.py and implement compute_distances_two_loops.

knn.ipynb box7 直接对compute_distances_two_loops 进行了调用。这里我先完成一下compute_distances_two_loops 函数。

compute the distance between each test point in X and each training point in self.X_train using a nested loop over both the training data and the test data
Inputs:
- X: A numpy array of shape(num_test, D) containing test data.
Returns:
- dists: A numpy array of shape(num_test, num_train) where dists[i, j]
is the Euclidean distance between the ith test point and the jth training point.

上面的要求大概就是让写一个函数,计算每一个X里面的test point 到每一个X_train point 的距离通过嵌套循环training_data 和 the test data。
这里的输入就是一个numpy array. 包含测试数据。
输出也是一个numpy array. shape 是(num_test, num_train) .而且每一个[i, j]的位置都是ith test 点和jth train点的欧式距离。

def compute_distances_two_loops(self, X):
	num_test = X.shape[0]   # 这里传入的X是待测试的数据集。这里取行数。总共500个测试图片。
	num_train = self.X_train.shape[0]   #具体到这里, self.X_train 是训练数据集。def train里面已经定义了。self.X_train = X。 这里同样取行数。总共5000个训练图片
	dists = np.zeros((num_test, num_train))    # 这里是创建一个零阶矩阵, shape是(num_test, num_train) 也就是(500, 5000)
	for i in range(num_test):
		for j in range(num_train):
			dists[i][j] = sum((X[i] - self.X_train[j]) ** 2)**0.5 
			# 这里是求欧式距离sqrt((x[0] - x1[0])**2 + (x[1] - x1[1]) ** 2....)		
			#这里还有一种numpy 的解法。
			# dists[i][j] = np.linalg.norm(X[i] - self.X_train[j])
	return dists

np.linalg.norm 使用方法。

x_norm=np.linalg.norm(x, ord=None, axis=None, keepdims=False)

linalg = linear(线性)+ algebra(代数), norm 则表示范数。
其中x 表示矩阵(可以是一维的)
ord 范数类型

这里只需要我们自己把两个点之间的差值算出来, np.linalg.norm 会自动帮我们算出来结果。

def 

猜你喜欢

转载自blog.csdn.net/funnyPython/article/details/82845865