python - 为什么这段代码在 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)))
解决方案
我没有太多使用 numpy ,但这是我对您问题的最佳猜测。
代码仅迭代X
而不是X
and Y
both 的原因是因为代码没有将 的每个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]]
推荐阅读
- c# - 在 Startup.cs 中运行迁移不适用于使用 WebApplicationFactory 的测试
- wordpress - wordpress & twitch-条件 & Twitch 状态
- swift - SwiftUI - TabView 与视图重叠
- android - 特定日期和月份的Android xamarin本地通知
- react-native - 使用 react-native-calendars 在每个日期渲染图像
- python - 将框架从原始窗口更改为另一个
- tensorflow - Tensorflow Object-API:将 ssd 模型转换为 tflite 并在 python 中使用
- android - 1 Activity/Multiple Fragments方法:为不同的Fragment设置不同的主题
- html - Apps 脚本:获取输入到 Web 应用程序中的 html 表单值
- pyfpdf - pyfpdf multicell中的行距非常大