首页 > 解决方案 > 为什么这段代码在 for 循环中只使用 x 而不是 x 和 y?

问题描述

为什么他们只在 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)))

标签: pythonnumpynumpy-random

解决方案


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

代码仅迭代X而不是Xand Yboth 的原因是因为代码没有将 的每个X值与 . 的每个值配对Y。相反,它希望 in 中的每个值X及其对应的值 in 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文档指出任何参数中的值 -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]]

推荐阅读