w3resource

Defining a TensorFlow constant Tensor for Neural Network Weights

Python TensorFlow Building and Training a Simple Model: Exercise-2 with Solution

Write a Python program that defines a TensorFlow constant tensor containing weights for a neural network layer with shape (10, 4).

Sample Solution:

Python Code:

import tensorflow as tf

# Define the shape of the weight tensor
weight_shape = (10, 4)

# Create a TensorFlow constant tensor for weights
weights = tf.constant(tf.random.normal(weight_shape), dtype=tf.float32)

# Print the weight tensor
print("Weight Tensor:")
print(weights)

Output:

Weight Tensor:
tf.Tensor(
[[-0.17399755 -0.06166992 -0.18227974  0.9468848 ]
 [ 0.6667386   0.7858261   1.5395325  -0.448641  ]
 [ 0.8488986   0.06063127  0.50501484 -0.20491312]
 [-0.5653967  -0.2263971  -0.25578663  0.6188185 ]
 [-0.5225996   1.1885293   0.14677407 -1.5749815 ]
 [-0.59405106 -0.7491368   0.6874295  -0.23348485]
 [ 2.1346924   2.0820951   0.4871456  -1.4516023 ]
 [-1.5244085   0.9741064  -1.4729421  -1.0187328 ]
 [-1.1803584   0.00808251  0.36181325 -0.6317905 ]
 [-1.1563174  -1.4196043   1.0241832   1.4271173 ]], shape=(10, 4), dtype=float32)

Explanation:

In the exercise above -

  • Import TensorFlow as tf.
  • Define the weight tensor shape as (10, 4) to indicate that you want a tensor with 10 rows (input units) and 4 columns (output units).
  • Use tf.random.normal(weight_shape) to create a random tensor with the specified shape.
  • Specify the data type of the weights as tf.float32.
  • Finally, we print the weight tensor to see its values.

Python Code Editor:


Previous: Creating a TensorFlow placeholder with variable batch size.
Next: Performing matrix multiplication with TensorFlow in Python.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-building-and-training-exercise-2.php