pytorch2keras
1.0.0
Pytorch to Keras 모델 변환기.
pip install pytorch2keras
변환기를 올바르게 사용하려면 ~/.keras/keras.json 을 변경하십시오.
...
"backend" : " tensorflow " ,
"image_data_format" : " channels_first " ,
... Tensorflow.js 형식으로의 적절한 변환은 새 플래그 names='short' 사용하십시오.
다음은 Tensorflow.js 모델을 얻는 방법입니다.
k_model = pytorch_to_keras ( model , input_var , [( 10 , 32 , 32 ,)], verbose = True , names = 'short' ) tensorflowjs_converter 로 변환 할 수 있지만 때로는 작동하지 않습니다. 대안으로, 당신은 텐서 플로 그래프를 가져 와서 냉동 모델로 저장할 수 있습니다. # Function below copied from here:
# https://stackoverflow.com/questions/45466020/how-to-export-keras-h5-to-tensorflow-pb
def freeze_session ( session , keep_var_names = None , output_names = None , clear_devices = True ):
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph where variable nodes are replaced by
constants taking their current value in the session. The new graph will be
pruned so subgraphs that are not necessary to compute the requested
outputs are removed.
@param session The TensorFlow session to be frozen.
@param keep_var_names A list of variable names that should not be frozen,
or None to freeze all the variables in the graph.
@param output_names Names of the relevant graph outputs.
@param clear_devices Remove the device directives from the graph for better portability.
@return The frozen graph definition.
"""
from tensorflow . python . framework . graph_util import convert_variables_to_constants
graph = session . graph
with graph . as_default ():
freeze_var_names =
list ( set ( v . op . name for v in tf . global_variables ()). difference ( keep_var_names or []))
output_names = output_names or []
output_names += [ v . op . name for v in tf . global_variables ()]
input_graph_def = graph . as_graph_def ()
if clear_devices :
for node in input_graph_def . node :
node . device = ""
frozen_graph = convert_variables_to_constants ( session , input_graph_def ,
output_names , freeze_var_names )
return frozen_graph
from keras import backend as K
import tensorflow as tf
frozen_graph = freeze_session ( K . get_session (),
output_names = [ out . op . name for out in k_model . outputs ])
tf . train . write_graph ( frozen_graph , "." , "my_model.pb" , as_text = False )
print ([ i for i in k_model . outputs ])my_model.pb TFJS 모델로 변환 할 때입니다. tensorflowjs_converter
--input_format=tf_frozen_model
--output_node_names= ' TANHTObs/Tanh '
my_model.pb
model_tfjs const MODEL_URL = `model_tfjs/tensorflowjs_model.pb` ;
const WEIGHTS_URL = `model_tfjs/weights_manifest.json` ;
const model = await tf . loadFrozenModel ( MODEL_URL , WEIGHTS_URL ) ; Pytorch 그래프의 Keras (Tensorflow Backend) 모델로 변환기입니다.
첫째, 유효한 Pytorch 모델을로드 (또는 생성)해야합니다.
class TestConv2d ( nn . Module ):
"""
Module for Conv2d testing
"""
def __init__ ( self , inp = 10 , out = 16 , kernel_size = 3 ):
super ( TestConv2d , self ). __init__ ()
self . conv2d = nn . Conv2d ( inp , out , stride = 1 , kernel_size = kernel_size , bias = True )
def forward ( self , x ):
x = self . conv2d ( x )
return x
model = TestConv2d ()
# load weights here
# model.load_state_dict(torch.load(path_to_weights.pth))다음 단계 - 올바른 모양으로 더미 변수를 만듭니다.
input_np = np . random . uniform ( 0 , 1 , ( 1 , 10 , 32 , 32 ))
input_var = Variable ( torch . FloatTensor ( input_np ))우리는 더미 변수를 사용하여 모델을 추적합니다 (Jit.Trace 포함).
from pytorch2keras import pytorch_to_keras
# we should specify shape of the input tensor
k_model = pytorch_to_keras ( model , input_var , [( 10 , 32 , 32 ,)], verbose = True ) 또한 모델 모양에 대한 정보를 만들기 위해 H 및 W 차원을 없애지 않도록 설정할 수 있습니다 (예 : 완전히 컨 컨토 워크) :
from pytorch2keras . converter import pytorch_to_keras
# we should specify shape of the input tensor
k_model = pytorch_to_keras ( model , input_var , [( 10 , None , None ,)], verbose = True ) 그게 다야! 모든 모듈이 올바르게 변환되면 Keras 모델은 k_model 변수에 저장됩니다.
다음은 pytorch_to_keras 모듈 pytorch2keras 유일한 방법입니다.
def pytorch_to_keras (
model , args , input_shapes = None ,
change_ordering = False , verbose = False , name_policy = None ,
):옵션 :
model - 변환 할 파이토치 모델 (nn.module);args 적절한 모양을 가진 더미 변수 목록;input_shapes (실험) 입력에 대한 과도한 모양이있는 목록;change_ordering (실험) 부울, 활성화되면 변환기는 BCHW BHWC 로 변경하려고합니다.verbose 부울, 상세한 전환 로그name_policy (실험적) [ keep , short , random ] 선택. 선택기는 대상 계층 명명 정책을 설정합니다. 활성화 :
상수
컨볼 루션 :
요소 측면 :
선의
정규화 :
풀링 :
tests 디렉토리를보십시오.
이 소프트웨어는 MIT 라이센스에 포함됩니다.