Create and print TensorFlow string tensor in Python
Python TensorFlow Basic: Exercise-16 with Solution
Write a Python program that creates a TensorFlow tensor with a string data type and print its value.
Sample Solution:
Python Code:
import tensorflow as tf
# Create a TensorFlow tensor with a string data type
# Tensors are multi-dimensional arrays with a uniform type (called a dtype ).
string_tensor = tf.constant("TensorFlow Exercises!", dtype=tf.string)
# Print the value of the string tensor
print("String Tensor Value:", string_tensor.numpy().decode())
Output:
String Tensor Value: TensorFlow Exercises!
Explanation:
In the exercise above -
- Import TensorFlow as tf.
- Create a TensorFlow tensor "string_tensor" containing the string "TensorFlow Exercises!" with the specified data type tf.string.
- To print the value of the string tensor, we use .numpy().decode() to convert the tensor to a Python string and then decode it.
Python Code Editor:
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://www.w3resource.com/machine-learning/tensorflow/python-tensorflow-basic-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics