Skip to main content
 首页 » 编程设计

python之类型错误 : Variable to save is not a Variable

2025年02月15日11over140

我有以下代码可以在分布式tensorflow中做一些简单的算术计算。一个最小的可重现示例是:-

import tensorflow as tf 
 
global_step_tensor = tf.Variable(10, trainable=False, name='global_step') 
 
cluster = tf.train.ClusterSpec({"local": ["localhost:2222", "localhost:2223","localhost:2224", "localhost:2225"]}) 
x = tf.constant(2) 
 
with tf.device("/job:local/task:0"): 
    y = x + 300 
 
model = tf.global_variables_initializer() 
 
saver = tf.train.Saver([y]) 
 
ChiefSessionCreator = tf.train.ChiefSessionCreator(scaffold=None, master='grpc://localhost:2222', config=None, checkpoint_dir='/home/chaitanya/tensorflow/codes/checkpoints') 
saver_hook = tf.train.CheckpointSaverHook(checkpoint_dir='/home/chaitanya/tensorflow/codes/checkpoints', save_secs=10, save_steps=None, saver=y, checkpoint_basename='model.ckpt', scaffold=None) 
summary_hook = tf.train.SummarySaverHook(save_steps=None, save_secs=10, output_dir='/home/chaitanya/tensorflow/codes/savepoints', summary_writer=None, scaffold=None, summary_op=y) 
 
with tf.train.MonitoredTrainingSession(master='grpc://localhost:2222', is_chief=True, checkpoint_dir='/home/chaitanya/tensorflow/codes/checkpoints',  
    scaffold=None, hooks=[saver_hook, summary_hook], chief_only_hooks=None, save_checkpoint_secs=10, save_summaries_steps=None, config=None) as sess: 
 
    while not sess.should_stop(): 
        sess.run(model) 
 
    while not sess.should_stop(): 
        result = sess.run(y) 
        print(result) 

错误如下:-

Traceback (most recent call last): 
  File "add_1.py", line 13, in <module> 
    saver = tf.train.Saver([y]) 
    raise TypeError("Variable to save is not a Variable: %s" % var) 
TypeError: Variable to save is not a Variable: Tensor("add_3:0", shape=(), dtype=int32, device=/job:local/task:3) 

请帮我想出正确的方法来使用这个函数。

请您参考如下方法:

当您简单地编写 x + 300 时,您并没有创建 tf.Variable。您需要显式使用 tf.get_variable() 或 tf.Variable() 来创建可以保存的变量。

y = tf.Variable(x + 300)