Tensorflow Debug:TypeError: Fetch argument .+ has invalid type

问题代码:

x = tf.placeholder(tf.float32,shape=[None,784])
y = tf.placeholder(tf.int32,shape=[None,1])

with tf.variable_scope("fc1"):
    weights1 = tf.get_variable('weight',shape=[784,128],dtype=tf.float32,initializer=tf.glorot_uniform_initializer())
    biases1 = tf.get_variable('biases',shape=[128,],dtype=tf.float32,initializer=tf.glorot_uniform_initializer())
    out1 = tf.add(tf.matmul(x,weights1),biases1)
    out1 = tf.nn.relu(out1)
    
with tf.variable_scope("fc2"):
    weights2 = tf.get_variable('weight',shape=[128,64],dtype=tf.float32,initializer=tf.glorot_uniform_initializer())
    biases2 = tf.get_variable('biases',shape=[64,],dtype=tf.float32,initializer=tf.glorot_uniform_initializer())
    out2 = tf.add(tf.matmul(out1,weights2),biases2)
    out2 = tf.nn.relu(out2)
    
with tf.variable_scope("fc3"):
    weights3 = tf.get_variable('weight',shape=[64,10],dtype=tf.float32,initializer=tf.glorot_uniform_initializer())
    biases3 = tf.get_variable('biases',shape=[10,],dtype=tf.float32,initializer=tf.glorot_uniform_initializer())
    out3 = tf.add(tf.matmul(out2,weights3),biases3)
    out3 = tf.nn.softmax(out3)
    
loss = tf.losses.sparse_softmax_cross_entropy(labels=y,logits=out3)
outlabel = tf.argmax(out3,axis=1)
acc = tf.metrics.accuracy(labels=y,predictions=outlabel)
optimizer = tf.train.AdamOptimizer(learning_rate=0.0002)
train = optimizer.minimize(loss)
batch_size = 128

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(80):
        i = int(0)
        lenth = len(train_images)
        while i<lenth:
            r = i+batch_size
            if r>=lenth: r=lenth-1
            batch_x = train_images[i:r]
            batch_y = train_labels[i:r]
            _,loss = sess.run((train,loss),feed_dict={x:batch_x,y:batch_y})
            print('loss:%s , acc: '%(loss))

错误信息:

loss:2.3943863 , acc: 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    270         self._unique_fetches.append(ops.get_default_graph().as_graph_element(
--> 271             fetch, allow_tensor=True, allow_operation=True))
    272       except TypeError as e:

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3034     with self._lock:
-> 3035       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3036 

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3123       raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
-> 3124                                                            types_str))
   3125 

TypeError: Can not convert a float32 into a Tensor or Operation.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-7-3f1ab98d5659> in <module>()
      9             batch_x = train_images[i:r]
     10             batch_y = train_labels[i:r]
---> 11             _,loss = sess.run((train,loss),feed_dict={x:batch_x,y:batch_y})
     12             print('loss:%s , acc: '%(loss))

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    887     try:
    888       result = self._run(None, fetches, feed_dict, options_ptr,
--> 889                          run_metadata_ptr)
    890       if run_metadata:
    891         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1103     # Create a fetch handler to take care of the structure of fetches.
   1104     fetch_handler = _FetchHandler(
-> 1105         self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
   1106 
   1107     # Run request and get response.

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds, feed_handles)
    412     """
    413     with graph.as_default():
--> 414       self._fetch_mapper = _FetchMapper.for_fetch(fetches)
    415     self._fetches = []
    416     self._targets = []

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in for_fetch(fetch)
    232     elif isinstance(fetch, (list, tuple)):
    233       # NOTE(touts): This is also the code path for namedtuples.
--> 234       return _ListFetchMapper(fetch)
    235     elif isinstance(fetch, dict):
    236       return _DictFetchMapper(fetch)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches)
    339     """
    340     self._fetch_type = type(fetches)
--> 341     self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
    342     self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
    343 

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in <listcomp>(.0)
    339     """
    340     self._fetch_type = type(fetches)
--> 341     self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
    342     self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
    343 

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in for_fetch(fetch)
    240         if isinstance(fetch, tensor_type):
    241           fetches, contraction_fn = fetch_fn(fetch)
--> 242           return _ElementFetchMapper(fetches, contraction_fn)
    243     # Did not find anything.
    244     raise TypeError('Fetch argument %r has invalid type %r' %

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    273         raise TypeError('Fetch argument %r has invalid type %r, '
    274                         'must be a string or Tensor. (%s)'
--> 275                         % (fetch, type(fetch), str(e)))
    276       except ValueError as e:
    277         raise ValueError('Fetch argument %r cannot be interpreted as a '

TypeError: Fetch argument 2.3943863 has invalid type <class 'numpy.float32'>, must be a string or Tensor. (Can not convert a float32 into a Tensor or Operation.)

感觉看的一头雾水,直到我看到了https://blog.csdn.net/myjiayan/article/details/60579395。大神讲的非常到位啊…

原来问题就出在

_,loss = sess.run((train,loss),feed_dict={x:batch_x,y:batch_y})

这句,看出问题了么。等号左边的loss和sess.run里的loss重名了!那么跑一遍后,loss就会等于计算出的那个值,比如是0.25,然后再作为参数传入sess.run,即sess.run((train,0.25),feed_dict),于是就出错了!!

改正后

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(80):
        i = int(0)
        lenth = len(train_images)
        while i<lenth:
            r = i+batch_size
            if r>=lenth: r=lenth-1
            batch_x = train_images[i:r]
            batch_y = train_labels[i:r]
            _,_loss = sess.run((train,loss),feed_dict={x:batch_x,y:batch_y})
            print('loss:%s , acc: '%(_loss))

问题解决。

posted @ 2019-03-22 01:03  大胖子球花  阅读(1072)  评论(0)    收藏  举报