Python读取PaddlePaddle模型权重文件! |
一. 具体操作过程
- 要读取的文件是没有格式的,这里使用的是Numpy包fromfile函数。本程序的目的是为了改变权重文件的通道顺序,把一个目录下的所有权重文件原来的格式的
[out, in, h, w]
转换为[h, w, in, out]
新的格式。- 具体可以参考博客:NumPy 文件存取 tofile,fromfile, load,save

import numpy as np
import os
path = "parse_best_model/weight" #要读取的权重文件夹
path_save ="parse_best_model/weight_now/" #要保存到的新权重文件夹
if not os.path.exists(path_save):
os.makedirs(path_save)
items_all = os.listdir(path)
for items in items_all:
weight_flatn = np.fromfile(path+"/"+items, dtype=np.float32) # 读取权重文件
[one1, one2] = items.split('_', 1) # stage.4.3.0.conv.weights out-in-h-w_(512, 1024, 1, 1)切分字符串
[cout, cin, h, w] = one2.replace(" ", "").split('(', 3)[1].split(')', 1)[0].split(',') #把out, in, h, w提取出来
weight_oral = weight_flatn.reshape(int(cout), int(cin), int(h), int(w)) #转换为原始的shape
print("oral_shape: ", weight_oral.shape)
weight_now = weight_oral.transpose(2, 3, 1, 0) #调整为新的shape形式
print("now_shape: ", weight_now.shape)
print("========================================")
iters_now = one1+"_h-w-in-out_"+'('+h+","+w+","+cout+","+cin+')' #调整新的权重文件名字。
weight_now.tofile(path_save+iters_now) #保存新的权重文件。

中间过程不懂的函数可以参考如下博客: