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) #保存新的權重文件。
中間過程不懂的函數可以參考如下博客: