Python中的双重总和

时间:2015-10-27 08:56:38

标签: python numpy sum

我现在正在使用BFGS算法进行编程,我需要创建一个带有doulbe总和的函数。我需要返回 FUNCTION 而不是数字,因此sum+=之类的内容是不可接受的。

def func(X,W):
    return a function of double sum of X, W  

一个说明性的例子:

X = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4],[5,5,5,5]])  
W = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])

我想获得一个函数,对于X[i]中的每个实例X,以及W[j]中的每个W,都会返回numpy.dot(X[i],W[j])之和的函数1}}。例如,X[1]W[2]应为2*3+2*3+2*3+2*3

----------这个竞争由我编辑:-------------

当我看到下面提供的答案时,我认为我的问题不够明确。实际上,我想要一个功能:

Func = X[0]W[0]+X[0]W[1]+X[0]W[2]+ X[1]W[0]+X[1]W[1]+X[1]W[2]+ 
X[2]W[0]+X[2]W[1]+X[2]W[2]+ X[3]W[0]+X[3]W[1]+X[3]W[2] + 
X[4]W[0]+X[4]W[1]+X[4]W[2]

-------------------结束编辑后的内容--------------

如果我只有W的一个维度,那么使用numpy.sum(X,W)就可以轻松解决问题。

但是,如何用Python返回两个和的函数?

3 个答案:

答案 0 :(得分:1)

如果我的问题是正确的,那么这应该完全符合您的要求(python-2.7):

always @(posedge clk) begin
  case (p_s)
    ...
    s3: begin
      if (shifted2 < z) begin
        z <= z - shifted2; 

        // Note that As, Bs... are all dependent on fx which in turn is dependent on As, Bs... so one of these NEEDS to be stored in a register to break the combinational loop
        As <= fx;
        Bs <= fx >>> 1;
        Cs <= fx >>> 3;
        Ds <= fx >>> 6;
        Es <= fx >>> 7;

        // If you want Fsx and test to match, you must have them both update at the same time, before you had Fsx getting its value from the sum of the values of As, Bs... that were just generated while test would get the value from the sum of the previous values of As, Bs...
        Fsx <= fx;
        test <= fxw;
      end
      shifted2 <= shifted2 >>> 1;
      n_s <= s4; // You had 4, but I assume this should be s4
    end
    ...
  endcase
end

// Note, you could use an assign for this, but just to illustrate the point
always @(*) begin
  fx = 0; // Need a value for fx when state ISNT s3 or s4, this is combinational logic after all
  if ((p_s == s3) || (p_s == s4)) begin
    fx = As + Bs + Cs + Ds + Es;
  end
end

只需将sample_main函数替换为带有X和W的函数。

答案 1 :(得分:1)

如果要返回函数f(i,j) - > X [i] .W [j]:

def func(X,W):
    def f(i,j): return np.dot(X[i],W[j])
    return f

会奏效。

修改

您在编辑中命名为Func VALUE sum([np.dot(x,w) for x in X for w in W])计算,或者效率更高,np.einsum('ij,kj->',X,W)。 如果你想返回返回Func FUNCTION ,你可以这样做:

def func(X,W):
    Func=np.einsum('ij,kj->',X,W)
    return lambda : Func

然后f=func(X,W); print(f())会在您的示例中打印360,名为Func的值。

答案 2 :(得分:0)

实际上,我想在我的Python代码中实现L_BFGS算法。灵感来自@ B.M提供的两个答案。和@siebenschlaefer,我想出了如何在我的代码中实现:

func =  np.sum(np.sum(log_p_y_xz(Y[i][t], Z[i], sigma_eta_ti(X[i],w[t],gamma[t]))+log_p_z_x(alpha, beta, X[i]) for t in range(3)) for i in range (5))    

请不要介意公式的详细信息,我想说的是,我在这里使用了两个sum,只使用i in rage (5)t in range (3)告诉代码执行和。

再次感谢@ B.M提供的答案。和@siebenschlaefer !!