【发布时间】:2018-10-26 20:00:58
【问题描述】:
我试图将简单的 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,并且能够使用从backend 获得的会话编写model.pbtxt。模型的大小和配置与此代码相同。
使用 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 解决这个问题?这是否会在大图中添加额外的节点?我们应该只在大数据和大机器上训练时使用这些管道吗?
【问题讨论】:
-
我发现如果我不使用 tf.data.Dataset,那么代码可以正常工作。但我想知道为什么?
标签: python tensorflow