<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ tensor - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ tensor - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 27 Jul 2026 17:33:12 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/tensor/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use TensorFlow for Deep Learning – Basics for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ TensorFlow is a library that helps engineers build and train deep learning models. It provides all the tools we need to create neural networks. We can use TensorFlow to train simple to complex neural networks using large sets of data. TensorFlow is u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/tensorflow-basics/</link>
                <guid isPermaLink="false">66d0362131fbfb6c3390f1f3</guid>
                
                    <category>
                        <![CDATA[ Deep Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ neural networks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tensor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Tue, 14 Feb 2023 23:46:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/tensorflow.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>TensorFlow is a library that helps engineers build and train deep learning models. It provides all the tools we need to create neural networks.</p>
<p>We can use TensorFlow to train simple to complex neural networks using large sets of data.</p>
<p>TensorFlow is used in a variety of applications, from image and speech recognition to natural language processing and robotics. TensorFlow enables us to quickly and easily build powerful AI models with high accuracy and performance.</p>
<p>TensorFlow also works with GPUs and TPUs, which are types of computer chips built to extend TensorFlow’s capabilities. These chips make TensorFlow run faster, which is helpful when you have a lot of data to work with.</p>
<p>In this article, we will learn about tensors and how to work with tensors using TensorFlow. Let’s dive right in.</p>
<h2 id="heading-what-is-a-tensor">What is a Tensor?</h2>
<p>A simple explanation would be that a tensor is a multi-dimensional array.</p>
<p><img src="https://miro.medium.com/max/1050/1*rLcM-j8b61Xlfk81k_exKw.png" alt="Image" width="600" height="400" loading="lazy">
<em>Scalar, Vector, Matrix and Tensor</em></p>
<p>A scalar is a single number. A vector is an array of numbers. A matrix is a 2-dimensional array. A tensor is an n-dimensional array.</p>
<p>In TensorFlow, everything can be considered a tensor including a scalar. A scalar would be a tensor of dimension 0, a vector of dimension 1, and a matrix of dimension 2.</p>
<p>Now, this is useful because we are not limited to working with complex datasets in TensorFlow. TensorFlow can handle any type of data and feed it to machine learning models.</p>
<h2 id="heading-what-is-tensorflow">What is TensorFlow?</h2>
<p>TensorFlow is an open-source software library for building neural networks. Google Brain team was the one who built it and it is the most popular deep learning library in the market today.</p>
<p>You can use TensorFlow to build AI models including image and speech recognition, natural language processing, and predictive modeling.</p>
<p><img src="https://miro.medium.com/max/1050/1*mPUeOmKYoWvPcZFjMdsiUQ.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Classification neural network</em></p>
<p>TensorFlow uses a dataflow graph to represent computations. To put it simply, TensorFlow has made it easy to build complex machine learning models.</p>
<p>TensorFlow takes care of a lot of work behind the scenes which makes it useful while building and training any type of machine learning model. TensorFlow also manages the computation, including parallelization and optimization, on the user’s behalf.</p>
<h2 id="heading-tensorflow-and-keras">TensorFlow and Keras</h2>
<p><img src="https://miro.medium.com/max/1050/1*X7QA_c8KHk7nD0tywv-OVg.png" alt="Image" width="600" height="400" loading="lazy">
<em>Tensorflow and Keras</em></p>
<p>TensorFlow has a high-level API called Keras. Keras was a standalone project which is now available within the TensorFlow library. Keras makes it easy to define and train models while TensorFlow provides more control over the computation.</p>
<p>TensorFlow supports a wide range of hardware, including CPUs, GPUs, and TPUs. TPUs are Tensor processing Unites, built specifically to work with Tensors and TensorFlow.</p>
<p>We can also run TensorFlow on mobile devices and IoT devices using TensorFlow Lite. TensorFlow also has a large community of developers, and it is updated with new features and capabilities.</p>
<h2 id="heading-how-to-build-tensors-with-tensorflow">How to Build Tensors with TensorFlow</h2>
<p>Let’s start writing some code. If you don't have TensorFlow installed, you can use a <a target="_blank" href="https://colab.research.google.com/">Google colab notebook</a> to follow along.</p>
<p>Let’s start by importing TensorFlow and printing out the version.</p>
<pre><code><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
print(tf.__version__)
</code></pre><pre><code>OUTPUT:
<span class="hljs-number">2.9</span><span class="hljs-number">.2</span>
</code></pre><p>Let’s first create a scalar using tf.constant. We use tf.constant to create a new constant value. We can also use tf.variable to create a variable value. We will then print the value and also check the dimension of the scalar using the ndim property. Its dimension will be zero because it is a single value.</p>
<pre><code>scalar = tf.constant(<span class="hljs-number">7</span>)
print(scalar)
print(scalar.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor(<span class="hljs-number">7</span>, shape=(), dtype=int32)
<span class="hljs-number">0</span>
</code></pre><p>Now let’s create a vector and print its dimensions. You can see that the dimension is 1.</p>
<pre><code>vector = tf.constant([<span class="hljs-number">10</span>,<span class="hljs-number">10</span>])
print(vector)
print(vector.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor([<span class="hljs-number">10</span> <span class="hljs-number">10</span>], shape=(<span class="hljs-number">2</span>,), dtype=int32)
<span class="hljs-number">1</span>
</code></pre><p>Now let’s try creating a matrix and printing its dimensions.</p>
<pre><code>matrix = tf.constant([
    [<span class="hljs-number">10</span>,<span class="hljs-number">11</span>],
    [<span class="hljs-number">12</span>,<span class="hljs-number">13</span>]
])
print(matrix)
print(matrix.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">10</span> <span class="hljs-number">11</span>]
 [<span class="hljs-number">12</span> <span class="hljs-number">13</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
<span class="hljs-number">2</span>
</code></pre><p>You will see that the dimension is now 2. You can also see that the shape of the matrix is 2 by 2.</p>
<p>Shapes and dimensions are useful when working with TensorFlow because we will often change them while using these data to train neural networks.</p>
<p>We have seen that these tensors have a default datatype of int32. What if we want to create a dataset with a custom datatype?</p>
<p>tf.constant provides us with the dtype argument. Let’s create the same matrix again with float16 as the data type.</p>
<pre><code>tensor_1 = tf.constant([
    [
        [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
    ],
    [
        [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
    ],
    [
        [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
    ]
],dtype=<span class="hljs-string">'float32'</span>)
print(tensor_1)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[[<span class="hljs-number">1.</span> <span class="hljs-number">2.</span> <span class="hljs-number">3.</span>]]

 [[<span class="hljs-number">4.</span> <span class="hljs-number">5.</span> <span class="hljs-number">6.</span>]]

 [[<span class="hljs-number">7.</span> <span class="hljs-number">8.</span> <span class="hljs-number">9.</span>]]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>), dtype=float32)
</code></pre><p>Now let’s create a tensor. We will input a 3-dimensional array to tf.constant. We will also print its dimensions.</p>
<pre><code>tensor = tf.constant([
    [
        [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
    ],
    [
        [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
    ],
    [
        [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
    ]
])
print(tensor)
print(tensor.ndim)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[[<span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span>]]
 [[<span class="hljs-number">4</span> <span class="hljs-number">5</span> <span class="hljs-number">6</span>]]
 [[<span class="hljs-number">7</span> <span class="hljs-number">8</span> <span class="hljs-number">9</span>]]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>), dtype=int32)
<span class="hljs-number">3</span>
</code></pre><p>Now we have a tensor of dimension 3 and shape 3 by 1 by 3. This is the simplest tensor you can create. In real-world scenarios, we will be dealing with tensors of higher dimensions and bigger shapes.</p>
<p>Now let’s look at how to create a variable tensor. We won’t be using variable tensors very often compared to constant tensors, but it is good to know that we have an option.</p>
<p>We will use tf.Variable to create a variable tensor. The difference between the constant tensor and variable tensor is that you can change the data in a variable tensor, but you can’t change the values in a constant tensor. Let’s create a variable tensor and print the dimensions.</p>
<pre><code>var_tensor = tf.Variable([
    [
        [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
    ],
    [
        [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
    ],
    [
        [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
    ]
])
print(var_tensor)
</code></pre><pre><code>OUTPUT:
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">tf.Variable</span> '<span class="hljs-attr">Variable:0</span>' <span class="hljs-attr">shape</span>=<span class="hljs-string">(3,</span> <span class="hljs-attr">1</span>, <span class="hljs-attr">3</span>) <span class="hljs-attr">dtype</span>=<span class="hljs-string">int32,</span> <span class="hljs-attr">numpy</span>=
<span class="hljs-string">array([[[1,</span> <span class="hljs-attr">2</span>, <span class="hljs-attr">3</span>]],
       [[<span class="hljs-attr">4</span>, <span class="hljs-attr">5</span>, <span class="hljs-attr">6</span>]],
       [[<span class="hljs-attr">7</span>, <span class="hljs-attr">8</span>, <span class="hljs-attr">9</span>]]], <span class="hljs-attr">dtype</span>=<span class="hljs-string">int32)</span>&gt;</span></span>
</code></pre><h1 id="heading-how-to-generate-and-load-tensors">How to Generate and Load Tensors</h1>
<p>Let’s look at how to generate tensors. In most cases, you won’t be creating tensors from scratch. You will either load a dataset, convert other datasets like NumPy arrays to tensors, or generate tensors. First, let’s look at how to generate tensors.</p>
<p>Let’s create a tensor with random values. There are two common ways you can do this: generate a normal distribution of data or a uniform distribution of data.</p>
<p><img src="https://miro.medium.com/max/1050/0*tRWkwBjuQvgi2rGG.png" alt="Image" width="600" height="400" loading="lazy">
<em>Normal distribution</em></p>
<p>The normal distribution is a bell-shaped curve that represents the distribution of data. Most of the data will be close to the average and fewer data will be away from the average. This means the probability of getting a value near the average is higher.</p>
<p><img src="https://miro.medium.com/max/1050/0*SOM1PR1htTNzuRMS.png" alt="Image" width="600" height="400" loading="lazy">
<em>Uniform distribution</em></p>
<p>The uniform distribution is a straight line that represents the distribution of data. All the values in a uniform distribution will have an equal probability of occurring within a given range.</p>
<p>Before we generate random values, you must understand what a seed is. If we use a seed value, we can regenerate the same set of data multiple times. This will be useful when we want to test our machine-learning model against the same data after we tweak its performance.</p>
<p>Let’s create two arrays of random tensors. We will first set a seed and generate the random values using that seed.</p>
<pre><code>seed = tf.random.Generator.from_seed(<span class="hljs-number">42</span>)
</code></pre><p>Now we will create a normal and uniform distribution with the shape of 3 by 2.</p>
<pre><code>normal_tensor = seed.normal(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(normal_tensor)
uniform_tensor = seed.uniform(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(uniform_tensor)
</code></pre><pre><code>OUTPUT:
tf.Tensor( [[<span class="hljs-number">-0.7565803</span>  <span class="hljs-number">-0.06854702</span>]  [ <span class="hljs-number">0.07595026</span> <span class="hljs-number">-1.2573844</span> ]  [<span class="hljs-number">-0.23193765</span> <span class="hljs-number">-1.8107855</span> ]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
tf.Tensor( [[<span class="hljs-number">0.7647915</span>  <span class="hljs-number">0.03845465</span>]  [<span class="hljs-number">0.8506975</span>  <span class="hljs-number">0.20781887</span>]  [<span class="hljs-number">0.711869</span>   <span class="hljs-number">0.8843919</span> ]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
</code></pre><p>We have two tensors created, one with a normal distribution of random numbers and the other with a uniform distribution of random numbers.</p>
<p>Next, we will create a tensor with zeros and ones. In TensorFlow, tensors filled with zeros or ones are often used as a starting point for creating other tensors. They can also be placeholders for inputs in a computational graph.</p>
<p>To create a tensor of zeroes, use the tf.zeros function with a shape as the input argument. To create a tensor with ones, we use tf.ones with the shape as input argument.</p>
<pre><code>zeros = tf.zeros(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(zeros)
ones = tf.ones(shape=(<span class="hljs-number">3</span>,<span class="hljs-number">2</span>))
print(ones)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
 [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
 [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
tf.Tensor(
[[<span class="hljs-number">1.</span> <span class="hljs-number">1.</span>]
 [<span class="hljs-number">1.</span> <span class="hljs-number">1.</span>]
 [<span class="hljs-number">1.</span> <span class="hljs-number">1.</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>), dtype=float32)
</code></pre><p>Now, let’s look at converting NumPy arrays into tensors. If you don’t know <a target="_blank" href="https://numpy.org/">what NumPy is</a>, it is a Python library for numerical computing. It helps us handle large datasets and perform a variety of computations on them.</p>
<p>Let’s import NumPy and create a NumPy array using NumPy’s arrange function.</p>
<pre><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
numpy_arr = np.arange(<span class="hljs-number">1</span>,<span class="hljs-number">25</span>,dtype=np.int32)
</code></pre><p>Now, we can create a tensor using the tf.constant function with the NumPy array as input. TensorFlow has built-in support to handle NumPy arrays, so it is just a matter of importing a NumPy array and setting a shape.</p>
<pre><code>print(numpy_arr)
numpy_tensor = tf.constant(numpy_arr,shape=[<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>])
print(numpy_tensor)
</code></pre><pre><code>OUTPUT:
[ <span class="hljs-number">1</span>  <span class="hljs-number">2</span>  <span class="hljs-number">3</span>  <span class="hljs-number">4</span>  <span class="hljs-number">5</span>  <span class="hljs-number">6</span>  <span class="hljs-number">7</span>  <span class="hljs-number">8</span>  <span class="hljs-number">9</span> <span class="hljs-number">10</span> <span class="hljs-number">11</span> <span class="hljs-number">12</span> <span class="hljs-number">13</span> <span class="hljs-number">14</span> <span class="hljs-number">15</span> <span class="hljs-number">16</span> <span class="hljs-number">17</span> <span class="hljs-number">18</span> <span class="hljs-number">19</span> <span class="hljs-number">20</span> <span class="hljs-number">21</span> <span class="hljs-number">22</span> <span class="hljs-number">23</span> <span class="hljs-number">24</span>]
tf.Tensor(
[[[ <span class="hljs-number">1</span>  <span class="hljs-number">2</span>  <span class="hljs-number">3</span>]
  [ <span class="hljs-number">4</span>  <span class="hljs-number">5</span>  <span class="hljs-number">6</span>]
  [ <span class="hljs-number">7</span>  <span class="hljs-number">8</span>  <span class="hljs-number">9</span>]
  [<span class="hljs-number">10</span> <span class="hljs-number">11</span> <span class="hljs-number">12</span>]]
 [[<span class="hljs-number">13</span> <span class="hljs-number">14</span> <span class="hljs-number">15</span>]
  [<span class="hljs-number">16</span> <span class="hljs-number">17</span> <span class="hljs-number">18</span>]
  [<span class="hljs-number">19</span> <span class="hljs-number">20</span> <span class="hljs-number">21</span>]
  [<span class="hljs-number">22</span> <span class="hljs-number">23</span> <span class="hljs-number">24</span>]]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">3</span>), dtype=int32)
</code></pre><p>You can see both the NumPy array as well as our tensor. The original NumPy array was 1x12 but our tensor is 2x4x3. This is called re-shaping a tensor which we will often do while training deep neural networks.</p>
<h1 id="heading-basic-operations-using-tensorflow">Basic Operations using Tensorflow</h1>
<p>We have learned how tensors are created in TensorFlow. Now let’s look at some basic operations using tensors.</p>
<p>We will start by getting some information on our tensors. Let’s create a 4D tensor with 0 values with the shape 2x3x4x5.</p>
<pre><code>rank4_tensor = tf.zeros([<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>])
print(rank4_tensor)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[[[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]]
 [[[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]
  [[<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]
   [<span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span> <span class="hljs-number">0.</span>]]]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>), dtype=float32)
</code></pre><p>We have created our rank 4 tensor. Now let's get some information about the size, shape (number of values), and the dimension of the tensor. </p>
<p>We will use tf.size function to get the size. The shape and ndim properties will give us the shape and dimensions of the tensor. </p>
<pre><code>print(<span class="hljs-string">"Size"</span>,tf.size(rank4_tensor))
print(<span class="hljs-string">"shape"</span>,rank4_tensor.shape)
print(<span class="hljs-string">"Dimension"</span>,rank4_tensor.ndim)
</code></pre><pre><code>OUTPUT: 

Size tf.Tensor(<span class="hljs-number">120</span>, shape=(), dtype=int32)
shape (<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
Dimension <span class="hljs-number">4</span>
</code></pre><p>Let’s look at some simple calculations using the tensor. I will create a new basic tensor.</p>
<pre><code>basic_tensor = tf.constant([[<span class="hljs-number">10</span>,<span class="hljs-number">11</span>],[<span class="hljs-number">12</span>,<span class="hljs-number">13</span>]])
print(basic_tensor)
</code></pre><pre><code>OUTPUT: 

tf.Tensor(
[[<span class="hljs-number">10</span> <span class="hljs-number">11</span>]
 [<span class="hljs-number">12</span> <span class="hljs-number">13</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
</code></pre><p>Let’s try some simple operations. We can add, subtract, multiply, and divide every value in a tensor using the basic operators.</p>
<pre><code>print(basic_tensor + <span class="hljs-number">10</span>)
print(basic_tensor - <span class="hljs-number">10</span>)
print(basic_tensor * <span class="hljs-number">10</span>)
print(basic_tensor / <span class="hljs-number">10</span>)
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">20</span> <span class="hljs-number">21</span>]
 [<span class="hljs-number">22</span> <span class="hljs-number">23</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">0</span> <span class="hljs-number">1</span>]
 [<span class="hljs-number">2</span> <span class="hljs-number">3</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">100</span> <span class="hljs-number">110</span>]
 [<span class="hljs-number">120</span> <span class="hljs-number">130</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">1.</span>  <span class="hljs-number">1.1</span>]
 [<span class="hljs-number">1.2</span> <span class="hljs-number">1.3</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=float64)
</code></pre><p>Now let’s try matrix multiplication. I will create two simple tensors tensor_011 and tensor_012.</p>
<pre><code>tensor_011 = tf.constant([[<span class="hljs-number">2</span>,<span class="hljs-number">2</span>],[<span class="hljs-number">4</span>,<span class="hljs-number">4</span>]])
tensor_012 = tf.constant([[<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],[<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]])
</code></pre><p>Keep in mind that in matrix multiplication, the inner dimensions should match. For example, a (3, 5) <em> (3, 5) multiplication won’t work but (3, 5) </em> (5, 3) will work.</p>
<p>The final shape of the resulting matrix will be its outer dimension. so, a 3x5 tensor multiplied by a 5x3 tensor will give us a 5x5 tensor. We will use the tf.matmul function to perform matrix multiplication.</p>
<pre><code>print(tf.matmul(tensor_011,tensor_012))
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">12</span> <span class="hljs-number">16</span>]
 [<span class="hljs-number">24</span> <span class="hljs-number">32</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
</code></pre><p>Next, let’s look at reshaping and transposing a matrix. As we saw before, we will often use reshaping to change our matrix structure while training neural networks.</p>
<p>For example, an image pixel matrix of 28x28 will be converted into a 1-dimensional 784-pixel array for an image classification neural network.</p>
<p>To reshape, we use the tf.reshape function. To transpose, we use the tf.transpose function. If you don't know what a transpose is, it's converting rows into columns and columns into rows.</p>
<pre><code>print(tf.reshape(tensor_011,[<span class="hljs-number">4</span>,<span class="hljs-number">1</span>]))
print(tf.transpose(tensor_011))
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">2</span>]
 [<span class="hljs-number">2</span>]
 [<span class="hljs-number">4</span>]
 [<span class="hljs-number">4</span>]], shape=(<span class="hljs-number">4</span>, <span class="hljs-number">1</span>), dtype=int32)
tf.Tensor(
[[<span class="hljs-number">2</span> <span class="hljs-number">4</span>]
 [<span class="hljs-number">2</span> <span class="hljs-number">4</span>]], shape=(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>), dtype=int32)
</code></pre><p>Finally, let’s look at some aggregate operations like min, max, standard deviation, square and square root.</p>
<p>To find the minimum and maximum values, we use the tf.reduce_min and tf.reduce_max functions. And to find the sum of the array, we use the tf.reduce_sum function.</p>
<pre><code>tensor_013 = tf.constant([
    [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>],
    [<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>],
    [<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
],dtype=<span class="hljs-string">'float32'</span>)
print(tf.reduce_min(tensor_013))
print(tf.reduce_max(tensor_013))
print(tf.reduce_sum(tensor_013))
</code></pre><pre><code>OUTPUT:
tf.Tensor(<span class="hljs-number">1.0</span>, shape=(), dtype=float32)
tf.Tensor(<span class="hljs-number">9.0</span>, shape=(), dtype=float32)
tf.Tensor(<span class="hljs-number">45.0</span>, shape=(), dtype=float32)
</code></pre><p>Now for the standard deviation and variance, we use the tf.math.reduce_std function and tf.math.reduce_variance function.</p>
<pre><code>print(tf.math.reduce_std(tensor_013))
print(tf.math.reduce_variance(tensor_013))
</code></pre><pre><code>OUTPUT:
tf.Tensor(<span class="hljs-number">2.5819888</span>, shape=(), dtype=float32)
tf.Tensor(<span class="hljs-number">6.6666665</span>, shape=(), dtype=float32)
</code></pre><p>Let’s find the square, square root, and log of each value in a tensor.</p>
<pre><code>print(tf.sqrt(tensor_013))
print(tf.square(tensor_013))
print(tf.math.log(tensor_013))
</code></pre><pre><code>OUTPUT:
tf.Tensor(
[[<span class="hljs-number">1.</span>        <span class="hljs-number">1.4142135</span> <span class="hljs-number">1.7320508</span>]
 [<span class="hljs-number">2.</span>        <span class="hljs-number">2.236068</span>  <span class="hljs-number">2.4494898</span>]
 [<span class="hljs-number">2.6457512</span> <span class="hljs-number">2.828427</span>  <span class="hljs-number">3.</span>       ]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>), dtype=float32)
tf.Tensor(
[[ <span class="hljs-number">1.</span>  <span class="hljs-number">4.</span>  <span class="hljs-number">9.</span>]
 [<span class="hljs-number">16.</span> <span class="hljs-number">25.</span> <span class="hljs-number">36.</span>]
 [<span class="hljs-number">49.</span> <span class="hljs-number">64.</span> <span class="hljs-number">81.</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>), dtype=float32)
tf.Tensor(
[[<span class="hljs-number">0.</span>        <span class="hljs-number">0.6931472</span> <span class="hljs-number">1.0986123</span>]
 [<span class="hljs-number">1.3862944</span> <span class="hljs-number">1.609438</span>  <span class="hljs-number">1.7917595</span>]
 [<span class="hljs-number">1.9459102</span> <span class="hljs-number">2.0794415</span> <span class="hljs-number">2.1972246</span>]], shape=(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>), dtype=float32)
</code></pre><p>We have learned the basics of TensorFlow in this article. You are now equipped to work with TensorFlow and use it to model data.</p>
<p>If you want to start using this knowledge and build a project, you can check out my course on <a target="_blank" href="https://learn.manishmshiva.com/tensorflow-basics-handwriting-recognition-using-computer-vision">building a handwriting recognition neural network using TensorFlow</a>. You can also learn advanced TensorFlow concepts using the <a target="_blank" href="https://www.tensorflow.org/overview">official documentation.</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Tensorflow is a powerful library to build deep-learning models. It has all the tools we need to construct neural networks to solve problems like image classification, sentiment analysis, stock market predictions, etc. </p>
<p>With the advent of technologies like ChatGPT, learning TensorFlow will give you a head start in the current job market.</p>
<p><em>Hope you liked this article. You can learn more about me and my articles/videos at</em> <a target="_blank" href="https://www.manishmshiva.com/"><em>manishmshiva.com</em></a><em>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ PyTorch Tensor Methods – How to Create Tensors in Python ]]>
                </title>
                <description>
                    <![CDATA[ By Srijan PyTorch is an open-source Python-based library. It provides high flexibility and speed while building, training, and deploying deep learning models. At its core, PyTorch involves operations involving tensors. A tensor is a number, vector, m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/pytorch-tensor-methods/</link>
                <guid isPermaLink="false">66d4614e706b9fb1c166b9b7</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pytorch ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tensor ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 03 Dec 2020 17:00:26 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5fc667ad49c47664ed828110.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Srijan</p>
<p>PyTorch is an open-source Python-based library. It provides high flexibility and speed while building, training, and deploying deep learning models.</p>
<p>At its core, PyTorch involves operations involving <em>tensors.</em> A tensor is a number, vector, matrix, or any n-dimensional array.</p>
<p>In this article, we will see different ways of creating tensors using PyTorch tensor methods (functions).</p>
<h2 id="heading-topics-well-cover">Topics we'll cover</h2>
<ul>
<li>tensor</li>
<li>zeros</li>
<li>ones</li>
<li>full</li>
<li>arange</li>
<li>linspace</li>
<li>rand</li>
<li>randint</li>
<li>eye</li>
<li>complex</li>
</ul>
<h3 id="heading-the-tensor-method">The tensor() method</h3>
<p>This method returns a tensor when <code>data</code> is passed to it. <code>data</code> can be a scalar, tuple, a list or a <em>NumPy</em> array.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=76" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>In the above example, a NumPy array that was created using <code>np.arange()</code> was passed to the <code>tensor()</code> method, resulting in a 1-D tensor.</p>
<p>We can create a multi-dimensional tensor by passing a tuple of tuples, a list of lists, or a multi-dimensional NumPy array.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=77" height="179" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>When an empty tuple or list is passed into <code>tensor()</code>, it creates an empty tensor.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=78" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-zeros-method">The zeros() method</h3>
<p>This method returns a tensor where all elements are zeros, of specified <code>size</code> (shape). The <code>size</code> <strong>can</strong> be given as a tuple or a list or neither.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=4" height="200" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>We could have passed <code>3, 2</code> inside a tuple or a list as well. It is self-explainable that passing negative numbers or a float would result in a run time error.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=8" height="318" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Passing an empty tuple or an empty list gives a tensor of size (dimension) 0, having 0 as its only element, whose data type is float.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=10" height="205" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-ones-method">The ones() method</h3>
<p>Similar to <code>zeros()</code>, <code>ones()</code> returns a tensor where all elements are 1, of specified <code>size</code> (shape). The <code>size</code> <strong>can</strong> be given as a tuple or a list or neither.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/53&amp;cellId=19" height="400" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Like <code>zeros()</code>, passing an empty tuple or list gives a tensor of 0 dimension, having 1 as the sole element, whose data type is float.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=23" height="205" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-full-method">The full() method</h3>
<p>What if you want all the elements of a tensor to be equal to some value but not only 0 and 1? Maybe 2.9?</p>
<p><code>full()</code> returns a tensor of a shape given by the <code>size</code> argument, with all its elements equal to the <code>fill_value</code>.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=27" height="200" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Here, we have created a tensor of shape <code>3, 2</code> with the <code>fill_value</code> as 3. Here again, passing an empty tuple or list creates a scalar tensor of zero dimension.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=31" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>While using <code>full</code>, it is <strong>necessary</strong> to give <code>size</code> as a tuple or a list.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=33" height="444" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-arange-method">The arange() method</h3>
<p>This method returns a 1-D tensor, with elements from <code>start</code> (inclusive) to <code>end</code> (exclusive) with a common difference <code>step</code>. The default value for <code>start</code> is 0 while that for <code>step</code> is 1.</p>
<p>The elements of the tensor can be said to be in <strong>Arithmetic Progression</strong>, with <code>step</code> as common difference.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=37" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Here, we created a tensor which starts from 2 and goes until 20 with a <code>step</code> (common difference) of 2.</p>
<p>All the three parameters, <code>start</code>, <code>end</code> and <code>step</code> can be positive, negative or float.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=41" height="297" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>While choosing <code>start</code>, <code>end</code>, and <code>step</code>, we need to ensure that <code>start</code> and <code>end</code> are consistent with the <code>step</code> sign.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=41" height="297" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Since <code>step</code> is set as -2, there is no way -42 can reach -22 (exclusive). Hence, it gives an error.</p>
<h3 id="heading-the-linspace-method">The linspace() method</h3>
<p>This method returns a 1-D dimensional tensor, with elements from <code>start</code> (inclusive) to <code>end</code> (inclusive). However, unlike <code>arange()</code>, here, <code>steps</code> isn't the common difference but the number of elements to be in the tensor.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=45" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>PyTorch automatically decides the common difference based on the <code>steps</code> given.</p>
<p>Not providing a value for <code>steps</code> is deprecated. For <em>backwards compatibility</em>, not providing a value for steps creates a tensor with <strong>100</strong> elements. According to the official documentation, in a future PyTorch release, failing to provide a value for steps will throw a runtime error.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=47" height="748" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Unlike <code>arange()</code>, <code>linspace</code> can have a <code>start</code> greater than <code>end</code> since the common difference is automatically calculated.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=49" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Since <code>steps</code> here is not a common difference, but the number of elements, it can only be a non-negative integer.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=51" height="297" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-rand-method">The rand() method</h3>
<p>This method returns a tensor filled with random numbers from a uniform distribution on the interval 0 (inclusive) to 1 (exclusive). The shape is given by the <code>size</code> argument. The <code>size</code> argument can be given as a tuple or list or neither.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=55" height="200" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Passing an empty tuple or list creates a scalar tensor of zero dimension.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=56" height="158" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-randint-method">The randint() method</h3>
<p>This method returns a tensor filled with random integers generated uniformly between <code>low</code> (inclusive) and <code>high</code> (exclusive). The shape is given by the <code>size</code> argument. The default value for <code>low</code> is 0.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=59" height="242" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>When only one <code>int</code> argument is passed, <code>low</code> gets the value 0, by default, and <code>high</code> gets the passed value.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=60" height="200" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>The <code>size</code> argument only takes a tuple or a list. An empty tuple or list creates a tensor with zero dimension.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=62" height="318" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-eye-method">The eye() method</h3>
<p>This method returns a 2-D tensor with ones on the diagonal and zeros elsewhere. The number of rows is given by <code>n</code> and columns is given by <code>m</code>.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=65" height="179" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>The default value for <code>m</code> is the value of <code>n</code>. When only <code>n</code> is passed, it creates a tensor in the form of an <strong>identity matrix</strong>. An identity matrix has its diagonal elements as 1 and all others as 0. </p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=66" height="242" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h3 id="heading-the-complex-method">The complex() method</h3>
<p>This method returns a complex tensor with its real part equal to <code>real</code> and its imaginary part equal to <code>imag</code>. Both <code>real</code> and <code>imag</code> are tensors.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=69" height="363" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>The data type of both the <code>real</code> and <code>imag</code> tensors should be either <code>float</code> or <code>double</code>.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=70" height="523" width="800" title="Embedded content" loading="lazy"></iframe></div>

<p>Also, the <code>size</code> of both tensors, <code>real</code> and <code>imag</code>, should be the same, since the corresponding elements of the two matrices form a complex number.</p>
<div class="embed-wrapper"><iframe src="https://jovian.ai/embed?url=https://jovian.ai/srijansrj5901/different-ways-to-create-tensors/v/51&amp;cellId=72" height="499" width="800" title="Embedded content" loading="lazy"></iframe></div>

<h2 id="heading-conclusion">Conclusion</h2>
<p>We've covered ten different ways to create tensors using PyTorch methods. You can go through the <a target="_blank" href="https://pytorch.org/docs/stable/torch.html">official documentation</a> to know more about other PyTorch methods. </p>
<p>You can click <a target="_blank" href="https://jovian.ai/srijansrj5901/different-ways-to-create-tensors">here</a> to go to the Jupyter notebook where you can play around with these methods.</p>
<p>If you want to learn more about PyTorch, check out <a target="_blank" href="https://jovian.ai/learn/deep-learning-with-pytorch-zero-to-gans">this</a> amazing course on freeCodeCamp's <a target="_blank" href="https://www.youtube.com/watch?v=5ioMqzMRFgM&amp;t=3s&amp;ab_channel=freeCodeCamp.org">YouTube</a> channel.</p>
<p>Stay safe!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to get started debugging TensorFlow ]]>
                </title>
                <description>
                    <![CDATA[ By Daniel Deutsch Table of Contents What this is about The reference code base 1. Fetch and print values within Session.run 2. Use the tf.Print operation 3. Use Tensorboard visualization for monitoring a) clean the graph with proper names and name s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/debugging-tensorflow-a-starter-e6668ce72617/</link>
                <guid isPermaLink="false">66c348b81718310854c7aabc</guid>
                
                    <category>
                        <![CDATA[ debugging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tensor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TensorFlow ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 16 Jul 2018 12:35:46 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*Tpvh9TOicl1dT3W-" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Daniel Deutsch</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#what-this-is-about">What this is about</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#the-reference-code-base">The reference code base</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#1-fetch-and-print-values-within-sessionrun">1. Fetch and print values within Session.run</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#2-use-the-tfprint-operation">2. Use the tf.Print operation</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#3-use-tensorboard-visualization-for-monitoring">3. Use Tensorboard visualization for monitoring</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#a-clean-the-graph-with-proper-names-and-name-scopes">a) clean the graph with proper names and name scopes</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#b-add-tfsummaries">b) Add tf.summaries</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#c-add-a-tfsummaryfilewriter-to-create-log-files">c) Add a tf.summary.FileWriter to create log files</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#d-start-the-tensorboard-server-from-your-terminal">d) Start the tensorboard server from your terminal</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#4-use-the-tensorboard-debugger">4. Use the Tensorboard debugger</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#5-use-the-tensorflow-debugger">5. Use the TensorFlow debugger</a></li>
<li><a target="_blank" href="https://github.com/Createdd/Writing/blob/master/2018/articles/DebugTFBasics.md#conclusio">Conclusion</a></li>
</ul>
<h3 id="heading-what-this-is-about">What this is about</h3>
<blockquote>
<p><em>Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. — BRIAN W. KERNIGHAN</em></p>
</blockquote>
<p>Debugging in general can be a tedious and challenging task. Nevertheless, you must be comfortable going through the written code and identifying problems. Normally there are many guides, and the process of debugging is often well documented for many languages and frameworks.</p>
<p>When it comes to TensorFlow, however, some new challenges arise because of the way it works.</p>
<p>As the <a target="_blank" href="https://www.tensorflow.org/guide/low_level_intro">official documentation</a> states:</p>
<p>A TensorFlow Core program consists of two discrete sections:</p>
<ol>
<li>Building the computational graph (a tf.Graph).</li>
<li>Running the computational graph (using a tf.Session).</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/5pJQsrMBjTL0bpKAOpec0kfI0MklVYYH7TIa" alt="Image" width="252" height="448" loading="lazy">
_Source and credit to [https://www.tensorflow.org/guide/graphs](https://www.tensorflow.org/guide/graphs" rel="noopener" target="<em>blank" title=")</em></p>
<p>The actual computation is done with <code>session.run()</code>, which means that we need to find a way to inspect values inside this function.</p>
<h3 id="heading-the-reference-code-base">The reference code base</h3>
<p>As a reference, I will provide my Github repository with the corresponding code <a target="_blank" href="https://github.com/Createdd/tensorFlowTest/blob/debug/mnistPlain/mnistBasic.py">here</a>.</p>
<p>We will use a basic neural network to classify handwritten digits from the MNIST dataset, using:</p>
<ul>
<li><code>tf.nn.softmax_cross_entropy_with_logits_v2</code> as the TF classification operation for defining the loss</li>
<li><code>tf.train.GradientDescentOptimizer</code> for minimizing the loss</li>
</ul>
<p>Running this small neural network shows that it can already achieve an accuracy of ~92%:</p>
<h3 id="heading-the-process-of-debugging">The process of debugging</h3>
<p>Now for debugging, there are basically 5 (pragmatic) ways to achieve this.</p>
<blockquote>
<p><em>As a side note: It is often useful to assert shapes to ensure that everything works together as intended.</em></p>
</blockquote>
<h4 id="heading-1-fetch-and-print-values-within-sessionrun">1. Fetch and print values within Session.run</h4>
<p>This is probably the fastest and easiest way to get the information you need.</p>
<ul>
<li>easy and fast</li>
<li>any evaluation can be fetched from everywhere</li>
<li>it’s necessary to hold the reference to the tensor, which is bad in complex models</li>
</ul>
<p>In essence, you run the session in a print statement and feed it the dictionary, like so: <code>print( f"The bias parameter is: {sess.run(b, feed_dict={x: mnist.test.images, y_: mnist.test.labels})}" )</code></p>
<p>If the code gets more complex, the <a target="_blank" href="https://www.tensorflow.org/api_docs/python/tf/Session#partial_run">partial_run execution of a session</a> could be used. But since this is an experimental feature I will not implement this for demonstration.</p>
<p>Additionally, don’t forget the <code>[.eval()](https://www.tensorflow.org/api_docs/python/tf/Tensor#eval)</code> method for evaluating tensors specifically.</p>
<p><a target="_blank" href="https://github.com/Createdd/tensorFlowTest/blob/debug/fetchValuesInSession/mnistBasic.py">See the full code here on Github.</a></p>
<h4 id="heading-2-use-the-tfprint-operation">2. Use the tf.Print operation</h4>
<p>The <a target="_blank" href="https://www.tensorflow.org/api_docs/python/tf/Print">tf.Print method</a> comes in handy during run-time evaluation when we don’t want to explicitly fetch the code with session.run(). It is an identity op that prints data when evaluating.</p>
<ul>
<li>it allows us to see the development of values during evaluation</li>
<li>it has limited configuration and therefore can easily clog the terminal</li>
</ul>
<p>Yufeng G created a fantastic video and <a target="_blank" href="https://towardsdatascience.com/using-tf-print-in-tensorflow-aa26e1cff11e">article about how to use the tf.Print statement</a>. And as he points out, it is vital to structure the print node the way that it is used further. As he says:</p>
<blockquote>
<p><em>It is vitally important that you actually use this returned node, because if you don’t, it will be dangling.</em></p>
</blockquote>
<p>In my code, I added a print statement that fetches the values within the session to illustrate how both methods perform differently in execution.</p>
<p>With runtime evaluation comes the possibility of <a target="_blank" href="https://www.tensorflow.org/api_guides/python/check_ops#asserts-and-boolean-checks">runtime assertion</a> with <code>tf.Assert</code> .</p>
<p><a target="_blank" href="https://github.com/Createdd/tensorFlowTest/blob/debug/tfPrint/mnistBasic.py">See the full code here.</a></p>
<h4 id="heading-3-use-tensorboard-visualization-for-monitoring">3. Use Tensorboard visualization for monitoring</h4>
<p>Before diving into this debugging method, be aware that there is the Tensorboard and the Tensorboard debugger!</p>
<p>The <a target="_blank" href="https://www.tensorflow.org/guide/summaries_and_tensorboard">TF website</a> offers a great tutorial for implementing and using the board.</p>
<p>A key for the usage is the serializing of the data. TensorFlow provides the summary operations, which allow you to export condensed information about the model. They are like anchors telling the visualization board what to plot.</p>
<p><strong>a) Clean the graph with proper names and name scopes</strong></p>
<p>First we need to organize all the variables and operations with the <code>[scope](https://www.tensorflow.org/guide/graph_viz#name_scoping_and_nodes)</code> <a target="_blank" href="https://www.tensorflow.org/guide/graph_viz#name_scoping_and_nodes">methods</a> that TF provides.</p>
<pre><code><span class="hljs-keyword">with</span> tf.name_scope(<span class="hljs-string">"variables_scope"</span>):    x = tf.placeholder(tf.float32, shape=[None, <span class="hljs-number">784</span>], name=<span class="hljs-string">"x_placeholder"</span>)    y_ = tf.placeholder(tf.float32, shape=[None, <span class="hljs-number">10</span>], name=<span class="hljs-string">"y_placeholder"</span>)
</code></pre><p><strong>b) Add tf.summaries</strong></p>
<p>For example:</p>
<pre><code><span class="hljs-keyword">with</span> tf.name_scope(<span class="hljs-string">"weights_scope"</span>):    W = tf.Variable(tf.zeros([<span class="hljs-number">784</span>, <span class="hljs-number">10</span>]), name=<span class="hljs-string">"weights_variable"</span>)    tf.summary.histogram(<span class="hljs-string">"weight_histogram"</span>, W)
</code></pre><p><strong>c) Add a tf.summary.FileWriter to create log files</strong></p>
<p>Tip: Make sure to create sub folders for each log to avoid accumulation of graphs.</p>
<p><strong>d) Start the tensorboard server from your terminal</strong></p>
<p>For example: <code>tensorboard --logdir=./tfb_logs/ --port=8090 --host=127.0.0.1</code></p>
<p>Navigating to the tensorboard server (in this case <code>http://127.0.0.1:8090</code>) shows the following:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/offiWwNnxs5aZ7J8i3J7hOn1fUVxsXQ3291B" alt="Image" width="800" height="299" loading="lazy">
<em>The distributions tab of tensorboard</em></p>
<p>Now the full power and use of tensorboard becomes clear. It allows you very easily to spot errors in your machine learning model. My code example is a very simple one. Imagine a model with multiple layers and more variables and operations!</p>
<p><a target="_blank" href="https://github.com/Createdd/tensorFlowTest/blob/debug/tensorboard/mnistBasic.py">See full code here on Github.</a></p>
<h4 id="heading-4-use-the-tensorboard-debugger">4. Use the Tensorboard debugger</h4>
<p>As the <a target="_blank" href="https://github.com/tensorflow/tensorboard/tree/master/tensorboard/plugins/debugger">Tensorboard Github repository</a> states:</p>
<blockquote>
<p><em>This dashboard is in its alpha release. Some features are not yet fully functional.</em></p>
</blockquote>
<p>However, it can still be used and provides cool debugging features. Please check out the Github repository to get an adequate overview. Also, see their <a target="_blank" href="https://www.youtube.com/watch?v=XcHWLsVmHvk">video</a> to get a deeper understanding. They have done a great job.</p>
<p>To accomplish this, there are 3 things to add to our previous example:</p>
<ol>
<li>Import <code>from tensorflow.python import debug as tf_debug</code></li>
<li>Add your session with <code>tf_debug.TensorBoardDebugWrapsperSession</code></li>
<li>Add to your tensorboard server the <code>debugger_port</code></li>
</ol>
<p>Now you have the option to debug the whole visualized model like with any other debugger, but with a beautiful map. You are able to select certain nodes and inspect them, control execution with the “step” and “continue” buttons, and visualize tensors and their values.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/TfHCodSEr9yVNORtks9rB8mbJccZWEb8vueQ" alt="Image" width="800" height="295" loading="lazy">
<em>The debugger feature of tensorboard in action</em></p>
<p>There is much more to talk about regarding this unique feature of Tensorflow, but I will probably dedicate another article to that.</p>
<p><a target="_blank" href="https://github.com/Createdd/tensorFlowTest/blob/debug/tensorboardDebugger/mnistBasic.py">See my full code here on Github.</a></p>
<h4 id="heading-5-use-the-tensorflow-debugger">5. Use the TensorFlow debugger</h4>
<p>The last method, but also very powerful, is the <a target="_blank" href="https://www.tensorflow.org/guide/debugger">CLI TensorFlow debugger</a>.</p>
<p>This debugger focuses on the command-line interface (CLI) of tfdbg, as opposed to the graphical user interface (GUI) of tfdbg, that is the TensorBoard Debugger Plugin.</p>
<p>You simply wrap the session with <code>tf_debug.LocalCLIDebugWrapperSession(sess)</code> and then you start the debugging with executing the file (maybe it's necessary to add the <code>--debug</code> flag).</p>
<p>It basically allows you to run and step through the execution of your model, while providing evaluation metrics.</p>
<p>I think the <a target="_blank" href="https://www.tensorflow.org/guide/debugger#frequently_asked_questions">official documention</a> could be improved, but they have also created a <a target="_blank" href="https://www.youtube.com/watch?v=CA7fjRfduOI&amp;t=53s">video</a> which introduces the feature in a good way.</p>
<p>So the key features here are the commands <code>invoke_stepper</code> and then pressing <code>s</code> to step through each operation. It is the basic debugger functionality of a debugger but in the CLI. It looks like this:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/iU14oHmUGXh3dF35HToJ6MFFpB-fOTUq7ZIS" alt="Image" width="800" height="580" loading="lazy">
<em>Evaluation metrics while debugging with the CLI</em></p>
<p><a target="_blank" href="https://github.com/Createdd/tensorFlowTest/blob/debug/tfdbg/mnistBasic.py">See the full code here on Github.</a></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>As shown, there are many ways to debug a TensorFlow application. Each method has its own strengths and weaknesses. I didn’t mention the Python debugger, because it is not TensorFlow specific, but keep in mind that the simple Python debugger already provides some good insights!</p>
<p>There is a great <a target="_blank" href="https://wookayin.github.io/tensorflow-talk-debugging/#74">presentation by Wookayin</a> who talks about these concepts as well but also goes over some general debugging advise. That advice is:</p>
<ul>
<li>name tensors properly</li>
<li>check and sanitize input</li>
<li>logging</li>
<li>assertions</li>
<li>proper use of exceptions</li>
<li>failing fast -&gt; immediately abort if something is wrong</li>
<li>don’t repeat yourself</li>
<li>organize your modules and code</li>
</ul>
<p>I am really excited for all the features that TensorFlow has to offer for people who are building machine learning systems. They are doing a great job! Looking forward to further developments! :)</p>
<p>Thanks for reading my article! Feel free to leave any feedback!</p>
<p>Daniel is a LL.M. student in business law, working as a software engineer and organizer of tech related events in Vienna. His current personal learning efforts focus on machine learning.</p>
<p>Connect on:</p>
<ul>
<li><a target="_blank" href="https://www.linkedin.com/in/createdd">LinkedIn</a></li>
<li><a target="_blank" href="https://github.com/Createdd">Github</a></li>
<li><a target="_blank" href="https://medium.com/@ddcreationstudi">Medium</a></li>
<li><a target="_blank" href="https://twitter.com/DDCreationStudi">Twitter</a></li>
<li><a target="_blank" href="https://steemit.com/@createdd">Steemit</a></li>
<li><a target="_blank" href="https://hashnode.com/@DDCreationStudio">Hashnode</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
