错误:无法将int转换为Tensor或Operation。在张量流中制作CNN

时间:2018-05-27 07:20:12

标签: python tensorflow

我正在尝试使用CNN在tensorflow中创建一个自动编码器。这是我的代码。

hm_epochs = 10
learning_rate = 0.001
dropout = 0.2
batch_size = 128

x = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))

def conv_layer(x, filters):
  return tf.layers.conv2d(inputs=x, filters=filters, kernel_size=[3, 3], padding="same", activation=tf.nn.relu)

def downsample_layer(x):
  return tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2, padding='same')

def dropout_layer(x, dropout):
  return tf.layers.dropout(inputs=x, rate=dropout)

def deconv_layer(x, filters):
  return tf.layers.conv2d_transpose(inputs=x, filters=filters, kernel_size=[3, 3], strides=2, padding="same", activation=tf.nn.relu)

def model(x):

  with tf.name_scope('encoder'):
    print('input shape:', x.shape)

    conv1 = conv_layer(x, 32)
    conv1 = downsample_layer(conv1)
    conv1 = dropout_layer(conv1, dropout)
    print('conv1 shape:', conv1.shape)

    conv2 = conv_layer(conv1, 16)
    conv2 = downsample_layer(conv2)
    conv2 = dropout_layer(conv2, dropout)
    print('conv2 shape:', conv2.shape)

    conv3 = conv_layer(conv2, 8)
    encoded = downsample_layer(conv3)
    print('encoded shape:', encoded.shape)

  with tf.name_scope('decoder'):  
    conv4 = conv_layer(encoded, 8)
    conv4 = deconv_layer(conv4, 16)
    conv4 = dropout_layer(conv4, dropout)
    conv4 = tf.image.resize_images(conv4, size=(7,7), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
    print('conv4 shape:', conv4.shape)

    conv5 = deconv_layer(conv4, 32)
    conv5 = dropout_layer(conv5, dropout)
    print('conv5 shape:', conv5.shape)

    conv6 = conv_layer(conv5, 32)
    decoded = deconv_layer(conv6, 1)
    print('decoded shape:', decoded.shape)

    return decoded

def train_model(x):
  output = model(x)
  loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=x, logits=output))
  opt = tf.train.AdamOptimizer(learning_rate).minimize(loss)

  mnist = input_data.read_data_sets("MNIST_data/")
  hm_batches = mnist.train.num_examples // batch_size
  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epochs in range(hm_epochs):
      loss = 0
      for _ in range(hm_batches):
        batch_img, batch_label = mnist.train.next_batch(batch_size)
        batch_img = batch_img.reshape((-1, 28, 28, 1))

        _, c = sess.run([opt, loss], feed_dict={x: batch_img})
        loss += c
      print("Epoch: {0}/{1} - loss: {2}".format(epochs+1, hm_epochs, loss))
train_model(x)

当我运行模型时,我收到此错误:

TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    281         self._unique_fetches.append(ops.get_default_graph().as_graph_element(
--> 282             fetch, allow_tensor=True, allow_operation=True))
    283       except TypeError as e:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3589     with self._lock:
-> 3590       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3591 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3678       raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
-> 3679                                                            types_str))
   3680 

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

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-50-484079d033a4> in <module>()
----> 1 train_model(x)

<ipython-input-49-f458dca502dd> in train_model(x)
     15         batch_img = batch_img.reshape((-1, 28, 28, 1))
     16 
---> 17         _, c = sess.run([opt, loss], feed_dict={x: batch_img})
     18         loss += c
     19       print("Epoch: {0}/{1} - loss: {2}".format(epochs+1, hm_epochs, loss))

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    898     try:
    899       result = self._run(None, fetches, feed_dict, options_ptr,
--> 900                          run_metadata_ptr)
    901       if run_metadata:
    902         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1118     # Create a fetch handler to take care of the structure of fetches.
   1119     fetch_handler = _FetchHandler(
-> 1120         self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
   1121 
   1122     # Run request and get response.

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds, feed_handles)
    425     """
    426     with graph.as_default():
--> 427       self._fetch_mapper = _FetchMapper.for_fetch(fetches)
    428     self._fetches = []
    429     self._targets = []

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in for_fetch(fetch)
    243     elif isinstance(fetch, (list, tuple)):
    244       # NOTE(touts): This is also the code path for namedtuples.
--> 245       return _ListFetchMapper(fetch)
    246     elif isinstance(fetch, dict):
    247       return _DictFetchMapper(fetch)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches)
    350     """
    351     self._fetch_type = type(fetches)
--> 352     self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
    353     self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
    354 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in <listcomp>(.0)
    350     """
    351     self._fetch_type = type(fetches)
--> 352     self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
    353     self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
    354 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in for_fetch(fetch)
    251         if isinstance(fetch, tensor_type):
    252           fetches, contraction_fn = fetch_fn(fetch)
--> 253           return _ElementFetchMapper(fetches, contraction_fn)
    254     # Did not find anything.
    255     raise TypeError('Fetch argument %r has invalid type %r' % (fetch,

/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    284         raise TypeError('Fetch argument %r has invalid type %r, '
    285                         'must be a string or Tensor. (%s)' %
--> 286                         (fetch, type(fetch), str(e)))
    287       except ValueError as e:
    288         raise ValueError('Fetch argument %r cannot be interpreted as a '

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

在模型图中,变量x未转换为int。另外,我尝试使用xtf.convert_to_tensor()转换为张量,但这并没有帮助。 我已经看到堆栈溢出的其他答案,但得到相同的错误。 请帮帮我。

1 个答案:

答案 0 :(得分:0)

错误是因为您已将\\b声明为loss的张量,然后在cross entropy loss内再次使用loss作为int来打印失利。将损失变量重命名为此循环中的其他内容:

train loop