MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / repeat_elements

Function repeat_elements

tensorflow/python/keras/backend.py:2753–2810  ·  view source on GitHub ↗

Repeats the elements of a tensor along an axis, like `np.repeat`. If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output will have shape `(s1, s2 * rep, s3)`. Arguments: x: Tensor or variable. rep: Python integer, number of times to repeat. axis: Axis along which to

(x, rep, axis)

Source from the content-addressed store, hash-verified

2751
2752@keras_export('keras.backend.repeat_elements')
2753def repeat_elements(x, rep, axis):
2754 """Repeats the elements of a tensor along an axis, like `np.repeat`.
2755
2756 If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output
2757 will have shape `(s1, s2 * rep, s3)`.
2758
2759 Arguments:
2760 x: Tensor or variable.
2761 rep: Python integer, number of times to repeat.
2762 axis: Axis along which to repeat.
2763
2764 Returns:
2765 A tensor.
2766
2767 Example:
2768 ```python
2769 >>> b = tf.constant([1, 2, 3])
2770 >>> tf.keras.backend.repeat_elements(b, rep=2, axis=0)
2771 <tf.Tensor: id=70, shape=(6,), dtype=int32,
2772 numpy=array([1, 1, 2, 2, 3, 3], dtype=int32)>
2773 ```
2774 """
2775 x_shape = x.shape.as_list()
2776 # For static axis
2777 if x_shape[axis] is not None:
2778 # slices along the repeat axis
2779 splits = array_ops.split(value=x,
2780 num_or_size_splits=x_shape[axis],
2781 axis=axis)
2782 # repeat each slice the given number of reps
2783 x_rep = [s for s in splits for _ in range(rep)]
2784 return concatenate(x_rep, axis)
2785
2786 # Here we use tf.tile to mimic behavior of np.repeat so that
2787 # we can handle dynamic shapes (that include None).
2788 # To do that, we need an auxiliary axis to repeat elements along
2789 # it and then merge them along the desired axis.
2790
2791 # Repeating
2792 auxiliary_axis = axis + 1
2793 x_shape = array_ops.shape(x)
2794 x_rep = array_ops.expand_dims(x, axis=auxiliary_axis)
2795 reps = np.ones(len(x.shape) + 1)
2796 reps[auxiliary_axis] = rep
2797 x_rep = array_ops.tile(x_rep, reps)
2798
2799 # Merging
2800 reps = np.delete(reps, auxiliary_axis)
2801 reps[axis] = rep
2802 reps = array_ops.constant(reps, dtype='int32')
2803 x_shape *= reps
2804 x_rep = array_ops.reshape(x_rep, x_shape)
2805
2806 # Fix shape representation
2807 x_shape = x.shape.as_list()
2808 x_rep.set_shape(x_shape)
2809 x_rep._keras_shape = tuple(x_shape)
2810 return x_rep

Callers 1

resize_volumesFunction · 0.85

Calls 13

tupleFunction · 0.85
onesMethod · 0.80
tileMethod · 0.80
reshapeMethod · 0.80
concatenateFunction · 0.70
rangeFunction · 0.50
as_listMethod · 0.45
splitMethod · 0.45
shapeMethod · 0.45
expand_dimsMethod · 0.45
deleteMethod · 0.45
constantMethod · 0.45

Tested by

no test coverage detected