Course Content
Introduction to TensorFlow
Introduction to TensorFlow
Creating Tensors
Creating Tensors
This lesson focuses on the creation of tensors using TensorFlow. TensorFlow provides numerous methods to initialize tensors. By the end of this lesson, you will be proficient in generating tensors for a wide range of applications.
Basic Tensor Initializers
tf.constant()
: this is the simplest way to create a tensor. As the name suggests, tensors initialized with this method hold constant values and are immutable;
import tensorflow as tf # Create a 2x2 constant tensor tensor_const = tf.constant([[1, 2], [3, 4]]) print(tensor_const)
tf.Variable()
: unliketf.constant()
, a tensor defined usingtf.Variable()
is mutable. This means its value can be changed, making it perfect for things like trainable parameters in models;
import tensorflow as tf # Create a variable tensor tensor_var = tf.Variable([[1, 2], [3, 4]]) print(tensor_var)
tf.zeros()
: create a tensor filled with zeros;
import tensorflow as tf # Zero tensor of shape (3, 3) tensor_zeros = tf.zeros((3, 3)) print(tensor_zeros)
tf.ones()
: conversely, this creates a tensor filled with ones;
import tensorflow as tf # Ones tensor of shape (2, 2) tensor_ones = tf.ones((2, 2)) print(tensor_ones)
tf.fill()
: creates a tensor filled with a specific value;
import tensorflow as tf # Tensor of shape (2, 2) filled with 6 tensor_fill = tf.fill((2, 2), 6) print(tensor_fill)
tf.linspace()
andtf.range()
: these are fantastic for creating sequences;
import tensorflow as tf # Generate a sequence of numbers starting from 0, ending at 9 tensor_range = tf.range(10) print(tensor_range) # Create 5 equally spaced values between 0 and 10 tensor_linspace = tf.linspace(0, 10, 5) print(tensor_linspace)
tf.random
: generates tensors with random values. Several distributions and functions are available within this module, liketf.random.normal()
for values from a normal distribution, andtf.random.uniform()
for values from a uniform distribution.
Note
You can also set a fixed seed to obtain consistent results with every random number generation using
tf.random.set_seed()
. However, be aware that by doing this, you'll receive the same number for any random generation within TensorFlow.If you wish to achieve consistent numbers for a specific command only, you can provide a
seed
argument to that command with the desired seed value.
import tensorflow as tf # Set random seed tf.random.set_seed(72) # Tensor of shape (2, 2) with random values normally distributed # (by default `mean=0` and `std=1`) tensor_random = tf.random.normal((2, 2), mean=4, stddev=0.5) print(tensor_random) # Tensor of shape (2, 2) with random values uniformly distributed # (by default `min=0` and `max=1`) tensor_random = tf.random.uniform((2, 2), minval=-2, maxval=2) print(tensor_random)
Converting Between Data Structures
TensorFlow tensors can be seamlessly converted to and from familiar Python data structures.
- From Numpy Arrays: TensorFlow tensors and Numpy arrays are quite interoperable. Use
tf.convert_to_tensor()
;
import numpy as np import tensorflow as tf # Create a NumPy array based on a Python list numpy_array = np.array([[1, 2], [3, 4]]) # Convert a NumPy array to a tensor tensor_from_np = tf.convert_to_tensor(numpy_array) print(tensor_from_np)
- From Pandas DataFrames: for those who are fans of data analysis with Pandas, converting a DataFrame or a Series to a TensorFlow tensor is straightforward. Use
tf.convert_to_tensor()
as well;
import pandas as pd import tensorflow as tf # Create a DataFrame based on dictionary df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # Convert a DataFrame to a tensor tensor_from_df = tf.convert_to_tensor(df.values) print(tensor_from_df)
Note
Always ensure that the data types of your original structures (Numpy arrays or Pandas DataFrames) are compatible with TensorFlow tensor data types. If there's a mismatch, consider type casting.
- Converting a constant tensor to a
Variable
: you can initialize aVariable
using various tensor creation methods such astf.ones()
,tf.linspace()
,tf.random
, and so on. Simply pass the function or the pre-existing tensor totf.Variable()
.
import tensorflow as tf # Create a variable from a tensor tensor = tf.random.normal((2, 3)) variable_1 = tf.Variable(tensor) # Create a variable based on other generator variable_2 = tf.Variable(tf.zeros((2, 2))) # Display tensors print(variable_1) print('-' * 50) print(variable_2)
To get better at creating tensors, try practicing with different shapes and values. For more details on specific commands, check the official TensorFlow documentation. It has all the information you need about any command or module in the library.
Swipe to start coding
Alright! Let's put your newfound knowledge of tensor creation and conversion to the test. Here's your challenge:
-
Tensor Initialization
- Create a tensor named
tensor_A
with shape(3,3)
having all elements as5
; - Create a mutable tensor named
tensor_B
with shape(2,3)
initialized with any values of your choice; - Create a tensor named
tensor_C
with shape(3,3)
filled with zeros; - Create a tensor named
tensor_D
with shape(4,4)
filled with ones; - Create a tensor named
tensor_E
which has 5 linearly spaced values between 3 and 15; - Create a tensor named
tensor_F
with random values and shape(2,2)
.
- Create a tensor named
-
Conversions
- Given the NumPy array
np_array
, convert it into a TensorFlow tensor namedtensor_from_array
; - Convert the DataFrame
df
into a tensor namedtensor_from_dataframe
.
- Given the NumPy array
Note
Make sure to use the most appropriate commands for the situation (e.g., create an array filled with ones using
tf.ones()
rather thantf.fill()
).
Solution
Thanks for your feedback!
Creating Tensors
Creating Tensors
This lesson focuses on the creation of tensors using TensorFlow. TensorFlow provides numerous methods to initialize tensors. By the end of this lesson, you will be proficient in generating tensors for a wide range of applications.
Basic Tensor Initializers
tf.constant()
: this is the simplest way to create a tensor. As the name suggests, tensors initialized with this method hold constant values and are immutable;
import tensorflow as tf # Create a 2x2 constant tensor tensor_const = tf.constant([[1, 2], [3, 4]]) print(tensor_const)
tf.Variable()
: unliketf.constant()
, a tensor defined usingtf.Variable()
is mutable. This means its value can be changed, making it perfect for things like trainable parameters in models;
import tensorflow as tf # Create a variable tensor tensor_var = tf.Variable([[1, 2], [3, 4]]) print(tensor_var)
tf.zeros()
: create a tensor filled with zeros;
import tensorflow as tf # Zero tensor of shape (3, 3) tensor_zeros = tf.zeros((3, 3)) print(tensor_zeros)
tf.ones()
: conversely, this creates a tensor filled with ones;
import tensorflow as tf # Ones tensor of shape (2, 2) tensor_ones = tf.ones((2, 2)) print(tensor_ones)
tf.fill()
: creates a tensor filled with a specific value;
import tensorflow as tf # Tensor of shape (2, 2) filled with 6 tensor_fill = tf.fill((2, 2), 6) print(tensor_fill)
tf.linspace()
andtf.range()
: these are fantastic for creating sequences;
import tensorflow as tf # Generate a sequence of numbers starting from 0, ending at 9 tensor_range = tf.range(10) print(tensor_range) # Create 5 equally spaced values between 0 and 10 tensor_linspace = tf.linspace(0, 10, 5) print(tensor_linspace)
tf.random
: generates tensors with random values. Several distributions and functions are available within this module, liketf.random.normal()
for values from a normal distribution, andtf.random.uniform()
for values from a uniform distribution.
Note
You can also set a fixed seed to obtain consistent results with every random number generation using
tf.random.set_seed()
. However, be aware that by doing this, you'll receive the same number for any random generation within TensorFlow.If you wish to achieve consistent numbers for a specific command only, you can provide a
seed
argument to that command with the desired seed value.
import tensorflow as tf # Set random seed tf.random.set_seed(72) # Tensor of shape (2, 2) with random values normally distributed # (by default `mean=0` and `std=1`) tensor_random = tf.random.normal((2, 2), mean=4, stddev=0.5) print(tensor_random) # Tensor of shape (2, 2) with random values uniformly distributed # (by default `min=0` and `max=1`) tensor_random = tf.random.uniform((2, 2), minval=-2, maxval=2) print(tensor_random)
Converting Between Data Structures
TensorFlow tensors can be seamlessly converted to and from familiar Python data structures.
- From Numpy Arrays: TensorFlow tensors and Numpy arrays are quite interoperable. Use
tf.convert_to_tensor()
;
import numpy as np import tensorflow as tf # Create a NumPy array based on a Python list numpy_array = np.array([[1, 2], [3, 4]]) # Convert a NumPy array to a tensor tensor_from_np = tf.convert_to_tensor(numpy_array) print(tensor_from_np)
- From Pandas DataFrames: for those who are fans of data analysis with Pandas, converting a DataFrame or a Series to a TensorFlow tensor is straightforward. Use
tf.convert_to_tensor()
as well;
import pandas as pd import tensorflow as tf # Create a DataFrame based on dictionary df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # Convert a DataFrame to a tensor tensor_from_df = tf.convert_to_tensor(df.values) print(tensor_from_df)
Note
Always ensure that the data types of your original structures (Numpy arrays or Pandas DataFrames) are compatible with TensorFlow tensor data types. If there's a mismatch, consider type casting.
- Converting a constant tensor to a
Variable
: you can initialize aVariable
using various tensor creation methods such astf.ones()
,tf.linspace()
,tf.random
, and so on. Simply pass the function or the pre-existing tensor totf.Variable()
.
import tensorflow as tf # Create a variable from a tensor tensor = tf.random.normal((2, 3)) variable_1 = tf.Variable(tensor) # Create a variable based on other generator variable_2 = tf.Variable(tf.zeros((2, 2))) # Display tensors print(variable_1) print('-' * 50) print(variable_2)
To get better at creating tensors, try practicing with different shapes and values. For more details on specific commands, check the official TensorFlow documentation. It has all the information you need about any command or module in the library.
Swipe to start coding
Alright! Let's put your newfound knowledge of tensor creation and conversion to the test. Here's your challenge:
-
Tensor Initialization
- Create a tensor named
tensor_A
with shape(3,3)
having all elements as5
; - Create a mutable tensor named
tensor_B
with shape(2,3)
initialized with any values of your choice; - Create a tensor named
tensor_C
with shape(3,3)
filled with zeros; - Create a tensor named
tensor_D
with shape(4,4)
filled with ones; - Create a tensor named
tensor_E
which has 5 linearly spaced values between 3 and 15; - Create a tensor named
tensor_F
with random values and shape(2,2)
.
- Create a tensor named
-
Conversions
- Given the NumPy array
np_array
, convert it into a TensorFlow tensor namedtensor_from_array
; - Convert the DataFrame
df
into a tensor namedtensor_from_dataframe
.
- Given the NumPy array
Note
Make sure to use the most appropriate commands for the situation (e.g., create an array filled with ones using
tf.ones()
rather thantf.fill()
).
Solution
Thanks for your feedback!