zoukankan      html  css  js  c++  java
  • output operand requires a reduction, but reduction is not enabled

    http://stackoverflow.com/questions/11625412/add-a-vector-to-array

    A really stupid question, but I could not figure the right way..

    1. A is a 2 by 2 matrix, and B is a 2 by 1 matrix.
    2. In a 10 iterations loop, B_new=A*B. B_new is 2 by 1.
    3. Save B_new to an output matrix B_final after each iteration. So in the end, B_final is 2 by 10.

    However, I have problem of adding B to B_new in a loop. Below is my code, can anyone give me some suggestions?

    import numpy as np
    a=np.ones(shape=(2,2))
    b=np.ones(shape=(2,1))     
    c_final=np.zeros(shape=(2,10))for i in range(0,10):
        c=np.dot(a,b)
        b=c
        c_final[:,i]=c

    Here is the error message:

        c_final[:,i]=c
    ValueError: output operand requires a reduction, but reduction isnot enabled



    The error you're seeing is because when numpy broadcasts c_final[:,i] and np.dot(a,b)together it produces an array with shape (2,2), which then can't be assigned to c_final[:,i]since it has a shape of (2,1). I think it's much clearer if you just play around with it in the interpreter:

    >>>import numpy as np
    >>> a = np.ones((2,2))>>> b = np.ones((2,1))>>> c_final = np.zeros((2,10))>>> np.dot(a,b)
    array([[2.],[2.]])>>> np.dot(a,b).shape
    (2,1)>>> c_final[:,0]
    array([0.,0.])>>> c_final[:,0].shape
    (2,)>>> np.broadcast(c_final[:,0],np.dot(a,b)).shape
    (2,2)

    The way around this is to flatten np.dot(a,b) by using np.squeeze or something similar so that when they are broadcast together they produce a 2 element array. For example:

    >>> c_final[:,0]= np.dot(a,b).squeeze()

    You're not alone in finding the error message unhelpful. Someone filed a ticket about this about a year ago.

  • 相关阅读:
    leetcode 437. 路径总和 III
    leetcode 113. 路径总和 II
    题解 【CF387B】George and Round
    题解 【CF489B】 BerSU Ball
    题解【2.23考试T3】val
    题解【2.23考试T1】div
    题解 【洛谷P4290】 [HAOI2008]玩具取名
    题解 【洛谷P1035】[NOIP2002]级数求和
    题解【洛谷P1046】[NOIP2005] 陶陶摘苹果
    题解【洛谷P1618】 三连击(升级版)
  • 原文地址:https://www.cnblogs.com/jilichuan/p/3012349.html
Copyright © 2011-2022 走看看