首页 > 解决方案 > tf.concat 给出“形状必须至少为 2 级,但为 1 级”的错误,即使两个张量的形状相同

问题描述

我正在尝试连接两个相同形状的张量流常量,但出现错误。这是代码。(我只是编辑它以明确初始化值)

将张量流导入为 tf

b1 = tf.constant(value=[5,8])
b2 = tf.constant(value=[6,9])
b3= tf.concat( [b1, b2] , 1) 

with tf.Session( ) as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run([ b3] ))

给出这个错误

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1658   try:
-> 1659     c_op = c_api.TF_FinishOperation(op_desc)
   1660   except errors.InvalidArgumentError as e:

InvalidArgumentError: Shapes must be equal rank, but are 2 and 1
    From merging shape 0 with other shapes. for 'stack_38' (op: 'Pack') with input shapes: [2,2], [2].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-96-3acc40ce0738> in <module>()
      1 c1 = [[5,8], [7,4]]
      2 c2 = [6,9]
----> 3 c3= tf.stack( [c1, c2] )
      4 with tf.Session( ) as sess:
      5     sess.run(tf.global_variables_initializer())

/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs)
    178     """Call target, and fall back on dispatchers if there is a TypeError."""
    179     try:
--> 180       return target(*args, **kwargs)
    181     except (TypeError, ValueError):
    182       # Note: convert_to_eager_tensor currently raises a ValueError, not a

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py in stack(values, axis, name)
   1003                                                       expanded_num_dims))
   1004 
-> 1005   return gen_array_ops.pack(values, axis=axis, name=name)
   1006 
   1007 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_array_ops.py in pack(values, axis, name)
   5446   axis = _execute.make_int(axis, "axis")
   5447   _, _, _op = _op_def_lib._apply_op_helper(
-> 5448         "Pack", values=values, axis=axis, name=name)
   5449   _result = _op.outputs[:]
   5450   _inputs_flat = _op.inputs

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    786         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    787                          input_types=input_types, attrs=attr_protos,
--> 788                          op_def=op_def)
    789       return output_structure, op_def.is_stateful, op
    790 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/deprecation.py in new_func(*args, **kwargs)
    499                 'in a future version' if date is None else ('after %s' % date),
    500                 instructions)
--> 501       return func(*args, **kwargs)
    502 
    503     doc = _add_deprecated_arg_notice_to_docstring(

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in create_op(***failed resolving arguments***)
   3298           input_types=input_types,
   3299           original_op=self._default_original_op,
-> 3300           op_def=op_def)
   3301       self._create_op_helper(ret, compute_device=compute_device)
   3302     return ret

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in __init__(self, node_def, g, inputs, output_types, control_inputs, input_types, original_op, op_def)
   1821           op_def, inputs, node_def.attr)
   1822       self._c_op = _create_c_op(self._graph, node_def, grouped_inputs,
-> 1823                                 control_input_ops)
   1824 
   1825     # Initialize self._outputs.

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1660   except errors.InvalidArgumentError as e:
   1661     # Convert to ValueError for backwards compatibility.
-> 1662     raise ValueError(str(e))
   1663 
   1664   return c_op

ValueError: Shapes must be equal rank, but are 2 and 1
    From merging shape 0 with other shapes. for 'stack_38' (op: 'Pack') with input shapes: [2,2], [2].

即使这两个张量的形状完全相同。如果我做axis = 0它可以工作,如果我用相同数字的常规numpy数组替换张量,它可以工作,但是一些tensorflow常量和axis = 1的组合会导致问题。

标签: pythontensorflow

解决方案


我对您的问题有点困惑,但是两个张量的第 0 轴维度必须相同才能沿第 1 轴连接。使 b1 具有形状 [6,8] 或 b2 具有形状 [5,9] 有什么作用?这些情况中的任何一种都应该导致成功的串联。

编辑是因为我第一次看错了剧本。正如我评论的那样,您不能在第一个轴上连接,因为您的张量排名为 1(它们只有轴 0,或者它们只有 1 个维度)。如果它们是 2 级(需要两个维度来描述形状),那么您可以毫无问题地在第一个轴上连接。

例如,您可以跨轴 = 1 连接 tensor([[5,8]]) 和 tensor([[6,9]]),因为它们具有形状 [1,2] 而不仅仅是形状 [2]。


推荐阅读