python - 使用 GPU 与 CPU 计算损失的 tensorflow

标签 python tensorflow

我对使用 GPU 与 CPU 计算损失时在损失计算中得到的差异感到有点困惑。

模型是 6 层 CNN。

从检查点加载模型并使用相同的数据运行它。先用 CPU 再用 GPU 计算损失。

CPU 损失:0.4687191 GPU损失:0.46873742

有人可以向我解释为什么这些损失的计算方式不同吗?

#WITH CPU! - testing cpu vs cpu optimizer calculations
import time
tf.reset_default_graph()



new_saver = tf.train.import_meta_graph('./graph/final.meta')

with tf.Session() as sess:
  new_saver.restore(sess, tf.train.latest_checkpoint('./tmp'))

  optimize = tf.get_default_graph().get_operation_by_name( "optimizer" )
  c_loss = sess.run('loss:0', feed_dict={'x:0': x_train[0:128], 'y:0': y_train[0:128], 'is_training:0': True})
  print('initial:  c_loss', c_loss)  

  sess.run(optimize, feed_dict={'x:0': x_train[0:128], 'y:0': y_train[0:128], 'is_training:0': True})
  c_loss = sess.run('loss:0', feed_dict={'x:0': x_train[0:128], 'y:0': y_train[0:128], 'is_training:0': True})

  print('post:  c_loss', c_loss)

输出:
初始值:c_loss 0.4687191
帖子:c_loss 0.5455321

#WITH GPU! - testing cpu vs gpu optimizer calculations
import time
tf.reset_default_graph()


new_saver = tf.train.import_meta_graph('gdrive/My Drive/graph/final.meta')

with tf.Session() as sess:
  new_saver.restore(sess, tf.train.latest_checkpoint('gdrive/My Drive/tmp'))

  optimize = tf.get_default_graph().get_operation_by_name( "optimizer" )
  c_loss = sess.run('loss:0', feed_dict={'x:0': x_train[0:128], 'y:0': y_train[0:128], 'is_training:0': True})
  print('initial:  c_loss', c_loss)  

  sess.run(optimize, feed_dict={'x:0': x_train[0:128], 'y:0': y_train[0:128], 'is_training:0': True})
  c_loss = sess.run('loss:0', feed_dict={'x:0': x_train[0:128], 'y:0': y_train[0:128], 'is_training:0': True})

  print('post:  c_loss', c_loss)

输出:
初始值:c_loss 0.46873742
帖子:c_loss 0.5432756

编辑: 还。想补充一下我用两个不同的 CPU session 加载模型,发现上面的损失计算是相同的。它们仅在我使用 GPU 计算损失时发生变化。

最佳答案

如果您对用于训练模型的数据进行混洗,它们可能会有所不同。尝试在代码上方(但在导入之后)修复 numpy.random.seed(123),然后禁用改组,损失应该相同。

例如,tensorlayers 小批量生成器允许您将 shuffle 参数设置为 False。

import numpy as np
import tensorlayers as tl

X = np.asarray([['a','a'], ['b','b'], ['c','c'], ['d','d'], ['e','e'], ['f','f']])
y = np.asarray([0,1,2,3,4,5])

for batch in tl.iterate.minibatches(inputs=X, targets=y, batch_size=16, shuffle=False):
    print(batch)

关于python - 使用 GPU 与 CPU 计算损失的 tensorflow ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53114494/

相关文章:

python - 如何让 TensorFlow 的 'import_graph_def' 返回 Tensors

python - 如何在keras中为tensorboard提供学习率值

OS X 与 Ubuntu 上的 Python asyncio 性能

python - 构造列表中出现次数的列表

python - 使用微调的 Inception-v3 模型对单个图像进行预测

python - 更快地计算 face_descriptor

使用 dataset.map 进行 tensorflow 数据集图像转换

python - 使模型中的用户默认为当前用户

python - 从列表 python 添加类似的字母数字元素

python - 扭曲的调用远程