使用多个数组更改列表的形状python

问题描述

最初,我有一个名为voltage的字典,其中有206个数组,每个数组的形状为(25,3,1)。我已使用以下代码将字典转换为数组列表

temp = []
input= []

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

input是我的列表的名称。当我检查列表的形状时,会得到(1,206,2)

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

我想将列表的形状更改为(206,25,1)。当我将input传递给以下模型时,出现错误(如下所示)。

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

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

x = Conv2D(32,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')

model.fit(x=input,y=output,steps_per_epoch=None,epochs=1000)

ValueError:检查输入时出错:预期input_5为4 尺寸,但具有 (1、206、2)形状

不胜感激。

解决方法

您可以执行以下操作:

import numpy as np

d = {1: np.random.rand(25,3,1),2: np.random.rand(25,3: np.random.rand(25,4: np.random.rand(25,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,1)

创建所需大小的空numpy数组,然后将字典volatge值附加到所需位置。

如果您的键不规则(表示1、4、6等),则可以创建将arr的第一项映射到voltage值的映射。