Have been completely stuck on a rather silly issue: I'm trying to compute the dot product of some attributes between objects, but keep getting a Value Error - Shape Mismatch - but the shapes are identical (2,1) and (2,1), since the arrays are just attributes of different instances of the same class:
class MyClass(Object):
def __init__(self, a,b, x,y):
self.prop_1 = np.array((a,b))
self.prop_2 = np.array((x,y))
where all a, b, x, and y are scalars. then further down I'm trying
def MyFunction(Obj1, Obj2):
results = np.dot(Obj1.prop_1 - Obj2.prop_1, Obj2.prop_2 - Obj2.prop_3)
which keeps throwing the Value Error
ValueError: shapes (2,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)
Mathematically, this dot product should be fine - but the final bit of the error message kind of suggests I have to transpose one of the arrays. I'd be very thankful for a short explanation of the numpy shape interpretation to avoid this kind of error!
EDIT:
Think I misphrased this a bit. When I initiate my objects via (case a)
a,b = np.random.rand(2)
x,y = np.random.rand(2)
MyClass(a, b, x, y)
Everything works like a charm. If instead however I initiate as (case b)
a = np.random.rand(1)
b = np.random.rand(1)
x = np.random.rand(1)
y = np.random.rand(1)
MyClass(a, b, x, y)
the dot product later on fails to work because of the shape mismatch.
I have noticed that in case b, each individual value is of shape (1,) and it's clear to me that combining two of these will result in shape (2,1) instead of shape () in case a - but why do these two ways of declaring a variable result in different shapes?
As you can tell I'm relatively new to Python and thought this was just a neat way to perform multiple assignments - turns out there is some further reasoning behind it, and i'd be interested to hear about that.
np.dot(a.T, b)?np.dot(a.ravel(), b.ravel())would also work. - Quang HoangMyClassi.e. what are the values ofa,betc? Also please fix the typo ininnitand where are all theselfarguments? Ifaandbwere scalars, thenself.prop_1would have a shape of(2,)and you wouldn't have a problem. - Dandotdoes the inner, scalar product. For 2d (which you have) it does matrix product - remember the manual row with columns method? - hpaulj1,but once I combine them I end up with the shape mentioned in the question. - LoschmidtsSchnitzelnp.random.randomcreates numpy arrays. When you tried to initiate your array with other arrays you made an array of arrays. Numpy logically assumed you wanted to make a 2D array, otherwise you'd have passed in simple floats. When you wenta, b = np.random.random(2)you took advantage of unpacking to assign each element of the sequence (the array in this case) to it's own variable. This results inaandbbeing simple floats. Later when you trynp.array((a, b)), since you've passed in floats, numpy will you a 1D array. - Dan