user10794514
user10794514

Reputation:

What is the difference between this two lines of code? ML arrays

So I started learning ML and I need to code in Python. I follow a tutorial on back propagation. So, in it, I am presented with the problem of turning an algorithm to support matrix multiplication so it would run faster. The following code is from a function that updates the biases and weights. I needed to change it so instead of running each input-output pair at a single time, I would run the entire inputs and outputs matrices. The mini-batch is a list with 10 elements. Each element in the list is two tuples, one tuple is the input, a 784x1 sized matrix. The other tuple is the output, a 10x1 sized matrix. I tried to group the inputs to a 784x10x1 array and then convert it to 784x10 array. I did it in two ways as shown in the following code:

# for clearance - batch[0] is the first tuple in the element in mini_batch, which is, as recalled, the input array.
# mini_batch[0][0] is the input array of the first element in mini_batch, which is a 784x1 array as I mentioned earlier 
inputs3 = np.array([batch[0] for batch in mini_batch]).reshape(len(mini_batch[0][0]), len(mini_batch))
inputs2 = np.array([batch[0].ravel() for batch in mini_batch]).transpose()

both inputs3 and inputs2 are 784x10 arrays but for some reason, they are not equal. I don't understand why, so I would really appreciate if someone could explain to me why there's a difference.

Upvotes: 2

Views: 145

Answers (1)

mayankmehtani
mayankmehtani

Reputation: 435

>>> A = np.array([[1,2,3],[4,5,6]])
>>> A.reshape(3,2)
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> A.transpose()
array([[1, 4],
       [2, 5],
       [3, 6]])

From this short example you can see that A.transpose() != A.reshape(3,2).

Imagine a blank matrix with dimensions 3x2. A.reshape(3,2) will read values form A(a 2x3 matrix) left to right starting from the top row and storing them in the blank matrix. Making these matrices have different values.

Upvotes: 1

Related Questions