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

时间:2019-01-01 22:57:27

标签: python tensorflow

我试图合并两个相同形状的张量流常量,但出现错误。这是代码。 (我只是对其进行编辑以使init值明确)

将tensorflow导入为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数组替换张量,则它会工作,但是某些张量流常量和axis = 1的组合会引起问题。

1 个答案:

答案 0 :(得分:2)

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

已编辑,因为我是第一次误读脚本。正如我评论的那样,由于张量为1级(它们只有一个0轴,或者它们只有1个维度),因此无法在第一条轴上并置。如果它们是2级(需要用两个维来描述形状),则可以在第一个轴上串联而不会出现问题。

例如,您可以沿轴= 1串联张量([[5,8]])和张量([[6,9]]),因为它们具有形状[1,2],而不仅仅是形状[2] ]。