简体   繁体   English

如何在不转换为 Numpy 数组的情况下将 TensorFlow 张量转换为 PyTorch 张量?

[英]How to convert TensorFlow tensor to PyTorch tensor without converting to Numpy array?

I want to use a pre-trained Pytorch model in Tensorflow and I need to convert the tensorflow tensors to pytorch tensors. I want to use a pre-trained Pytorch model in Tensorflow and I need to convert the tensorflow tensors to pytorch tensors. But I don't want to convert the pytorch tensor to a numpy array and convert that to a tensorflow tensor since I'm getting the error of " You must feed a value for placeholder tensor".但我不想将 pytorch 张量转换为 numpy 数组并将其转换为 tensorflow 张量,因为我收到“占位符张量”的错误。 I need this conversion when I'm making the graph so the tensorflow tensor doesn't have value and cannot be converted to numpy?我在制作图表时需要这种转换,所以 tensorflow 张量没有值并且不能转换为 numpy? Any solution for that?有什么解决办法吗?

Operations you do to Tensorflow tensors are "remembered" in order to calculate and back-propagate gradients.您对 Tensorflow 张量执行的操作会被“记住”,以便计算和反向传播梯度。 Same is true for PyTorch tensors. PyTorch 张量也是如此。 All this is ultimately required to train the model in both frameworks.所有这些最终都是在两个框架中训练 model 所必需的。 This also is the reason why you can't convert tensors between the two frameworks: They have different ops and gradient calculation systems.这也是你不能在两个框架之间转换张量的原因:它们有不同的操作和梯度计算系统。 They are incapable of capturing any operation that happens beyond their framework.他们无法捕获超出其框架的任何操作。 For example, you can't (as of Jan 2021) have python for loops in custom loss functions.例如,您不能(截至 2021 年 1 月)在自定义损失函数中使用 python 循环。 It has to be implemented into the framework in order to work.它必须被实施到框架中才能工作。 Similarly, there is no implementation of converting pytorch operations to Tensorflow operations.同样,没有将 pytorch 操作转换为 Tensorflow 操作的实现。

This answer shows how it's done when your tensor is well-defined (not a placeholder).这个答案显示了当您的张量定义明确(不是占位符)时它是如何完成的。 But there is currently no way to propagate gradients from Tensorflow to PyTorch or vice-versa.但是目前没有办法将梯度从 Tensorflow 传播到 PyTorch 或反之亦然。 Maybe in the future there will be some kind of massive update to both frameworks that lets them inter-operate, but I doubt that.也许将来会对这两个框架进行某种大规模更新,使它们可以互操作,但我对此表示怀疑。 It's best to use them both separately.最好分别使用它们。

So, in short, you can't convert placeholder tensors between two frameworks.所以,简而言之,你不能在两个框架之间转换占位符张量。 You have to stick to one of the libraries or use concrete tensors + numpy mediator to communicate in-between frameworks.您必须坚持使用其中一个库或使用具体张量 + numpy 调解器在框架之间进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM