And conversion between tensorflow model pytorch

Reference Links:
https://github.com/bermanmaxim/jaccardSegment/blob/master/ckpt_to_dd.py

A. Tensorflow model turn pytorch model

import tensorflow as tf
import deepdish as dd
import argparse
import os
import numpy as np

def tr(v):
    # tensorflow weights to pytorch weights
    if .I == 4:
        return np.ascontiguousarray(v.transpose(3,2,0,1))
    elif .I == 2:
        return np.ascontiguousarray(v.transpose())
    return v

def read_ckpt(ckpt):
    # https://github.com/tensorflow/tensorflow/issues/1823
    reader = tf.train.NewCheckpointReader(ckpt)
    weights = {n: reader.get_tensor(n) for (n, _) in reader.get_variable_to_shape_map().items()}
    pyweights = {k: tr(v) for (k, v) in weights.items()}
    return pyweights
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Converts ckpt weights to deepdish hdf5")
    parser.add_argument("infile", type=str,
                        help="Path to the ckpt.")  # ***model.ckpt-22177***
    parser.add_argument("outfile", type=str, nargs='?', default='',
                        help="Output file (inferred if missing).")
    args = parser.parse_args()
    if args.outfile == '':
        args.outfile = os.path.splitext(args.infile)[0] + '.h5'
    outdir = os.path.dirname(args.outfile)
    if not os.path.exists(outdir):
        os.makedirs (OutDir)
    weights = read_ckpt(args.infile)
    dd.io.save(args.outfile, weights)

  

Model.h5 model will be 1. Run the code, as follows:
Note: python consistent and version tensorflow used pytorch

 

2. Use: load change in the model pytorch:
It is assumed that the network parameter stored consistent naming

 

net = ...
import torch
import deepdish as dd
net = resnet50(..)
model_dict = net.state_dict()
# First parameter value converted to tensor form numpy
pretrained_dict =  = dd.io.load('./model.h5')
new_pre_dict = {}
for k,v in pretrained_dict.items():
    new_pre_dict[k] = torch.Tensor(v)
# Update
model_dict.update(new_pre_dict)
#load
net.load_state_dict(model_dict)

  

Two. Pytorch turn tensorflow (Continued ..)

 

Original: https: //blog.csdn.net/weixin_42699651/article/details/88932670

 

Guess you like

Origin www.cnblogs.com/qbdj/p/11024565.html