python - tf.train.write_graph 使用所有内存并导致 MemoryError
问题描述
我试图以文本格式将简单的 MNIST 模型图导出到 proto 缓冲区文件。
实际上,我正在使用tf.keras
模块,但后来我决定切换,因为在 keras 序列模型中很难为输入和输出张量重命名/分配名称。
这是我的代码:
import tensorflow as tf
import numpy as np
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
x_test = np.reshape(x_test, (-1, 784))/255
x_train = np.reshape(x_train, (-1, 784))/255
X = tf.placeholder(dtype=tf.float32, shape=[None, 784])
Y = tf.placeholder(dtype=tf.float32, shape=[None, 10])
h1 = tf.get_variable('h1',shape=[784, 16])
b1 = tf.zeros(shape=[16])
h2 = tf.get_variable('h2', shape=[16,10])
b2 = tf.zeros(shape=[10])
l1 = tf.nn.relu(tf.matmul(X, h1) + b1)
logits = tf.matmul(l1, h2) + b2
# l1 = tf.layers.dense(inputs=X, units=16, activation=tf.nn.relu)
# logits = tf.layers.dense(inputs=l1, units=10, activation=tf.nn.softmax)
loss = tf.losses.softmax_cross_entropy(onehot_labels=Y, logits=logits)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits, -1), tf.argmax(Y, -1)), tf.float32))
data_pipeline = tf.data.Dataset.from_tensor_slices((x_train, y_train))
iter = data_pipeline.shuffle(1000).repeat().batch(1024).make_one_shot_iterator()
next_item = iter.get_next()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(5):
for i2 in range(1000):
x, y = sess.run(next_item)
if i2 % 100 == 0:
lss = sess.run(loss, feed_dict={X: x, Y: y})
print('Loss at {} => {} is {}'.format(i, i2, lss))
sess.run(optimizer, feed_dict={X: x, Y: y})
print('Final Accuracy : ', sess.run(accuracy, feed_dict={X: x_train, Y: y_train}))
# tf.train.write_graph(sess.graph, './', 'temp.pbtxt')
# This line here is causing the Memory Error
系统信息和图书馆信息
- 操作系统:Ubuntu 18.04 LTS
- 总内存:8.0 GB
- 交换:4 GB
- 张量流 1.8
- 二进制安装
更多信息
正如我之前提到的,当我使用 keras 时,我可以轻松地按顺序导出 keras,并且能够model.pbtxt
使用从backend
. 模型的大小和配置与此代码相同。
使用 tensorflow 1.4,即使使用 4 GB 的 RAM,我也能够轻松导出和保存此类模型。现在我有 8 个,为什么会抛出 MemoryError?抱歉确切的日志,它只显示一次,现在每次我运行这段代码时,我的系统都崩溃了,因为它用完了所有的内存
此外,当我运行代码时,我收到一个警告:
2018-05-16 21:42:08.844531: W tensorflow/core/framework/allocator.cc:101] 376320000 的分配超过了系统内存的 10%。
问题
我该如何解决这个问题,是什么原因造成的?
编辑
我通过正常的 numpy 修改删除了 tf.data.Dataset,一切正常。我仍然想知道,为什么不使用 tf.data.Dataset 解决这个问题?这会为大图添加额外的节点吗?我们应该只在大数据和大机器上训练时使用这些管道吗?
解决方案
尝试将批量大小设置为较低的值,它应该可以解决问题。
例如
iter = data_pipeline.shuffle(1000).repeat().batch(256).make_one_shot_iterator()
推荐阅读
- json - 将存储为变量的 URL 转换为 Google Apps 脚本文件中 JSON 有效负载中的 href
- angular - 如何在 Angular 的过滤器中使用参数?
- c++ - 更改字符串中的一个字母以生成新单词 c++
- node.js - NodeJS express 发送错误的标头
- python - 如何正确使用 tensorflow 数据集用于 keras 的多个输入层
- android - 在 android 中使用字符串资源的问题,它是一个 html 实体
- javascript - 如何将 JS 和 GSAP 按钮转换为 REACT JS
- c# - 如何做一个接收数组的递归函数,找到它的总和以及数组中除以总和的整数
- java - 可以用Java中的变量创建数组吗?
- jenkins - 将文件中的每个文件路径替换为符号链接后面的路径