Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Learning Variables in Tensorflow with tf.variable

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Have you worked with TensorFlow in Python? Do you want to learn something new in TensorFlow?

intro

Then you have come to the right place. This article is focused on one of the critical classes of the Python programming language, i.e., TensorFlow. We will work with the variable in TensorFlow. We will learn different ways to work with the variable in TensorFlow. Let's dive into the article to know more.

TensorFlow

TensorFlow is a package of Python programming languages for effective numerical computing. It serves as a foundational library for the creation of deep learning and machine learning models. TensorFlow is actually a high-level library. A variable is a state or value that can have its value changed by operations. The Variable() function Object() { [native code] } is used to generate variables in TensorFlow.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of the Variable in TensorFlow

tf_tensorflow.Variable(initial_value = None, trainable = None, validate_shape = True, caching_device = None, name = None, variable_def = None, dtype = None, import_scope = None, constraint = None, synchronization = tf.VariableSynchronization.AUTO, aggregation = tf.compat.v1.VariableAggregation.NONE, shape = None)

Parameters

It has many parameters like:

  • initial_value: It is, by default, set to None. The Variable's initial value is "Tensor," or a Python object that can be convertible to a "Tensor."
     
  • validate_shape: It is, by default, set to True. If it is False, it allows you to initialize the variable with a shape that is unknown. The shape of the initial value must be known if True, which is the default.
     
  • trainable: It is, by default, set to None. If it is True, GradientTapes will be responsible for keeping an eye on the usage of the variable.
     
  • name: It is, by default, set to None. It is the optional name of the Variable.
     
  • dtype: It is, by default, set to None. If it is set, the initial_value will be converted to the type that has been specified. 
     
  • variable_def: This value is, by default, set to None.
     
  • shape: It is, by default, set to None. If you specify any shape, the shape will be assigned to the variable.

Create a Variable in TensorFlow

You can use the tf.Variable() constructor to create a variable when you are working with TensorFlow.

Following is the syntax for creating a variable in Tensorflow.

import tensorflow as tf_tensorflow
tensor = tf_tensorflow.Variable([2,3])

 

You can check the following things about a TensorFlow variable:

  1. dimension,
     
  2. shape,
     
  3. size, and
     
  4. dtype.
     

Let's see an example to check all the above things:

Program

# importing the TensorFlow package
import tensorflow as tf_tensorflow

# Creating a Variable
tensor_var = tf_tensorflow.Variable([2, 3])

# This will print the shape of your variable.
print("The shape of your variable is: ", tensor_var.shape)

# This will print the number of dimensions in your variable.
print("The number of dimensions in the variable is: ", tf_tensorflow.rank(tensor_var).numpy())

# This will print the size of your variable.
print("The size of your TensorFlow variable is: ", tf_tensorflow.size(tensor_var).numpy())

# Now, check the data type of your variable.
print("The data type of your TensorFlow variable is: ", tensor_var.dtype)

Output:

output

Assign or Change the elements of the Variable in Tensorflow

We can use the assign() method to change the value of the variable. You just have to find the index and then assign the value using the assign() method at the respective index.

Some other methods are also available that you can use the change or assign the values of the variables. You can use the Variable.assign_sub() and Variable.assign_add().

Example 1

assign(): You can use this method to add or change the value of the variable.

Syntax:

assign(value_to_assign, use_locking=False, name=None, read_value=True)


It has many parameters like:

  1. value_to_assign: It is the value that you want to assign the value of the variable.
     
  2. use_locking: It refers to the locking during the assignment. 
     

Program:

# importing the TensorFlow package
import tensorflow as tf_tensorflow
 
tensor_var = tf_tensorflow.Variable([2, 3])
tensor_var[1].assign(4)
print(tensor_var)

 

Output:

output

Example 2

Syntax:

assign_add(value_to_add, use_locking=False, name=None, read_value=True)

 

It has many parameters like:

  1. value_to_add: It is the value that you want to add to the value of the variable.
     
  2. read_value: If it is True, a value that evaluates the changed value of your variable will be returned, and if it is False, it will return the assigned op.
     
  3. name: It is the name of the operation.
     
  4. use_locking: It refers to the locking during the assignment. 
     

Program:

# Import the TensorFlow package.
import tensorflow as tf_tensorflow
 
# Creating a TensorFlow variable.
tensor_var = tf_tensorflow.Variable([2, 3])
 
# Now, you can use the assign_add() method.
tensor_var.assign_add([1, 1])
print(tensor_var)


Output:

output

Example 3

Syntax:

assign_sub(value_to_assign, use_locking=False, name=None, read_value=True)

 

It has many parameters like:

  1. value_to_subtract: It is the value that you want to subtract from the value of the variable.
     
  2. read_value: If it is True, a value that evaluates the changed value of your variable will be returned, and if it is False, it will return the assigned op.
     
  3. name: It is the name of the operation.
     
  4. use_locking: It refers to the locking during the assignment. 
     

Program:

