Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Creating Tensors | Tensors
Introduction to TensorFlow
course content

Conteúdo do Curso

Introduction to TensorFlow

Introduction to TensorFlow

1. Tensors
2. Basics of TensorFlow

book
Creating Tensors

Creating Tensors

Welcome back! Now that you're familiar with what tensors are, it's time to start creating them. TensorFlow offers a plethora of ways to initialize tensors. By the end of this lesson, you'll be well-versed in generating tensors for a variety 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;
12345
import tensorflow as tf # Create a 2x2 constant tensor tensor_const = tf.constant([[1, 2], [3, 4]]) print(tensor_const)
copy
  • tf.Variable(): Unlike tf.constant(), a tensor defined using tf.Variable() is mutable. This means its value can be changed, making it perfect for things like trainable parameters in models;
12345
import tensorflow as tf # Create a variable tensor tensor_var = tf.Variable([[1, 2], [3, 4]]) print(tensor_var)
copy
  • tf.zeros(): Create a tensor filled with zeros;
12345
import tensorflow as tf # Zero tensor of shape (3, 3) tensor_zeros = tf.zeros((3, 3)) print(tensor_zeros)
copy
  • tf.ones(): Conversely, this creates a tensor filled with ones;
12345
import tensorflow as tf # Ones tensor of shape (2, 2) tensor_ones = tf.ones((2, 2)) print(tensor_ones)
copy
  • tf.fill(): Creates a tensor filled with a specific value;
12345
import tensorflow as tf # Tensor of shape (2, 2) filled with 6 tensor_fill = tf.fill((2, 2), 6) print(tensor_fill)
copy
  • tf.linspace() and tf.range(): These are fantastic for creating sequences;
123456789
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)
copy
  • tf.random: Generates tensors with random values. Several distributions and functions are available within this module, like tf.random.normal() for values from a normal distribution, and tf.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.

1234567891011121314
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)
copy

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();
12345678910
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)
copy
  • 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;
12345678910
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)
copy

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 a Variable using various tensor creation methods such as tf.ones(), tf.linspace(), tf.random, and so on. Simply pass the function or the pre-existing tensor to tf.Variable().
12345678910111213
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)
copy

Remember, practice makes perfect! So, try creating tensors with different shapes and values to get a better grasp of these concepts. If you wish to delve further into a specific command, consider checking out the official TensorFlow documentation. There, you'll find comprehensive information on any command or module within the library.

Tarefa
test

Swipe to show code editor

Alright! Let's put your newfound knowledge of tensor creation and conversion to the test. Here's your challenge:

  1. Tensor Initialization

    • Create a tensor named tensor_A with shape (3,3) having all elements as 5.
    • 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).
  2. Conversions

    • Given the NumPy array np_array, convert it into a TensorFlow tensor named tensor_from_array.
    • Convert the DataFrame df into a tensor named tensor_from_dataframe.

Note

Make sure to use the most appropriate commands for the situation (e.g., create an array filled with ones using tf.ones() rather than tf.fill()).

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 6
toggle bottom row

book
Creating Tensors

Creating Tensors

Welcome back! Now that you're familiar with what tensors are, it's time to start creating them. TensorFlow offers a plethora of ways to initialize tensors. By the end of this lesson, you'll be well-versed in generating tensors for a variety 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;
12345
import tensorflow as tf # Create a 2x2 constant tensor tensor_const = tf.constant([[1, 2], [3, 4]]) print(tensor_const)
copy
  • tf.Variable(): Unlike tf.constant(), a tensor defined using tf.Variable() is mutable. This means its value can be changed, making it perfect for things like trainable parameters in models;
12345
import tensorflow as tf # Create a variable tensor tensor_var = tf.Variable([[1, 2], [3, 4]]) print(tensor_var)
copy
  • tf.zeros(): Create a tensor filled with zeros;
12345
import tensorflow as tf # Zero tensor of shape (3, 3) tensor_zeros = tf.zeros((3, 3)) print(tensor_zeros)
copy
  • tf.ones(): Conversely, this creates a tensor filled with ones;
12345
import tensorflow as tf # Ones tensor of shape (2, 2) tensor_ones = tf.ones((2, 2)) print(tensor_ones)
copy
  • tf.fill(): Creates a tensor filled with a specific value;
12345
import tensorflow as tf # Tensor of shape (2, 2) filled with 6 tensor_fill = tf.fill((2, 2), 6) print(tensor_fill)
copy
  • tf.linspace() and tf.range(): These are fantastic for creating sequences;
123456789
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)
copy
  • tf.random: Generates tensors with random values. Several distributions and functions are available within this module, like tf.random.normal() for values from a normal distribution, and tf.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.

1234567891011121314
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)
copy

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();
12345678910
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)
copy
  • 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;
12345678910
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)
copy

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 a Variable using various tensor creation methods such as tf.ones(), tf.linspace(), tf.random, and so on. Simply pass the function or the pre-existing tensor to tf.Variable().
12345678910111213
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)
copy

Remember, practice makes perfect! So, try creating tensors with different shapes and values to get a better grasp of these concepts. If you wish to delve further into a specific command, consider checking out the official TensorFlow documentation. There, you'll find comprehensive information on any command or module within the library.

Tarefa
test

Swipe to show code editor

Alright! Let's put your newfound knowledge of tensor creation and conversion to the test. Here's your challenge:

  1. Tensor Initialization

    • Create a tensor named tensor_A with shape (3,3) having all elements as 5.
    • 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).
  2. Conversions

    • Given the NumPy array np_array, convert it into a TensorFlow tensor named tensor_from_array.
    • Convert the DataFrame df into a tensor named tensor_from_dataframe.

Note

Make sure to use the most appropriate commands for the situation (e.g., create an array filled with ones using tf.ones() rather than tf.fill()).

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 6
Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
We're sorry to hear that something went wrong. What happened?
some-alt