Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the simple steps to master the Tensor5 of Tensorflow

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about what are the simple steps of mastering Tensorflow Tensor5, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.

The definition of tensor: what is a tensor

The tensor is a uniform multidimensional array of TensorFlow. They are very similar to NumPy arrays, and they are immutable, which means that once they are created, they cannot be changed. You can only use edits to create new copies.

Let's see how the tensor works with the code example. But first, to use the TensorFlow object, we need to import the TensorFlow library. We often use NumPy with TensorFlow, so we can also import NumPy using the following line:

Creation of import tensorflow as tfimport numpy as np tensors: creating tensor objects

There are several ways to create a tf.Tensor object. Let's start with a few examples. You can use multiple TensorFlow functions to create tensor objects, as shown in the following example:

# you can create tf.Tensor objects with the `tf.originant` function: X = tf.constant ([[1, 2, 3, 4, 5]]) # you can use the `tf.ones` function to create tf.Tensor objects: y = tf.ones (1) # you can use the `tf.zeros` function to create tf.Tensor objects: Z = tf.zeros ((1) # you can use the `tf.range` function to create tf.Tensor objects: Q = tf.range (start=1, limit=6) Delta=1) print (x) print (y) print (z) print (Q) output: tf.Tensor ([[12345]], shape= (1,5), dtype=int32) tf.Tensor ([[1.1.1.1.1]], shape= (1,5), dtype=float32) tf.Tensor ([[0. 0. 0. 0. 0.], shape= (1,5), dtype=float32) tf.Tensor ([12345], shape= (5,), dtype=int32)

As you can see, we used three different functions to create a tensor object of shape (1) and a fourth tensor object of shape (5,) using the tf.range () function. Note that tf.ones and tf.zeros accept shapes as required parameters because their element values are predetermined.

Characteristics of tensor objects

Tf.Tensor creates objects that have several characteristics. First, they have the number of dimensions. Second, they have a shape, a list of the length of the dimension. All tensors have a size, that is, the total number of elements in the tensor. Finally, their elements are recorded in a unified data type (datatype). Let's take a closer look at these features.

Dimension

Tensors are classified according to their dimensions:

Rank-0 (scalar) tensor: a tensor with a single value and no axis (0 dimension)

Rank-1 tensor: a tensor containing a list of uniaxial (one-dimensional) values

Rank-2 tensor: a tensor containing 2 axes (2 dimensions); and

Rank-N tensor: a tensor containing N axes (three dimensions).

For example, we can create a Rank-3 tensor by passing a three-layer nested list object to tf.constant. For this example, we can split the number into a three-layer nested list, each with three elements:

Three_level_nested_list = [0,1,2], [3,4,5]], [[6,7,8], [9,10] 11]] rank_3_tensor = tf.constant (three_level_nested_list) print (rank_3_tensor) Output:tf.Tensor ([0 12] [3 45]] [[6 7 8] [9 10 11], shape= (2, 2, 3), dtype=int32)

We can view the number of dimensions for which the "rank_3_tensor" object currently has a ".ndim" attribute.

Tensor_ndim = rank_3_tensor.ndimprint ("The number of dimensions in our Tensor object is", tensor_ndim) Output:The number of dimensions in our Tensor object is 3 shape

Shape feature is another attribute that each tensor has. It displays the size of each dimension as a list. We can view the shape of the rank_3_tensor object created using the .shape property, as shown below:

Tensor_shape = rank_3_tensor.shapeprint ("The shape of our Tensor object is", tensor_shape) Output:The shape of our Tensor object is (2,2,3)

As you can see, our tensor has two elements in the first layer, two elements in the second layer, and three elements in the third layer.

Size

Size is another feature of the tensor, which means how many elements the tensor has. We cannot use the properties of a tensor object to measure size. Instead, we need to use the tf.size function. Finally, we will use the instance function .NumPy () to convert the output to NumPy for more readable results:

Tensor_size = tf.size (rank_3_tensor) .numpy () print ("The size of our Tensor object is", tensor_size) Output:The size of our Tensor object is 12 data type