# Import the TensorFlow package.
import tensorflow as tf_tensorflow

# Creating a variable.
tensor_var = tf_tensorflow.Variable([2, 3])\

# Now, using assign_sub() method.
tensor_var.assign_sub([1, 1])
print(tensor_var)


Output:

output

Change the shape of the Variable in Tensorflow

You can use the shape() method to modify the shape of your variable. You must pass the variable and the shape you want to give.

Program

# Import the TensorFlow package.
import tensorflow as tf_tensorflow

tensor_var = tf_tensorflow.Variable([[4, 3, 2, 1]])
print(tensor_var)

tensor_var = tf_tensorflow.reshape(tensor_var,shape=(2, 2))
print(tensor_var)

 

Output:

output

Change the data type of the Variable in Tensorflow

You can even create the variable with a specific data type. If you want to create a variable of the tensor with a specific data type, you can specify the dtype argument. 

Program

# Import the TensorFlow package.
import tensorflow as tf_tensorflow
 
tensor_var = tf_tensorflow.Variable([[4, 3, 2, 1]], dtype=float)
tensor_var

 

Output:

output

Operations using the Variables

You can also perform many operations when you are working with the variables of TensorFlow, like:

  1. Addition,
     
  2. Subtraction,
     
  3. Multiplication,
     
  4. Division, and
     
  5. Many other Operations.

Program

# Importing the TensorFlow packages.
import tensorflow as tf_tensorflow

# Creating two TensorFlow variables.
tensor_var1 = tf_tensorflow.Variable([2, 3])
tensor_var2 = tf_tensorflow.Variable([4, 5])
print("The Addition of the tensors is: ", tensor_var1+tensor_var2)

print("The Subtraction of the tensors is: ", tensor_var1-tensor_var2)

print("The Multiplication of the tensors is: ", tensor_var1*tensor_var2)

print("The Division of the tensors is: ", tensor_var1/tensor_var2)


Output:

output

Broadcasting using the Variable

You can also execute multiple operations by combining these operations with different Variable objects similar to Tensor objects. The smaller variables can instantaneously expand out to fit the larger variables, just like NumPy arrays. 

When you attempt to multiply a scalar variable by another variable, the scalar variable will be stretched to multiply all of the variable's elements.

Program

# Importing the TensorFlow package.
import tensorflow as tf_tensorflow

# Create two TensorFlow variables.
tensor_var1 = tf_tensorflow.Variable([2, 3])
tensor_var2 = tf_tensorflow.Variable([2])

# Using the broadcasting.
result = tensor_var1*tensor_var2
print(result)

 

Output:

output

Hardware Used for Variable in Tensorflow

You can also check the type of device, like the processor, which is used to process the variable. 

You can use the .device attribute to use this functionality.  

Program

# Importing the TensorFlow package.
import tensorflow as tf_tensorflow
 
# Creating a TensorFlow variable.
tensor_var = tf_tensorflow.Variable([3, 4])
 
print('The specification of the hardware variable used is: '+tensor_var.device)

 

Output:

output

Frequently Asked Questions

Who created TensorFlow?

Google developed and released TensorFlow, a Python library for quick numerical computations.

Is TensorFlow AI or ML?

TensorFlow is a platform for end-to-end machine learning.

Is TensorFlow a coding?

Python, JavaScript, C++, and Java are just a few programming languages that support TensorFlow.

Is TensorFlow easy to learn?

TensorFlow is an end-to-end open-source platform for machine learning. Novices and experts may easily create machine learning models using TensorFlow.

Does Google use TensorFlow?

Many internal Google teams and products, including Search, Gmail, Maps, Translate, Android, Photos, YouTube, and Play, use TensorFlow.

Conclusion

In this article, we have studied one of the programming languages, i.e., Python. We have studied variable in TensorFlow in detail. We have tried to understand the use of the Variable in TensorFlow with an example.

We hope that this article has provided you with the help to enhance your knowledge regarding TensorFlow and if you would like to learn more, check out our articles on tensorflow and tensorflow on aws.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning

Topics covered
1.
Introduction
2.
TensorFlow
3.
Syntax of the Variable in TensorFlow
3.1.
Parameters
4.
Create a Variable in TensorFlow
4.1.
Program
5.
Assign or Change the elements of the Variable in Tensorflow
5.1.
Example 1
5.2.
Example 2
5.3.
Example 3
6.
Change the shape of the Variable in Tensorflow
6.1.
Program
7.
Change the data type of the Variable in Tensorflow
7.1.
Program
8.
Operations using the Variables
8.1.
Program
9.
Broadcasting using the Variable
9.1.
Program
10.
Hardware Used for Variable in Tensorflow
10.1.
Program
11.
Frequently Asked Questions
11.1.
Who created TensorFlow?
11.2.
Is TensorFlow AI or ML?
11.3.
Is TensorFlow a coding?
11.4.
Is TensorFlow easy to learn?
11.5.
Does Google use TensorFlow?
12.
Conclusion