python - 在 Tensorflow 1.9 的一个脚本中运行不同的模型

标签 python python-3.x tensorflow

我有一个非常简单的模型,它由一个 tf.Variable() 组成,这是谁的代码:

import tensorflow as tf

save_path="model1/model1.ckpt"

num_input = 2
n_nodes_hl1 = 2

with tf.variable_scope("model1"):
        hidden_1_layer = {
                'weights' : tf.Variable(tf.random_normal([num_input, n_nodes_hl1]), name='Weight1')
        }

def train_model():
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        save_model(sess)

def save_model(sess):
    saver = tf.train.Saver(tf.global_variables(), save_path)
    saver.save(sess, save_path)

def load_model(sess):
    saver = tf.train.Saver(tf.global_variables(), save_path)
    saver.restore(sess, save_path)

def run_model():
    print("model1 running...")
    with tf.Session() as sess:
        load_model(sess)
        x = sess.run(hidden_1_layer)
        print(x)

#train_model() 

第二个模型完全相同,但名称从“model1”更改为“model2”。两种模型都经过训练、保存并且分别完美运行。所以现在我想使用以下脚本测试它们:

import model1 as m1
import model2 as m2

m1.run_model()
m2.run_model()

这里我收到一条错误消息:

NotFoundError (see above for traceback): Key model2/Weight2 not found in checkpoint

所以看起来运行导入会导致将所有变量添加到公共(public)图中(即使它们在单独的变量范围内),然后它无法从保存在模型 1 的检查点中的模型 2 中找到变量。 谁能解决我的问题? 在 Tensorflow 中是否可以在一个脚本中运行几个不同的模型?

编辑 - 问题已解决 解决方法很简单。您要做的是为每个模型创建单独的图表。这意味着您声明或计算的所有张量都必须在该图中。您还必须将其作为 Session 中的参数,例如:tf.Session(graph=self.graph) 整个示例如下:

import tensorflow as tf

save_path="model1/model1.ckpt"
class model1:
    num_input = 2
    n_nodes_hl1 = 2

    def init(self):
        self.graph = tf.Graph()
        with self.graph.as_default():
            with tf.variable_scope("model1"):
                    self.hidden_1_layer = {
                            'weights' : tf.Variable(tf.random_normal([self.num_input, self.n_nodes_hl1]), name='Weight1')
                    }

    def train_model(self):
        init = tf.global_variables_initializer()
        with tf.Session(graph = self.graph) as sess:
            sess.run(init)
            self.save_model(sess)

    def save_model(self, sess):
        saver = tf.train.Saver(tf.global_variables(), save_path)
        saver.save(sess, save_path)

    def load_model(self, sess):
        saver = tf.train.Saver(tf.global_variables(), save_path)
        saver.restore(sess, save_path)

    def run_model(self):
        print("model1 running...")
        with tf.Session(graph = self.graph) as sess:
            self.load_model(sess)
            x = sess.run(self.hidden_1_layer)
            print(x)

最佳答案

哦!常见的“我想使用多个模型”的问题!只需确保在每个模型后重置图表:

tf.reset_default_graph()

您的代码如下所示:

import tensorflow as tf

import model1 as m1
m1.run_model()

tf.reset_default_graph()

import model2 as m2
m2.run_model()

为什么?当您使用 tf.Variable 在 tensorflow 中创建变量时,该变量将添加到默认图。如果您一个接一个地导入两个模型,您只是在默认图表中创建了所有变量!这是迄今为止最简单的解决方案。将默认图视为一 block 黑板:您可以画出您喜欢的 ML 模型,但在重新使用之前需要将其擦干净!

注意:如果你想知道,另一种方法是为每个模型创建单独的图表,但它更令人担忧,我只在你必须有的时候推荐它两种模型同时出现

额外:将您的模型封装在 Tensorflow 类中

在避免使用多个图表的情况下(说真的,这太可怕了!)一个更奇特的方法是将整个模型封装在一个类中。因此,您的代码将如下所示:

import tensorflow as tf

class model():
    self.num_input = 2
    self.n_nodes_hl1 = 2
    def init(self, new_save_path)
        self.save_path=new_save_path

        tf.reset_default_graph()

        with tf.variable_scope("model1"):
            self.hidden_1_layer = {
                    'weights' : tf.Variable(tf.random_normal([self.num_input,
                                self.n_nodes_hl1]), name='Weight1')
            }
        self.saver = tf.train.Saver(tf.global_variables(), self.save_path)
        self.sess = tf.Session()
        self.sess.run(tf.global_variables_initializer())

    def save_model(self):
        self.saver.save(self.sess, self.save_path)

    def load_model(self):
        self.saver.restore(self.sess, self.save_path)

    def run_model(self):
        print("model1 running...")
        load_model()
        x = sess.run(self.hidden_1_layer)
        print(x)

    #train_model(self) 

这样你就可以简单地做:

import model

m1 = model('model1/model1.ckpt') # These two lines could be put into one
m1.run_model()                   #  m1 = model('model1/model1.ckpt').run_model()

m2 = model('model2/model2.ckpt')
m2.run_model()

您还想在 for 循环中使用它吗?

import model

model_file_list = ['model1/model1.ckpt', 'model2/model2.ckpt']

for model_file in model_list:
    m = model(model_file ).run_model()
    # Run tests, print stuff, save stuff here!

关于python - 在 Tensorflow 1.9 的一个脚本中运行不同的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51747660/

相关文章:

python - Pandas 分钟数据可变长度窗口查找从现在到关闭时间的最小值

python-3.x - Pandas 按组垂直合并值

Python Django 名称错误 : name 'datetime' is not defined

python - 拉丁字母的字母生成算法?

python-3.x - HuggingFace(信息提供者)运行​​时错误: mat1 and mat2 shapes cannot be multiplied (1536x23 and 22x32)

python - 如何使用来自 Tensorflow 对象检测 API 的 Mask-RCNN 模型创建自己的数据集?

python - google colab 在此过程中设置了 '^C'

python - TensorFlow、Keras、Flask - 无法通过 Flask 将我的 Keras 模型作为 Web 应用程序运行

python - 从 Python3 代码中运行 bash 脚本的问题

python - 通过允许容差匹配两个包含略有不同的浮点值的列表