Tensors usually contain numeric data types, such as floating points and integers, but may also contain many other data types, such as plural and string.

However, each tensor object must store all its elements in a unified data type. Therefore, we can also use the .dtype property to view the data type selected for a specific tensor object, as follows:

Tensor_dtype = rank_3_tensor.dtypeprint ("The data type selected for this Tensor object is", tensor_dtype) Output:The data type selected for this Tensor object is tensor operation index

An index is a numerical representation of the position of an item in a sequence. This sequence can refer to many things: a list, a string, or any sequence of values.

TensorFlow also follows standard Python index rules, which are similar to list indexes or NumPy array indexes.

Some rules about indexing:

The index starts at zero (0).

A negative index ("- n") value indicates a backward count from the end.

The colon (":") is used for slicing: start: stop: step.

Commas (",") are used to reach a deeper level.

Let's create a rank_1_tensor with the following lines:

Single_level_nested_list = [0,1,2,3,4,5,6,7,8,9,10,11] rank_1_tensor = tf.constant (single_level_nested_list) print (rank_1_tensor) Output: tf.Tensor ([0 12 3 4 5 7 8 9 10 11], shape= (12,), dtype=int32)

Test our rule 1, 1, 2, 2, 3:

# Rule 1, index starts from 0 print ("First element is:", rank_1_tensor [0] .numpy ()) # rule 2, negative index print ("Last element is:", rank_1_tensor [- 1] .numpy ()) # rule 3 Slice print ("Elements in between the 1st and the last are:", rank_1_ tensor [1:-1] .numpy () Output: First element is: 0 Last element is: 11 Elements in between the 1st and the last are: [1 2 3 4 5 6 7 8 9 10]

Now, let's create the rank_2_tensor with the following code:

Two_level_nested_list = [0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]] rank_2_tensor = tf.constant (two_level_nested_list) print (rank_2_tensor) Output:tf.Tensor ([[0 12 3 45] [6 7 8 9 10 11]], shape= (2, 6), dtype=int32)

And test rule 4 with several examples:

Print ("The 1st element of the first level is:", rank_2_tensor [0]. Numpy ()) print ("The 2nd element of the first level is:", rank_2_tensor [1] .numpy ()) # Rule 4, comma represents a deeper print ("The 1st element of the second level is:", rank_2_tensor [0,0]. Numpy ()) print ("The 3rd element of the second level is:", rank_2_tensor [0) 2] .numpy () Output: The first element of the first level is: [0 1 2 3 4 5] The second element of the first level is: [6 7 8 9 10 11] The first element of the second level is: 0 The third element of the second level is: 2

Now that we've introduced the basics of indexing, let's take a look at the basic operations we can do with tensors.

Basic operation of tensor

You can easily perform basic mathematical operations on tensors, such as:

Addition

Element multiplication

Matrix multiplication

Find the maximum or minimum value

Find the index of the Max element

Calculate the Softmax value

Let's take a look at these operations. We will create two tensor objects and apply these operations.

A = tf.constant ([[2,4], [6,8]], dtype=tf.float32) b = tf.constant ([[1,3], [5,7]], dtype=tf.float32)

We can start with addition.

# We can use the 'tf.add ()' function and pass the tensor as a parameter. Add_tensors = tf.add (an add_tensors b) print (add_tensors) Output:tf.Tensor ([[3. 7.] [11. 15.]], shape= (2,2), dtype=float32)

Multiplication

# We can use the 'tf.multiply ()' function and pass the tensor as a parameter. Multiply_tensors = tf.multiply (a multiply_tensors b) print (multiply_tensors) Output:tf.Tensor ([[2.12.] [30. 56.], shape= (2,2), dtype=float32)

Matrix multiplication:

# We can use the 'tf.matmul ()' function and pass the tensor as a parameter. Matmul_tensors = tf.matmul (a matmul_tensors b) print (matmul_tensors) Output:tf.Tensor ([[2.12.] [30. 56.], shape= (2,2), dtype=float32)

Note: the Matmul operation is the core of deep learning algorithms. Therefore, although you will not use matmul directly, it is important to understand these operations.

