-1

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?

  • 2
    `weights` is a (10,8) array of floats. `latice` is a (2,10,5) array of floats.. It doesn't make any sense to talk of putting `weights` in `latice`. `latice[0,0,0]` is the slot for ONE float, not 80. – hpaulj Jan 11 '23 at 04:33
  • I was the author of an answer in your first link. If you already know you can't put the array in a scalar slot, why mention that case at all? In order to "insert" that (10,8) array into `latice`, it either needs to be object dtype (which makes it list like), or have enough dimensions so that `latice[0,0,0].shape` is (10,8). – hpaulj Jan 12 '23 at 19:44

2 Answers2

0

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)
Kraigolas
  • 5,121
  • 3
  • 12
  • 37
0

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')