-2

I'm new in python and I'm trying to do the multiplication of a 2d matrix with a 1d one. I use np.dot to do it but it gives me a wrong output. I'm trying to do this:

#X_train.shape = 60000
w = np.zeros([784, 1])
lista = range (0, len(X_train))
for i in lista:
    score = np.dot(X_train[i,:], w)
print score.shape

Out-> (1L,)

the output should be (60000,1)

Any idea of how I can resolve the problem?

jasmin
  • 19
  • 5
  • 1) The [dot product](https://en.wikipedia.org/wiki/Dot_product) is not an element wise multiplication of two arrays, which would be achieved by X*Y. 2) In the loop you overwrite score every time, only the last one is returned. 3) Why multiplication with w in the first place, when all of its elements are zero? This makes all products zero as well. Maybe a sample input with small n and sample output makes it more accessible, what you try to achieve. – Mr. T Feb 22 '18 at 11:39
  • i put here just a part of code.w is going to change in base of some if condition and even if i put the print under the score it prints 60000 times the same result (1L,). When i do the multiplication with dot product outside of for it works. Anyway i will see more carefully the dot product. Thanks – jasmin Feb 22 '18 at 11:54
  • I'm afraid that your intentions are not clear. Could you maybe provide some more details? – Chris Feb 22 '18 at 11:57
  • If you want to do matrix multiplication, there is no need for the loop - this is exactly what `np.dot` is for. If your X_train is of shape (6000, 784) and `w` is of shape (784, 1) `np.dot(X_train, w)` will result in the desired shape of (6000, 1). – MB-F Feb 22 '18 at 13:32
  • `X_train.shape` can't be 6000. `shape` is always a tuple. If you mean (6000,), then how can you index `X_train[i,:]` (as though it were 2d)? Or is it (60000,784)? In the loop you calculate `score`, but then replace it next time through. So the last shape is the shape of the last calculation. `dot` of a (n,) with (n,1) will produce a (1,) result. – hpaulj Feb 22 '18 at 18:27

1 Answers1

0

You should avoid the for loop altogether. Indeed, np.dot is supposed to work on N-dim arrays and does the looping internally. See for example

In [1]: import numpy as np

In [2]: a = np.random.rand(1,2)  # a.shape = (1,2)

In [3]: b = np.random.rand(2,3)  # b.shape = (2,3)

In [4]: np.dot(a,b)
Out[4]: array([[ 0.33735571,  0.29272468,  0.09361096]])
Chris
  • 531
  • 5
  • 11
  • When I multiply them outside of the for loop it gives me the desired result. The problem is when i put the operation inside the for loop, but I should use it because i need it for further calculation. Maybe the problem is to the indexes I give? – jasmin Feb 22 '18 at 11:32