在 Tensorflow 中加载多个模型

2023-12-27

我在 Tensorflow 中编写了以下卷积神经网络 (CNN) 类 [为了清楚起见,我尝试省略一些代码行。]

class CNN:
def __init__(self,
                num_filters=16,        # initial number of convolution filters
             num_layers=5,           # number of convolution layers
             num_input=2,           # number of channels in input
             num_output=5,          # number of channels in output
             learning_rate=1e-4,    # learning rate for the optimizer
             display_step = 5000,   # displays training results every display_step epochs
             num_epoch = 10000,     # number of epochs for training
             batch_size= 64,        # batch size for mini-batch processing
             restore_file=None,      # restore file (default: None)

            ):

                # define placeholders
                self.image = tf.placeholder(tf.float32, shape = (None, None, None,self.num_input))  
                self.groundtruth = tf.placeholder(tf.float32, shape = (None, None, None,self.num_output)) 

                # builds CNN and compute prediction
                self.pred = self._build()

                # I have already created a tensorflow session and saver objects
                self.sess = tf.Session()
                self.saver = tf.train.Saver()

                # also, I have defined the loss function and optimizer as
                self.loss = self._loss_function()
                self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.loss)

                if restore_file is not None:
                    print("model exists...loading from the model")
                    self.saver.restore(self.sess,restore_file)
                else:
                    print("model does not exist...initializing")
                    self.sess.run(tf.initialize_all_variables())

def _build(self):
    #builds CNN

def _loss_function(self):
    # computes loss


# 
def train(self, train_x, train_y, val_x, val_y):
    # uses mini batch to minimize the loss
    self.sess.run(self.optimizer, feed_dict = {self.image:sample, self.groundtruth:gt})


    # I save the session after n=10 epochs as:
    if epoch%n==0:
        self.saver.save(sess,'snapshot',global_step = epoch)

# finally my predict function is
def predict(self, X):
    return self.sess.run(self.pred, feed_dict={self.image:X})

我已经为两个不同的任务独立训练了两个 CNN。每份大约需要1天时间。假设 model1 和 model2 保存为 'snapshot-model1-10000' and 'snapshot-model2-10000' (及其相应的元文件)分别。我可以测试每个模型并分别计算其性能。

现在,我想在单个脚本中加载这两个模型。我自然会尝试执行以下操作:

cnn1 = CNN(..., restore_file='snapshot-model1-10000',..........) 
cnn2 = CNN(..., restore_file='snapshot-model2-10000',..........)

我遇到错误[错误信息很长。我只是复制/粘贴了其中的一个片段。]

NotFoundError: Tensor name "Variable_26/Adam_1" not found in checkpoint files /home/amitkrkc/codes/A549_models/snapshot-hela-95000
     [[Node: save_1/restore_slice_85 = RestoreSlice[dt=DT_FLOAT, preferred_shard=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save_1/Const_0, save_1/restore_slice_85/tensor_name, save_1/restore_slice_85/shape_and_slice)]]

有没有办法从这两个文件加载两个单独的 CNN?欢迎任何建议/评论/反馈。

谢谢你,


就在这里。使用单独的图表。

g1 = tf.Graph()
g2 = tf.Graph()

with g1.as_default():
    cnn1 = CNN(..., restore_file='snapshot-model1-10000',..........) 
with g2.as_default():
    cnn2 = CNN(..., restore_file='snapshot-model2-10000',..........)

EDIT:

如果你想让它们进入同一个图表。您必须重命名一些变量。一种想法是让每个 CNN 处于单独的作用域中,并让 saver 处理该作用域中的变量,例如:

saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES), scope='model1')

并在 cnn 中将所有构造包装在范围内:

with tf.variable_scope('model1'):
    ...

EDIT2:

另一个想法是重命名 saver 管理的变量(因为我假设您想使用保存的检查点而不重新训练所有内容。保存允许图形和检查点中使用不同的变量名称,请查看初始化文档。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Tensorflow 中加载多个模型 的相关文章

随机推荐