<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Locus.Focus on Medium]]></title>
        <description><![CDATA[Stories by Locus.Focus on Medium]]></description>
        <link>https://medium.com/@locus.focus?source=rss-26d4a4ca6b8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9P_ij_q97laquIQx0zlKiw.gif</url>
            <title>Stories by Locus.Focus on Medium</title>
            <link>https://medium.com/@locus.focus?source=rss-26d4a4ca6b8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:20:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@locus.focus/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Let’s talk Transformers in Machine Learning!]]></title>
            <link>https://medium.com/@locus.focus/lets-talk-transformers-in-machine-learning-14ea5ad8b8cb?source=rss-26d4a4ca6b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ea5ad8b8cb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Locus.Focus]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 21:00:11 GMT</pubDate>
            <atom:updated>2023-12-29T21:00:11.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*-HLDxPmsHDV-90RB.jpg" /><figcaption>Transformers, sometimes called foundation models, are already being used with many data sources for a host of applications.</figcaption></figure><p>For the past few years since the release of paper “Attention is all you need” by the Google Brain Team, transformers are taking the machine learning world by storm. These incredible models have been breaking multiple records and pushing the SOTA.</p><p>They are used in various applications such as machine language translation, conversational chatbots, and even in some powerful search engines. Transformers are rage in deep learning now-a-days. But how do they work? How did they outperformed the previous released models like RNNs, GRUs and LSTMs?</p><p>Transformers are redefining the boundaries of machine learning by breaking free from the constraints of labeled data. Previously, training neural networks demanded vast amounts of labeled data, often entailing significant time and expense.</p><p>Transformers, however, have ushered in a new paradigm. By leveraging their ability to discern patterns mathematically, they access a previously untapped wealth of information — the trillions of images and petabytes of text that reside untouched on the web and within corporate databases. This unprecedented access to raw, unlabeled data fuels a new era of machine learning possibilities. Moreover, the mathematical architecture underpinning transformers inherently supports parallel processing, enabling these models to execute tasks with remarkable swiftness. Thus, transformers not only unlock vast reserves of data but also streamline the learning process itself, heralding a transformative era for machine intelligence.</p><h4><strong>Attention Mechanism</strong></h4><p>To understand Transformers, we need to firstly know about the attention mechanism.</p><p>To get an intuitive understanding of the attention mechanism, let’s start with trying to understand a complex sentence with multiple clauses. Imagine reading: “The cat, nestled on the windowsill, watched the birds flitting between the branches, while the sun cast long shadows across the lawn.” With an RNN, your understanding might build sequentially, focusing on “The cat” first, then “nestled,” and so on. But how do you connect “cat” to “birds” later in the sentence? That’s where the Transformer’s spotlight shines.</p><p>The model uses multiple attention mechanisms to analyze the sentence. One might focus on the relationship between “cat” and “nestled,” highlighting how the cat’s position helps understand its action. Another might attend to the connection between “birds” and “branches,” revealing the context of their fluttering. All these connections are woven together, allowing the model to grasp the complete meaning of the sentence, understanding not just individual words but also their interplay and context.</p><p>Model has the ability to reference or tend towards certain words. How model knows which word to “attend” is learnt while training with backpropagation. This approach makes Transformers incredibly powerful for tasks like machine translation where they can connect words across languages, considering both grammar and semantic relationships. Similarly, in question answering, Transformers can effectively analyze a document and “attend” to relevant parts to answer complex queries that require understanding context and relationships.</p><h4>The Model Architecture</h4><p>Transformers are in many cases replacing convolutional and recurrent neural networks (CNNs and RNNs), the most popular types of deep learning models just five years ago.</p><p>Like most neural networks, transformer models are basically large encoder/decoder blocks that process data. Small but strategic additions to these blocks (shown in the diagram below) make transformers uniquely powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*wdFGxUjQa04eZe1WfsQ8oA.png" /><figcaption>The encoder and decoder blocks of Transformers architecture</figcaption></figure><p>Let’s walk through the architecture model step by step.</p><ul><li><strong>Input Embeddings</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*3xBfiRcMf4Rru2E09V9TTw.png" /><figcaption>Word Embeddings Layer</figcaption></figure><p>This layer takes the input to the word embeddings layer. The layer collects all the words in the input and convert it into a lookup table with learned vector representing each word. Each word is mapped to a vector with continuous values to represent that word.</p><ul><li><strong>Positional Encodings</strong></li></ul><p>The next layer adds the positional embeddings to the outputs from the embeddings layer. This is done using positional encoding. Sine and Cosine functions are used to encode the positions with cosine function used for Odd positions and sine function is used for even positioning. These functions are chosen due to there easy to learnable capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*gG0aQMZ1z-qAWIntex9KJw.png" /><figcaption>sine and cosine functions for positional encodings</figcaption></figure><ul><li><strong>Multi-headed attentions</strong></li></ul><p>Moving on to the Multi-headed Attentions layer, it’s like having a team of experts focusing on different aspects of the input. This layer employs attention mechanisms to allow the model to weigh the importance of different words in the input. It’s as if each word gets a personalized attention score from multiple “heads” or perspectives. These attention scores are then combined, offering a nuanced understanding of the input that captures various relationships and dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*miwAPLx6nTeo8TzEIxLqMg.png" /><figcaption>Architecture of a single head attention</figcaption></figure><p>The input matrix is fed by splitting into Query (Q), Key (K) and Values (V). Each of the splits is passed through a linear network. Further Q and K are dot product to form the score matrix, which is a representation of how much the words in queries and keys are related to each other. The higher the score the more related are the words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*GnoJ3v0QcTWqttDSMca0jg.png" /><figcaption>Score matrix obtained by multiplying queries and keys</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*95tFREVVxl_U9BpQ3u1Pyg.png" /><figcaption>The Score Matrix: The higher the score the more focus on that words</figcaption></figure><p>The score matrix is further normalized by dividing the sqrt(dimension of matrix) to get a stable output. Further it is passed through a softmax function to distribute the values more efficiently.</p><p>For getting better results, multiple such heads are used so that each heads learns a different aspect of the input making it more connected.</p><p>But in case of decoder models, there’s a catch.</p><ul><li><strong>Attention Masking Concept for Decoder models</strong></li></ul><p>During each decoding step, the attention mechanism uses this mask to assign weights to the input sequence elements. The padding positions, marked with zeros in the mask, receive zero attention weight, effectively masking them out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*0nAk1SsHKqLpdCMeEqFsHg.png" /><figcaption>Mask is added after scaling and before taking softmax</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MouyHFk0vvpvm2y7seKA1Q.png" /><figcaption>Softmax handle the -inf values giving those words which appear later in the sequence a zero focus.</figcaption></figure><ul><li><strong>Residual Connections, Norm Layer and Feed forward Network.</strong></li></ul><p>In the next step the multi-headed attention output is concatenated with the original input. This method is called residual connection. In the grand scheme of things, the Residual Connections layer is like a safety net for information flow. It ensures that the original input information doesn’t get lost in the shuffle. Just like a reliable backup, this layer adds the initial input to the output of the previous layer, allowing the model to retain valuable information. It’s a clever way to prevent potential information loss and keeps the learning process stable and efficient.</p><p>Now, let’s talk about the Norm Layer, which plays the role of the peacekeeper in our neural network world. This layer normalizes the output from previous layers, making sure that the values don’t go haywire and disrupt the harmony of the model. It’s like setting a standard for behavior — ensuring that the data maintains a consistent scale and doesn’t get too carried away. This normalization step helps in smoother and more predictable training, contributing to the overall stability of the model.</p><p>Finally, we have the Feed Forward Network, the powerhouse that adds a layer of complexity and abstraction. This network takes the information processed so far and transforms it in a nonlinear way, bringing out intricate patterns and representations. It’s akin to having a sophisticated filter that refines the features extracted from the input. This step allows the model to grasp high-level relationships and dependencies, providing a more nuanced understanding of the input data.</p><ul><li><strong>Final Multimodal attention</strong></li></ul><p>This section has queries and keys from the input and values as the output from the first multimodal attention layer of the decoder. The Encoders and Decoders can be stacked upon each other so as to generate better and efficient outputs. The generation stops when decoder gets an &lt;end&gt; token as the output from the final classifier layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWtnMWI3fiAHQ6Q6jxIvQQ.png" /><figcaption>The Encoder maps input sequence into “Embeddings” and is fed to the decoder along with the previous generated sequential output. The process ends when an &lt;end&gt; token is received as output.</figcaption></figure><p>Pheww! That was a lot of stuffs for today. But we will be back with more on Transformers!</p><p>Soon we are going to release a series on the most popular transformers models with some working codes and examples. Make sure to follow Locus Focus, so that you don’t miss any articles from us!</p><p>Stay Tuned and Follow us for more!</p><p>If you liked the article, do leave us a like!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*eMsptz-Qy82OBvWNkoEN_A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ea5ad8b8cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The story of Tensors (TensorFlow)]]></title>
            <link>https://medium.com/@locus.focus/the-story-of-tensors-tensorflow-97607553691f?source=rss-26d4a4ca6b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/97607553691f</guid>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Locus.Focus]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 19:11:32 GMT</pubDate>
            <atom:updated>2023-10-24T19:11:32.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EAw_xxO8DtHVWgHE.png" /><figcaption>TensorFlow</figcaption></figure><p>Let’s start with the story of a mysterious town…</p><p><em>Once upon a time in the bustling town of DataVille, there lived a curious young engineer named Ekta. Ekta had always been fascinated by the invisible threads of information that connected the world. She dreamed of finding a way to bring these threads to life, to see the magic that flowed through data.</em></p><p><em>One sunny morning, while sipping her morning coffee and brainstorming ideas, Ekta stumbled upon a mysterious old book in the corner of her favorite bookstore. The book was titled “The Tale of Tensors: Unveiling the Secrets of Data.” Ekta’s eyes lit up as she flipped through its pages.</em></p><p><em>Within the ancient pages, she discovered the story of “Tensors” — the fundamental building blocks of data. Tensors were said to have the power to hold any kind of information, from numbers to words, and even the intricacies of images and sounds. They could stretch, twist, and adapt to any form of data, much like magical clay.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*VoSrxRJtTvymhQKALiMkUA.png" /></figure><p>Tensors are a fundamental concept in mathematics and are particularly essential in the fields of data science, machine learning, and deep learning. Think of tensors as generalizations of matrices; while matrices are 2D arrays, tensors can have any number of dimensions.</p><p>In essence, tensors enable the representation and manipulation of complex, multi-dimensional data, and they serve as the foundation for modern machine learning, deep learning, and neural networks. While tensors themselves aren’t new, their pivotal role in these fields is a significant development that has transformed the way we approach and solve complex problems with data.</p><p>I have prepared a <a href="https://colab.research.google.com/drive/1Qg8hMibKYxzpYsn2MjFDOLuByOtsAD5m?usp=sharing">Google Colab</a> for the syntax of some more basic Tensor functions and operations. Also do check out the official documentation of <a href="https://www.tensorflow.org/api_docs/python/tf">TensorFlow</a> for more information and knowledge.</p><h3>Basic Operations</h3><ol><li><strong>tf.constant</strong></li></ol><p>The tf.constant function in TensorFlow is used to create a constant tensor with a specified value. The basic syntax for creating a constant tensor is:</p><pre>import tensorflow as tf # Creating a constant tensor <br>my_tensor = tf.constant(value, dtype=tf.float32)</pre><p>2D tensors and 3D tensors using tf.constant</p><pre>import tensorflow as tf <br><br># Creating a 2D tensor (matrix) <br>matrix_2d = tf.constant([[1, 2, 3], <br>                         [4, 5, 6], <br>                         [7, 8, 9]], dtype=tf.float32)<br><br><br># Creating a 3D tensor<br>tensor_3d = tf.constant([[[1, 2, 3],<br>                        [4, 5, 6]],<br>                       [[7, 8, 9],<br>                        [10, 11, 12]]], dtype=tf.float32)</pre><p>2D and 3D tensors are commonly used in various machine learning and deep learning applications, especially when working with data like images, time series, or spatial data, which require multi-dimensional representations.</p><p><strong>Note:</strong> Mixed type of tensors can’t be formed using tf.constant. For Example:</p><pre>import tensorflow as tf<br>tensor_1 = tf.constant([1,2,3,4,’i’])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxsHHSpBRzhFcyI4OFKChQ.png" /><figcaption>The above code will give this as an error.</figcaption></figure><p><strong>2. Identity (Eye) Tensor:</strong></p><p>The tf.eye function is used to create an identity (or eye) tensor. An identity tensor is a square matrix where all elements in the main diagonal are set to 1, and all other elements are 0.</p><p>Here’s an example of creating a 3x3 identity tensor using TensorFlow:</p><pre>import tensorflow as tf<br># Creating a 3x3 identity tensor<br>identity_tensor = tf.eye(3, dtype=tf.float32)</pre><p><strong>3. Zero Tensor:</strong></p><p>The tf.zeros function is used to create a tensor filled with zeros. You can specify the shape and data type of the tensor.</p><p>Here’s an example of creating a 2x4 zero tensor with TensorFlow:</p><pre>import tensorflow as tf<br># Creating a 2x4 zero tensor<br>zero_tensor = tf.zeros([2, 4], dtype=tf.float32)</pre><p><strong>4. Rank, Shape and Size</strong></p><pre>import tensorflow as tf<br># Create a tensor<br> tensor = tf.constant([[1, 2], [3, 4]])<br># Get the rank of the tensor<br> rank = tf.rank(tensor)<br> print(“Rank of the tensor:”, rank.numpy()) # Output: 2<br># Get the shape of the tensor<br> shape = tf.shape(tensor)<br> print(&quot;Shape of the tensor:&quot;, shape.numpy()) # Output: [2 2]<br># Get the size of the tensor<br> size = tf.size(tensor)<br> print(&quot;Size of the tensor:&quot;, size.numpy()) # Output: 4</pre><p>Understanding the rank, shape, and size of tensors is fundamental when working with TensorFlow, as it allows you to manipulate and reshape tensors effectively in various machine learning tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9H_6YLsN4N-l48UL" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>5. Indexing and Slicing</strong></p><p>In TensorFlow, you can perform indexing and slicing operations on tensors similarly to how you would in Python. You can access specific elements or sub-tensors within a tensor using indices. Here’s an overview of indexing in TensorFlow:</p><ul><li>Indexing a 1D Tensor (Vector):<br> You can access elements of a 1D tensor (vector) using square brackets and integer indices.</li></ul><pre><br> vector = tf.constant([1, 2, 3, 4, 5])<br> element = vector[2] # Accessing the third element (index 2)<br> print(element.numpy()) # Outputs: 3<br> sub_tensor = vector[1:4] # Access elements from index 1 to 3 (excludes 4)<br> print(sub_tensor.numpy()) # Outputs: [2 3 4]</pre><ul><li>Indexing a 2D Tensor (Matrix):</li></ul><pre> matrix = tf.constant([[1, 2, 3],<br> [4, 5, 6],<br> [7, 8, 9]])<br> element = matrix[1, 2] # Accessing the element at row 1, column 2<br> print(element.numpy()) # Outputs: 6<br> sub_matrix = matrix[1:3, 0:2] # Accessing a sub-matrix<br> print(sub_matrix.numpy())<br> # Outputs:<br> # [[4 5]<br> # [7 8]]</pre><p>These are the fundamental ways to perform indexing and slicing in TensorFlow. You can apply similar principles for higher-dimensional tensors. Indexing is particularly useful for extracting specific data points or sub-tensors when working with complex machine learning models.</p><p><strong>6. tf.math</strong></p><p>In TensorFlow, you can work with complex numbers and perform various operations on them using the `tf.complex` function, as well as `tf.sqrt`, `tf.abs`, and the basic arithmetic operations (`+`, `-`, `*`, and `/`). Here’s how to use these operations with complex numbers:</p><pre>import tensorflow as tf<br><br># Creating complex numbers<br>z1 = tf.complex(3.0, 4.0)  # 3 + 4i<br>z2 = tf.complex(1.0, 2.0)  # 1 + 2i<br><br># Square root<br>sqrt_z1 = tf.sqrt(z1)<br><br># Absolute value<br>abs_z1 = tf.abs(z1)<br><br># Addition<br>sum_z = z1 + z2<br><br># Subtraction<br>diff_z = z1 - z2<br><br># Multiplication<br>product_z = z1 * z2<br><br># Division<br>quotient_z = z1 / z2</pre><p>These operations allow you to work with complex numbers in TensorFlow, making it suitable for various applications, including signal processing and quantum computing simulations.</p><p><strong>7. tf.math (Continued)</strong></p><pre>import tensorflow as tf<br><br># Creating a sample tensor<br>tensor = tf.constant([[1, 2, 3], [4, 5, 6]])<br><br># Reduce Sum<br>sum_all = tf.reduce_sum(tensor)  # Output: 21<br><br># Reduce Max<br>max_value = tf.reduce_max(tensor)  # Output: 6<br><br># Argmax<br>max_index = tf.argmax(tensor)  # Output: 5 (index of the maximum value)<br><br># Power<br>squared = tf.pow(tensor, 2)  # Output: [[ 1  4  9]<br>                            #          [16 25 36]]<br><br># Top_k<br>top_values, top_indices = tf.math.top_k(tensor, k=2)<br># Output (Top 2 Values): [3 6]<br># Output (Top 2 Indices): [2 2]<br>                            <br></pre><ul><li>tf.reduce_sum(tensor) — Reduce Sum:<br> The ‘tf.reduce_sum’ function is used to compute the sum of all elements in the ‘tensor’.</li><li>tf.reduce_max(tensor) — Reduce Max:<br>The ‘tf.reduce_max’ function calculates the maximum value in the ‘tensor’.</li><li>tf.argmax(tensor) — Argmax:<br>The ‘tf.argmax’ function returns the indices of the maximum values in the ‘tensor’.</li><li>tf.pow(tensor, 2)` — Power (Squared):<br>The ‘tf.pow’ function is used to calculate the element-wise power of the `tensor`.</li><li>tf.math.top_k(tensor, k=2) — Top_k:<br>The ‘tf.math.top_k’ function returns the top k values and their indices in the ‘tensor’.</li></ul><p>These operations showcase common operations in TensorFlow for reducing, extracting information, and performing element-wise computations on tensors. They are frequently used in various machine learning and numerical applications.</p><p><strong>8. tf.einsum (V.imp and powerful)</strong></p><p>Suppose you have two tensors, A and B, and you want to compute their matrix multiplication (dot product). You can achieve this using tf.einsum as follows:</p><pre>import tensorflow as tf<br># Define two input tensors<br>A = tf.constant([[1, 2],<br>                [3, 4]])<br>B = tf.constant([[5, 6],<br>                [7, 8]])<br># Use tf.einsum to perform matrix multiplication<br>result = tf.einsum(&#39;ij,jk-&gt;ik&#39;, A, B)</pre><pre># Output</pre><pre>[[19 22]<br> [43 50]]</pre><p>In this example, &#39;ij,jk-&gt;ik&#39; is the Einstein summation notation that defines the operation. It specifies that you want to compute the dot product of A and B. The result is stored in the result tensor.</p><p>You can use tf.einsum for a wide range of operations, such as element-wise multiplication, summation, contraction, and more. The notation is powerful and flexible, allowing you to express complex operations concisely. You&#39;ll need to understand the Einstein summation notation to use tf.einsum effectively, and the TensorFlow documentation provides detailed examples and explanations to help you get started with it.</p><p><strong>9. tf.linalg</strong></p><p>The ‘tf.linalg’ module in TensorFlow provides a wide range of methods for linear algebra operations, making it an important tool for tasks such as solving systems of linear equations, performing matrix factorizations, computing eigenvalues and eigenvectors, and more. Here are some important methods and functions available in ‘tf.linalg’:</p><pre>import tensorflow as tf<br><br># Create sample matrices<br>A = tf.constant([[1.0, 2.0], [3.0, 4.0]], dtype=tf.float32)<br>B = tf.constant([[5.0, 6.0], [7.0, 8.0]], dtype=tf.float32)<br><br># Matrix Transposition<br>transposed_A = tf.linalg.matrix_transpose(A)<br><br># Matrix Multiplication<br>matmul_result = tf.linalg.matmul(A, B)<br><br># Matrix Inversion<br>A_inverse = tf.linalg.inv(A)<br><br># Solve Linear System<br>linear_system_solution = tf.linalg.solve(A, B)<br><br># QR Decomposition<br>q, r = tf.linalg.qr(A)<br><br># SVD (Singular Value Decomposition)<br>s, u, v = tf.linalg.svd(A)<br><br># Cholesky Decomposition<br>cholesky_L = tf.linalg.cholesky(A)<br><br># Eigenvalue and Eigenvector Computations<br>eigenvalues, eigenvectors = tf.linalg.eigh(A)<br><br># Matrix Norm<br>matrix_norm = tf.linalg.norm(A)</pre><p><strong>10. Other important functions</strong></p><p>Try running and checking the outputs of some of the following more important functions.</p><pre>import tensorflow as tf<br><br># Reshaping (tf.reshape)<br>original_tensor = tf.constant([1, 2, 3, 4, 5, 6])<br>reshaped_tensor = tf.reshape(original_tensor, (2, 3))<br><br># Concatenating (tf.concat)<br>tensor1 = tf.constant([1, 2])<br>tensor2 = tf.constant([3, 4])<br>concatenated_tensor = tf.concat([tensor1, tensor2], axis=0)<br><br># Adding Dimensions (tf.expand_dims)<br>original_tensor = tf.constant([1, 2, 3])<br>expanded_tensor = tf.expand_dims(original_tensor, axis=1)<br><br># Padding (tf.pad)<br>t3 = tf.constant([[1, 2], [3, 4]])<br>paddings = tf.constant([[1,2],<br>                        [3,4]])<br>print(tf.pad(t3,paddings,&#39;CONSTANT&#39;, constant_values = 0)) #zero is default value for constant padding<br>paddings = tf.constant([[2, 2,], [2, 2]])<br>print(tf.pad(t3,paddings,&#39;REFLECT&#39;))<br>print(tf.pad(t3,paddings,&#39;SYMMETRIC&#39;))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1O1WqbM2kHSk5bYt" /><figcaption>Photo by <a href="https://unsplash.com/@gregbulla?utm_source=medium&amp;utm_medium=referral">Greg Bulla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>11. RaggedTensors</strong></p><p>Ragged Tensors are a type of tensor in TensorFlow that handle sequences of variable lengths. They are particularly useful for working with data that doesn’t have a fixed shape, such as text data where sentences or paragraphs may have different lengths. Ragged Tensors can be created, manipulated, and used in various TensorFlow operations.</p><p>Here’s a basic overview of how to work with Ragged Tensors:</p><pre>import tensorflow as tf<br><br># Creating Ragged Tensors<br><br># From Python Lists<br>data = [[1, 2], [3, 4, 5], [6]]<br>ragged_from_lists = tf.RaggedTensor.from_nested_row_lengths(data)<br><br># From Ragged Constants<br>values = [1, 2, 3, 4, 5, 6]<br>splits = [0, 2, 5, 6]  # Defines the boundaries between rows<br>ragged_from_constants = tf.RaggedTensor.from_row_splits(values, splits)<br><br># Concatenation<br>ragged1 = tf.RaggedTensor.from_value_rowids([1, 2, 3, 4, 5, 6], [0, 0, 1, 1, 1, 2])<br>ragged2 = tf.RaggedTensor.from_value_rowids([7, 8], [0, 0])<br>concatenated = tf.concat([ragged1, ragged2], axis=0)<br><br># Indexing and Slicing<br>element = ragged1[1, 2]  # Access the element at row 1, column 2<br>slice = ragged1[0:2]  # Get a slice from row 0 to row 1<br><br># Row Lengths<br>row_lengths = ragged1.row_lengths()<br><br># Conversion to Dense Tensor<br>dense_tensor = ragged1.to_tensor()</pre><p>Ragged Tensors are commonly used in Natural Language Processing (NLP) for processing sequences of variable-length sentences, text documents, and tokens. They also find applications in time series data, speech processing, and any data where the length of sequences varies.</p><p>Overall, Ragged Tensors are a versatile tool for handling data with irregular shapes, making them a valuable addition to TensorFlow’s data manipulation capabilities.</p><p><strong>12. Variables</strong></p><ul><li>Variables are a specific type of tensor that are designed for use in machine learning models. They are often used to store model parameters, such as weights and biases. Variables are mutable, which means their values can be changed during training. This property is crucial for updating model parameters during optimization.</li><li>Example of creating a variable:</li></ul><pre>import tensorflow as tf<br>initial_values = tf.constant([1.0, 2.0, 3.0])<br>model_weights = tf.Variable(initial_values)</pre><p>That’s it!</p><p>To sum it up, TensorFlow’s fundamental functions are the bedrock of advanced machine learning. These operations, spanning from tensor creation to variable definition, serve as the building blocks for powerful neural networks and data processing. With these core functions, TensorFlow stands at the forefront of AI, offering endless potential for deep learning and beyond.</p><p>Well that was quite a long tutorial!</p><p>Thanks for being with me till the end! Stay Tuned and Do follow me for more!</p><p>If you liked the article in any way do give a thumbs up!</p><figure><img alt="Please Follow Me 🥺🥺" src="https://cdn-images-1.medium.com/max/500/0*d14tJ3IR4BDswtIM.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97607553691f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey to TensorFlow & Installation]]></title>
            <link>https://medium.com/@locus.focus/a-journey-to-tensorflow-installation-703e8bbf435e?source=rss-26d4a4ca6b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/703e8bbf435e</guid>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[installation]]></category>
            <dc:creator><![CDATA[Locus.Focus]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 03:40:51 GMT</pubDate>
            <atom:updated>2023-10-23T05:18:14.378Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start with a small story….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rGwuOLEeER-ZOdMJ" /><figcaption>Photo by <a href="https://unsplash.com/@dandimmock?utm_source=medium&amp;utm_medium=referral">Dan Dimmock</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>““ In a small research lab, some passionate scientists were embarking on a journey to create a machine learning model. They needed a tool that was as flexible as their imagination, and that’s when they stumbled upon TensorFlow.</em></p><p><em>With TensorFlow, the scientist found the freedom to work on various platforms, from desktops to mobile devices, making their dreams come to life effortlessly. The scientist marveled at the scalability of TensorFlow, as it tackled massive datasets and complex models with grace.</em></p><p><em>But the true beauty of TensorFlow lay in its versatility. Whether it was deep learning, reinforcement learning, or a host of other algorithms, TensorFlow was always up to the task.</em></p><p><em>As the scientist delved deeper into this magical world, they realized that TensorFlow offered different paths for different explorers. For newcomers, high-level APIs like Keras provided an easy start, while the more seasoned researchers reveled in the lower-level APIs that gave them control and flexibility.</em></p><p><em>But it wasn’t just about the technology. TensorFlow had a thriving community, a network of like-minded individuals who offered support and guidance. It was a place where knowledge blossomed.</em></p><p><em>TensorFlow was not just a tool; it was a canvas for visualization. With TensorBoard, the scientist watched their model’s journey, visualizing the training process, model graphs, and key metrics. It was like watching art come to life.</em></p><p><em>And then came the moment of truth. The scientist’s creation was ready to leave the lab and venture into the real world. With TensorFlow’s support for cloud platforms and mobile devices, the transition from research and development to production was seamless.</em></p><p><em>In the end, our scientist had harnessed the incredible power of TensorFlow to bring their vision to life. And thus, the story of TensorFlow continued, inspiring many more dreamers and innovators in the enchanting world of machine learning.””</em></p><p>Certainly, let’s continue the story, delving into the concept of tensors:</p><p>Amid the scientist’s exploration with TensorFlow, they encountered a fundamental concept that gave the framework its name — <strong>Tensors</strong>.</p><p>Tensors, in the realm of machine learning, are the fundamental building blocks of data. Think of them as multi-dimensional arrays, where each dimension represents a particular aspect of the data. The beauty of tensors lies in their ability to adapt to the needs of different machine learning models.</p><p>Our scientist soon realized that these tensors could hold anything from numbers to strings, and even complex data structures. It was this adaptability that allowed TensorFlow to handle the rich and diverse data encountered in real-world applications.</p><p>TensorFlow leveraged these tensors to perform intricate operations, from simple addition to complex mathematical transformations. These operations were the gears that powered the machine learning models, enabling them to learn from data, make predictions, and tackle various tasks.</p><p>Let’s have a look at some :</p><h3>Installation</h3><p>Installing TensorFlow can vary depending on your system and your specific requirements. Here’s a general guide for installing TensorFlow on a Python environment using pip. Make sure you have Python installed before proceeding:</p><ul><li><strong>Create a virtual environment (Optional but Recommended): </strong>It’s good practice to create a virtual environment to keep your TensorFlow installation isolated from other Python packages. Additionally, virtual environments help manage dependencies and prevent conflicts with other Python packages. You can create a virtual environment using venv or virtualenv.</li></ul><pre>python -m venv myenv<br>source myenv/bin/activate  # On Windows, use &#39;myenv\Scripts\activate&#39;</pre><ul><li><strong>Install TensorFlow: </strong>Once your virtual environment is activated, you can use pip to install TensorFlow. The command you use depends on whether you want to install the CPU-only version or the version with GPU support (if you have a compatible GPU).</li></ul><p>CPU-only version</p><pre>pip install tensorflow</pre><p>For GPU-supported TensorFlow (ensure you have CUDA and cuDNN installed for this):</p><pre>pip install tensorflow-gpu</pre><ul><li><strong>Verify Installation:</strong> You can verify your TensorFlow installation by opening a Python interpreter within your virtual environment and importing TensorFlow:</li></ul><pre>python<br>import tensorflow as tf<br>print(tf.__version__)</pre><p>Please note that TensorFlow’s installation requirements and procedures can change, so it’s a good idea to check the official TensorFlow installation guide for the most up-to-date instructions, especially if you have specific hardware or system requirements:</p><p>Official TensorFlow installation guide: <a href="https://www.tensorflow.org/install">https://www.tensorflow.org/install</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TOmQhNpH7pmwXLg2" /><figcaption>Photo by <a href="https://unsplash.com/@sunnystate?utm_source=medium&amp;utm_medium=referral">Reuben Juarez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the coming TensorFlow series we would be watching the journey of TensorFlow and will be learning computer vision from it.</p><p>So do follow us as we will be unwrapping the world of TensorFlow in our upcoming articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703e8bbf435e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Unlocking the Potential: A Deep Dive into Elevating Machine Learning Performance”]]></title>
            <link>https://medium.com/@locus.focus/unlocking-the-potential-a-deep-dive-into-elevating-machine-learning-performance-e80f66de1e69?source=rss-26d4a4ca6b8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e80f66de1e69</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[model-selection]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Locus.Focus]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 16:23:13 GMT</pubDate>
            <atom:updated>2023-08-14T16:23:13.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Success" src="https://cdn-images-1.medium.com/max/1024/0*jTAfXQIsMrMSAQrG" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaearle?utm_source=medium&amp;utm_medium=referral">Joshua Earle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As we venture into the captivating landscape of machine learning, the spotlight falls on the captivating art of predictive modeling. Imagine the thrill of crafting models that learn from the past, enabling them to predict the future with astonishing accuracy. If you’re anything like me, you’ve undoubtedly pondered: “What are the secrets to taking these predictions to the next level?”</p><p>Join me as we delve into a treasure trove of insights that have been distilled through years of hands-on experience and a keen study of the brightest minds in our field. This isn’t just a guide; it’s a personalized roadmap tailored to all of us who yearn to push the boundaries of our skills.</p><p>This guide is your ticket to boosting your machine learning game. All it takes is one brilliant idea to crack a tough problem wide open. Think of it as striking gold in the world of algorithms. Inside, you’ll uncover a jackpot of many innovative concepts to explore!</p><p>I’ve divided this guide into four exciting sections:</p><ol><li><strong>Supercharge Your Performance with Data.</strong></li><li><strong>Elevate Your Game with Algorithmic Tweaks.</strong></li><li><strong>Fine-Tune for Maximum Impact.</strong></li><li><strong>Power Up Your Performance with Ensembles.</strong></li></ol><p>So, grab an idea, make strides, and when you’re ready for more, come back for another round. This guide is your roadmap to constant progress and excellence.</p><h3><strong>Supercharge Your Performance with Data</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LGK_d3Z9TylYrw6_" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever felt stuck while trying to predict something? Don’t worry, I’ve got your back with 6 awesome strategies to make your machine learning game stronger. It doesn’t matter if you’re new or a pro — these tricks will help you get better results.</p><p>1. <strong>Get More Data:</strong><br> — Collect Cool Stuff: Grab more good-quality data for supercharging your models.<br> — Invent Data: If you can’t find more, make new data using smart tricks.</p><p>2. <strong>Make Your Data Shine:</strong><br> — Clean It Up: Fix missing or messy data to make it shine.<br> — Mix It Up: Play with your data to make it even more interesting for your models.</p><p>3. <strong>Think Differently:</strong><br> — Flip the Script: Change your problem’s style to find new solutions.</p><p>4. <strong>Improve Your Data Moves:</strong><br> — Scale It Right: Adjust your numbers so your algorithms dance better.<br> — Shape It Up: Twist and turn your data to find hidden patterns.</p><p>5.<strong> Explore Other Dimensions:</strong><br> — Jump Dimensions: Use cool techniques to look at your data in a new way.</p><p>6.<strong> Find Hidden Treasures:</strong><br> — Pick the Best: Choose the most important data parts for your models.<br> — Make New Stuff: Create fresh data that your models will love.</p><p>Think of these tricks as your special tools to level up your machine learning skills. Now, you’ve got a bunch of new perspectives and editions of your dataset ready to roll.</p><p>Next up: Let’s put each of these to the test by running them through predictive modeling algorithms. This is where the real fun begins!</p><h3>Elevate Your Game with Algorithmic Tweaks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xEAeAUKxBwgx7uXc" /><figcaption>Photo by <a href="https://unsplash.com/@and_machines?utm_source=medium&amp;utm_medium=referral">and machines</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Whether it’s supervised, unsupervised, or other types of learning, machine learning algorithms hold the key to unlocking the full potential of data and driving progress in the field. :</p><p>1. <strong>Reshaping Resampling: </strong>When it comes to gauging skill on fresh data, opt for a resampling method that’s tailored to your available dataset. I’ve found that a combo of k-fold cross-validation and a hold-out validation set often hits the sweet spot.</p><p>2. <strong>Metric That Matters:</strong> Don’t just settle for any evaluation metric — pick one that resonates with your unique problem and domain. Keep in mind, it’s not always about the run-of-the-mill classification accuracy.</p><p>3. <strong>Anchoring with a Baseline:</strong> Before diving into algorithm comparisons, set the stage with a performance baseline. I usually lean towards using a random or a simple zero-rule algorithm (predicting mean or mode) to set the starting line.</p><p>4.<strong> Linear Wonders:</strong> Don’t underestimate the power of linear algorithms. They’re a go-to for me, being simple to grasp and quick to train. If they cut it for you, give a variety of linear methods a whirl.</p><p>5. <strong>Embracing Nonlinear Magic</strong>: Nonlinear algorithms bring complexity but often offer superior performance. I love exploring their potential, despite the hunger for more data. Take a tour of nonlinear methods to see what resonates.</p><p>6. <strong>Insights from the Prose:</strong> Literature can be a goldmine for algorithmic inspiration. Peek into what’s worked for others to uncover algorithm types or tweaks to classic methods that might just solve your puzzle.</p><p>7.<strong> Tuning into Configurations:</strong> While detailed parameter tuning comes later, don’t underestimate the importance of initial configurations. Give each algorithm a fair shot by setting it up thoughtfully right from the start.</p><p>These personalized strategies have been my compass in navigating the intriguing world of machine learning algorithms. They’ll help you chart a course to algorithm mastery, tailored to your unique challenges.</p><p>Now, let’s take it up a notch and focus on boosting performance through precise algorithm tuning.</p><h3>Fine-Tune for Maximum Impact</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WgHF6MAuf0Ea_BrM" /><figcaption>Photo by <a href="https://unsplash.com/@jdiegoph?utm_source=medium&amp;utm_medium=referral">Diego PH</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Fine-tuning algorithms might become your favorite pastime — and, yes, it can be time-consuming. In the blink of an eye, you might spot a couple of top performers through spot-checking. But here’s the deal: getting the absolute best from them can be a journey of days, weeks, or even months.</p><p>Here’s the plan:</p><p>1. <strong>Get cozy with diagnostics: </strong>Those precious insights your algorithms offer. Learning curves can reveal if your method is overdoing or underdoing things. You’ll get different visual clues from different algorithms. Dive in and see what they’re getting right and where they stumble.</p><p>2. <strong>Tune those parameters and let your intuition run wild:</strong> Over time, you might develop an instinct for what works. It’s like unlocking a secret code to configuring algorithms just right. Give it a whirl and surprise yourself with new parameter combos to try out.</p><p>3. <strong>Seek wisdom from the masters:</strong> What parameter ranges are favored in the literature? It’s a fantastic starting point for your tuning adventure.</p><p>4. <strong>Embrace randomness with random search:</strong> It might lead you to configurations you’d never dream up. Grid search, on the other hand, lets you explore standard parameter values and fine-tune them, step by step.</p><p>5. <strong>Tweak more than just parameters:</strong> Dive into the heart of your algorithm, optimizing structure, learning rates, and more. Patterns, genetic algorithms — there’s a world of optimization waiting.</p><p>6.<strong> Look beyond the obvious:</strong> Different implementations of the same algorithm can hold surprises. Explore extensions and customizations — they might just be the performance boosters you’re after.</p><p>7. <strong>Don’t be shy — reach out to the pros:</strong> A quick email to algorithm experts, outlining your challenge, could lead to groundbreaking insights or fresh ideas you’ve never considered.</p><p>Now, you’re armed with a handpicked selection of finely tuned algorithms. You might even discover “the one” among them.</p><p>With one or more models ready to roll, you can make predictions or dive into production. And if you’re gunning for even higher performance, consider combining predictions from multiple models — it’s a surefire way to lift your results to new heights.</p><h3>Power Up Your Performance with Ensembles</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sEtM6wn0ieOj52qw" /><figcaption>Photo by <a href="https://unsplash.com/@artlambi?utm_source=medium&amp;utm_medium=referral">Arthur Lambillotte</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>And here’s a little secret I’ve been delving into lately: ensemble learning. It’s like discovering a hidden gem that holds the key to remarkable results. As I’ve ventured into this realm, I’ve witnessed how uniting different models can lead to outcomes that truly stand out and shine.</p><p>So, remember this gem of wisdom. After all the meticulous fine-tuning, it’s here, in the world of ensemble learning, that you can truly witness your efforts soaring to new heights. It’s about harmonizing predictions and weaving them into an orchestra of excellence. And trust me, this move has the potential to transform the ordinary into the truly extraordinary.</p><ol><li><strong>Blend Model Predictions:</strong> Start by directly merging predictions from various models. Use the same or different algorithms to create these models. Combine their predictions by taking an average or selecting the most common prediction.</li><li><strong>Blend Data Representations:</strong> Explore merging predictions from models trained on diverse data representations. Think of it as tapping into different angles of the same problem. Train well-performing models on various projections, then bring their predictions together.</li><li><strong>Blend Data Samples:</strong> Combine models trained on different slices of your data. Craft multiple sub-samples from your training data, train robust models, and then blend their predictions. This “bootstrap aggregation” or bagging works wonders when each model contributes unique, uncorrelated predictions.</li><li><strong>Correct Predictions :</strong> Consider correcting the predictions of your well-performing models. You could explicitly adjust predictions or leverage boosting to learn from prediction errors.</li><li><strong>Master the Art of Combination:</strong> Why not use a new model to learn the best way to combine predictions? Enter the realm of “stacked generalization” or stacking. It works beautifully when sub-models excel in different ways, and the aggregator model is a straightforward linear blend. This can even be taken to multiple layers.</li></ol><p>As a result, you’ll be armed with one or more ensembles of high-performing models that outshine any single model.</p><p>With one or more ensembles at your disposal, it’s time to step up your prediction game. You can choose to finalize and deploy these ensembles for real-world predictions or production scenarios. The sky’s the limit!</p><p>Follow us for more!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cmRNQNTFnTLGxkZZ" /><figcaption>Photo by <a href="https://unsplash.com/@arizonanthony?utm_source=medium&amp;utm_medium=referral">Anthony Cantin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e80f66de1e69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>