raise ValueError("No variables to save") ValueError: No variables to save
时间: 2024-03-23 22:36:33 浏览: 28
这个错误通常在 TensorFlow 中使用 `tf.train.Saver()` 保存模型参数时出现。
这个错误的意思是没有可以保存的变量。这通常是因为在创建 `tf.train.Saver()` 对象时,没有将要保存的变量传递给 `Saver()` 对象。
例如,以下代码会产生这个错误:
```python
import tensorflow as tf
# 定义模型
x = tf.placeholder(tf.float32, shape=[None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 创建 Saver 对象
saver = tf.train.Saver()
# 运行会话,保存变量
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.save(sess, "/tmp/model.ckpt")
```
这里的问题在于,我们创建了 `Saver()` 对象,但却没有将要保存的变量传递给 `Saver()` 对象。因此,当我们调用 `saver.save()` 方法时,会抛出 "No variables to save" 的错误。
要解决这个问题,我们需要将要保存的变量传递给 `Saver()` 对象。例如,将上面的代码修改为:
```python
import tensorflow as tf
# 定义模型
x = tf.placeholder(tf.float32, shape=[None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 创建 Saver 对象
saver = tf.train.Saver([W, b])
# 运行会话,保存变量
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.save(sess, "/tmp/model.ckpt")
```
这里,我们将要保存的变量 `[W, b]` 传递给了 `Saver()` 对象,因此在保存模型参数时就不会出现 "No variables to save" 的错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)