Examples of other operations we listed above:

# use the 'tf.reduce_max ()' and 'tf.reduce_min ()' functions to find the maximum or minimum value print ("The Max value of the tensor object b is:", tf.reduce_max (b). Numpy ()) # use the 'tf.argmax ()' function to find the index print of the largest element ("The index position of the max element of the tensor object b is:" Tf.argmax (b) .numpy () # uses the tf.nn.softmax' function to calculate softmaxprint ("The softmax computation result of the tensor object b is:", tf.nn.softmax (b). Numpy ()) Output:The Max value of the tensor object b is: 1.0The index position of the Max of the tensor object b is: [11] The softmax computation result of the tensor object b is: [[0.11920291 0.880797] [0.11920291 0.880797]] manipulate the shape

Just like in NumPy arrays and pandas data frames, you can reshape tensor objects.

This transformation is very fast because the underlying data does not need to be copied. For reshaping operations, we can use the tf.reshape function

# our initial tensor a = tf.constant ([[1,2,3,4,5,6]]) print ('The shape of the initial Tensor object is:', a.shape) b = tf.reshape (a, [6,1]) print (' The shape of the first reshaped Tensor object is:', b.shape) c = tf.reshape (a, [3,2]) print ('The shape of the second reshaped Tensor object is:', c.shape) # if we pass-1 with the shape parameter Then the tensor becomes flattened. Print ('The shape of the flattened Tensor object is:', tf.reshape (a, [- 1]) Output:The shape of our initial Tensor object is: (1,6) The shape of our initial Tensor object is: (6,1) The shape of our initial Tensor object is: (3,2) The shape of our flattened Tensor object is: tf.Tensor ([1 23 456], shape= (6,), dtype=int32)

As you can see, we can easily reshape our tensor objects. It is important to note, however, that when reshaping, the developer must be reasonable. Otherwise, the tensor may be confused and even produce errors. So, be careful.

Broadcast

When we try to combine multiple tensor objects, smaller tensors can automatically stretch to accommodate larger tensors, just like NumPy arrays. For example, when you try to multiply a scalar tensor by a rank 2 tensor, the scalar will be stretched by multiplying each rank 2 tensor element. See the following example:

M = tf.constant ([5]) n = tf.constant ([[1, tf.multiply (m, n)) Output:tf.Tensor ([[5 10] [15 20]], shape= (2, 2), dtype=int32)

Thanks to the broadcast, you don't have to worry about size matching when doing mathematical operations on tensors.

Special types of tensors

We tend to generate a rectangular tensor and store the value as an element. However, TensorFlow also supports irregular or special types of tensors, including:

Jagged tensor

String tensor

Sparse tensor

Let's take a closer look at what each one is.

Jagged tensor

A jagged tensor is a tensor with different quantity elements along the dimension axis.

You can build an irregular tensor, as follows

Ragged_list = [[1,2,3], [4,5], [6]] ragged_tensor = tf.ragged.constant (ragged_list) print (ragged_tensor) Output: string tensor

A string tensor is a tensor that stores a string object. We can create a string tensor, just like you create a normal tensor object. However, we pass the string object as an element instead of a numeric object, as follows:

String_tensor = tf.constant (["With this", "code, I am", "creating a String Tensor"]) print (string_tensor) Output:tf.Tensor ([b'With this' b'code, I am' b'creating a String Tensor'], shape= (3,), dtype=string) sparse tensor

Finally, the sparse tensor is a rectangular tensor of sparse data. When there is a null value in the data, the sparse tensor is the object. Creating sparse tensors is a bit time-consuming and should be more mainstream. Here's an example:

Sparse_tensor = tf.sparse.SparseTensor (indices= [[0,0], [2,2], [4,4]], values= [25,50,100], dense_shape= [5] 5]) # We can convert the sparse tensor into a dense tensor print (tf.sparse.to_dense (sparse_tensor)) Output:tf.Tensor ([[250000] [000000] [005000] [0000100]], shape= (5) 5), dtype=int32) after reading the above content Do you have any further understanding of what are the simple steps to master Tensorflow's Tensor5? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report