简体   繁体   中英

How to insert a matrix into an numpy array?

I have some weights that are generated via the command:

weights = np.random.rand(9+1, 8)                                                  
for i in range(8): # 7 to 8
    weights[9][i] = random.uniform(.5,1.5)

Then, I try to insert it into an element of the following lattice :

lattice = np.zeros((2,10,5))
lattice[0][0][0] = weights
print(lattice)

This results in the error:

ValueError: setting an array element with a sequence.

My question is: How can I insert the weights into the lattice ?

I am aware that the problem is that the lattice is filled with float values, so it cannot accept a matrix.

I'm interested in finding a way to generate a lattice with the correct number of elements so that I can insert my matrices. An example would be very helpful.

I've read several posts on stackoverflow, including:

how to append a numpy matrix into an empty numpy array

ValueError: setting an array element with a sequence

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

Initialize the lattice like so in order to have entries that can be filled with matrices.

lattice = np.empty(shape=(2,10,5), dtype='object')

Presumably you won't need this to actually be a numpy array until you've finished filling the lattice. Thus, what you can do is just use nested lists, and then call numpy array on the entire list. You could do something like:

lattice = [[[None for _ in range(5)] for _ in range(10)] for _ in range(2)]

and then use:

lattice[0][0][0] = weights

and when you've filled in all the elements, call:

lattice = np.array(lattice)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM