【问题标题】:Why does this code use only x instead of both x and y in for loop? [closed]为什么这段代码在 for 循环中只使用 x 而不是 x 和 y? [关闭]
【发布时间】:2019-07-27 09:12:59
【问题描述】:

为什么他们只在 for 循环中使用 X 而不是 X 和 Y?为什么我们使用 1, -1 的 reshape?

# implement a loop which computes Euclidean distances between each element in X and Y
# store results in euclidean_distances_vector_l list
X = np.random.uniform( low=lower_boundary, high=upper_boundary, size=(sample_size, n) )
Y = np.random.uniform( low=lower_boundary, high=upper_boundary, size=(sample_size, n) )

for index, x in enumerate(X):
    euclidean_distances_vector_l.append(euclidean_distances(x.reshape(1, -1), Y[index].reshape(1, -1)))

【问题讨论】:

    标签: python numpy numpy-random


    【解决方案1】:

    我没有太多地使用 numpy,但这是我对你问题的最佳猜测。

    代码只遍历X 而不是XY 的原因是代码没有将X 的每个值与Y 的每个值配对。相反,它想要X 中的每个值以及Y 中的对应 值。考虑以下示例:

    X = [0, 1, 2, 3, 4]
    Y = [5, 6, 7, 8, 9]
    
    for index, x in enumerate(X):
        print(x, Y[index])
    
    # Prints:
    # 0 5
    # 1 6
    # 2 7
    # 3 8
    # 4 9
    

    就您关于reshape 的问题而言,documentation 指出任何参数中的值 -1 表示该维度的长度应从原始数组的长度推断。我的猜测是x.reshape(1, -1) 会将x 重组为一个二维数组,其中第一个维度的长度为1,第二个维度的长度只要它需要保存x 中的所有值。

    X = [1, 2, 3, 4, 5]
    X2 = X.reshape(1, -1)
    
    # The value of X2 will be:
    # [[1, 2, 3, 4, 5]]
    

    【讨论】:

      【解决方案2】:

      如果没有仔细测试,在我看来 xy zip 也可以正常工作:

      for x,y in zip(X,Y):
          euclidean_distances_vector_l.append(euclidean_distances(x.reshape(1, -1), y.reshape(1, -1)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        • 2022-12-09
        • 2010-11-05
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 2021-03-20
        相关资源
        最近更新 更多