【发布时间】:2020-04-17 08:44:29
【问题描述】:
我想在我的代码中找到一种避免循环的方法。我需要实现以下公式,一开始很简单:
换句话说:一个索引列表被解析为I。对于 I 中指定的每个索引,需要减去数组 x 中所有后续索引的值。对减去的值进行一些计算。总结一切。完成。
我当前的代码:
def loss(x, indices):
"""
Args:
x: array_like, dtype=float
indices: array_like, dtype=int
Example:
>>> x = np.array([0.3, 0.5, 0.2, 0.1, 1.2, 2.4, 2.8, 1.5, 3.2])
>>> indices = np.array([0, 2, 3, 6])
>>> print(loss(x, indices))
21.81621815885847
"""
total = 0.0
for index in indices:
# Broadcasting here, as all values from all following indices have
# to be subtracted from the value at the given i index.
difference = x[index] - x[index + 1:]
# Sum all up
log_addition = 1.0 + np.log(np.abs(difference))
total += np.sum(log_addition)
return total
具有挑战性的部分是 'i' 索引在输出范围内随机分布。有什么想法吗?
【问题讨论】:
标签: python numpy vectorization