Change the shape of list with multiple arrays python


Initially, I had a dictionary named voltage with 206 arrays each of the shape (25,3,1). I have converted the dictionary into a list of arrays using the following code

temp = []
input= []

for value, key in voltage.items():
    temp = [key,value]

input is the name of my list. When I check the shape of the list, I get (1,206,2)

np.shape(input) - gives (1,206,2)

I want to change the shape of the list to (206, 25,3,1). When I pass the input to the following model I get an error (attached below).

K = Input(shape=(25,3,1))

x = Conv2D(16,(2,2), strides=2, activation='relu', data_format='channels_last', padding='same')(K)   
x = BatchNormalization()(x)

x = Conv2D(32,(2,2), activation='relu', data_format='channels_last' , padding='same')(x)  
x = BatchNormalization()(x)

x = Flatten()(x)

x = Dense(320, activation='relu')(x)
x = Dense(160, activation='relu')(x)
x = Dense(80, activation='relu')(x)
x = Dense(1)(x)

model = Model(K,x)

model.compile(optimizer='adam',loss='mse'), y=output, steps_per_epoch=None, epochs=1000)

ValueError: Error when checking input: expected input_5 to have 4
dimensions, but got array with
(1, 206, 2) shape

Would appreciate some help.


You could do the following:

import numpy as np

d = {1: np.random.rand(25, 3, 1),
2: np.random.rand(25, 3, 1),
3: np.random.rand(25, 3, 1),
4: np.random.rand(25, 3, 1)}

arr = np.empty((len(d.keys()), *d[1].shape))

for i, k in enumerate(d.keys()):
    arr[i] = d[k]

print(arr.shape)  # (4, 25, 3, 1)

Create an empty numpy array in the desired size, and then append the dict, volatge, value to the desired position.

If your keys are not regular (meaning 1, 4, 6 etc) you could create a map that maps the first entry of the arr to the voltage value.

Answered By – David

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.