错误无法将列表转换为Tensor或Operation

时间:2016-09-30 03:55:29

标签: tensorflow

运行tensorflow program时,我不断收到以下错误消息,其中大部分内容与TypeError: Fetch argument[....]has invalid type <class 'list'>, must be a string or Tensor. (Can not convert a list into a Tensor or Operation.)类似,直接导致此错误的相关代码段为_, loss, lr, gradients = sess.run((self.optimizer, self.net.cost, self.learning_rate_node, self.net.gradients_node), feed_dict={self.net.x: batch_x,self.net.y: util.crop_to_shape(batch_y,pred_shape), self.net.keep_prob: dropout})

我对导致此错误消息的原因感到困惑,因为它可以由作者成功运行,如github帖子所示。

总错误消息如下:

`回溯(最近一次呼叫最后):
  文件“/develop/tfw/lib/python3.4/site-packages/tensorflow/python/client/session.py”,第480行,在_process_fetches中     allow_operation =真)
  文件“/develop/tfw/lib/python3.4/site-packages/tensorflow/python/framework/ops.py”,第2301行,as_graph_element
    %(类型(obj)。名称,types_str))
TypeError:无法将列表转换为Tensor或Operation。

在处理上述异常期间,发生了另一个异常:

追踪(最近一次通话):   文件“test.py”,第30行,in     path = trainer.train(generator,“。/ unet_trained”,training_iters = 20,epochs = 100,display_step = 2)   在火车上输入文件“/home/user/test/u-net/ver3/unet.py”,第364行     self.net.keep_prob:dropout})   文件“/develop/tfw/lib/python3.4/site-packages/tensorflow/python/client/session.py”,第340行,在运行中     run_metadata_ptr)   文件“/develop/tfw/lib/python3.4/site-packages/tensorflow/python/client/session.py”,第523行,在_run中     processed_fetches = self._process_fetches(fetches)   在_process_fetches中输入文件“/develop/tfw/lib/python3.4/site-packages/tensorflow/python/client/session.py”,第493行     %(subfetch,fetch,type(subfetch),str(e))) TypeError:[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, :0'shape =(16,)dtype = float32&gt;,,,,,,,,]具有无效类型,必须是字符串或Tensor。 (无法将列表转换为Tensor或Operation。) `

1 个答案:

答案 0 :(得分:0)

如果您使用Tensorflow版本r0.9或以前的版本,则Session.run不会在fetches参数中接受任意嵌套的列表或元组。因此,元组中的self.net.gradients_node(这是一个张量列表)会导致您的TypeError。此代码应在Tensorflow r0.10中有效。 如果您希望保持在r0.9,请修改以下行:

_, loss, lr, gradients = sess.run((self.optimizer, self.net.cost, self.learning_rate_node, self.net.gradients_node), feed_dict={self.net.x: batch_x,self.net.y: util.crop_to_shape(batch_y,pred_shape), self.net.keep_prob: dropout})

list_of_outputs = sess.run([self.optimizer, self.net.cost, self.learning_rate_node]+ self.net.gradients_node, feed_dict={self.net.x: batch_x,self.net.y: util.crop_to_shape(batch_y,pred_shape), self.net.keep_prob: dropout})
loss = list_of_outputs[1]
lr = list_of_outputs[2]
gradients = list_of_outputs[2:]

或(使用Python 3。*)

_,loss,lr,*gradients = sess.run([self.optimizer, self.net.cost, self.learning_rate_node]+ self.net.gradients_node, feed_dict={self.net.x: batch_x,self.net.y: util.crop_to_shape(batch_y,pred_shape), self.net.keep_prob: dropout})

这应该有效