由于工作需要,目前需要融合两个模型,但是两个模型的框架完全不一样,一个是pytorch一个是keras。头疼。
目前有两个确认可行的方案。
方案一:将其中一者的模型转化为另一框架,然后进行融合。遇到的问题在于两个模型都有预训练模型,所以如果这样的转换,模型可以复现,但是训练的参数怎么办呢?难道又要重新训练吗?
方案二:将一种一者的输出结果保存为h5,因为两个模型只是作为特征提取,而本身并不参与新模型的反向传播。但是问题在于,数据多了h5也多,而且非常不方便新模型的参数调整。
但是就在做这个工作一个月后出现了tfpyth. 或许有希望吧。所以记录下tfpyth的代码学习,看看别人是如何进行转换的。
def test_pytorch_in_tensorflow_eager_mode():
tf.enable_eager_execution()
tfe = tf.contrib.eager
def pytorch_expr(a, b):
return 3 * a + 4 * b * b
x = tfpyth.eager_tensorflow_from_torch(pytorch_expr)
assert tf.math.equal(x(tf.convert_to_tensor(1.0), tf.convert_to_tensor(3.0)), 39.0)
dx = tfe.gradients_function(x)
assert all(tf.math.equal(dx(tf.convert_to_tensor(1.0), tf.convert_to_tensor(3.0)), [3.0, 24.0]))
tf.disable_eager_execution()
x = tfpyth.eager_tensorflow_from_torch(pytorch_expr) ,输入的是是一个函数。
**def eager_tensorflow_from_torch(func):
"""
Wraps a PyTorch function into a TensorFlow eager-mode function (ie can be executed within Tensorflow eager-mode).
:param func: Function that takes PyTorch tensors and returns a PyTorch tensor.
:return: Differentiable Tensorflow eager-mode function.
"""
@tf.custom_gradient
def compute(*inputs):
th_inputs = [th.tensor(tf_input.numpy(), requires_grad=True) for tf_input in inputs]
th_output = func(*th_inputs)
#输入的是tensorflow下的tensor, 先转化为pytorch下的tensor
#经过func也就是前面的pytorch_expr,然后输出的也是pytorch 的tensor。