Tensorflow 2 – Using tf.Variable examples

Last updated on August 23, 2021 Guest Contributor Loading... Post a comment

Below are some practical examples of using tf.Variable, which can help you create modifiable tensors in Tensorflow 2.

Example 1: Creating a New Variable and Assigning New Value

The code:

import tensorflow as tf

a = tf.Variable([
                 [1, 2],
                 [3, 4]
])
print(a)

# Assign a new value to a
a.assign(value=[
              [5, 6],
              [7, 8]
])

print(a)

Output:

<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[1, 2],
       [3, 4]], dtype=int32)>
<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[5, 6],
       [7, 8]], dtype=int32)>

Example 2: Adding/Subtracting Value

The code:

import tensorflow as tf

test_var = tf.Variable([
                        [0, 0],
                        [1, 2]
])

# Add a value to test_var
test_var.assign_add([ 
                     [10, 10],
                     [0, 0]
])

print(test_var)

# Subtract a value from test_var
test_var.assign_sub([
                     [5, 5],
                     [1, 0]
])

print(test_var)

Output:

<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[10, 10],
       [ 1,  2]], dtype=int32)>
<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy=
array([[5, 5],
       [0, 2]], dtype=int32)>

You can find more information about tf.Variable at: https://www.tensorflow.org/api_docs/python/tf/Variable.

What’s Next?

We’ve gone through a few examples of using tf.Variable. At this point, you should get a better understanding and feel more comfortable when working with it. This knowledge is essential and you will see it a lot. If you’d like to learn more about Python and machine learning stuff, take a look at the following articles:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like