How to convert matrices to column vectors and append all together in python

Question:

I’m more familiar with Matlab, but I’m current working with python. If I have 4 matrices / arrays in python, how can I covert each to a column vector and then append them together to form one large column vector?

In Matlab, I have:

W1 = rand(hiddenSize, visibleSize) * 2 * r - r;
W2 = rand(visibleSize, hiddenSize) * 2 * r - r;
b1 = zeros(hiddenSize, 1);
b2 = zeros(visibleSize, 1);

theta = [W1(:) ; W2(:) ; b1(:) ; b2(:)]; 

theta is the final column vector I’m interested in. How would I do this in python?

I think that I would use reshape function to create the column vectors (something like W1 = reshape(W1, size(W1)) ), but I couldn’t get that to work and I’m not sure how to append each to create one large column vector. Any insight would be great!

Asked By: celine36

||

Answers:

If you are moving from Matlab to Python, I highly recommend you install the NumPy (and maybe Scipy) packages.

Using NumPy you could do this:

import numpy as np
W1 = np.arange(25*64).reshape(25, 64)
W2 = np.arange(25*64).reshape(64, 25)
b1 = np.arange(25)
b2 = np.arange(64)

theta = np.concatenate([W1.flat, W2.flat, b1, b2])
print(theta.shape)
# (3289,)

Here is an introduction to NumPy for Matlab users.

Answered By: unutbu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.