Tensorflow Estimator预测很慢

Ste*_*let 7 performance tensorflow tensorflow-estimator

我训练了一个tf.estimator.LinearClassifier.虽然训练和评估模型需要一段合理的时间用于我的数据大小(约60秒),但预测需要更长的时间(约1小时).

预测代码如下:

predictionResult = estimator.predict(input_fn=lambda: my_input_fn2(predictionValidationFile, False, 1))
predictionList = [prediction for prediction in  predictionResult]
Run Code Online (Sandbox Code Playgroud)

有:

def my_input_fn2(file_path, perform_shuffle=False, repeat_count=1):
def _parse_function(example_proto):      
  keys_to_features = {"xslm": tf.FixedLenFeature([10000], tf.float32),
                      "xrnn": tf.FixedLenFeature([10000], tf.float32),
                      "target": tf.FixedLenFeature([10000], tf.float32)}
  parsed_features = tf.parse_single_example(example_proto, keys_to_features)      
  myfeatures = {'xrnn':parsed_features['xrnn'], 'xslm':parsed_features['xslm']}
  return myfeatures, parsed_features['target'] 

dataset = (tf.data.TFRecordDataset(file_path)                
           .map(_parse_function))     
dataset = dataset.repeat(repeat_count) 
dataset = dataset.batch(1)  
iterator = dataset.make_one_shot_iterator()
batch_feature,  batch_labels = iterator.get_next()    
xs= tf.reshape(batch_feature['xslm'],[-1,1])
xr= tf.reshape(batch_feature['xrnn'],[-1,1])
x = {'xrnn':xr, 'xslm':xs}
y = tf.reshape(batch_labels, [-1,1])
return x, y
Run Code Online (Sandbox Code Playgroud)

当运行10 000个样本(对应于一个批次)时,第二行需要0.8秒才能执行.有500万个样本,预测需要一个多小时.

我在这个阶段的猜测是,这种缓慢的性能仅仅是由于估计器predict()函数返回一个python生成器而不是返回实际的预测结果.对于每个批次,生成器最终会对函数进行10 000次调用以获得10 000个预测结果.这似乎效率低下.

有没有选择加快速度?

小智 0

您对速度缓慢的原因是正确的。它正在为每个项目调用该函数,因为函数中的 bach 大小默认为 1。

您应该将批量大小作为参数传递给函数并替换

dataset = dataset.batch(1) 
Run Code Online (Sandbox Code Playgroud)

dataset = dataset.batch(batch_size) 
Run Code Online (Sandbox Code Playgroud)