首页 > 解决方案 > 替换嵌套循环

问题描述

我刚从 Python 开始,我无法理解我应该如何实现以下目标(我是一名 Java 程序员)。

这是初始代码:

  def compute_distances_two_loops(self, X):
    """
    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.
    """

    num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train))

    for i in range(num_test):
      for j in range(num_train):
        #####################################################################
        # TODO:                                                             #
        # Compute the l2 distance between the ith test point and the jth    #
        # training point, and store the result in dists[i, j]. You should   #
        # not use a loop over dimension.                                    #
        #####################################################################
        dists[i, j] = np.sum(np.square(X[i] - self.X_train[j]))
        #####################################################################
        #                       END OF YOUR CODE                            #
        #####################################################################
    return dists

这是一段代码,它应该有一个更少的嵌套循环,同时仍然输出相同的数组:

  def compute_distances_one_loop(self, X):
    """
    Compute the distance between each test point in X and each training point
    in self.X_train using a single loop over the test data.

    Input / Output: Same as compute_distances_two_loops
    """
    num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train))

    for i in range(num_test):
      tmp = '%s %d' % ("\nfor i:", i)
      print(tmp)

      print(X[i])
      print("end of X[i]")
      print(self.X_train[:]) # all the thing [[ ... ... ]]
      print(": before, i after")
      print(self.X_train[i]) # just a row
      print(self.X_train[i, :])

      #######################################################################
      # TODO:                                                               #
      # Compute the l2 distance between the ith test point and all training #
      # points, and store the result in dists[i, :].                        #
      #######################################################################
      dists[i, :] = np.sum(np.square(X[i] - self.X_train[i, :]))
      print(dists[i])
      #######################################################################
      #                         END OF YOUR CODE                            #
      #######################################################################
    return dists

似乎应该对我有所帮助,但我仍然无法弄清楚。

您可以看到,我的缺陷之一是我对“:”的确切工作原理缺乏了解。

我花了几个小时试图弄清楚这件事,但似乎我真的缺乏一些核心知识。任何人都可以帮助我吗?这个练习是为斯坦福的视觉识别课程准备的:这是第一个作业,但这不是我真正的家庭作业,因为我自己做这门课只是为了娱乐。

目前,我的一段代码输出 的对角线的正确值two_loops,但适用于整行。我不明白我应该如何将:fromdists[i, :]- self.X_train[i, :]零件同步。如何计算 X[i] 减去遍历整个 self.X_train 的迭代?

注意num_test是 500x3072 和num_train5000x3072。3072 来自 32x32x3,它们是 32x32 图片的 RGB 值。是一个 500x5000 矩阵,映射 的第 i 个元素和 的第 j 个元素dists[i,j]之间的 L2 距离。num_testnum_train

标签: pythonpython-3.xnumpymachine-learning

解决方案


def compute_distances_one_loop(self, X):
    """
    Compute the distance between each test point in X and each training point
    in self.X_train using a single loop over the test data.

    Input / Output: Same as compute_distances_two_loops
    """
    num_test = X.shape[0]
    num_train = self.X_train.shape[0]
    dists = np.zeros((num_test, num_train))

    for i in range(num_test):
      tmp = '%s %d' % ("\nfor i:", i)
      print(tmp)

      #######################################################################
      # TODO:                                                               #
      # Compute the l2 distance between the ith test point and all training #
      # points, and store the result in dists[i, :].                        #
      #######################################################################
      dists[i] = np.sum(np.square(X[i] - self.X_train), axis=1)
      print(dists[i])
      #######################################################################
      #                         END OF YOUR CODE                            #
      #######################################################################
    return dists

在循环中使用 self.X_train 删除打印,因为长度不同。(IndexOutOfRangeException) 我不确定这是否正在删除第二个循环,但它是一个可行的解决方案。

另一个评论,我认为你对欧几里德距离公式有误。你最后错过了 sqrt。


推荐阅读