Skip to main content
 首页 » 编程设计

python之使用 Saver v2 加载模型

2024年10月17日7bhlsheji

我刚刚将本地安装的 Tensorflow 更新为 0.11rc2,我收到一条消息说我应该向我的保护程序添加一个参数以使其保存在版本 2 中。我更新了它,现在我无法加载保存在版本 2 中的模型这种格式。当我运行我的模型时,它会在每个纪元后保存。保存时,它用于保存名为 translate.ckpt-3916 和 translate.ckpt-3916.meta 的文件。现在我得到三个文件而不是两个,分别命名为 translate.ckpt-3916.index、translate.ckpt-3916.meta 和 translate.ckpt-3916。 data-000000-of-000001。

要加载数据,我使用以下代码:

ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir) 
    if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path): 
        print("Reading model parameters from %s" % ckpt.model_checkpoint_path) 
        model.saver.restore(session, ckpt.model_checkpoint_path) 
    else: 
        print("Created model with fresh parameters.") 
        session.run(tf.initialize_all_variables()) 
return model 

model 是一个模型对象,它已经用我的程序的标准超参数初始化了。这对 saver v1 没有问题。 ckpt.model_checkpoint_path 评估为 translate.ckpt-3916 的路径,无论版本如何,因此如果检查点是使用 v2 保存的,则找不到文件。

该目录中的 checkpoint 文件的内容(当使用任一版本保存时)是:

model_checkpoint_path: "translate.ckpt-3916" 
all_model_checkpoint_paths: "translate.ckpt-3916" 

saver v2有没有新的加载数据的方法?否则,我该如何加载我的检查点?

编辑: 将 if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path): 行更改为 if ckpt and ckpt.model_checkpoint_path:,如 this question 所示。似乎更进一步但随后抛出以下错误:

InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [84] rhs shape= [98] 
 [[Node: save/Assign_54 = Assign[T=DT_FLOAT, _class=["loc:@NLC/Logistic/Linear/Bias"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](NLC/Logistic/Linear/Bias, save/RestoreV2_54)]] 

请您参考如下方法:

我在编辑中发布的方法实际上是使它起作用的正确方法。我得到的错误是因为数据在我创建检查点和我尝试加载它之间发生了变化。

只是为了使其可见,通过将行 if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path): 更改为 if 来完成从上面代码中的 V2 检查点加载ckpt 和 ckpt.model_checkpoint_path: