【问题标题】:Formula that maps the index of a numpy array to the corresponding index in the flattened vector?将numpy数组的索引映射到展平向量中的相应索引的公式?
【发布时间】:2021-07-27 12:40:12
【问题描述】:

如题,将numpy数组的索引映射到展平向量中对应索引的公式是什么?

作为一个具体的例子:

np.random.seed(2021)
X = np.random.normal(size=(5,4,3))
x = X.flatten(order='C')
ix = (1,2,2)

计算索引i 以使x[i] 返回与X[ix] 相同的值的公式是什么?理想情况下,同样的公式也适用于高阶张量。

【问题讨论】:

  • numpy.ravel_multi_index 这样做

标签: python arrays numpy tensor


【解决方案1】:

您可以创建一个函数,根据X 中的值的相对位置重新调整部分索引购买将数组和行数与ix 中的值相乘

def calculate_index(x, i):
    return x[0].size * i

np.random.seed(2021)
X = np.random.normal(size=(5, 4, 3))
x = X.flatten(order='C')
x[calculate_index(X, ix[0]) + calculate_index(X[0], ix[1]) + ix[2]]

X, ix[0] 将根据列表的数量 (5) 给出相对索引。

X[0], ix[1]) 将根据列表 (4) 中的行数给出相对索引。

ix[2] 将给出行的相对索引。

ix = (1, 2, 2)
print(X[ix])
# -0.720158835135297
print(x[calculate_index(X, ix[0]) + calculate_index(X[0], ix[1]) + ix[2]])
# -0.720158835135297


ix = (3, 3, 0)
print(X[ix])
# 1.2242357215843627
print(x[calculate_index(X, ix[0]) + calculate_index(X[0], ix[1]) + ix[2]])
# 1.2242357215843627

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2019-03-31
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    相关资源
    最近更新 更多