纯Python中的Numpy Sum Axis 1
这似乎是一个奇怪的问题,但是如何用纯Python重写下一行:
np.sum(three_dim_matrix, axis=1).cumsum(axis=1)
cumsum 应该应用于二维矩阵,所以我已经可以找到 cumsum 的代码:
from itertools import accumulate
[list(accumulate(row)) for row in two_dim_matrix]
如果你真的想知道为什么我不使用 numpy,问题是 MINLP 的优化器(例如 GEKKO)不支持在 numpy 功能中定义目标函数
示例:
example = np.array([[[ 70, 110, 130],
[-50, -100, -200]],
[[300, 140, 120],
[300, 140, 120]],
[[ 400, 180, -240],
[1000, 320, 560]]])
first_step = np.sum(example, axis=1)
# [[ 20 10 -70]
# [ 600 280 240]
# [1400 500 320]]
second_step = np.cumsum(first_step, axis=1)
# [[ 20 30 -40]
# [ 600 880 1120]
# [1400 1900 2220]]
This may seem like a strange question, but how do you rewrite in pure python next line:
np.sum(three_dim_matrix, axis=1).cumsum(axis=1)
cumsum
is supposed to be applied to a two-dimensional matrix, so the code for cumsum I could already find:
from itertools import accumulate
[list(accumulate(row)) for row in two_dim_matrix]
If you're really wondering why I don't use numpy
, the problem is that optimizers for MINLP (such, GEKKO) don't support defining objective functions in numpy
features
Example:
example = np.array([[[ 70, 110, 130],
[-50, -100, -200]],
[[300, 140, 120],
[300, 140, 120]],
[[ 400, 180, -240],
[1000, 320, 560]]])
first_step = np.sum(example, axis=1)
# [[ 20 10 -70]
# [ 600 280 240]
# [1400 500 320]]
second_step = np.cumsum(first_step, axis=1)
# [[ 20 30 -40]
# [ 600 880 1120]
# [1400 1900 2220]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的示例显示的两个步骤中,
data
是输入列表:或者两个步骤组合(应该更快,因为它不构建中间列表):
在线试用!
In the two steps your example shows,
data
being the input list:Or both steps combined (should be faster, as it doesn't build intermediate lists):
Try it online!
您可以通过在正确的级别中循环到结构中解决此问题:
您还可以将所有这些组合在一个语句中,类似于凯利·邦迪(Kelly Bundy)的答案,通过将积聚在中间矩阵的行上累积,而无需实际构建中间矩阵:
You can solve this by looping into the structure at just the right level:
You can also combine all this in one statement, similarly to Kelly Bundy's answer, by calling accumulate right on the rows of the intermediate matrix without actually building the intermediate matrix:
回到原始问题,可以使用Minlp求解器(例如Gekko)使用大多数Numpy功能。这是使用3D矩阵的示例。定义目标函数时,只需分别包含每个项即可。
这是MINLP(混合整数非线性编程)求解器
apopt
的解决方案。Getting back to the original problem, it is okay to use most Numpy functions with MINLP solvers such as Gekko. Here is an example that uses a 3D matrix. When defining the objective function, just include each term separately.
This is the solution with MINLP (Mixed Integer Nonlinear Programming) solver
APOPT
.