在Tensorflow中,如何将张量/数组添加到已经包含多个张量/数组的张量/数组中。 tf.concat和st.stack需要相同的形状

时间:2019-01-01 23:25:32

标签: python tensorflow

这是我要尝试做的一个最小示例。在这里,我只使用常规的python数组来最小化代码,但我希望使用tensorflow张量来做到这一点。

import tensorflow as tf

c1 = [[5,8], [7,4]]
c2 = [6,9]
c3= tf.stack( [c1, c2] ) 
with tf.Session( ) as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run([ c3] ))

这是我得到的错误

---------------------------------------------------------------------------
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].

我也尝试过使用不同的轴值以及tf.concat。似乎都需要相等的形状才能合并张量。

我正在寻找这样的结果

c3=[[5,8], [7,4], [6,9] ]

1 个答案:

答案 0 :(得分:1)

我认为您想要的是tf.concat。因此,您需要数组具有相同的尺寸,而不是形状。因此,将c2提升为二维数组将解决此问题:

c1 = [[5,8], [7,4]]

# change c2 to be 2-D
c2 = [[6,9]]

# use concat
c3= tf.concat( [c1, c2], axis=0) 

with tf.Session( ) as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(c3))

请注意,如果使用张量,则可以使用tf.expand_dims(c2 ,0)将c2(如果是占位符/变量)提升为二维张量。