我在 tensorflow 中使用 ssd + mobilenet 作为我的基础模型进行了迁移学习,并冻结了一个新模型。现在我想将该模型转换为 pytorch。有什么办法可以实现吗?任何帮助都会非常有帮助..
如何将我的 tensorflow 模型转换为 pytorch 模型?
数据挖掘
张量流
火炬
2021-10-08 02:21:01
1个回答
您可以在 pytorch 中构建相同的模型。然后从 tensorflow 中提取权重并手动分配给 pytorch 中的每一层。根据层的数量,它可能很耗时。构建模型取决于模型,我认为在 pytorch 中并非一切皆有可能,而在 tensorflow 中可能。下面给出了如何在 pytorch 中分配权重和从 tensorflow 中提取权重的示例。
从张量流变量中获取权重W和b:
weights = sess.run(W)
bias = sess.run(b)
哪里sess是tf.Session。
为 pytorch 分配权重:
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Kernel_Emb(nn.Module):
def __init__(self,D_in,H,D_out):
super(Kernel_Emb, self).__init__()
self.linear1 = nn.Linear(D_in,H)
self.linear2 = nn.Linear(H,D_out)
self.linear1.weight = torch.nn.Parameter(weights)
self.linear1.bias = torch.nn.Parameter(bias)
如果变量未在 tensorflow 中定义(来源:https ://stackoverflow.com/questions/36193553/get-the-value-of-some-weights-in-a-model-trained-by-tensorflow ):
如果您当前没有指向 的指针,您可以通过调用 [ ][4]
tf.Variable获取当前图中可训练变量的列表。tf.trainable_variables()该函数返回当前图中所有可训练对象的列表,您可以通过匹配属性tf.Variable来选择您想要的对象。v.name例如:# Desired variable is called "tower_2/filter:0". var = [v for v in tf.trainable_variables() if v.name == "tower_2/filter:0"][0]
其它你可能感兴趣的问题