python - 在多次运行的范围内选择轨迹中的最后一个点
问题描述
更新:进一步简化了问题:我有一个 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
(optimization_steps, run_count, x_dimension)
包含函数参数轨迹的形状ys
(optimization_steps, run_count)
包含相应函数值轨迹的形状
我需要限制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}')
解决方案
推荐阅读
- python - Python 和 TensorFlow 中的产品匹配
- c# - 如果与表有多个关系,则命名父实体关系 - 实体数据模型 - ADO.Net
- amazon-web-services - 使用 cloudformation 从 eks 集群在 aws 中创建 OIDC 提供程序
- shell - 如何将参数传递给 shell 脚本
- kotlin - Kotlin Coroutine Flow:如何从流中获取第一项(即文件元数据)并将其余项作为内容流传递?
- go - 如何使用 postman multipart/form-data 传递和解析嵌套对象
- snowplow - 架构:与正则表达式模式不匹配
- amazon-web-services - 如何通过 kubectl 连接在私有 PVC 上运行的 AWS RDS 数据库实例
- javascript - 在位置 0 的 json 中发送表单 -unexpected token 时出错
- caching - Outlook 加载项缓存