Creates a tensor with all elements set to 1. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to 1. For example: ```python tf.ones([2, 3], tf.int32) # [[1, 1, 1], [1, 1, 1]] ``` Args: shape: A list of integers, a tuple of integers, or a 1
(shape, dtype=dtypes.float32, name=None)
| 2532 | |
| 2533 | @tf_export("ones") |
| 2534 | def ones(shape, dtype=dtypes.float32, name=None): |
| 2535 | """Creates a tensor with all elements set to 1. |
| 2536 | |
| 2537 | This operation returns a tensor of type `dtype` with shape `shape` and all |
| 2538 | elements set to 1. |
| 2539 | |
| 2540 | For example: |
| 2541 | |
| 2542 | ```python |
| 2543 | tf.ones([2, 3], tf.int32) # [[1, 1, 1], [1, 1, 1]] |
| 2544 | ``` |
| 2545 | |
| 2546 | Args: |
| 2547 | shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type |
| 2548 | `int32`. |
| 2549 | dtype: The type of an element in the resulting `Tensor`. |
| 2550 | name: A name for the operation (optional). |
| 2551 | |
| 2552 | Returns: |
| 2553 | A `Tensor` with all elements set to 1. |
| 2554 | """ |
| 2555 | dtype = dtypes.as_dtype(dtype).base_dtype |
| 2556 | with ops.name_scope(name, "ones", [shape]) as name: |
| 2557 | one = True if dtype == dtypes.bool else 1 |
| 2558 | if not isinstance(shape, ops.Tensor): |
| 2559 | try: |
| 2560 | # Create a constant if it won't be very big. Otherwise create a fill op |
| 2561 | # to prevent serialized GraphDefs from becoming too large. |
| 2562 | output = _constant_if_small(one, shape, dtype, name) |
| 2563 | if output is not None: |
| 2564 | return output |
| 2565 | |
| 2566 | # Go through tensor shapes to get int64-if-needed semantics |
| 2567 | shape = constant_op._tensor_shape_tensor_conversion_function( |
| 2568 | tensor_shape.TensorShape(shape)) |
| 2569 | except (TypeError, ValueError): |
| 2570 | # Happens when shape is a list with tensor elements |
| 2571 | shape = ops.convert_to_tensor(shape, dtype=dtypes.int32) |
| 2572 | if not shape._shape_tuple(): |
| 2573 | shape = reshape(shape, [-1]) # Ensure it's a vector |
| 2574 | output = fill(shape, constant(one, dtype=dtype), name=name) |
| 2575 | assert output.dtype.base_dtype == dtype |
| 2576 | return output |
| 2577 | |
| 2578 | |
| 2579 | @tf_export(v1=["placeholder"]) |