纯Python中的Numpy Sum Axis 1

发布于 2025-01-20 09:19:35 字数 942 浏览 2 评论 0原文

这似乎是一个奇怪的问题,但是如何用纯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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡忘如思 2025-01-27 09:19:36

在您的示例显示的两个步骤中,data 是输入列表:

first_step = [list(map(sum, zip(*rows))) for rows in data]
second_step = [list(accumulate(row)) for row in first_step]

或者两个步骤组合(应该更快,因为它不构建中间列表):

both_steps = [list(accumulate(map(sum, zip(*rows)))) for rows in data]

在线试用!

In the two steps your example shows, data being the input list:

first_step = [list(map(sum, zip(*rows))) for rows in data]
second_step = [list(accumulate(row)) for row in first_step]

Or both steps combined (should be faster, as it doesn't build intermediate lists):

both_steps = [list(accumulate(map(sum, zip(*rows)))) for rows in data]

Try it online!

╭⌒浅淡时光〆 2025-01-27 09:19:36

您可以通过在正确的级别中循环到结构中解决此问题:

first_step = [
    [sum(col) for col in zip(*m)]
    for m in example
]

second_step = [list(accumulate(row)) for row in first_step]

您还可以将所有这些组合在一个语句中,类似于凯利·邦迪(Kelly Bundy)的答案,通过将积聚在中间矩阵的行上累积,而无需实际构建中间矩阵:

combined = [
    list(accumulate(sum(col) for col in zip(*m)))
    for m in example
]

You can solve this by looping into the structure at just the right level:

first_step = [
    [sum(col) for col in zip(*m)]
    for m in example
]

second_step = [list(accumulate(row)) for row in first_step]

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:

combined = [
    list(accumulate(sum(col) for col in zip(*m)))
    for m in example
]
兮颜 2025-01-27 09:19:36

回到原始问题,可以使用Minlp求解器(例如Gekko)使用大多数Numpy功能。这是使用3D矩阵的示例。定义目标函数时,只需分别包含每个项即可。

from gekko import GEKKO
import numpy as np
m = GEKKO()            
three_dim_matrix = m.Array(m.Var,(2,2,3),lb=0,ub=1)
f = np.sum(three_dim_matrix, axis=1).cumsum(axis=1)
g = f.flatten()
[m.Minimize(gi) for gi in g]
m.options.SOLVER=1
m.solve()
print(three_dim_matrix)

这是MINLP(混合整数非线性编程)求解器apopt的解决方案。

 --------- APM Model Size ------------
 Each time step contains
   Objects      :            0
   Constants    :            0
   Variables    :           12
   Intermediates:            0
   Connections  :            0
   Equations    :            6
   Residuals    :            6
 
 Number of state variables:             12
 Number of total equations: -            0
 Number of slack variables: -            0
 ---------------------------------------
 Degrees of freedom       :             12
 
 ----------------------------------------------
 Steady State Optimization with APOPT Solver
 ----------------------------------------------
    1  0.00000E+00  0.00000E+00
 Successful solution
 
 ---------------------------------------------------
 Solver         :  APOPT (v1.0)
 Solution time  :   1.520000002346933E-002 sec
 Objective      :   0.000000000000000E+000
 Successful solution
 ---------------------------------------------------
 
[[[[0.0] [0.0] [0.0]]
  [[0.0] [0.0] [0.0]]]

 [[[0.0] [0.0] [0.0]]
  [[0.0] [0.0] [0.0]]]]

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.

from gekko import GEKKO
import numpy as np
m = GEKKO()            
three_dim_matrix = m.Array(m.Var,(2,2,3),lb=0,ub=1)
f = np.sum(three_dim_matrix, axis=1).cumsum(axis=1)
g = f.flatten()
[m.Minimize(gi) for gi in g]
m.options.SOLVER=1
m.solve()
print(three_dim_matrix)

This is the solution with MINLP (Mixed Integer Nonlinear Programming) solver APOPT.

 --------- APM Model Size ------------
 Each time step contains
   Objects      :            0
   Constants    :            0
   Variables    :           12
   Intermediates:            0
   Connections  :            0
   Equations    :            6
   Residuals    :            6
 
 Number of state variables:             12
 Number of total equations: -            0
 Number of slack variables: -            0
 ---------------------------------------
 Degrees of freedom       :             12
 
 ----------------------------------------------
 Steady State Optimization with APOPT Solver
 ----------------------------------------------
    1  0.00000E+00  0.00000E+00
 Successful solution
 
 ---------------------------------------------------
 Solver         :  APOPT (v1.0)
 Solution time  :   1.520000002346933E-002 sec
 Objective      :   0.000000000000000E+000
 Successful solution
 ---------------------------------------------------
 
[[[[0.0] [0.0] [0.0]]
  [[0.0] [0.0] [0.0]]]

 [[[0.0] [0.0] [0.0]]
  [[0.0] [0.0] [0.0]]]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文