我使用TensorFlow来预测神经网络的输出。我有一个类,其中描述了神经网络,还有一个主文件,负责进行预测并根据结果更新权重。然而,预测速度似乎非常慢。以下是我的代码结构:
class NNPredictor(): def __init__(self): self.input = tf.placeholder(...) ... self.output = (...) #神经网络输出 def predict_output(self, sess, input): return sess.run(tf.squeeze(self.output), feed_dict = {self.input: input})
主文件的结构如下:
sess = tf.Session()predictor = NNPredictor()input = #初始值 for i in range(iter): output = predictor.predict_output(sess, input) input = #output的某个函数
但是,如果我在类中使用以下函数定义:
def predict_output(self): return self.output
并将主文件改为如下结构:
sess = tf.Session()predictor = NNPredictor()input = #初始值 output_op = predictor.predict_value()for i in range(iter): output = np.squeeze(sess.run(output_op, feed_dict = {predictor.input: input})) input = #output的某个函数
代码运行速度几乎提高了20-30倍。我不太理解这里的运行机制,想知道最佳实践是什么。
回答:
这与Python掩盖的底层内存访问有关。以下是一些示例代码来说明这个概念:
import timeruns = 10000000class A: def __init__(self): self.val = 1 def get_val(self): return self.val# 使用方法然后调用对象属性obj = A()start = time.time()total = 0for i in xrange(runs): total += obj.get_val()end = time.time()print end - start# 直接使用对象属性start = time.time()total = 0for i in xrange(runs): total += obj.valend = time.time()print end - start# 首先赋值给局部变量start = time.time()total = 0local_var = obj.get_val()for i in xrange(runs): total += local_varend = time.time()print end - start
在我的电脑上,运行时间如下:
1.495761156080.6561100482940.551875114441
具体到你的情况,第一种情况下你调用了对象方法,而第二种情况没有。如果你以这种方式多次调用代码,将会有显著的性能差异。