首页 > 解决方案 > 在多次运行的范围内选择轨迹中的最后一个点

问题描述

更新:进一步简化了问题:我有一个 2d 矩阵m和一个 predicate p。如何在不遍历行和列的情况下提取m满足谓词的每一行中的最后一个元素?p

import numpy as np

m = np.array([[0.1, 0.2, 1.1, 1.2], [0.1, 1.5, 0.9, 1.6], [2, 3, 4, 5]])

idxs = np.full((3,), np.nan)
values = np.full((3,), np.nan)
for i in range(3):
  for j in reversed(range(4)):
    if 0 <= m[i, j] <= 1:
      idxs[i] = j
      values[i] = m[i, j]
      break

print(f'idxs: {idxs}')
print(f'values: {values}')

输出

idxs: [ 1. 2. nan]
values: [0.2 0.9 nan]

原始问题:我有运行多个优化的 GPU 代码沿多维曲面运行。它返回给我两个 Numpy 数组:

我需要限制xs在某个区域并忽略它之外的点;从每个轨迹中选择xs仍在区域内的最后一个点;然后最终得到y这些最后点和对应的最大值x。我将这段代码简化为下面的代码,但我希望应该有一些方法可以对其进行矢量化。

有什么建议么?

# Demo of non-vectorized approach
import numpy as np

linears = np.linspace(0, 10, num=11)
sins = np.sin(linears)
exps = np.exp(linears)
xs = np.stack([sins, 0.5 * exps, 0.5 + 0.4 * sins], axis=1)
ys = np.stack([linears] * 3, axis = 1)
print(f'xs: {xs}')
print(f'ys: {ys}')

last_x_within = np.full((3,), np.nan)
last_y_within = np.full((3,), np.nan)
for run_idx in range(3):
  for traj_idx in reversed(range(11)):
    x = xs[traj_idx, run_idx]
    if x >= 0 and x <= 1:
      last_x_within[run_idx] = x
      last_y_within[run_idx] = ys[traj_idx, run_idx]
      break
best_run = np.argmax(last_y_within)
best_x = last_x_within[best_run]

print(f'last_x_within: {last_x_within}')
print(f'last_y_within: {last_y_within}')
print(f'Best: x {best_x}, run {best_run}')

标签: pythonnumpy

解决方案


推荐阅读