问题
This is the error I am getting:
File "/data/eduardoj/linear.py", line 305, in _fit_model
de_dl = (dl_dt + de_dt) * dt_dl
File "/data/eduardoj/MSc-env/lib/python3.4/site-packages/numpy/matrixlib/defmatrix.py", line 343, in __mul__
return N.dot(self, asmatrix(other))
ValueError: shapes (1,53097) and (1,53097) not aligned: 53097 (dim 1) != 1 (dim 0)
And this is the piece of code of numpy where it is crashing:
340 def __mul__(self, other):
>* 341 if isinstance(other, (N.ndarray, list, tuple)) :
342 # This promotes 1-D vectors to row vectors
343 return N.dot(self, asmatrix(other))
344 if isscalar(other) or not hasattr(other, '__rmul__') :
345 return N.dot(self, other)
346 return NotImplemented
(There is a break point there >*
)
In my script I have a loop containing the following line:
de_dl = (dloss_dt + dr_dt) * dt_dl
The expected types and shapes for de_dl
, dloss_dt
, dr_dt
and dt_dl
are:
ndarray float32 (1, 53097)
So, I just want to compute the element-wise multiplication. I am using pudb3 for debugging my script. I checked that in the first iteration (i == 0
) it works great (initially producing zeros). I notice that for this first iteration the thread did NOT reach the break-point I set. In the next iteration (i==1
), I decided to stopped right before to calling the multiplication just to make sure the type and shape of dloss_dt
, dr_dt
and dt_dl
were the still the same. They were.
Though they were the same, it seems that the program went through a different set of steps and some how ended in this N.dot
multiplication.
So, I am asking for any clue of what might be keeping me from operating just a simple element-wise multiplication.
回答1:
The snippet of numpy source code you showed in your question corresponds to the __mul__ method of np.matrixlib.defmatrix.matrix.
This method gets called when you right-multiply a matrix object with another matrix or array, i.e. A * B
is equivalent to A.__mul__(B)
if A
is a matrix (it doesn't matter whether B
is an ndarray or matrix).
The only way that method could possibly be called is if (dl_dt + de_dt)
is a matrix (or some other derived matrix class) rather than an ndarray. Therefore, either dl_dt
or de_dt
is being cast to a matrix somewhere in your code.
Since __mul__
is not called on the first iteration, this must occur somewhere after line 305 in your code (de_dl = (dl_dt + de_dt) * dt_dl
).
来源:https://stackoverflow.com/questions/35117660/numpy-ndarray-multiplication-switching-to-matrix-multiplication