Python 字典到展平向量,然后向量回到字典

Python 字典到展平向量,然后向量回到字典,python,arrays,numpy,dictionary,vector,Python,Arrays,Numpy,Dictionary,Vector,我需要展平一个权重和偏差字典来进行梯度检查,我创建了这个函数来展平我的字典,它可以工作,但我似乎找不到一种方法来恢复这个过程 @staticmethod def flatten_dic(dic): keys = [] count = 0 theta = np.array([]) for i in dic.keys(): new_vector = np.reshape(dic[i], (-1, 1)) keys = keys + [i

我需要展平一个权重和偏差字典来进行梯度检查,我创建了这个函数来展平我的字典,它可以工作,但我似乎找不到一种方法来恢复这个过程

@staticmethod
def flatten_dic(dic):
    keys = []
    count = 0
    theta = np.array([])
    for i in dic.keys():
        new_vector = np.reshape(dic[i], (-1, 1))
        keys = keys + [i] * new_vector.shape[0]
        if count == 0:
            theta = new_vector
        else:
            theta = np.concatenate((theta, new_vector), axis=0)
        count = count + 1
    return theta, keys
输入

{"W1":[[1,2,3],[3,2,1]],"W2":[1,2,3]}
它输出

[1,2,3,3,2,1,1,2,3]

这将在结果中为您提供一个展开列表,这也将保留您的原始词典。

但我的问题是如何还原该过程,因为我想更改展开向量中的数据并将其转换回词典Supplose有人给您一个展开列表并告诉您从中构建词典,你能做到吗?把你的字典复制一份,想用它做什么就用它做什么。如果你能保留原始风管,有什么必要重建它?是的,但我需要将其重建到字典中,以便在正向传播中使用,不可能仅从展平列表中创建字典,但我也可以提取关键点,因此,通过组合键和扁平列表,我相信这是可能的
r = {"W1":[[1,2,3],[3,2,1]],"W2":[1,2,3]}

result = []

def flatten(_list): 
    if type(_list[0]) == list: 
        for e in _list: 
           flatten(e) 
    else: 
       result.extend(_list) 

[flatten(e) for e in r.values()]