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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/machine-learning/tensorflow/python-tensorflow-basic-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics