Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Creating Tensors | Tensors
Introduction to 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;

import tensorflow as tf

# Create a 2x2 constant tensor
tensor_const = tf.constant([[1, 2], [3, 4]])
print(tensor_const)
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;

import tensorflow as tf

# Create a variable tensor
tensor_var = tf.Variable([[1, 2], [3, 4]])
print(tensor_var)
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;

import tensorflow as tf

# Zero tensor of shape (3, 3)
tensor_zeros = tf.zeros((3, 3))
print(tensor_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;

import tensorflow as tf

# Ones tensor of shape (2, 2)
tensor_ones = tf.ones((2, 2))
print(tensor_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;

import tensorflow as tf

# Tensor of shape (2, 2) filled with 6
tensor_fill = tf.fill((2, 2), 6)
print(tensor_fill)
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;

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)
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.

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)
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();

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)
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;

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)
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().

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)
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.

Compito

Swipe to start coding

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()).

Soluzione

import tensorflow as tf
import numpy as np
import pandas as pd

# 1. Tensor initialization
tensor_A = tf.fill((3, 3), 5)
tensor_B = tf.Variable([[1,2,3], [4,5,6]])
tensor_C = tf.zeros((3,3))
tensor_D = tf.ones((4,4))
tensor_E = tf.linspace(3.0, 15.0, 5)
tensor_F = tf.random.normal((2,2))

# Set up a NumPy array and a DataFrame
np_array = np.array([[7, 8], [9, 10], [11, 12]])
df = pd.DataFrame({'col1': [13, 14, 15], 'col2': [16, 17, 18]})

# 2. Conversions
tensor_from_array = tf.convert_to_tensor(np_array)
tensor_from_dataframe = tf.convert_to_tensor(df)

# Print out each tensor
print('tensor_A:', tensor_A, '\n', '-' * 80)
print('tensor_B:', tensor_B, '\n', '-' * 80)
print('tensor_C:', tensor_C, '\n', '-' * 80)
print('tensor_D:', tensor_D, '\n', '-' * 80)
print('tensor_E:', tensor_E, '\n', '-' * 80)
print('tensor_F:', tensor_F, '\n', '-' * 80)
print('tensor_from_array:', tensor_from_array, '\n', '-' * 80)
print('tensor_from_dataframe:', tensor_from_dataframe)

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 6
single

single

import tensorflow as tf
import numpy as np
import pandas as pd

# 1. Tensor initialization
tensor_A = tf.___((___), ___)
tensor_B = tf.___([___])
tensor_C = tf.___(___)
tensor_D = tf.___(___)
tensor_E = tf.___(___)
tensor_F = tf.___.___(___)

# Set up a NumPy array and a DataFrame
np_array = np.array([[7, 8], [9, 10], [11, 12]])
df = pd.DataFrame({'col1': [13, 14, 15], 'col2': [16, 17, 18]})

# 2. Conversions
tensor_from_array = tf.___(___)
tensor_from_dataframe = tf.___(___)

# Print out each tensor
print('tensor_A:', tensor_A, '\n', '-' * 80)
print('tensor_B:', tensor_B, '\n', '-' * 80)
print('tensor_C:', tensor_C, '\n', '-' * 80)
print('tensor_D:', tensor_D, '\n', '-' * 80)
print('tensor_E:', tensor_E, '\n', '-' * 80)
print('tensor_F:', tensor_F, '\n', '-' * 80)
print('tensor_from_array:', tensor_from_array, '\n', '-' * 80)
print('tensor_from_dataframe:', tensor_from_dataframe)

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

We use cookies to make your experience better!
some-alt