Python TensorFlow scalar multiplication
Python TensorFlow Basic: Exercise-4 with Solution
Write a Python program that multiplies a TensorFlow tensor by a scalar value and prints the result.
Sample Solution:
Python Code:
import tensorflow as tf
# Create a TensorFlow tensor
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
ts = tf.constant([100, 200, 300], dtype=tf.float32)
# Define the scalar value
sc = 3.0
# Multiply the tensor by the scalar
result_tensor = ts * sc
# Print the result
print("Original Tensor:", ts.numpy())
print("Scalar Value:", sc)
print("Result Tensor (After multiplying the tensor by the scalar):", result_tensor.numpy())
Output:
Original Tensor: [100. 200. 300.] Scalar Value: 3.0 Result Tensor (After multiplying the tensor by the scalar.): [300. 600. 900.]
Explanation:
In the exercise above, we create a TensorFlow tensor "ts" with values [1.0, 2.0, 3.0] and a scalar value "sc" of 3.0. We then multiply the tensor by the scalar using the * operator, which performs element-wise multiplication. Finally, we print the original tensor, the scalar value, and the resultant tensor.
Python Code Editor:
Previous: Python TensorFlow create and update tensor shape.
Next: Python TensorFlow dot product of two vectors.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics