0
votes

I am looking to apply dot product operation on a matrix m (2,6) and a vector v(6,)

The resultant vector should be of shape (6,)

When i implement the logic in python myself, i get the above required result.. ie. a vector with size 6. However if i use np.dot(m,v) it gives same results but it removes the extra zeros

Why is this happening? Pls help. code below

def vector_matrix_multiplication_using_numpy(m, v):
    ''' 
        this is where we multiply a matrix with a vector
        remember it is important that m.shape[1] == v.shape[0]
        also m is a 2D tensor

        resultant will be a vector of the shape
        (m.shape[0])

    '''
    assert len(m.shape) == 2
    assert len(v.shape) == 1
    assert m.shape[1] == v.shape[0]

    return np.dot(m,v)





def vector_matrix_multiplication_using_python(m, v):
    ''' 
        this is where we multiply a matrix with a vector
        remember it is important that m.shape[1] == v.shape[0]
        also m is a 2D tensor

        resultant will be a vector of the shape
        (m.shape[0])

    '''
    assert len(m.shape) == 2
    assert len(v.shape) == 1
    assert m.shape[1] == v.shape[0]

    z = np.zeros((m.shape[1])).astype(np.int32)

    for i in range(m.shape[0]):
        z[i] = vector_multiplication_using_python(m[i, :],v)

    return z


    m = np.random.randint(2,6, (3,7))
    v = np.random.randint(5,17, (7))
    print(vector_matrix_multiplication_using_numpy(m,v),\
                vector_matrix_multiplication_using_python(m, v))

output is as below:

[345 313 350] [345 313 350   0   0   0   0]

EDIT:

i was incorrect. matrix with vector multiplication works as below m = (n,p) shape v = (p,) shape

resultant output is v = (n) shape this particular edit in code fixed the issue:

z = np.zeros((m.shape[0])).astype(np.int32)
1
relax! Where is this method implementation? vector_multiplication_using_pythonHaramoz

1 Answers

1
votes

When I print your example, m and v shapes are as follows: m:(3, 7) n:(7,) The numpy dot product output comes as follows:

[305 303 319]

Which is actually correct, because you see shape(3x7) dot shape(7) ==> shape(3,) shape of the output. So it is correct. There must be some thing wrong with your python implementation then. I request you to share the whole code or look into it your self. Hope it helps. Feel free to ask if you have further question. :)

Edit:

Please note, that you are doing this wrong here.

z = np.zeros((m.shape[1])).astype(np.int32)

you are assigning 7 zeros here, your output takes first three digits, rest zeros remain intact. So to answer to your question, numpy is not removing zeros, You are adding extra zeros, which is wrong!

you can do z = np.zeros((m.shape[0])).astype(np.int32) and I think that will solve the issue. :) cheers!!