Course Content
TensorFlow for Beginners
About Lesson

To create variables in TensorFlow we use tensorflow.get_variable()

Syntax:

tf.get_variable(name = "", values, dtype, initializer)

argument

  • `name = “”`: Name of the variable
  • `values`: Dimension of the tensor
  • `dtype`: Type of data. Optional
  • `initializer`: How to initialize the tensor. Optional

 

If the initializer is specified, there is no need to include the `values` as the shape of `initializer` is used.

import tensorflow as tf  
  
# Create a Variable  
var = tf.get_variable("var", [1, 2])  
print(var)  
  
#following initializes the variable with a initial/default value  
var_init_1 = tf.get_variable("var_init_1", 
[1, 2], 
dtype=tf.int32,  
initializer=tf.zeros_initializer)  
print(var_init_1)         
  
#Initializes the first value of the tensor equals to tensor_const  
tensor_const = tf.constant([[10, 20],[30, 40]])  
var_init_2 = tf.get_variable("var_init_2", 
dtype=tf.int32,  
initializer=tensor_const)  
print(var_init_2)

 

The output will be <tf.Variable ‘var:0’ shape=(1, 2) dtype=float32_ref> <tf.Variable ‘var_init_1:0’ shape=(1, 2) dtype=int32_ref> <tf.Variable ‘var_init_2:0’ shape=(2, 2) dtype=int32_ref>