📜  Python – tensorflow.constant()(1)

📅  最后修改于: 2023-12-03 15:19:03.536000             🧑  作者: Mango

Python - tensorflow.constant()

Introduction

In TensorFlow, you can create constants using the tf.constant() method. A constant value is a tensor whose value cannot be changed. The tf.constant() method is used to define these values. This method takes a Python value as input, and returns a TensorFlow constant tensor representing the input value.

Syntax
tf.constant(
    value,
    dtype=None,
    shape=None,
    name='Const')
Parameters
  • value: The value of the constant tensor.
  • dtype: The data type of the tensor. If not specified, TensorFlow infers the data type from the input value.
  • shape: The shape of the tensor. If not specified, TensorFlow infers the shape from the input value.
  • name: The name for the tensor.
Examples
Example 1: Create a Constant Tensor with Default Data Type and Shape
import tensorflow as tf

# creating a constant tensor with value 5
a = tf.constant(5)
print(a) # output: Tensor("Const:0", shape=(), dtype=int32)

In this example, we are creating a constant tensor with the value 5. Since the dtype and shape are not specified, TensorFlow infers the data type and shape from the input value (which is an integer). The output is a tensor with the name Const and the data type int32.

Example 2: Create a Constant Tensor with Custom Data Type and Shape
import tensorflow as tf

# creating a constant tensor with value 2.0 and data type float32
b = tf.constant(2.0, dtype=tf.float32, shape=[2, 3])
print(b) # output: Tensor("Const_1:0", shape=(2, 3), dtype=float32)

In this example, we are creating a constant tensor with the value 2.0, the data type float32, and the shape [2, 3]. The output is a tensor with the name Const_1, the data type float32, and the shape (2, 3).

Example 3: Changing the Name of a Constant Tensor
import tensorflow as tf

# creating a constant tensor with value 7 and name "my_constant"
c = tf.constant(7, name="my_constant")
print(c) # output: Tensor("my_constant:0", shape=(), dtype=int32)

In this example, we are creating a constant tensor with the value 7 and the name my_constant. The output is a tensor with the name my_constant and the data type int32.

Conclusion

In this tutorial, we learned how to use the tf.constant() method to create constant tensors in TensorFlow. We also learned how to specify the data type, shape, and name of a constant tensor. These constant tensors can be used as inputs to TensorFlow operations, making it easy to create complex mathematical models with ease.