<?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 Rakesh Ganya on Medium]]></title>
        <description><![CDATA[Stories by Rakesh Ganya on Medium]]></description>
        <link>https://medium.com/@rakesh.ganya28?source=rss-9055c60ca6a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ssda_6lZpkFPdZZT5zPr5w.png</url>
            <title>Stories by Rakesh Ganya on Medium</title>
            <link>https://medium.com/@rakesh.ganya28?source=rss-9055c60ca6a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:55:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakesh.ganya28/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[Building Sequential Models with RNN(Recurrent Neural Networks) Using Keras API]]></title>
            <link>https://medium.com/@rakesh.ganya28/building-sequential-models-with-rnn-recurrent-neural-networks-using-keras-api-d32a83d7b6b5?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d32a83d7b6b5</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 07:01:38 GMT</pubDate>
            <atom:updated>2024-08-14T07:01:38.907Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will delve into the world of <strong>Sequential Data Modelling</strong> using <strong>Recurrent Neural Networks (RNN)</strong> with the Keras API. We will explore the fundamental concepts behind RNNs and understand how they excel at handling time-series data, text, and other sequential inputs. This article will introduce you to the key RNN architecture modules, including recurrent layers, activation functions, and the integration of these components to capture temporal dependencies in data. By the end of this post, you’ll have a clear understanding of how these modules work together to build powerful models for sequential data classification and prediction.</p><h3>What is Sequence Modeling?</h3><p><strong>Sequence modeling</strong> is a type of problem in machine learning where the goal is to predict or generate sequences of data. These sequences could be made up of words, numbers, events, or any other data points that are naturally ordered in a specific way. Examples of sequences include sentences in a language, time series data like stock prices, or even sequences of events like user clicks on a website.</p><h3>Why is Sequence Modeling Used in Machine Learning?</h3><p>Sequence modeling is essential for tasks where the order of data points affects the outcome. Here are some key reasons it’s used:</p><ol><li><strong>Handling Temporal Dependencies</strong>: In many real-world problems, the current data point is dependent on previous data points. For example, in time series forecasting, future values depend on past observations.</li><li><strong>Contextual Understanding</strong>: In natural language processing (NLP), understanding the context provided by preceding words in a sentence is crucial for tasks like language translation, sentiment analysis, or text generation.</li><li><strong>Predictive Tasks</strong>: Sequence modeling is used to predict the next element in a sequence, such as the next word in a sentence or the next value in a time series, based on the previous elements.</li></ol><p><strong>RNNs</strong> are specifically designed to handle sequence modeling tasks.</p><h3>What is RNN and Why it is used?</h3><p>A <strong>Recurrent Neural Network (RNN)</strong> is a type of artificial neural network specifically designed for processing sequential data, such as time series, text, or any data where the order of the elements is important. Unlike traditional feedforward neural networks, RNNs have connections that form directed cycles, which allows them to maintain a “memory” of previous inputs in the sequence. This memory is crucial for understanding and predicting the next element in a sequence.</p><p>RNNs are used because they excel at handling tasks that involve sequential data where the context or order of information is essential. Their ability to remember previous inputs enables them to capture temporal dependencies, making them ideal for:</p><ul><li><strong>Time Series Forecasting</strong>: Predicting future values based on past observations.</li><li><strong>Natural Language Processing (NLP)</strong>: Tasks like language modeling, text generation, and machine translation.</li><li><strong>Speech Recognition</strong>: Understanding and transcribing spoken language by considering the flow of words over time.</li><li><strong>Sequence Classification</strong>: Categorizing sequences of data, such as sentiment analysis in text or identifying activities in sensor data.</li></ul><p>RNNs are powerful because they can model the temporal dynamics and dependencies within sequences, making them a go-to choice for problems where the sequence matters.</p><h3>How RNN Architecture works?</h3><p>This is the simple architecture to understand the flow of steps in RNN, which can be tuned more complex for complex dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5L7HzsvDgAbR21Ce8PMrw.png" /><figcaption><strong>RNN Architecture</strong></figcaption></figure><h3>Main Modules of RNN Architecture</h3><blockquote><strong>Recurrent Layer (RNN Layer)</strong></blockquote><blockquote>Purpose: The core component of an RNN, the recurrent layer, processes input sequences one step at a time. It has connections that loop back on themselves, allowing information to persist across different time steps. This looping structure gives RNNs their ability to maintain a memory of past inputs.</blockquote><blockquote><strong>Input Layer</strong></blockquote><blockquote>Purpose: This layer handles the input data, often representing it in a format suitable for the RNN to process. For example, in text processing, the input might be a sequence of word embeddings, while in time series analysis, it could be numerical values over time.</blockquote><blockquote><strong>Activation Function</strong></blockquote><blockquote>Purpose: An activation function introduces non-linearity into the RNN, allowing it to learn complex patterns in the data. The activation function is applied at each step in the recurrent layer to the weighted sum of the inputs and the recurrent connection.</blockquote><blockquote><strong>Output Layer</strong></blockquote><blockquote>Purpose: The output layer takes the final hidden state from the recurrent layer (or intermediate states, depending on the application) and processes it to produce the final prediction or classification.</blockquote><blockquote><strong>Loss Function</strong></blockquote><blockquote>Purpose: The loss function measures how well the RNN’s predictions match the actual data. It quantifies the error, guiding the network during training.</blockquote><blockquote>Common Loss Functions:</blockquote><blockquote>Cross-Entropy Loss: Used for classification tasks.</blockquote><blockquote>Mean Squared Error (MSE): Common in regression tasks involving continuous output.</blockquote><blockquote><strong>Backpropagation Through Time (BPTT)</strong></blockquote><blockquote>Purpose: BPTT is a specialized version of backpropagation used to train RNNs. It unrolls the RNN over time and computes gradients at each time step, allowing the network to update its weights based on the error over the entire sequence.</blockquote><blockquote>Functionality: Helps the RNN learn to minimize the loss by adjusting the weights in the recurrent and output layers.</blockquote><h3>Loss Optimizer</h3><p>In this blog, we will explore the Adam optimizer, one of the most advanced and widely used optimization algorithms. For a comprehensive understanding of optimizers, including some of the more traditional ones, I recommend checking out our previous blog post, which provides a detailed overview. Reviewing that content will help reinforce your understanding and prepare you for this deep dive into Adam.</p><p><a href="https://medium.com/@rakesh.ganya28/gradient-descent-variants-explained-enhancing-loss-function-optimization-cf0f5a2cb2ae">Gradient Descent Variants Explained: Enhancing Loss Function Optimization</a></p><h4>Adam (Adaptive Moment Estimation) Loss Optimizer Algorithm</h4><p>Adam combines the strengths of both RMSProp and Momentum, making it a very effective and widely used optimizer.</p><p><strong>How it works:</strong></p><ol><li><strong>Momentum Component</strong>: Adam maintains an exponentially decaying average of past gradients, similar to momentum.</li><li><strong>RMSProp Component</strong>: Adam also keeps an exponentially decaying average of past squared gradients, similar to RMSProp.</li><li><strong>Bias Correction</strong>: Adam includes a bias correction step to account for the fact that the estimates (moving averages) can be biased towards zero, especially in the early stages of training.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*0c1jawTVaR9TckfF7kWiDw.png" /><figcaption>Momentum and RMSProp</figcaption></figure><p><strong>Summary</strong>:</p><ul><li><strong>RMSProp</strong>: Adapts the learning rate based on the scale of the past gradients.</li><li><strong>Momentum</strong>: Accelerates learning by accumulating past gradients.</li><li><strong>Adam</strong>: Combines the benefits of RMSProp and Momentum, adjusting the learning rate dynamically for each parameter and ensuring faster, more stable convergence.</li></ul><h4>Weight Update Formula in Adam:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*M-WNTNwCIC7NYhnDSs-0Pw.png" /><figcaption>Adam Weight Update Rule</figcaption></figure><h3>RNN Specializations for Sequence Modeling</h3><h4><strong>Dynamic Input Size Handling</strong></h4><blockquote><strong>Flexibility</strong></blockquote><blockquote>RNNs can process sequences of different lengths because they operate on the input data one element at a time, maintaining a hidden state that evolves as it processes each step in the sequence.</blockquote><blockquote><strong>Real-World Examples</strong></blockquote><blockquote>For instance, in text processing, sentences or paragraphs can vary significantly in length. RNNs can effectively model these sequences without needing to pad or truncate them to a fixed size, as would be necessary with an ANN.</blockquote><h4>Benefits of Sharing Weights and Biases</h4><blockquote><strong>Avoiding Parameter Explosion</strong>:</blockquote><blockquote>If weights and biases were not shared, the number of parameters in an RNN would grow significantly with the length of the sequence. For example, in a sequence of 100 time steps, if each step had its own set of weights and biases, the network would need to learn 100 times more parameters. This would not only make the model extremely complex but also make it prone to overfitting and harder to train.</blockquote><blockquote><strong>Efficiency</strong>:</blockquote><blockquote>By sharing weights and biases, the RNN keeps the number of parameters relatively small, making the model more computationally efficient and easier to train. This efficiency is crucial when dealing with long sequences or when training on large datasets.</blockquote><h4>How Shared Weights and Biases Help Share Past Information:</h4><blockquote><strong>Temporal Consistency</strong>:</blockquote><blockquote>Since the same weights are used at each time step, the network processes the sequence in a consistent manner. This consistency helps the RNN learn temporal patterns in the data. The hidden state at each time step captures information from previous steps, which is then passed forward to influence future predictions.</blockquote><h3>RNN: Timeseries Sequential Model Implementation</h3><h4>Sample Data</h4><pre># Basic Python Libraries<br>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import warnings<br><br># Deep Learning Librarys<br>import tensorflow as tf<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, SimpleRNN<br><br>warnings.filterwarnings(&#39;ignore&#39;)<br>%matplotlib inline<br><br># Sample Data<br># Generate synthetic data for 3 weeks (21 data points)<br>np.random.seed(101)<br>time_series_data = np.random.rand(21)<br><br># RNN: Data Preparation<br>def create_dataset(data, time_step=1):<br>    X, y = [], []<br>    for i in range(len(data) - time_step):<br>        X.append(data[i:(i + time_step)])<br>        y.append(data[i + time_step])<br>    return np.array(X), np.array(y)<br><br># Prepare Data<br>time_step = 5 # Using the previous 7 day&#39;s data to predict the next day<br>X, y = create_dataset(time_series_data, time_step)<br><br># Overall Data<br>time_series_data<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*EuJNjH2BghWqO20JmrtOOw.png" /><figcaption>Overall Sample Data</figcaption></figure><p>Predictors Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IPcBfVTgF85dq4XoisOVQQ.png" /></figure><p>Response Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*EcRXW05B6qbmNPYAUAjnIw.png" /></figure><h4><strong>Data Reshaping</strong></h4><p>Converting arrays to rows and columns structure like DataFrame</p><pre># Reshape input to be [samples, time steps, features] which is required for RNN<br>X = X.reshape(X.shape[0], X.shape[1], 1)<br><br>X</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*MfpcBAnfgpU0w9lPqpr9oA.png" /></figure><h4><strong>RNN Model Construction[Optimizer: ADAM]</strong></h4><pre># Build the RNN Model<br>model = Sequential()<br># SimpleRNN Layer: The RNN layer has 20 units and uses the ReLU activation function. The input shape is specified as (time_step, 1).<br>model.add(SimpleRNN(20, activation=&quot;relu&quot;, input_shape=(time_step, 1)))<br># Dense Layer: A fully connected Dense layer with 1 unit is added, which outputs the prediction.<br>model.add(Dense(1))<br># Compilation: The model is compiled using the Adam optimizer and Mean Squared Error (MSE) loss function.<br>model.compile(optimizer=&quot;ADAM&quot;, loss=&quot;mse&quot;)</pre><h4>Model Training</h4><pre># Train Model<br>model.fit(X, y, epochs=100, verbose=1) # Training: The model is trained on the prepared data for 50 epochs. The verbose=1 option means progress will be printed during training.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*ZtLD9Ehzn8U-u6tiLVpPfA.png" /><figcaption>Loss over Epochs</figcaption></figure><h4><strong>Make Predictions</strong></h4><pre># Make Forecast predictions<br>predictions = model.predict(X) # Predictions: The model makes predictions based on the input sequences in X.</pre><h4><strong>Actuals vs Predictions</strong></h4><ul><li>To see how well model has been trained on Train Data.</li><li>It demonstrates training, making predictions, and comparing predicted values with actual data.</li></ul><pre># Initialize the plot<br>sns.set(style=&quot;darkgrid&quot;)<br><br># Plot actual data vs predictions using Seaborn<br>plt.figure(figsize=(10, 6))<br>sns.lineplot(x=range(1, len(time_series_data) + 1), y=time_series_data, label=&#39;Actual Data&#39;, marker=&quot;o&quot;)<br>sns.lineplot(x=range(time_step + 1, len(predictions) + time_step + 1), y=predictions.flatten(), label=&#39;Predicted Data&#39;, linestyle=&#39;--&#39;, marker=&quot;o&quot;)<br><br># Set plot labels and title<br>plt.ylabel(&#39;Value&#39;)<br>plt.xlabel(&#39;Time Step&#39;)<br>plt.title(&#39;Actual Data vs Predicted Data&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*fsbtczmJXE4xMDwfvxnBQg.png" /><figcaption>RNN [Adam Optimizer] Model Training</figcaption></figure><h4><strong>Last Actual and Predicted Next Value</strong></h4><ul><li>It predicts the next value in the sequence after the last known data point.</li></ul><pre># Print the last actual value and the predicted next value<br>print(f&quot;Last actual value: {time_series_data[-1]}&quot;)<br>next_value = model.predict(np.array([time_series_data[-time_step:]]).reshape((1, time_step, 1)))<br>print(f&quot;Predicted next value: {next_value[0][0]}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*-i6vpNAETxajpirVx1E7eA.png" /><figcaption>Last Actual Value and Prediction</figcaption></figure><h3>Final Thoughts</h3><ul><li>With <strong>ADAM = Momentum + RMSPROP optimizer</strong>, the RNN Sequential Model has made weights updation jump smartly based on previous gradients mean and variance, which makes it more reasonable and helps to train well. i.e., to understand last sequence and predict almost near to the last actual value, which is better than SGD based model training.</li><li>In above plot, we can observe that both actual and trained predictions are nearly close, meaning that our RNN able to learn past sequence information in order to predict next values.</li></ul><p>I hope with the end of this post, you would have got a brief idea about the <strong>RNN(Recurrent Neural Network)</strong> modules, and how a Sequential Model implementation can be achieved through Keras API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d32a83d7b6b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification Made Easy with CNN(Convolutional Neural Network) & Keras API]]></title>
            <link>https://medium.com/@rakesh.ganya28/image-classification-made-easy-with-cnn-convolutional-neural-network-keras-api-73b8b9345b92?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b8b9345b92</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 16:01:27 GMT</pubDate>
            <atom:updated>2024-08-01T16:01:27.511Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will try to understand and implement the image classification using Convolutional Neural Networks (CNN) in conjunction with Keras. In due course, this article will introduce you to the key CNN architecture modules, including convolutional layers, pooling layers, activation function and fully connected layers. where, highlighting how these modules come together to effectively classify images.</p><h3>What is CNN and why it is used?</h3><p><strong>Convolutional Neural Networks (CNNs)</strong> are a type of deep learning model specifically designed for processing structured grid data like images.</p><p>CNNs are specifically designed to handle the spatial structure and complexity of image data, making them far more efficient and effective for image classification tasks.</p><h3>How CNN Works?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41FrfvFIZQGaaKlTMd0rWQ.png" /><figcaption><strong>CNN Steps Flow</strong></figcaption></figure><p>This is one way of setting up CNN steps, but it is possible to add more and reduce as per the complexity of model we wanted to build.</p><h3>Main Modules of CNN Architecture</h3><blockquote><strong>Image</strong>: It is the training image.</blockquote><blockquote><strong>Convolutional Layer</strong>: Applies filters to the input image to extract features like edges, corners, and textures.</blockquote><blockquote><strong>Feature Map</strong>: It stores resulted output after applying Convolutional filter.</blockquote><blockquote><strong>Activation Function</strong>: A function applied to the output/result to introduce non-linearity into the model. ex:- ReLU activation can be used in CNN, which can helps mitigating the vanishing gradient problem.</blockquote><blockquote><strong>Max Pooling Layer</strong>: Down samples the output of the convolutional layer to reduce dimensionality.</blockquote><blockquote><strong>Flattening Layer:</strong> Converts the 2D feature maps into a 1D vector.</blockquote><blockquote><strong>Fully Connected Layer / Dense Network:</strong> Performs classification using traditional neural network techniques.</blockquote><blockquote><strong>Drop Out Layer:</strong> It helps prevent overfitting by randomly turning off n% of the neurons in the layer to which it is applied during each training step</blockquote><h3>Special Concepts used in CNN</h3><h4><strong>ReLU(Rectified Linear Unit): Activation Function</strong></h4><ul><li><strong>Range</strong>: Outputs zero for negative inputs and the input itself for positive inputs.</li><li><strong>Use Case</strong>: Commonly used in hidden layers of deep networks due to its simplicity and effectiveness in mitigating the vanishing gradient problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*c55mXpJGziFN8kWsQx6jiQ.png" /><figcaption>ReLU Activation</figcaption></figure><h4>He: Weights &amp; Bias Initialization</h4><ul><li>Developed by Kaiming He et al.</li><li>Specifically designed for layers with ReLU (Rectified Linear Unit) activation functions.</li><li>Helps to address the issue where ReLU neurons can die if weights are initialized improperly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*opa5DwRfwr2qo5lZpf07XQ.png" /><figcaption><strong>He Initialization</strong></figcaption></figure><h3>Difference between ANN(Artificial Neural Network) and CNN(Convolutional Neural Network)</h3><p>Before we jump to have a quick recap, what is ANN and what are the main modules in ANN architecture, have a quick look over my past article below.</p><p><a href="https://medium.com/@rakesh.ganya28/ann-based-multi-class-image-classification-using-tensorflow-and-keras-383a5ddf9944">ANN-Based Multi-Class Image Classification Using TensorFlow and Keras</a></p><p>Due to having below benefits in CNN, it becomes more robust and reliable implementation model for complex images, where in below cases the ANN can still work and provide good results.</p><blockquote>Cases which ANN can handle?</blockquote><blockquote><strong>Simpler Images [Hand Written Numbers]</strong> with smaller in resolution i.e., 10 * 10 or 20 * 20 etc., Hence input size will be smaller, else the with higher input size, higher weights and that too in dense neural network, the weights count grow in 10k size. Training those many weights will be cumbersome with huge computational cost</blockquote><blockquote><strong>Pixel Static Images</strong>, where pixels are always behave similarly without any dislocation, in real world scenarios which is harder to maintain.</blockquote><blockquote>Cases which CNN can handle?</blockquote><p>If above are not the cases then ANN model will struggle a lot to train the weights and learn the patterns in the images to become a good model.</p><p>To handle this CNN model has been developed, where it can handle all the problems which might encounter in the above cases.</p><blockquote><strong>Higher Resolutional Image Size Issue</strong>: CNN reduces huge image size, ex:- higher resolutional image with having size 1000 * 1000 resolution into lower dimensional input, so that weights won’t become huge count in the Neural Network.</blockquote><blockquote><strong>Complex Images: [vehicles, animals, human beings…..]</strong>It can able to derive important features like eyes, nose, mouth and then club into head in the case of any animal image. which is not the case in ANN.</blockquote><blockquote><strong>Pixels Local Shifts Issue: </strong>It can handle pixels location shifts, even in this case, it tries to pick the features from the image.</blockquote><h4>Architecture Difference Between ANN and CNN?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*mmMIZDAwKMCyYSkR-ZBQHw.png" /><figcaption><strong>ANN Architecture</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ts9tf0c3orMyyj4M7vPmvw.png" /><figcaption><strong>CNN Architecture</strong></figcaption></figure><p>This smart architecture helps to find key features from complex image and performs image classification more robustly.</p><h3>Sample Image Dataset</h3><h4>MNIST</h4><p><strong>MNIST</strong> stands for <strong>Modified National Institute of Standards and Technology</strong> database. It’s a large dataset of handwritten digits (0–9) that’s commonly used for training various image processing systems.</p><p><strong>Key characteristics:</strong></p><ul><li>Contains 60,000 training images and 10,000 testing images.</li><li>Each image is a 28x28 pixel grayscale image.</li></ul><pre># Basic Python Modules<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import warnings<br><br># Deep Learning Libraries<br>import tensorflow as tf<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten, Dropout<br>from tensorflow.keras.optimizers import SGD<br><br>warnings.filterwarnings(&quot;ignore&quot;)<br>%matplotlib inline<br><br># Load the MNIST dataset<br>mnist = tf.keras.datasets.mnist<br><br>(X_train_images, y_train_labels), (X_test_images, y_test_labels) = mnist.load_data()<br><br>print(f&quot;Train Images: {X_train_images.shape[0]}, Train Rows: {X_train_images.shape[1]}, Train Columns: {X_train_images.shape[1]}&quot;)<br>print(f&quot;Train Labels: {y_train_labels.shape[0]}&quot;)<br><br>print(f&quot;Test Images: {X_test_images.shape[0]}, Test Rows: {X_test_images.shape[1]}, Test Columns: {X_test_images.shape[1]}&quot;)<br>print(f&quot;Test Labels: {y_test_labels.shape[0]}&quot;)<br><br># Output<br>Train Images: 60000, Train Rows: 28, Train Columns: 28<br>Train Labels: 60000<br>Test Images: 10000, Test Rows: 28, Test Columns: 28<br>Test Labels: 10000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*lAuBdslMHFlq2yQD.png" /><figcaption>MNIST Sample Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*DbHXUmIascyxkcyU.png" /><figcaption>MNIST Sample Image</figcaption></figure><h3>CNN (Convolutional Neural Network) Based Image Classification Model : Using Keras API</h3><h4>Data Preprocessing</h4><blockquote><strong>Flatten Image: Raw Image -&gt; 1D Array</strong></blockquote><pre>X_train_images = X_train_images.reshape([-1, 28, 28, 1]).astype(&quot;float32&quot;) # 28(rows), 28(cols), 1(RGB dimension)<br>X_test_images = X_test_images.reshape([-1, 28, 28, 1]).astype(&quot;float32&quot;)</pre><blockquote><strong>Normalization</strong></blockquote><pre>X_train_images = X_train_images / 255.0<br>X_test_images = X_test_images / 255.0</pre><blockquote><strong>Dummy Variables Creation</strong></blockquote><pre>y_train_labels = tf.keras.utils.to_categorical(y_train_labels, 10)<br>y_test_labels = tf.keras.utils.to_categorical(y_test_labels, 10)</pre><h4><strong>Build Model</strong></h4><pre> def build_model(activation, initializer):<br>    model = Sequential()<br>    model.add(Conv2D(10, kernel_size=(3,3), activation=activation, input_shape=(28, 28, 1), kernel_initializer=initializer))<br>    model.add(MaxPooling2D(pool_size=(2,2)))<br>    model.add(Conv2D(5, kernel_size=(3,3), activation=activation, kernel_initializer=initializer))<br>    model.add(MaxPooling2D(pool_size=(2,2)))<br>    model.add(Flatten())<br>    model.add(Dense(20, activation=activation, kernel_initializer=initializer))<br>    model.add(Dropout(0.5))<br>    model.add(Dense(10, activation=&quot;softmax&quot;, kernel_initializer=initializer))<br>    return model</pre><h4><strong>Train and Evaluate Model</strong></h4><pre>def train_and_evaluate(activation, optimizer_class, learning_rate, initializer,<br>                        X_train_images, y_train_labels,<br>                        X_test_images, y_test_labels,<br>                        num_epochs):<br>    model = build_model(activation, initializer)<br>    optimizer = optimizer_class(learning_rate=learning_rate, clipnorm=1.0) # Using gradient clipping with norm<br>    model.compile(optimizer=optimizer, loss=&quot;categorical_crossentropy&quot;, metrics=[&quot;accuracy&quot;])<br>    history = model.fit(X_train_images, y_train_labels,<br>                        epochs=num_epochs, batch_size=100,<br>                        validation_data=(X_test_images, y_test_labels),<br>                        verbose=1)<br>    test_loss, test_accuracy = model.evaluate(X_test_images, y_test_labels, verbose=1)<br>    return model, history.history[&quot;loss&quot;], test_loss, test_accuracy</pre><h4><strong>Loss Over Epochs</strong></h4><pre>def plot_loss(num_epochs, losses, title):<br>    sns.set_style(&quot;dark&quot;)<br>    plt.figure(figsize=(10, 6))<br>    plt.plot(range(1, num_epochs+1), losses, &quot;b&quot;, label=&quot;Train Loss&quot;)<br>    plt.xlabel(&quot;Epoch&quot;)<br>    plt.ylabel(&quot;Loss&quot;)<br>    plt.title(title)<br>    plt.legend()<br>    plt.show()</pre><h4><strong>Weights Initialization</strong></h4><pre>initializer = tf.keras.initializers.HeNormal()</pre><h4><strong>Model Hyperparameters</strong></h4><pre>num_epochs = 10<br>activations = [&quot;relu&quot;]<br>optimizer_specs = {<br>    &quot;SGD&quot;: {SGD, 0.05}<br>}</pre><h4><strong>Execute Training</strong></h4><pre>for activation in activations:<br>    <br>    for opt_name, (optimizer_class, learning_rate) in optimizer_specs.items():<br>        <br>        print(&quot;Training model with {activation} activation and {opt_name} optimizer...&quot;)<br>        model, train_losses, test_losses, test_accuracy = train_and_evaluate(activation, <br>                                                            optimizer_class, <br>                                                            learning_rate,<br>                                                            initializer,<br>                                                            X_train_images, <br>                                                            y_train_labels,<br>                                                            X_test_images, <br>                                                            y_test_labels,<br>                                                            num_epochs)<br>        <br>        # Train Loss<br>        plot_loss(num_epochs, train_losses, f&quot;Loss over Epochs ({activation} + {opt_name})&quot;)<br>        <br>        # Test Accuracy <br>        print(f&quot;\n Test Accuracy with {activation} activation and {opt_name} optimizer: {test_accuracy: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEiZOeHNDojfYJAMAdNz9g.png" /><figcaption>Loss over epochs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*yZ8AW9devjLfdUkprtj8CQ.png" /><figcaption>Loss over epochs</figcaption></figure><p>Test Accuracy with relu activation and SGD optimizer: <strong>0.96</strong></p><h3><strong>Model Prediction</strong></h3><pre># Test Prediction on One Image<br>index = np.random.randint(0, X_test_images.shape[0])<br>test_image = X_test_images[index]<br>true_label = np.argmax(y_test_labels[index])<br><br># Add batch dimension (1, 28, 28, 1)<br>test_image_batch = np.expand_dims(test_image, axis=0)<br><br># Make prediction<br>prediction = model.predict(test_image_batch)<br>prediction_label = np.argmax(prediction)<br><br>print(f&quot;\nTrue Label: {true_label}&quot;)<br>print(f&quot;\nPrediction Label: {prediction_label}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*OGlw6tivm16iLzSArYYiPg.png" /><figcaption>Actual vs Prediction</figcaption></figure><pre># Plot actual image vs predicted label<br>plt.figure(figsize=(6, 3))<br><br>plt.subplot(1, 2, 1)<br>plt.imshow(test_image.squeeze(), cmap=&quot;gray&quot;)<br>plt.title(f&quot;Actual: {true_label}&quot;)<br><br>plt.subplot(1, 2, 2)<br>plt.imshow(test_image.squeeze(), cmap=&quot;gray&quot;)<br>plt.title(f&quot;Predicted: {prediction_label}&quot;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*16nRp78mg1qhV4dKJwuvbw.png" /><figcaption>Actual vs Prediction</figcaption></figure><h3>Final Thoughts</h3><ul><li>We can observe in earlier plot, that loss has been decreased over the epochs i.e., having good converge / having reached less loss in cost function.</li><li>Our model has reached 96% accuracy, which is good on this sample images dataset.</li><li>On more real world use cases, we have to look after for the data preprocessing and model overfitting precautions for having more robustic model.</li></ul><p>I hope with the end of this post, you would have got a brief idea about the CNN(Convolutional Neural Network) modules, and how an Image classification implementation can be achieved through Keras API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b8b9345b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANN(Artificial Neural Network)-Based Multi-Class Image Classification Using TensorFlow and Keras]]></title>
            <link>https://medium.com/@rakesh.ganya28/ann-based-multi-class-image-classification-using-tensorflow-and-keras-383a5ddf9944?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/383a5ddf9944</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 13:04:39 GMT</pubDate>
            <atom:updated>2024-08-01T16:08:13.653Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we try to touch main modules of ANN and tries to implement an ANN model for multi class image classification using both TensorFlow and Keras frameworks.</p><h3>What is ANN?</h3><p>Artificial Neural Networks (ANNs) mimic the <em>network of biological neurons</em>, enabling them to learn complex relationships between predictors and targets. They adjust their weights during training through a process called backpropagation. ANNs are foundational models for various applications, including image recognition, natural language processing (NLP), and predictive analytics.</p><h4><strong>Biological Neurons Connection</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5p7KSEDMx38YPzoM0lbDQQ.png" /><figcaption><strong>credit</strong> <a href="https://www.craiyon.com/"><strong>craiyon.com</strong></a></figcaption></figure><h4><strong>Simple Artificial Neural Network</strong></h4><p>Replica of Biological Neural Network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*vRCRktT6rxcwM5evltxMVg.png" /><figcaption><strong>Simple Dense Neural Network</strong></figcaption></figure><h3>What is the difference Between TensorFlow and Keras Framework?</h3><p>A quick recap about TensorFlow</p><h4><strong>What is TensorFlow?</strong></h4><p><strong>TensorFlow</strong> is an open-source library developed by Google for machine learning and deep learning applications. It provides a comprehensive, flexible ecosystem of tools, libraries, and community resources that allow researchers and developers to build and deploy machine learning-powered applications.</p><p>For more about this, go through on below previous post</p><p><a href="https://medium.com/@rakesh.ganya28/deep-learning-essentials-a-practical-introduction-to-tensorflow-cd4180522f2f">Deep Learning Essentials: A Practical Introduction to TensorFlow</a></p><h4>What is Keras?</h4><p>Keras is an open-source neural network library written in Python that runs on top of TensorFlow. It is designed to make implementing deep learning models as easy and straightforward as possible.</p><p>To make TensorFlow easier to operate for developing and deploying deep learning modules, Keras was developed. Keras acts as a <strong>high-level API</strong> (<strong>frontend</strong>) that simplifies the process of creating and training deep learning models, much like how scikit-learn (sklearn) simplifies machine learning tasks. With Keras, you can build complex neural networks with just a few lines of code, while all the low-level TensorFlow operations are handled in the background.</p><p>With the advent of <strong>TensorFlow 2.0</strong>, Keras has been fully integrated into TensorFlow as<strong> </strong><strong>tf.keras</strong>. This integration ensures better compatibility, optimized performance, and streamlined workflows.</p><p>Using Keras over raw TensorFlow offers several advantages:</p><ol><li><strong>Simplicity</strong>: Keras provides a clean and easy-to-use interface, enabling rapid prototyping and experimentation with deep learning models.</li><li><strong>Efficiency</strong>: Keras abstracts many complex TensorFlow operations, allowing you to focus on the higher-level structure and functionality of your models.</li><li><strong>Compatibility</strong>: tf.keras ensures seamless integration with TensorFlow, leveraging TensorFlow&#39;s robust ecosystem and performance optimizations.</li><li><strong>Flexibility</strong>: While Keras simplifies common use cases, it still allows for low-level customization when needed, providing the best of both worlds.</li></ol><h3>What are the Key Modules in Neural Network?</h3><h4>Weights Initialization</h4><ul><li>The process of setting the initial values of the weights before training the neural network.</li><li>Proper initialization can help the network converge faster and avoid issues like <strong>vanishing</strong> or <strong>exploding</strong> <strong>gradients</strong>.</li></ul><blockquote><strong>Vanishing Gradients</strong></blockquote><blockquote><strong>Vanishing Gradients</strong> occur when the gradients used to update the weights of a neural network during backpropagation become increasingly small as they propagate backward through the layers. This results in negligible weight updates, hindering the network’s ability to learn from the training data.</blockquote><blockquote>Core Issue</blockquote><blockquote><strong>Minimal Weight Updates:</strong> Due to extremely small gradients, the weights are adjusted by minuscule amounts, leading to slow or stalled training.</blockquote><blockquote>Consequence</blockquote><blockquote><strong>Ineffective Training:</strong> The network’s ability to learn complex patterns is compromised.</blockquote><blockquote><strong>Exploding gradients</strong></blockquote><blockquote><strong>Exploding gradients</strong> are the opposite of vanishing gradients. Instead of gradients becoming infinitesimally small, they grow exponentially large during backpropagation. This leads to significant weight updates in the neural network.</blockquote><blockquote>Core Issue</blockquote><blockquote><strong>Unstable Training:</strong> Large weight updates can destabilize the training process, causing the model’s parameters to diverge.</blockquote><blockquote><strong>Oscillations:</strong> The network’s parameters might oscillate wildly, preventing convergence to an optimal solution.</blockquote><blockquote>Consequence</blockquote><blockquote><strong>Divergence:</strong> The model fails to learn effectively and may produce erratic outputs.</blockquote><h4><strong>Forward Propagation</strong></h4><ul><li>It is the process of feeding input data through a neural network to generate an output. It’s essentially a one-way journey from the input layer to the output layer.</li><li>It calculates the predicted output using the current weights and biases of the network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*5ueP-b0SBAdxMFaOSP1XfA.png" /><figcaption>Forward Propagation</figcaption></figure><h4>Backward Propagation (Backpropagation)</h4><ul><li>It is an algorithm used to train artificial neural networks. It’s essentially the reverse process of forward propagation, where we calculate the error at the output layer and propagate it back through the network to adjust weights and biases.</li><li><strong>Error Correction</strong>: It allows the network to learn from its mistakes by adjusting parameters to minimize the error between predicted and actual outputs.</li><li><strong>Efficient Weight Update</strong>s: By calculating gradients efficiently, backpropagation ensures that weights are updated in a way that maximizes the improvement in the network’s performance.</li><li><strong>Optimization</strong>: Backpropagation is coupled with optimization algorithms (like gradient descent) to find the optimal set of weights and biases for the network.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*qI4_nmGCw63CZAelN2poqg.png" /><figcaption>Backward Propagation</figcaption></figure><h4>Activation Functions</h4><ul><li><strong>Definition</strong>: Functions applied to the output of each layer i.e., hidden layer (except the input layer) to introduce non-linearity into the model.</li><li><strong>Examples</strong>: <strong>Sigmoid</strong>, <strong>ReLU</strong> (Rectified Linear Unit), and <strong>Tanh</strong>.</li><li><strong>Function</strong>: They allow the neural network to learn complex patterns by making the model non-linear.</li></ul><p><strong>Sigmoid: Activation Function</strong></p><p>Squashes any output values between between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*h0KF58WP5HzWoxCEvKT0kQ.png" /><figcaption>Sigmoid Activation Function</figcaption></figure><h4>Chain Rule</h4><p>It is a concept in calculus, where it is used to compute the derivative of composite functions, crucial for backpropagation in neural networks.</p><ul><li><strong>In Backpropagation:</strong> In neural networks, it’s used in backpropagation to calculate the gradient of the loss function with respect to each weight.</li><li><strong>Step-by-step calculation:</strong> We calculate how the error changes with respect to the output of the previous layer, then how that output changes with respect to the activation function, and finally, how the activation function changes with respect to the weight.</li><li><strong>Multiplying the effects:</strong> By multiplying these individual changes, we get the total impact of the weight on the error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sg3MY194xNXawNOcmWTag.png" /><figcaption>Gradient Calculation through Chain Rule</figcaption></figure><h4>Optimizer</h4><p><strong>Stochastic Gradient Descent (SGD):</strong> A faster variant of Gradient Descent optimizer algorithm for large datasets. It updates parameters after processing each individual training example. It can be more susceptible to noise due to frequent updates.</p><p>For more about this, go through on below previous post.</p><p><a href="https://medium.com/@rakesh.ganya28/gradient-descent-variants-explained-enhancing-loss-function-optimization-cf0f5a2cb2ae">Gradient Descent Variants Explained: Enhancing Loss Function Optimization</a></p><h3>Sample Image Dataset</h3><h4>MNIST</h4><p><strong>MNIST</strong> stands for <strong>Modified National Institute of Standards and Technology</strong> database. It’s a large dataset of handwritten digits (0–9) that’s commonly used for training various image processing systems.</p><p><strong>Key characteristics:</strong></p><ul><li>Contains 60,000 training images and 10,000 testing images.</li><li>Each image is a 28x28 pixel grayscale image.</li></ul><pre># Basic Python Modules<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import warnings<br><br># Deep Learning Libraries<br>import tensorflow as tf<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, Activation<br>from tensorflow.keras.optimizers import SGD<br><br>warnings.filterwarnings(&quot;ignore&quot;)<br>%matplotlib inline<br><br># Load the MNIST dataset<br>mnist = tf.keras.datasets.mnist<br><br>(X_train_images, y_train_labels), (X_test_images, y_test_labels) = mnist.load_data()<br><br>print(f&quot;Train Images: {X_train_images.shape[0]}, Train Rows: {X_train_images.shape[1]}, Train Columns: {X_train_images.shape[1]}&quot;)<br>print(f&quot;Train Labels: {y_train_labels.shape[0]}&quot;)<br><br>print(f&quot;Test Images: {X_test_images.shape[0]}, Test Rows: {X_test_images.shape[1]}, Test Columns: {X_test_images.shape[1]}&quot;)<br>print(f&quot;Test Labels: {y_test_labels.shape[0]}&quot;)<br><br># Output<br>Train Images: 60000, Train Rows: 28, Train Columns: 28<br>Train Labels: 60000<br>Test Images: 10000, Test Rows: 28, Test Columns: 28<br>Test Labels: 10000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*CctQqfUDxBh1q87Fe-CS8Q.png" /><figcaption>MNIST Sample Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Au3anRMz2uXt0Dce8AqBwQ.png" /><figcaption>MNIST Sample Image</figcaption></figure><h3>ANN(Artificial Neural Network) Based Image Classification Model : Using TensorFlow Framework</h3><pre>n_hidden_layer_1 = 10 # 1st hidden layer&#39;s number of neurons<br>n_hidden_layer_2 = 5 # 2nd hidden layer&#39;s number of neurons<br>n_input = 784 # MNIST data input (img shape: 28*28)<br>n_output_layer_classes = 10 # MNIST total classes (0-9 digits)<br><br># Normalizing the Images<br>X_train_images = X_train_images / 255.0<br>X_test_images = X_test_images / 255.0<br><br><br># One-hot Encoding<br>y_train_labels = tf.keras.utils.to_categorical(y_train_labels, num_classes=10).astype(np.float32)<br>y_test_labels = tf.keras.utils.to_categorical(y_test_labels, num_classes=10).astype(np.float32)<br><br><br># Creating TensorFlow Dataset<br>train_dataset = tf.data.Dataset\<br>                .from_tensor_slices((X_train_images, y_train_labels))\<br>                .shuffle(60000)\<br>                .batch(100)<br><br>test_dataset = tf.data.Dataset\<br>                .from_tensor_slices((X_test_images, y_test_labels))\<br>                .batch(100) <br><br><br># Weights &amp; Bias Random Initialization<br>weights = {<br>    &quot;h1&quot;: tf.Variable(tf.random.normal([n_input, n_hidden_layer_1])),<br>    &quot;h2&quot;: tf.Variable(tf.random.normal([n_hidden_layer_1, n_hidden_layer_2])),<br>    &quot;out&quot;: tf.Variable(tf.random.normal([n_hidden_layer_2, n_output_layer_classes]))<br>}<br>biases = {<br>    &quot;b1&quot;: tf.Variable(tf.random.normal([n_hidden_layer_1])),<br>    &quot;b2&quot;: tf.Variable(tf.random.normal([n_hidden_layer_2])),<br>    &quot;out&quot;: tf.Variable(tf.random.normal([n_output_layer_classes]))<br>}<br><br><br># Building Model<br>def Model(x, weights, biases, activation): # x is predictors / columns / features of images data<br>    # Hidden Layer 1<br>    layer_1 = tf.add(tf.matmul(x, weights[&quot;h1&quot;]), biases[&quot;b1&quot;]) # i.e., Matrix multiplication ex:- y= mx + c<br><br>    if activation == &quot;sigmoid&quot;:<br>        layer_1 = tf.nn.sigmoid(layer_1)<br><br>    # Hidden Layer 2<br>    layer_2 = tf.add(tf.matmul(layer_1, weights[&quot;h2&quot;]), biases[&quot;b2&quot;]) # i.e., Matrix multiplication ex:- y= mx + c<br><br>    if activation == &quot;sigmoid&quot;:<br>        layer_2 = tf.nn.sigmoid(layer_2)<br><br>    # Output Layer<br>    out_layer = tf.add(tf.matmul(layer_2, weights[&quot;out&quot;]), biases[&quot;out&quot;]) # i.e., Matrix multiplication ex:- y= mx + c <br><br>    return tf.nn.softmax(out_layer)<br><br><br># Training Step<br>def train_step(images, labels, model_func, optimizer, loss_func):<br>    with tf.GradientTape() as tape:<br>        predictions = model_func(images)<br>        loss_value = loss_func(labels, predictions)<br>    grads = tape.gradient(loss_value, [*weights.values(), *biases.values()])<br>    optimizer.apply_gradients(zip(grads, [*weights.values(), *biases.values()]))    <br>    return loss_value<br><br><br># Train Model<br>def train_model(weights, biases, activation, optimizer, train_dataset, num_epochs):<br>    loss_func = tf.keras.losses.CategoricalCrossentropy()<br>    losses = []<br><br>    for epoch in range(num_epochs):<br>        epoch_loss_avg = tf.keras.metrics.Mean()<br>        for images, labels in train_dataset:<br>            model_func = lambda x: Model(x, weights, biases, activation)<br>            loss = train_step(images, labels, model_func, optimizer, loss_func)            <br>            epoch_loss_avg.update_state(loss) # Loss mean as per batch<br>        losses.append(epoch_loss_avg.result().numpy())<br>        if (epoch + 1) % 5 == 0:<br>            print(f&quot;Epoch {epoch + 1}, Loss: {epoch_loss_avg.result().numpy()}&quot;)<br><br>    return losses<br><br><br># Model Accuracy<br>def model_accuracy(weights, biases, activation, test_dataset):<br>    accuracy_metric = tf.keras.metrics.CategoricalAccuracy()<br>    for images, labels in test_dataset:<br>        predictions = Model(images, weights, biases, activation)<br>        accuracy_metric.update_state(labels, predictions)<br>    return accuracy_metric.result().numpy()<br><br><br># Plot Loss<br>def plot_loss(num_epochs, losses, title):<br>    sns.set_style(&quot;dark&quot;)<br>    plt.plot(range(1, num_epochs + 1), losses, &#39;b&#39;, label=&#39;Train Loss&#39;)<br>    plt.xlabel(&#39;Epoch&#39;)<br>    plt.ylabel(&#39;Loss&#39;)<br>    plt.title(title)<br>    plt.legend()<br>    plt.show()<br><br><br># Model Hyperparameters<br>num_epochs = 60<br>activations = [&quot;sigmoid&quot;]<br>optimizer_constructors = {<br>    &quot;SGD&quot;: lambda: tf.optimizers.SGD(learning_rate=0.05)<br>}<br><br><br># Start Training<br>for activation in activations:<br>    for opt_name, opt_constructor in optimizer_constructors.items():<br>        optimizer = opt_constructor()  # Create a new optimizer instance<br>        # When opt_constructor() is called, it executes the lambda function, which creates and returns a new tf.optimizers.SGD instance with the specified learning rate.<br>        print(f&quot;Training Model with {activation} activation and {opt_name} optimizer....&quot;)<br>        losses = train_model(weights, biases, activation, optimizer, train_dataset, num_epochs)<br>        plot_loss(num_epochs, losses, f&quot;Loss over Epochs ({activation} + {opt_name})&quot;)<br>        test_accuracy = model_accuracy(weights, biases, activation, test_dataset)<br>        print(f&quot;Test Accuracy with activation name: {activation} and optimizer: {opt_name} --&gt; {test_accuracy: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*9hU1hNlg2Luniuf-wpGuZg.png" /><figcaption>Loss overEpochs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*iBuA7Q1uNb30lOebPAUTNA.png" /><figcaption>Loss over Epochs</figcaption></figure><p>Test Accuracy with activation name: sigmoid and optimizer: SGD →<strong> 0.84</strong></p><h3>ANN(Artificial Neural Network) Based Image Classification Model : Using Keras API</h3><pre># Weights &amp; Bias Random Initializer<br>initializer = tf.keras.initializers.RandomNormal()<br><br><br># Building Model<br>def build_model(activation, initializer):<br>    model = Sequential()<br>    model.add(Dense(n_hidden_layer_1, input_shape=(n_input,), kernel_initializer=initializer))<br>    model.add(Activation(activation))<br>    model.add(Dense(n_hidden_layer_2, kernel_initializer=initializer))<br>    model.add(Activation(activation))<br>    model.add(Dense(n_output_layer_classes, kernel_initializer=initializer))<br>    model.add(Activation(&quot;softmax&quot;))<br>    return model<br><br><br># Training and Model Evaluation<br>def train_and_evaluate(activation, optimizer_class, learning_rate, initializer, <br>                        X_train_images, y_train_labels,<br>                        X_test_images, y_test_labels,<br>                        num_epochs):<br>    model = build_model(activation, initializer)<br>    optimizer = optimizer_class(learning_rate = learning_rate)<br>    model.compile(optimizer=optimizer, loss=&quot;categorical_crossentropy&quot;, metrics=[&quot;accuracy&quot;])<br>    history = model.fit(X_train_images, y_train_labels, <br>                        epochs=num_epochs, batch_size=100, <br>                        validation_data = (X_test_images, y_test_labels), <br>                        verbose=1)<br>    test_loss, test_accuracy = model.evaluate(X_test_images, y_test_labels, verbose=0)<br>    return history.history[&quot;loss&quot;], test_accuracy<br><br><br># Plot Loss<br>def plot_loss(num_epochs, losses, title):<br>    sns.set_style(&quot;dark&quot;)<br>    plt.plot(range(1, num_epochs + 1), losses, &quot;b&quot;, label=&quot;Train Loss&quot;)<br>    plt.xlabel(&quot;Epoch&quot;)<br>    plt.ylabel(&quot;Loss&quot;)<br>    plt.title(title)<br>    plt.legend()<br>    plt.show()<br><br><br># Model Hyperparameters<br>num_epochs = 60<br>activations = [&quot;sigmoid&quot;]<br>optimizer_constructors = {<br>    &quot;SGD&quot;: (SGD, 0.05)<br>}<br><br><br># Start Training<br>for activation in activations:<br>    for opt_name, (optimizer_class, learning_rate) in optimizer_constructors.items():<br>        print(f&quot;Training model with {activation} activation and {opt_name} optimizer...&quot;)<br>        losses, test_accuracy = train_and_evaluate(activation, <br>                                                    optimizer_class, <br>                                                    learning_rate, <br>                                                    initializer,<br>                                                    X_train_images, y_train_labels,<br>                                                    X_test_images, y_test_labels,<br>                                                    num_epochs)<br>        plot_loss(num_epochs, losses, f&quot;Loss over Epochs ({activation} + {opt_name})&quot;)<br>        print(f&quot;Test Accuracy with {activation} activation and {opt_name} optimizer: {test_accuracy: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwiakVAdDjXGZjtKQ6hA1A.png" /><figcaption>Loss over Epochs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*bkcpu0UgHeoU4iGEgV6f0w.png" /><figcaption>Loss over Epochs</figcaption></figure><p>Test Accuracy with sigmoid activation and SGD optimizer → <strong>0.91</strong></p><h3>Key Points</h3><ul><li>As we can see above, using Keras we were able to build complex neural networks more simply.</li><li>As we used random initialization, we would be requiring more epochs for SGD optimizer to learn the optimal weights.</li><li>We employed activation function like Sigmoid in hidden layers, to introduce non-linear learning pattern in Neural Network. We could also try other activation functions too to make Neural Network learning more robust.</li><li>We can improve model accuracy by using smart weights initialization, gradient clipping, trying out more activation functions within hidden layers.</li></ul><p>I hope with the end of this post, you would have got a brief idea about the Neural Network modules, and how an Image classification implementation can be achieved through TensorFlow framework and Keras API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383a5ddf9944" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Polynomial Regression Models in TensorFlow with Gradient Descent]]></title>
            <link>https://medium.com/@rakesh.ganya28/building-polynomial-regression-models-in-tensorflow-with-gradient-descent-15fda4697e89?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/15fda4697e89</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 12:16:00 GMT</pubDate>
            <atom:updated>2024-07-19T12:16:00.504Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we will be discussing polynomial regression models using TensorFlow and optimize them with gradient descent. And also will have a brief look how to implement them with Scikit-Learn library.</p><h3>What is Polynomial Regression?</h3><p>In statistics, polynomial regression is a form of regression analysis in which the relationship between the independent variable x and the dependent variable y is modelled as an nth degree polynomial.</p><blockquote><strong>Polynomial </strong>means sum of several terms that contain different powers of the same variable(s).</blockquote><h4>1. Linear Regression Equations</h4><p><em>Degree 1</em></p><p>A linear equation is the simplest form of an equation and represents a straight-line relationship between two variables.</p><pre># Simple Linear Equation / Linear Regression Model<br>y=mx+c<br><br>where:<br>• y is the dependent variable.<br>• x is the independent variable.<br>• m is the slope of the line.<br>• c is the y-intercept.<br><br># Example: y=10x+2</pre><p><strong><em>Goal</em></strong>: In a linear regression model, the goal is to find the best-fitting straight line through the data points. The parameters m (<strong>slope</strong>) and c (<strong>intercept</strong>) are determined by <strong><em>minimizing the sum of the squared differences between the observed values and the values predicted by the linear model (i.e., Loss function)</em></strong>.</p><blockquote><strong>Note</strong>: In Linear polynomial distributed data, it will exhibit no direction changes. It follows same direction as a straight line.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*SQZQnWRAzUNYWV_316swVA.png" /><figcaption>Linear Regression Model</figcaption></figure><p>To learn more about linear regression model, refer to my previous article.</p><p><a href="https://medium.com/@rakesh.ganya28/optimizing-linear-regression-loss-function-using-gradient-descent-algorithm-5f5efe72aec0">Optimizing Linear Regression Loss Function Using Gradient Descent Algorithm</a></p><h4><strong>2. Quadratic Equations</strong></h4><p><em>Degree 2</em></p><p>A quadratic equation represents a parabolic relationship between the two variables.</p><pre># Quadratic Non-Linear Equation <br>y = (m0 * x^2) + (m1 * x) + c<br><br>where:<br>• y is the dependent variable.<br>• x is the independent variable.<br>• m0 is the quadratic term coefficient.<br>• x^2 is the quadratic term.<br>• m1 is the linear term coefficient i.e., slope<br>• x is the linear term.<br>• cis the y-intercept.<br><br># Example: y = (1 * x**2) + (2 * x) + (-4.5)</pre><p><strong><em>Goal</em></strong>: A quadratic regression model can be used to fit a more complex curve to the data. The parameters m0, m1, and c are determined by <strong>minimizing the sum of the squared differences between the observed values and the values predicted by the quadratic model.</strong></p><blockquote>Note: In Quadratic polynomial distributed data, it will exhibit approximately one direction change.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Z-ktCdhAuK5BvE8_Lt_3PQ.png" /><figcaption>Quadratic Non-Linear Model</figcaption></figure><p>To learn more about non-linear quadratic regression model, refer to my previous article.</p><p><a href="https://medium.com/@rakesh.ganya28/deep-learning-essentials-a-practical-introduction-to-tensorflow-cd4180522f2f">Deep Learning Essentials: A Practical Introduction to TensorFlow</a></p><h4><strong>3. Cubic Equations</strong></h4><p><em>Degree 3</em></p><p>A cubic equation represents a more complex non-linear relationship between two variables.</p><pre># Cubic Non-Linear Equation <br>y = (m0 * x^3) + (m1 * x^2) + (m2 * x) + c<br><br>where:<br>• y is the dependent variable.<br>• x is the independent variable.<br>• m0 is the cubic term coefficient.<br>• x^3 is the cubicterm.<br>• m1 is the quadratic term coefficient.<br>• x^2 is the quadratic term.<br>• m2 is the linear term coefficient i.e., slope<br>• x is the linear term.<br>• cis the y-intercept.<br><br># Example: y = (1.5 * x**3) + (0.5 * x**2) + (-4 * x) + 0.05</pre><p><strong><em>Goal</em></strong>: A cubic regression model can be used to fit a more complex curve to the data. The parameters m0, m1, m2, and c are determined by <strong>minimizing the sum of the squared differences between the observed values and the values predicted by the cubic model.</strong></p><blockquote><strong>Note</strong>: In Cubic polynomial distributed data, it will exhibit approximately two directions change.</blockquote><p>Similarly with Quartic and Quintic Equations i.e.,</p><h4><strong>4. Quartic Equation</strong></h4><p>Degree 4</p><p>A quartic equation represents a more complex non-linear relationship between two variables.</p><blockquote>Note: In Quartic polynomial distributed data, it will exhibit approximately three directions change.</blockquote><pre># Quartic Non-Linear Equation <br>y = (m0 * x^4) + (m1 * x^3) + (m2 * x^2) + (m3 * x) + c</pre><h4><strong>5. Quintic Equation</strong></h4><p>Degree 5</p><p>A Quintic equation represents a more complex non-linear relationship between two variables.</p><blockquote><strong>Note</strong>: In Quintic polynomial distributed data, it will exhibit approximately four directions change.</blockquote><pre># Quintic Non-Linear Equation <br>y = (m0 * x^5) + (m1 * x^4) + (m2 * x^3) + (m3 * x^2) + (m4 * x) + c</pre><h3>Various Polynomial Regression Models Implementation: Using Scikit-Learn Library</h3><h4>Libraries</h4><pre>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import PolynomialFeatures<br>from sklearn.linear_model import LinearRegression<br><br>%matplotlib inline</pre><h4>Sample Data</h4><p>Train Data</p><pre># Synthetic Data<br>np.random.seed(11)<br>X = np.sort((np.random.rand(100,1) * 10), axis=0)[:62] # np.random.rand(100,1): 100 Random values &lt; 1 with 1 column; np.sort() , axis=0 sorting rows in 1st col<br>y = np.sin(X).ravel() + np.random.normal(0, 0.1, X.shape[0]) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Ikegt_pJSp16fKFA5Pa9Uw.png" /></figure><p>Test Data</p><pre>X_test = np.sort((np.random.rand(100,1) * 10), axis=0)[65:74]<br>y_test = np.sin(X_test).ravel() + np.random.normal(0.45, 0.26, X_test.shape[0])</pre><h4>EDA</h4><pre># Plot the synthetic data<br>sns.set_style(&quot;dark&quot;)<br>fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 5))<br>plt.scatter(X, y, color=&#39;black&#39;, label=&#39;Train Data&#39;)<br>plt.scatter(X_test, y_test, color=&#39;blue&#39;, label=&#39;Test Data&#39;)<br>plt.xlabel(&#39;X-values&#39;, fontsize=14)<br>plt.ylabel(&#39;y-values&#39;, fontsize=14)<br>plt.title(&#39;Synthetic Non-linear Data&#39;, fontsize=16)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*vLbs6fP78fiNyizcudFjHg.png" /><figcaption>Data Distribution: Train and Test Data</figcaption></figure><h4>Model Fit</h4><ul><li><strong>Linear Model</strong></li></ul><pre>linear_model = LinearRegression()<br>linear_model.fit(X, y)</pre><ul><li><strong>Quadratic Regression Model</strong></li></ul><pre>poly2 = PolynomialFeatures(degree=2)<br>x_poly2 = poly2.fit_transform(X)<br>quadratic_model = LinearRegression()<br>quadratic_model.fit(x_poly2, y)<br><br>print(&quot;--&quot;*20)<br>print(&quot;Raw X Values:&quot;)<br>print(&quot;--&quot;*20)<br>print(X[:5])<br>print(&quot;--&quot;*20)<br>print(&quot;Quadratic Transformed Features:&quot;)<br>print(&quot;--&quot;*20)<br>print(x_poly2[:5])<br><br># x**2 = 0.12780815**2 # 0.01633492</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*HdCfMN2h0nqbrG6M0r8HfQ.png" /><figcaption>Quadratic Transformed Vars i.e., x, x²</figcaption></figure><ul><li><strong>Cubic Regression Model</strong></li></ul><pre>poly3 = PolynomialFeatures(degree=3)<br>x_poly3 = poly3.fit_transform(X)<br>cubic_model = LinearRegression()<br>cubic_model.fit(x_poly3, y)<br><br><br>print(&quot;--&quot;*20)<br>print(&quot;Raw X Values:&quot;)<br>print(&quot;--&quot;*20)<br>print(X[:5])<br>print(&quot;--&quot;*20)<br>print(&quot;Cubic Transformed Features:&quot;)<br>print(&quot;--&quot;*20)<br>print(x_poly3[:5])<br><br># x**2 = 0.12780815**2 # 0.01633492<br># x**3 = 0.12780815**3 # 0.00208774</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*QWX_hDIxxS5gbDG0I44Dkg.png" /><figcaption>Cubic Transformed Vars i.e., x, x², x³</figcaption></figure><h4>Model Predictions</h4><pre>def plot_predictions(X, model, poly_features, line_style, color, label):<br>    X_poly = poly_features.transform(X)<br>    y_pred = model.predict(X_poly)<br>    # Plot<br>    plt.plot(X, y_pred, linestyle=line_style, color=color, label=label)<br><br># Plot Actual Data<br>sns.set_style(&quot;dark&quot;)<br>fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 5))<br>plt.scatter(X, y, color=&quot;black&quot;, label=&quot;Train Data&quot;)<br>plt.scatter(X_test, y_test, color=&quot;blue&quot;, label=&quot;Test Data&quot;)<br>plt.xlabel(&#39;X-values&#39;, fontsize=14)<br>plt.ylabel(&#39;y-values&#39;, fontsize=14)<br>plt.title(&#39;Polynomial Regression Models : Predictions&#39;, fontsize=16)<br><br># Plot Linear Model Predictions<br>y_pred_train = linear_model.predict(X)<br>y_pred_test = linear_model.predict(X_test)<br>plt.plot(X, y_pred_train, color=&quot;brown&quot;, label=&quot;Linear Model&quot;)<br>plt.plot(X_test, y_pred_test, linestyle=&quot;dotted&quot;, color=&quot;brown&quot;, label=&quot;Linear Model: Predictions&quot;)<br><br># Plot Quadratic Model Predictions<br>plot_predictions(X, quadratic_model, poly2, line_style=&quot;-&quot;, color=&quot;steelblue&quot;, label=&quot;Quadratic Model&quot;)<br>plot_predictions(X_test, quadratic_model, poly2, line_style=&quot;dotted&quot;, color=&quot;steelblue&quot;, label=&quot;Quadratic Model: Predictions&quot;)<br><br># Plot Cubic Model Predictions<br>plot_predictions(X, cubic_model, poly3, line_style=&quot;-&quot;, color=&quot;orange&quot;, label=&quot;Cubic Model&quot;)<br>plot_predictions(X_test, cubic_model, poly3, line_style=&quot;dotted&quot;, color=&quot;orange&quot;, label=&quot;Cubic Model: Predictions&quot;)<br><br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*DGhfFpwC5rdfMWlPxiMofQ.png" /><figcaption>Non-Linear Models Fit and Prediction</figcaption></figure><p><strong>Observations</strong></p><ul><li>In this sample data, the pattern as two direction changes that resembles with the polynomial cubic regression [degree=3] distribution.</li><li>Hence, on applying all three different polynomial regression models i.e., linear, quadratic and cubic models. Cubic model seems to follow the data pattern more accurately, as sample data follows assumption (i.e., two direction changes) of cubic model.</li></ul><h3>Cubic Polynomial Regression Model Implementation: Using TensorFlow and Gradient Descent</h3><h4>Libraries</h4><pre>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import tensorflow as tf<br>import warnings<br>from scipy.stats import norm<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>%matplotlib inline</pre><h4>Sample Data</h4><pre>x = tf.linspace(-2, 2, 150) # Generates a sequence of numbers linearly spaced between a specified start(-2) and stop(2) value<br>x = tf.cast(x, tf.float32)<br><br># Cubic Function<br>def f(x):<br>    # More cubic term affect due to 1.5 i.e.,,  <br>    y = (1.5 * x**3) + (0.5 * x**2) + (-4 * x) + 0.05<br>    return y<br><br># Preparing y values i.e., f(x) along with some noise to show as more realistic data, <br># Instead of having all data points as sequence line without having dispersion in data.<br>y = f(x) + tf.random.normal(shape=[x.shape[0]])</pre><h4>EDA</h4><pre>sns.set_style(&quot;dark&quot;)<br>fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10,5))<br>plt.plot(x, y.numpy(), &#39;.&#39;, label=&#39;Sample Data&#39;)<br>plt.plot(x, f(x), label=&#39;Ground Truth Pattern&#39;)<br>plt.title(&#39;Cubic Function Behaviour Sample Data&#39;, fontsize=16)<br>plt.xlabel(&#39;X Values&#39;, fontsize=14)<br>plt.ylabel(&#39;Y Values&#39;, fontsize=14)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*o81JirzPDZ0f8WdpcGQolA.png" /><figcaption>Cubic Polynomial Distributed Sample Data</figcaption></figure><h4>Polynomial Cubic Regression Model</h4><pre>class Model(tf.Module):<br><br>    def __init__(self):<br>        # Randomly generated weights<br>        init_weights = tf.random.uniform(shape=[4], minval=0.0, maxval=0.5, seed=11)<br>        # Initialize weights<br>        self.weight_c = tf.Variable(init_weights[0])<br>        self.weight_q = tf.Variable(init_weights[1])<br>        self.weight_l = tf.Variable(init_weights[2])<br>        self.bias = tf.Variable(init_weights[3])<br><br>    @tf.function<br>    def __call__(self, x):<br>        # Quadratic Model : cubic_weight * x^2 + quadratic_weight * x^2 + linear_weight * x + bias<br>        return (self.weight_c * x**3) + (self.weight_q * x**2) + (self.weight_l * x) + self.bias </pre><ul><li><strong>Model Fit</strong></li></ul><pre># Intialise Model<br>model = Model()</pre><ul><li>Initial Random Weights</li></ul><pre><br>print(f&quot;Initial Random Cubic Term Weight: {model.weight_c}&quot;)<br>print(f&quot;Initial Random Quadratic Term Weight: {model.weight_q}&quot;)<br>print(f&quot;Initial Random Linear Term Weight: {model.weight_l}&quot;)<br>print(f&quot;Initial Random bias Term Weight: {model.bias}&quot;)<br><br>model.variables</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lx-8xHkyR52TE3MeKmHF8w.png" /></figure><ul><li>Loss Function</li></ul><pre>def mse(y, y_pred):<br>    return tf.reduce_mean(tf.square(y - y_pred))</pre><ul><li>Hyperparameters</li></ul><pre>epochs = 300<br>learning_rate = 0.01<br>losses = []</pre><h4>Gradient Descent</h4><pre># Training Loop<br>for epoch in range(epochs):<br>    with tf.GradientTape() as tape:<br>        y_pred = model(x)<br>        loss = mse(y, y_pred)<br>    grads = tape.gradient(loss, model.variables) # find gradients of loss w.r.t weights and bias i.e., partial differentiation<br><br>    # Update weights and bias<br>    for g,v in zip(grads, model.variables):<br>        v.assign_sub(learning_rate * g)<br>    # Loss per Epoch<br>    loss = mse(y, model(x))<br>    losses.append(loss)<br>    if epoch % 25 == 0:<br>        print(f&quot;Epoch: {epoch}, Loss: {loss.numpy():.4f}&quot;)<br>        print(&quot;     &gt;&gt; &quot;, model.variables)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3kPBV2jCvM8pjUB8k63sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*mj1fpxzb1sTBlTXomD8n4A.png" /><figcaption>Cubic Non-Linear Model Fit</figcaption></figure><p><strong>Observations</strong></p><ul><li>In this sample data, the pattern has two direction changes that resembles with the polynomial cubic regression [degree=3] distribution.</li><li>Hence, we implemented Gradient Descent algorithm to estimate weights for the terms i.e., cubic, quadratic, linear and bias. Where, trained weights &amp; bias seems to follow the data pattern accurately, as which we can see above both actual data pattern and our trained weights predictions are close enough.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15fda4697e89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Essentials: A Practical Introduction to TensorFlow]]></title>
            <link>https://medium.com/@rakesh.ganya28/deep-learning-essentials-a-practical-introduction-to-tensorflow-cd4180522f2f?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd4180522f2f</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 13:29:08 GMT</pubDate>
            <atom:updated>2024-07-12T13:29:08.789Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll explore the basics of TensorFlow, a key framework for machine learning and deep learning model development. We’ll discuss foundational concepts and demonstrate how to setup a TensorFlow and how it is used to build basic model.</p><h3>What is TensorFlow?</h3><p><strong>TensorFlow</strong> is an open-source library developed by Google for machine learning and deep learning applications. It provides a comprehensive, flexible ecosystem of tools, libraries, and community resources that allow researchers and developers to build and deploy machine learning-powered applications.</p><h3>Why TensorFlow Used for Machine Learning or Deep Learning?</h3><h4><strong>Versatility</strong></h4><blockquote><strong>Platform Support:</strong> It supports deployment on multiple platforms including desktops, servers, mobile devices (<strong>TensorFlow-Lite</strong>), and the web(<strong>TensorFlow.js</strong>).</blockquote><h4><strong>Ease of Use</strong></h4><blockquote><strong>High Level API’s:</strong> TensorFlow provides high-level APIs like <strong>Keras</strong> which simplify the process of building and training models.</blockquote><blockquote><strong>Eager Execution:</strong> Allows <strong>immediate execution</strong>, where intuitive of easy debugging can be achieved.</blockquote><blockquote><strong>Graph-Based Execution:</strong> It allows models to be run independently of the Python environment, making it ideal for production deployment. This enables efficient and scalable inference on various platforms, including servers, mobile devices, and web applications, without needing a backend Python environment.</blockquote><h4>Production-Ready</h4><blockquote><strong>Model Deployment</strong>: TensorFlow Extended (TFX) facilitates the deployment of models into production environments.</blockquote><blockquote><strong>TensorFlow Serving</strong>: Provides tools for serving models in production with high performance and scalability.</blockquote><h3>Key Difference between TensorFlow Extended (TFX) and MLflow Platform</h3><p><strong>TensorFlow Extended (TFX)</strong>:</p><ul><li>It is an end-to-end platform for deploying production machine learning (ML) pipelines, designed specifically for <strong><em>TensorFlow</em></strong>. It includes components for data ingestion, validation, transformation, training, and serving.</li><li>It is ideal for projects already using TensorFlow, as it integrates seamlessly with the TensorFlow ecosystem.</li></ul><p><strong>MLflow</strong>:</p><ul><li>It is an open-source platform designed to manage the ML lifecycle, including experimentation, reproducibility, and deployment, regardless of the ML library used.</li><li>It is suitable for projects that use various ML libraries (e.g., TensorFlow, Keras, PyTorch, Scikit-learn, H2o).</li></ul><h3>How to Setup TensorFlow?</h3><p>Using pip (which is a package installer for python).</p><p><strong>Setting up TensorFlow for CPU-based System</strong></p><p>Install package</p><pre>pip install tensorflow</pre><p>Verify the installation</p><pre>import tensorflow as tf<br>print(tf.__version__)</pre><p><strong>Setting up TensorFlow for GPU-based System</strong></p><pre>pip install tensorflow-gpu</pre><p>Verify the installation</p><pre>import tensorflow as tf<br>print(tf.__version__)<br>print(tf.config.list_physical_devices(&#39;GPU&#39;))</pre><ul><li>Ensure your GPU driver and CUDA Toolkit are compatible with the TensorFlow version you install.</li></ul><blockquote>Keypoints:</blockquote><blockquote>In case we wanted to train a huge Neural Network or a Machine Learning with very high hyperparameters tuning then GPU based TensorFlow setup would be appropriate. As a result, for this we would be requiring GPU chip and essential NVIDIA CUDA drivers in the system.</blockquote><blockquote>But if we are trying out reasonable size of Neural Network and standard Machine Learning, then CPU based TensorFlow setup would fine for our development.</blockquote><h3>TensorFlow Essentials</h3><h4>Library Import</h4><pre>import os<br>import tensorflow as tf<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br><br># Version Check<br>print(tf.__version__)<br># 2.16.2</pre><h4>Inspect Installed TensorFlow Library Flavour</h4><p>Note: To check whether CPU or GPU flavour has been installed?</p><pre># Check whether TF currently using CPU/GPU: For higher performance use GPU, if exists on Computer which we are using.<br>if tf.config.list_physical_devices(&quot;GPU&quot;):<br>    print(&quot;TensorFlow using GPU&quot;)<br>else:<br>    print(&quot;Tensorflow using CPU&quot;)<br><br># Output <br>Tensorflow using CPU</pre><p>Observation:</p><ul><li>In my case, currently I am using CPU based TensorFlow, so it written ‘Tensorflow using CPU’.</li></ul><h4>Tensor Constant</h4><ul><li>tf.Tensor are immutable objects.</li><li>Mostly it is used for input data during Model training</li></ul><p>Note: In TensorFlow n-dimensional array is stored as Tensor object like below.</p><pre># col1, col2, col3<br>x = tf.constant([[10., 20., 30.], # row1<br>                [40., 50., 60]] # row2<br>                )<br><br>print(type(x)) # n-dimensional array stored as internal tensor object<br>print(x)<br>print(x.shape)<br>print(x.dtype)<br><br># Output<br>&lt;class &#39;tensorflow.python.framework.ops.EagerTensor&#39;&gt;<br>tf.Tensor(<br>[[10. 20. 30.]<br> [40. 50. 60.]], shape=(2, 3), dtype=float32)<br>(2, 3)<br>&lt;dtype: &#39;float32&#39;&gt;</pre><h4><strong>Mathematical Operations</strong></h4><ul><li>Adding</li></ul><pre># Adding n-dimensional tensor with same values <br>x_add = x + x<br><br>print(x_add)<br>print(x_add.shape)<br><br># Output<br>tf.Tensor(<br>[[ 20.  40.  60.]<br> [ 80. 100. 120.]], shape=(2, 3), dtype=float32)<br>(2, 3)</pre><ul><li>Multiplying</li></ul><pre># Multiplying n-dimensional tensor with constant value<br>x_ml_c = x * 5<br><br>print(x_ml_c)<br>print(x_ml_c.shape)<br><br># Output<br>tf.Tensor(<br>[[ 50. 100. 150.]<br> [200. 250. 300.]], shape=(2, 3), dtype=float32)<br>(2, 3)</pre><ul><li>Vectors Dot Product: Vectors M<em>atrix Multiplication</em></li></ul><pre># Dot product of n-dimensional tensor with same values i.e., matrix multiplication --&gt; sum(row * column)<br>x_dot_product = x @ tf.transpose(x)<br><br>print(x)<br>print(tf.transpose(x))<br>print(x_dot_product, &quot;\n\n&quot;)<br>print(&quot;Dot Product / Matrix Multiplication&quot;)<br>print(x_dot_product.shape, &quot;\n\n&quot;)<br><br># Explanation of matrix matrix multiplication<br>print(&quot;Explanation of matrix matrix multiplication&quot;)<br>print(&quot;x[00]position:&quot;, (10.*10.) + (20.*20.) + (30.*30.))<br>print(&quot;x[01]position:&quot;, (10.*40.) + (20.*50.) + (30.*60.))<br>print(&quot;x[10]position:&quot;, (40.*10.) + (50.*20.) + (60.*30.))<br>print(&quot;x[11]position:&quot;, (40.*40.) + (50.*50.) + (60.*60.))<br><br><br># Output<br>tf.Tensor(<br>[[10. 20. 30.]<br> [40. 50. 60.]], shape=(2, 3), dtype=float32)<br>tf.Tensor(<br>[[10. 40.]<br> [20. 50.]<br> [30. 60.]], shape=(3, 2), dtype=float32)<br>tf.Tensor(<br>[[1400. 3200.]<br> [3200. 7700.]], shape=(2, 2), dtype=float32) <br><br><br>Dot Product / Matrix Multiplication<br>(2, 2) <br><br><br>Explanation of matrix matrix multiplication<br>x[00]position: 1400.0<br>x[01]position: 3200.0<br>x[10]position: 3200.0<br>x[11]position: 7700.0</pre><ul><li>Vectors Concatenation</li></ul><pre># Data Concat<br>x_concat = tf.concat([x,x], axis=0) # Row wise addition<br><br>print(x.shape)<br>print(x)<br>print(x_concat.shape)<br>print(x_concat)<br><br># Output<br>(2, 3)<br>tf.Tensor(<br>[[10. 20. 30.]<br> [40. 50. 60.]], shape=(2, 3), dtype=float32)<br>(4, 3)<br>tf.Tensor(<br>[[10. 20. 30.]<br> [40. 50. 60.]<br> [10. 20. 30.]<br> [40. 50. 60.]], shape=(4, 3), dtype=float32)</pre><ul><li>Softmax Activation Function</li></ul><p>Note: It is one of the important activation function in deep learning to convert raw values into probabilities for multi class prediction.</p><pre># Converting raw values into softmax values<br>x_soft_max_values = tf.nn.softmax(x, axis=-1)<br><br>print(x.shape)<br>print(x)<br>print(x_soft_max_values.shape)<br>print(x_soft_max_values)<br><br># Output<br>(2, 3)<br>tf.Tensor(<br>[[10. 20. 30.]<br> [40. 50. 60.]], shape=(2, 3), dtype=float32)<br>(2, 3)<br>tf.Tensor(<br>[[2.0610598e-09 4.5397872e-05 9.9995458e-01]<br> [2.0610598e-09 4.5397872e-05 9.9995458e-01]], shape=(2, 3), dtype=float32)</pre><ul><li>Vector Sum: On Tensor Constant Object</li></ul><pre># Sum all the elements in tensor array : 10+20+30+40+50+60<br>x_sum = tf.reduce_sum(x)<br><br>print(x.shape)<br>print(x)<br>print(x_sum.shape)<br>print(x_sum)<br><br># Output<br>(2, 3)<br>tf.Tensor(<br>[[10. 20. 30.]<br> [40. 50. 60.]], shape=(2, 3), dtype=float32)<br>()<br>tf.Tensor(210.0, shape=(), dtype=float32)</pre><ul><li>Vector Sum: On Plain Python Array</li></ul><pre># Sum elements from array instead of tensor object<br>tf.reduce_sum([1,2,3])<br><br># Output<br>&lt;tf.Tensor: shape=(), dtype=int32, numpy=6&gt;</pre><ul><li>Convert Array to Tensor Object</li></ul><pre># Convert array to tensor object<br>x_temp = tf.convert_to_tensor([1,2,3]) # One row with 3 cols<br><br>print(x_temp.shape)<br>print(x_temp)<br><br># Output<br>(3,)<br>tf.Tensor([1 2 3], shape=(3,), dtype=int32)</pre><h4>Tensor: Variable</h4><p>Note: As tf.Tensor are immutable. But to store ML Model Weights, we require mutable variables i.e., we use tf.variable.</p><pre># Intialise with default values<br>var = tf.Variable([0.0, 0.0, 0.0])<br><br>print(var.shape)<br>print(var)<br><br># Output<br>(3,)<br>&lt;tf.Variable &#39;Variable:0&#39; shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)&gt;</pre><ul><li>Update variable values</li></ul><pre># Update variable with new values<br>var_new = var.assign([1,2,3])<br><br>print(var_new.shape)<br>print(var_new)<br><br># Output<br>(3,)<br>&lt;tf.Variable &#39;UnreadVariable&#39; shape=(3,) dtype=float32, numpy=array([1., 2., 3.], dtype=float32)&gt;</pre><ul><li>Find derivative of a function: <strong><em>x**2 + 2*x — 5</em></strong></li></ul><p>Note: As in Deep Neural Learning, we will be continously finding the derivatives of Loss function w.r.t. weights both in Forward and Backward Propagation. TensorFlow solve this derivative computation internally and can provides derivatives simply as below</p><pre># Define the input tensor x<br>x = tf.constant([-5.0, -2.5, 0.0, 2.5], dtype=tf.float32)<br><br># Derivative of function f(x)=x^2+2x−5 is 𝑓′(𝑥)=2𝑥+2 <br># TensorFlow implements automatic differentiation (autodiff), which uses calculus to compute gradients.<br>with tf.GradientTape() as g:<br>    g.watch(x)<br>    y = f(x) # y = 2𝑥+2 i.e., derived derivative of function f(x)<br><br># Compute the gradient of y with respect to x<br>grad_val = g.gradient(y, x)<br>print(&quot;x: &quot;, x)<br>print(&quot;𝑓′`: &quot;, grad_val)<br><br># Output<br># x:  tf.Tensor([-5.  -2.5  0.   2.5], shape=(4,), dtype=float32)<br># 𝑓′`:  tf.Tensor([-8. -3.  2.  7.], shape=(4,), dtype=float32)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0qTAkDnmD6h5kQw1MyDfg.png" /><figcaption>TensorFlow Gradient Calculation</figcaption></figure><h4>Tensor: Function</h4><blockquote>Difference between Python Plain Function and Tensor Function?</blockquote><p><strong>Python Function:</strong></p><ul><li><strong>Usage</strong>: Operates on standard Python objects and data types.</li><li><strong>Execution</strong>: Executes on CPU and utilizes Python’s interpreter.</li></ul><pre># Tensor operations in simple python function<br>def add(x,y):<br>    return x+y<br><br>x = tf.constant([10, 20])<br>y = tf.constant([100, 100])<br><br>add(x,y) # Immediate/Eager execution in python function<br><br># Output<br>&lt;tf.Tensor: shape=(2,), dtype=int32, numpy=array([110, 120])&gt;</pre><p><strong>Tensor Function (TensorFlow Function):</strong></p><ul><li><strong>Definition</strong>: A Tensor Function operates on TensorFlow tensors, which are multi-dimensional arrays or matrices used for numerical computation in TensorFlow.</li><li><strong>Usage</strong>: Specifically designed for numerical computations in machine learning and deep learning models.</li><li><strong>Execution</strong>: Can execute on both CPU and GPU, leveraging TensorFlow’s computational graph for efficient parallel processing.</li><li><strong>Benefits</strong>: Optimized for numerical operations, allows automatic differentiation for gradient-based optimization, and supports distributed computing.</li></ul><pre># Tensor operations in tensor function<br>@tf.function<br>def add(x,y):<br>    return x+y<br><br>x = tf.constant([10, 20])<br>y = tf.constant([100, 100])<br><br>add(x,y) # Graph execution is optimized and performed in a graph structure<br><br># Output<br>&lt;tf.Tensor: shape=(2,), dtype=int32, numpy=array([110, 120])&gt;</pre><p>Observation:</p><ul><li>Note: tf.function is a decorator that automatically optimizes TensorFlow operations for better performance.</li></ul><h4>Tensor: Module</h4><blockquote>Difference between Python Plain Class and Tensor Module?</blockquote><p><strong>Python Class:</strong></p><ul><li><strong>Usage</strong>: Used to structure and organize code into reusable components with properties and methods.</li><li><strong>Key Features</strong>: <strong>Encapsulation</strong>(process of protecting from other access by combining multiple properties and methods of data into a single class), <strong>inheritance</strong> (A child class (subclass) inherits all of the characteristics and methods from a parent class), and <strong>polymorphism</strong> (ex:- generic function/class that has various definitions).</li><li><strong>Example</strong>: Defines attributes like self.name and methods like def greet(self).</li></ul><p><strong>Tensor Module (TensorFlow Module):</strong></p><ul><li><strong>Definition</strong>: Same like python class.</li><li><strong>Key Features</strong>: Tensor operations, neural network layers, optimizers, and utilities.</li><li><strong>Benefits</strong>: You can save and restore the values of your variables using tf.train.Checkpoint. This is useful during training as it is quick to save and restore a model’s state.</li></ul><p>Basic Tensor Module</p><pre># Tensor Class<br>class SimplePred(tf.Module):<br>    def __init__(self, value):<br>        self.weight = tf.Variable(value) # Mutable Array (tensor obj) for Model weights (Here single weight)<br><br>    @tf.function<br>    def pred(self, x):<br>        return x * self.weight # Function: input * weight --&gt; output prediction<br>    <br># Load Model Object i.e., Tensor Module Class<br>model = SimplePred(3) # weight/coefficient<br># Prediction function<br>model.pred(tf.constant([1,2,3])) # Immutae Input Data Array (tensor obj)<br><br># Output<br>&lt;tf.Tensor: shape=(3,), dtype=int32, numpy=array([3, 6, 9])&gt;</pre><p>Save Tensor Module with Current Model State[Current Weights]</p><pre># Save Path<br>save_path = os.getcwd()+&quot;\\Data&quot;<br><br># Save Model (Tensor Module Code along with Model weights i.e., tf.Variable = 3)<br>tf.saved_model.save(model, save_path)</pre><p>Load Tensor Module with Last Saved Weights</p><pre># Load Model<br>loaded_model = tf.saved_model.load(save_path)<br>pred1 = loaded_model.pred(tf.constant([1, 2, 3])) # Input data : 1,2,3<br>print(&quot;Pred1:&quot;, pred1)<br>pred2 = loaded_model.pred(tf.constant([10, 20, 30])) # Input data : 10,20,30<br>print(&quot;Pred2:&quot;, pred2)<br><br># Output<br>Pred1: tf.Tensor([3 6 9], shape=(3,), dtype=int32)<br>Pred2: tf.Tensor([30 60 90], shape=(3,), dtype=int32)</pre><h4><strong>Basic Quadratic Model with TensorFlow</strong></h4><pre># Updated weights &amp; bias<br>class QuadraticModel(tf.Module):<br>    def __init__(self, w_q, w_l, b):<br>        # Initialise weights<br>        self.weight_q = tf.Variable(w_q) # Coefficient for quadratic term<br>        self.weight_l = tf.Variable(w_l) # Coefficient for linear term for Predictor<br>        self.bias = tf.Variable(b)<br>        print(f&quot;quadratic weight: {w_q}, linear weight: {w_l}, bias: {b}&quot;)<br><br>    @tf.function<br>    def predict(self,x):<br>        # Quadratic model with random weights &amp; bias: quadratic_weight * x^2 + linear_weight * x + bias<br>        pred = self.weight_q * (x**2) + self.weight_l * x + self.bias<br>        print(f&quot;Prediction: {pred}&quot;)<br>        return pred<br>    <br># Initiate Model Object<br>model = QuadraticModel(.9, 2.2, -4.5) # Manual Adjusted Weights and Bias<br><br># Plot Prediction<br>def plot_preds(x, y, f, model, title):<br>    sns.set_style(&quot;dark&quot;)<br>    plt.figure(figsize=(14,6))<br>    plt.plot(x, y.numpy(), &#39;.&#39;, label=&quot;Data&quot;)<br>    plt.plot(x, f(x), label=&quot;Ground Truth Pattern&quot;)<br>    plt.plot(x, model.predict(x), label=&quot;Predictions&quot;)<br>    plt.title(title, fontsize=16)<br>    plt.legend()<br>    plt.grid(True)<br>    plt.show()<br><br>plot_preds(x, y, f, model, &#39;Quadratic Model: With Manual Adjusted Weights &amp; Bias&#39;)<br><br># Output<br># quadratic weight: 0.9, linear weight: 2.2, bias: -4.5<br># Prediction: Tensor(&quot;add_1:0&quot;, shape=(80,), dtype=float32)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08XWwH2YZfoF5JvHva2Pyg.png" /><figcaption>Quadratic Model Training with TensorFlow</figcaption></figure><p>Observation</p><ul><li>Here we adjusted the weights i.e., quadratic weight &amp; linear weight (as per predictor) and then intercept value. In order to make our trained model to follow the actual ground truth pattern as close as possible.</li></ul><p><strong>Note</strong>: Just to keep our main focus on TensorFlow code implementation, hence we used basic Quadratic Regression Model with adjusted weights and bias.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd4180522f2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling Bias and Variance with Regularization Strategies]]></title>
            <link>https://medium.com/@rakesh.ganya28/controlling-bias-and-variance-with-regularization-strategies-f3f6d2b605eb?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f6d2b605eb</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 21:04:37 GMT</pubDate>
            <atom:updated>2024-07-05T21:04:37.613Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we delve into techniques for managing bias and variance using regularization strategies. We’ll explore how to implement these methods and highlight the key differences between them.</p><h3><strong>What is Bias-Variance Trade-off?</strong></h3><p><strong>High Bias</strong>: Models with high bias (e.g., linear regression) are often too simple and make strong assumptions about the data, potentially missing relevant relations (underfitting).</p><p><strong>High Variance</strong>: Models with high variance (e.g., decision trees) are highly flexible and can capture noise in the data, leading to overfitting.</p><blockquote>Think of it as balancing a seesaw. Too much bias tilts one side down, causing systematic errors. Too much variance tilts the other side, causing overfitting. The goal is to find a sweet spot where the model generalizes well.</blockquote><h3><strong>What is Regularization?</strong></h3><ul><li><strong>Definition</strong>: Regularization is a technique used in machine learning to prevent overfitting by adding a penalty to the loss function. This penalty discourages complex models that might fit the training data too closely.</li><li><strong>Simple Explanation</strong>: Think of regularization as a way to smooth out your model’s predictions, making sure it doesn’t bend too much to fit every tiny detail in the training data.</li></ul><p><strong>The Role of Regularization:</strong></p><ul><li><strong>Reduces Variance</strong>: By penalizing larger coefficients, regularization prevents the model from fitting the noise in the training data, thereby reducing overfitting.</li><li><strong>Controls Complexity</strong>: It keeps the model simpler and more generalizable.</li></ul><blockquote>It can also help in reducing bias but primarily focuses on reducing variance.</blockquote><h3>What is L1 Regularization (Lasso Regression)?</h3><p><strong>L1 Regularization</strong> adds the absolute value of the coefficients as a penalty term to the loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*-yCyolEDQCTFDoPSIznZHw.png" /></figure><h4>Benefits:</h4><ol><li><strong>Feature Selection</strong>: L1 regularization can shrink some coefficients to exactly zero, effectively selecting a simpler model with fewer features.</li><li><strong>Sparse Models</strong>: Creates sparse models that are easier to interpret.</li></ol><h3>What is L2 Regularization (Ridge Regression)?</h3><p><strong>L2 Regularization</strong> adds the squared value of the coefficients as a penalty term to the loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*mjrBFHDRTBLNskOIGBe39w.png" /></figure><h4>Benefits:</h4><ol><li><strong>Avoid Overfitting</strong>: By discouraging large coefficients, L2 regularization helps to avoid overfitting.</li><li><strong>Stable Solutions</strong>: It generally leads to more stable solutions where small changes in the input data result in small changes in the model.</li></ol><h3>What is Elastic Net Regularization?</h3><p><strong>Elastic Net Regularization</strong> combines both L1 and L2 regularization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*6gYzvpoLfamf_DQiMSifTw.png" /></figure><h4>Benefits:</h4><ol><li><strong>Best of Both Worlds</strong>: Combines the benefits of both L1 and L2 regularization.</li><li><strong>Handles Multicollinearity</strong>: Especially useful when features are highly correlated.</li><li><strong>Feature Selection and Stability</strong>: Provides both feature selection and stable solutions.</li></ol><h3>Implementing Linear Regression with Regularization</h3><ul><li>Through Gradient Descent Algorithm to optimise Loss function</li></ul><h4>Sample Data</h4><pre>df = pd.DataFrame({<br>    &quot;Product_Sell&quot;: [10, 15, 18, 22, 26, 30, 5, 31],<br>    &quot;Revenue_Generation&quot;: [1000, 1400, 1800, 2400, 2600, 2800, 700, 2900]<br>})<br><br>X = df[&#39;Product_Sell&#39;].values<br>y = df[&#39;Revenue_Generation&#39;].values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*O7ebfzy-a7rezY-AsRU7hw.png" /></figure><h4>L1 Regularization</h4><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br># L1 regularization parameter<br>lambda_L1 = 0.1  <br># Predictors List<br>predictors = [&quot;Product_Sell&quot;]<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}; l1_penality_intensity: {lambda_L1}&quot;)<br><br># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    for predictor in predictors: # Looping through each predictor<br><br>        # Selecting Predictor<br>        X_i = df[predictor].values<br><br>        # Predict <br>        y_pred = predict(X_i, m, b)<br>        pred_error = y - y_pred<br><br>        # Compute loss<br>        loss = np.mean(pred_error ** 2)<br><br>        # Simplified Derivatives of Loss Function<br>        m_gradient = (-2/n) * np.dot(pred_error, X_i) + lambda_L1 * np.sign(m) # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>        b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>        # Update latest weights and intercepts<br>        m = m - learning_rate * (m_gradient)<br>        b = b - learning_rate * (b_gradient)<br><br>        # Collect progress in each epoch<br>        weights.append(m)<br>        intercepts.append(b)<br>        preds.append(y_pred)<br>        losses.append(loss)<br><br>        # Print Progress<br>        print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)<br>print(&quot;Final Loss[MSE]: &quot;, round(losses[-1:][0],2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*vbxuYkNaQmiatLJVMLJdxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsTqDIvRqOH8ZusaOmz3lw.png" /></figure><h4>L2 Regularization</h4><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br># L2 regularization parameter<br>lambda_L2 = 0.1  <br># Predictors List<br>predictors = [&quot;Product_Sell&quot;]<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}; l2_penality_intensity: {lambda_L2}&quot;)<br><br># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    for predictor in predictors: # Looping through each predictor<br><br>        # Selecting Predictor<br>        X_i = df[predictor].values<br><br>        # Predict <br>        y_pred = predict(X_i, m, b)<br>        pred_error = y - y_pred<br><br>        # Compute loss<br>        loss = np.mean(pred_error ** 2)<br><br>        # Simplified Derivatives of Loss Function<br>        m_gradient = (-2/n) * np.dot(pred_error, X_i) + 2 * lambda_L2 * m # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>        b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>        # Update latest weights and intercepts<br>        m = m - learning_rate * (m_gradient)<br>        b = b - learning_rate * (b_gradient)<br><br>        # Collect progress in each epoch<br>        weights.append(m)<br>        intercepts.append(b)<br>        preds.append(y_pred)<br>        losses.append(loss)<br><br>        # Print Progress<br>        print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)<br>print(&quot;Final Loss[MSE]: &quot;, round(losses[-1:][0],2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*BVojQYSj8cz1JGYrKDAN-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRe21DNdYrun6OOoZj-F8A.png" /></figure><h4>Elastic Net Regularization</h4><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br># L1 regularization parameter<br>lambda_L1 = 0.1  <br># L2 regularization parameter<br>lambda_L2 = 0.1  <br># Predictors List<br>predictors = [&quot;Product_Sell&quot;]<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}; l1_penality_intensity: {lambda_L1}; l2_penality_intensity: {lambda_L2}&quot;)<br><br># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    for predictor in predictors: # Looping through each predictor<br><br>        # Selecting Predictor<br>        X_i = df[predictor].values<br><br>        # Predict <br>        y_pred = predict(X_i, m, b)<br>        pred_error = y - y_pred<br><br>        # Compute loss<br>        loss = np.mean(pred_error ** 2)<br><br>        # Simplified Derivatives of Loss Function<br>        m_gradient = (-2/n) * np.dot(pred_error, X_i) + lambda_L1 * np.sign(m) + 2 * lambda_L2 * m # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>        b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>        # Update latest weights and intercepts<br>        m = m - learning_rate * (m_gradient)<br>        b = b - learning_rate * (b_gradient)<br><br>        # Collect progress in each epoch<br>        weights.append(m)<br>        intercepts.append(b)<br>        preds.append(y_pred)<br>        losses.append(loss)<br><br>        # Print Progress<br>        print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)<br>print(&quot;Final Loss[MSE]: &quot;, round(losses[-1:][0],2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*CCX2jCgRh9sBykYpxfChLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfEaxpBup9vSfwwQlu7Lvw.png" /></figure><p><strong>Observations</strong></p><p>- All above variations of regularizations works pretty well, as it is simple data with single predictor. It will show significant differences, when there many predictors and huge data.</p><h3>Implementing Linear Regression with Regularization</h3><ul><li>Through scikit-learn Library</li></ul><h4>L1 Regularization</h4><pre>from sklearn import linear_model<br><br>alphas = np.logspace(-4,-1,4) # alphas / penality intensify. i.e., 10^4, 10^3, 10^2, 10^1<br>print(&quot;alphas: &quot;, alphas)<br># alphas:  [0.0001 0.001  0.01   0.1   ]<br><br># Lasso / L1 Regularization<br>lasso_cv = linear_model.LassoCV(alphas=alphas) # cross validation # , normalize=True<br>lasso_model = lasso_cv.fit(X_train, Y_train) # Model Fit<br>lasso_preds = lasso_model.predict(X_test) # Prediction<br>lasso_preds = [round(x,2) for x in lasso_preds]<br>df_lasso_coeffs = pd.DataFrame({&quot;variable&quot;: X_train.columns.tolist(), <br>                                &quot;Coeff&quot;:lasso_cv.coef_})<br><br># Variable Importance i.e., mod(coeff) != 0, which are significant for Model Fit<br>df_lasso_coeffs[df_lasso_coeffs[&quot;Coeff&quot;]!=0]<br># variable Coeff<br># Product_Sell 95.97024<br><br>print(&quot;lasso_cv.alpha_: &quot;, lasso_cv.alpha_)<br># lasso_cv.alpha_:  0.0001<br><br>def mse(true,pred):<br>    &#39;&#39;&#39; <br>    Calculate MSE value<br>    &#39;&#39;&#39;    <br>    return np.mean((pred-true)**2)<br><br>print(&quot;Loss: &quot;, round(mse(Y_test,lasso_preds),2))<br># Loss:  21452.96</pre><h4>L2 Regularization</h4><pre>alphas = np.logspace(-4,-1,4) # alphas / penality intensify. i.e., 10^4, 10^3, 10^2, 10^1<br>print(&quot;alphas: &quot;, alphas)<br># alphas:  [0.0001 0.001  0.01   0.1   ]<br><br># Ridge / L2 Regularization<br>ridge_cv = linear_model.RidgeCV(alphas=alphas) # cross validation # , normalize=True<br>ridge_model = ridge_cv.fit(X_train, Y_train) # Model Fit<br>ridge_preds = ridge_model.predict(X_test) # Prediction<br>ridge_preds = [round(x,2) for x in ridge_preds]<br>df_ridge_coeffs = pd.DataFrame({&quot;variable&quot;: X_train.columns.tolist(), <br>                                &quot;Coeff&quot;:ridge_cv.coef_})<br><br># Variable Importance i.e., mod(coeff) &gt; 0.001, which are significant for Model Fit<br>df_ridge_coeffs[df_ridge_coeffs[&quot;Coeff&quot;]&gt;=0.001]<br># variable Coeff<br># Product_Sell 95.934556<br><br>print(&quot;ridge_cv.alpha_: &quot;, ridge_cv.alpha_)<br># ridge_cv.alpha_:  0.1<br><br>print(&quot;Loss: &quot;, round(mse(Y_test,ridge_preds),2))<br># Loss:  21327.3</pre><h4>Elastic Net Regularization</h4><pre>alphas = np.logspace(-4,-1,4) # alphas / penality intensify. i.e., 10^4, 10^3, 10^2, 10^1<br>print(&quot;alphas: &quot;, alphas)<br># alphas:  [0.0001 0.001  0.01   0.1   ]<br><br># Elastic Net<br>elastic_net_cv = linear_model.ElasticNetCV(alphas=alphas) # cross validation # , normalize=True<br>elastic_net_model = elastic_net_cv.fit(X_train, Y_train) # Model Fit<br>elastic_net_preds = elastic_net_model.predict(X_test) # Prediction<br>elastic_net_preds = [round(x,2) for x in elastic_net_preds]<br>df_elastic_net_coeffs = pd.DataFrame({&quot;variable&quot;: X_train.columns.tolist(), <br>                                &quot;Coeff&quot;:elastic_net_cv.coef_})<br><br># Variable Importance i.e., mod(coeff) &gt; 0.001 which is also !=0, which are significant for Elastic Model Fit<br>df_elastic_net_coeffs[df_elastic_net_coeffs[&quot;Coeff&quot;]&gt;=0.001]<br># variable Coeff<br># Product_Sell 95.970134<br><br>print(&quot;elastic_net_cv.alpha_: &quot;, elastic_net_cv.alpha_)<br># elastic_net_cv.alpha_:  0.0001<br><br>print(&quot;Loss: &quot;, round(mse(Y_test,elastic_net_preds),2))<br># Loss:  21452.96</pre><p><strong>Keypoints</strong></p><ul><li>Above Hyperparameters i.e., penality score will be found using cross validation through hyper parameter tuning i.e., grid or random search.</li><li>All above variations of regularizations works pretty well, as it is simple data with single predictor. It will show significant differences, when there many predictors and huge data.</li><li>In general regularization works for, Prevents Overfitting: Regularization discourages complex models that might fit the training data too well, thus helping the model generalize better to new data.</li><li>Simplifies Models: By penalizing large coefficients, regularization can lead to simpler models that are easier to interpret and use.</li><li>Improves Stability: Regularization leads to more stable models where predictions are less sensitive to small changes in the training data.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f6d2b605eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Descent Variants Explained: Enhancing Loss Function Optimization]]></title>
            <link>https://medium.com/@rakesh.ganya28/gradient-descent-variants-explained-enhancing-loss-function-optimization-cf0f5a2cb2ae?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf0f5a2cb2ae</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 05:10:38 GMT</pubDate>
            <atom:updated>2024-07-04T05:14:36.148Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, different types of gradient descent algorithms will be discussed and its significance in reducing loss for estimating best coefficients during training loop.</p><p>Before we jump in, have a quick brush up, what does it mean by Gradient Descent in first place. Find the brief explanation of Gradient Descent from my previous article.</p><h4>Classical Gradient Descent (GD)</h4><p><a href="https://medium.com/@rakesh.ganya28/optimizing-linear-regression-loss-function-using-gradient-descent-algorithm-5f5efe72aec0">Optimizing Linear Regression Loss Function Using Gradient Descent Algorithm</a></p><p>Types of Gradient Descent Algorithms are:-</p><ul><li><strong>Stochastic Gradient Descent (SGD)</strong></li><li><strong>Batch Gradient Descent (BGD)</strong></li><li><strong>Coordinate Descent (CD)</strong></li></ul><p>Lets understand key difference between these algorithms using sample data.</p><pre>df = pd.DataFrame({<br>    &quot;Product_Sell&quot;: [10, 15, 18, 22, 26, 30, 5, 31],<br>    &quot;Revenue_Generation&quot;: [1000, 1400, 1800, 2400, 2600, 2800, 700, 2900]<br>})<br><br>X = df[&#39;Product_Sell&#39;].values<br>y = df[&#39;Revenue_Generation&#39;].values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*kRpdxcmr_yFRhpE7kAzRQg.png" /><figcaption>Sample Data</figcaption></figure><h3><strong>Stochastic Gradient Descent (SGD)</strong></h3><ul><li><strong>Concept:</strong> A faster variant of GD for large datasets. It updates parameters after processing each individual training example. It can be more susceptible to noise due to frequent updates.</li><li><strong>Process:</strong> Updates parameters based on the error for a <strong>single data point</strong> per iteration.</li></ul><p>· <strong>Update Formula: </strong>Same as GD formula, but the gradient is calculated using the error for a <strong>single training example</strong> chosen randomly in each iteration.</p><blockquote><strong>parameter_new = parameter_old - learning_rate * (gradient_from_single_example)</strong></blockquote><p><em>Initial Parameters</em></p><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}&quot;)</pre><p><em>Training</em></p><pre># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    # Randomly Suffle Data<br>    indices = np.random.permutation(X.shape[0])<br>    # print(&quot;indices: &quot;, indices)<br>    X_suffled = X[indices]<br>    y_suffled = y[indices]<br><br>    # Selecting random data point<br>    X_i = X_suffled[0]<br>    y_i = y_suffled[0]<br>    print(f&quot;X_i: {X_i}; y_i: {y_i}&quot;)<br><br>    # Predict <br>    y_pred = predict(X_i, m, b)<br>    pred_error = y_i - y_pred<br><br>    # Compute loss<br>    loss = np.mean(pred_error ** 2)<br><br>    # Simplified Derivatives of Loss Function<br>    m_gradient = (-2/n) * np.dot(pred_error, X_i) # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>    b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>    # Update latest weights and intercepts<br>    m = m - learning_rate * (m_gradient)<br>    b = b - learning_rate * (b_gradient)<br><br>    # Collect progress in each epoch<br>    weights.append(m)<br>    intercepts.append(b)<br>    preds.append(y_pred)<br>    losses.append(loss)<br><br>    # Print Progress<br>    print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*UJIC5DmA7B4H3VjzJDyX1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3Qsv-teVBx2Ei5Vijw0NQ.png" /><figcaption>Epoch wise Updates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWWN5f-8JEWGyygWIEk4_g.png" /><figcaption>Weights vs Loss over Epochs</figcaption></figure><p><em>Observations</em></p><ul><li>As we are finding gradient i.e., rate of change in loss w.r.t updated weights only on single data point, it will be way rougher &amp; more of inconsistent the weights updation happen initially in reducing the loss and then slowly becomes better to reduce loss. As single data provide way lesser data for better gradient calculation to update weights, so it takes more epochs to update to right weights to reduce loss.</li></ul><h3><strong>Batch Gradient Descent (BGD)</strong></h3><ul><li><strong>Concept:</strong> A compromise between GD and SGD. It updates parameters based on the error calculated for a small subset (mini-batch) of the training data, offering a balance between speed and stability.</li><li><strong>Process:</strong> Updates parameters based on the error for a <strong>mini-batch of data points</strong> per iteration.</li><li><strong>Update Formula: </strong>Same as GD formula, but the gradient is calculated using the error for a <strong>mini-batch of training examples</strong> chosen randomly in each iteration.</li></ul><blockquote>parameter_new = parameter_old - learning_rate * (average_gradient<strong>_over_mini_batch</strong>)</blockquote><p>Lets try different batch sizes and check how weights updates behaves.</p><h4>Case 1: Smaller Batch</h4><p><em>Initial Parameters</em></p><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br># Batch size<br>batch_size = 3<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}&quot;)</pre><p><em>Training</em></p><pre># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    # Randomly Suffle Data<br>    indices = np.random.permutation(X.shape[0])<br>    # print(&quot;indices: &quot;, indices)<br>    X_suffled = X[indices]<br>    y_suffled = y[indices]<br><br>    # Selecting random data point<br>    X_i = X_suffled[:batch_size]<br>    y_i = y_suffled[:batch_size]<br>    print(f&quot;X_i: {X_i}; y_i: {y_i}&quot;)<br><br>    # Predict <br>    y_pred = predict(X_i, m, b)<br>    pred_error = y_i - y_pred<br><br>    # Compute loss<br>    loss = np.mean(pred_error ** 2)<br><br>    # Simplified Derivatives of Loss Function<br>    m_gradient = (-2/n) * np.dot(pred_error, X_i) # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>    b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>    # Update latest weights and intercepts<br>    m = m - learning_rate * (m_gradient)<br>    b = b - learning_rate * (b_gradient)<br><br>    # Collect progress in each epoch<br>    weights.append(m)<br>    intercepts.append(b)<br>    preds.append(y_pred)<br>    losses.append(loss)<br><br>    # Print Progress<br>    print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ySZJFK1GREfMBQcB7lFN3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*On9NkDnk-wMZX1Yg_kv_HA.png" /><figcaption>Epoch wise Updates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3m_3olHIR3wZRGPW16wQPg.png" /><figcaption>Weights vs Loss over Epochs</figcaption></figure><p><em>Observations</em></p><ul><li>As we are finding gradient i.e., rate of change in loss w.r.t updated weights only on smaller batch size, it will be way rougher &amp; bit of inconsistent the weights updation happen initially in reducing the loss and then slowly becomes better to reduce loss. As mini batch size data provide lesser data for better gradient calculation to update weights, so it takes more epochs to update to right weights to reduce loss.</li></ul><h4>Case 1: Bigger Batch</h4><p><em>Initial Parameters</em></p><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br># Batch size<br>batch_size = 5<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}&quot;)</pre><p><em>Training</em></p><pre># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    # Randomly Suffle Data<br>    indices = np.random.permutation(X.shape[0])<br>    # print(&quot;indices: &quot;, indices)<br>    X_suffled = X[indices]<br>    y_suffled = y[indices]<br><br>    # Selecting random data point<br>    X_i = X_suffled[:batch_size]<br>    y_i = y_suffled[:batch_size]<br>    print(f&quot;X_i: {X_i}; y_i: {y_i}&quot;)<br><br>    # Predict <br>    y_pred = predict(X_i, m, b)<br>    pred_error = y_i - y_pred<br><br>    # Compute loss<br>    loss = np.mean(pred_error ** 2)<br><br>    # Simplified Derivatives of Loss Function<br>    m_gradient = (-2/n) * np.dot(pred_error, X_i) # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>    b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>    # Update latest weights and intercepts<br>    m = m - learning_rate * (m_gradient)<br>    b = b - learning_rate * (b_gradient)<br><br>    # Collect progress in each epoch<br>    weights.append(m)<br>    intercepts.append(b)<br>    preds.append(y_pred)<br>    losses.append(loss)<br><br>    # Print Progress<br>    print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*OCvrsrs8gZ59Z_CA2-PeeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77HwP9c6gxynMSuYJ7aMvw.png" /><figcaption>Epoch wise Updates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVlocfmOR7IKJxMiUFb2Jw.png" /><figcaption>Weights vs Loss over Epochs</figcaption></figure><p><em>Observations</em></p><ul><li>Bigger the batch size, smoother &amp; consistantly the weights updation happen in reducing the loss. As higher batch size provides more data for better gradient calculation to update weights.</li><li>It takes less epochs to update to right weights to reduce loss, as data to find correct gradient is higher.</li></ul><h3><strong>Coordinate Descent (CD)</strong></h3><ul><li><strong>Concept:</strong> An optimization algorithm that updates only one parameter (coordinate) at a time in the direction that minimizes the error function. It cycles through all parameters, updating each one individually until convergence.</li><li><strong>Process:</strong> Updates parameters <strong>one at a time</strong> by iteratively minimizing the function with respect to each parameter while holding others fixed.</li><li><strong>Update Formula: </strong>The specific formula can vary depending on the chosen update rule, but it involves calculating the gradient for a single parameter and updating it based on the negative gradient and learning rate. One common approach is cyclic coordinate descent, where parameters are updated in a fixed order.</li></ul><blockquote><strong>parameter_new = parameter_old - learning_rate * gradient_of_chosen_parameter</strong></blockquote><p><em>Initial Parameters</em></p><pre># Parameters Assignments<br>m = 0 # coefficients <br>b = 0 # bias / intercept<br><br>def predict(x, m, b):<br>    return m*x + b<br><br># Hyperparameters<br>learning_rate = 0.001<br># Epochs / Iterations to update weights<br>epochs = 100<br># Number of training samples<br>n = len(X)<br># Predictors List<br>predictors = [&quot;Product_Sell&quot;]<br><br>print(f&quot;Initial Assignments --&gt; weight: {m: .2f}; bias: {b: .2f}; learning rate: {learning_rate: .4f}; epochs: {epochs}&quot;)</pre><p><em>Training</em></p><pre># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br># Stochastic Gradient Descent <br>for epoch in range(epochs): # Training/Optimization Loop to find best parameters which reduces loss <br>    for predictor in predictors: # Looping through each predictor<br><br>        # Selecting Predictor<br>        X_i = df[predictor].values<br><br>        # Predict <br>        y_pred = predict(X_i, m, b)<br>        pred_error = y - y_pred<br><br>        # Compute loss<br>        loss = np.mean(pred_error ** 2)<br><br>        # Simplified Derivatives of Loss Function<br>        m_gradient = (-2/n) * np.dot(pred_error, X_i) # Matrix multiplication (multiply -&gt; sum) like weights * input in mx + c.<br>        b_gradient = (-2/n) * np.sum(pred_error) # list summation <br><br>        # Update latest weights and intercepts<br>        m = m - learning_rate * (m_gradient)<br>        b = b - learning_rate * (b_gradient)<br><br>        # Collect progress in each epoch<br>        weights.append(m)<br>        intercepts.append(b)<br>        preds.append(y_pred)<br>        losses.append(loss)<br><br>        # Print Progress<br>        print(f&quot;m: {m:.2f}, b:{b:.2f}, pred: {y}, loss: {loss: .2f}&quot;)<br><br># Final Parameters<br>print(f&quot;Final Parameters --&gt; m: {m: .2f}, b: {b: .2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Hv8iA-KJtiscUBgJg7l0uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXLX_CL0zLvUoTXm7BnssQ.png" /><figcaption>Epoch wise Updates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI8__rqzpcwfCy-y6k8ZWw.png" /><figcaption>Weights vs Loss over Epochs</figcaption></figure><p><em>Observations</em></p><ul><li>As we have single predictor, so it is similar to our earlier Gradient Descent algorithm implementation.</li><li>It takes less epochs to update to right weights to reduce loss, as data to find correct gradient is higher.</li></ul><p><strong>Final Key Points</strong></p><ul><li>For small datasets, GD might be sufficient.</li><li>For large datasets, SGD or mini-batch GD are preferred, with mini-batch GD often offering a good balance.</li><li>Coordinate descent can be useful for specific problems with efficient single-parameter updates.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf0f5a2cb2ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Linear Regression Loss Function Using Gradient Descent Algorithm]]></title>
            <link>https://medium.com/@rakesh.ganya28/optimizing-linear-regression-loss-function-using-gradient-descent-algorithm-5f5efe72aec0?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5efe72aec0</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 07:22:35 GMT</pubDate>
            <atom:updated>2024-07-01T07:22:35.437Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will explore the concepts of Gradient, Maxima and Minima, Loss Function, Gradient Descent, and Optimization to achieve the best parameter estimates.</p><h3>What is Gradient?</h3><p>It is the slope (or) rate of change happens between two y values(y1 → y2) of the function [let’s say f(x)] w.r.t x changes from x1-&gt;x2.</p><p>To find this, we perform differentiation, which is part of the calculus study. There are two types of differentiation. i.e.,</p><p><em>Type 1</em></p><ul><li>If x is scalar i.e., x = [1, 2, 4..] Then we perform → Single Variable Differentiation, also called as <strong><em>Single Variable Derivative/Gradient</em></strong>.</li><li>In other words, how f(x) rate of change happens w.r.t x.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*pRlaEcScUddxQCIauq0hgA.png" /><figcaption>Scalar Derivative Notation</figcaption></figure><p><em>Type 2</em></p><ul><li>If x is vector i.e., x1 = [1, 2, 4..]; x2 = [4, 3, 6..]; x3 = [4, 12, 43..];… Then we perform → Multi Variable Differentiation, also called as <strong><em>Multiple Variables Derivative/Gradient</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*uC1TvOxUktQMlTw7a0cusg.png" /><figcaption>Vector Derivative Notation</figcaption></figure><ul><li>In other words, how f(xi) rate of change happens w.r.t x1, x2, x3… individually. This is also called as <strong><em>Partial Differentiation</em></strong>, as each xi affects f(xi) individually, we try to find rate of change or slope of f(xi) individually on each xi.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*pQhYW345hiQTH-gS40dhCQ.png" /><figcaption>Partial Derivative Notation</figcaption></figure><p>Lets understand how slope is calculated in any simple function of data.</p><p><strong>Sample Data</strong></p><blockquote>Function(Cubic Polynomial): <em>f(x^3−3x) / y</em></blockquote><pre># Generate 30 samples between -2 and 2<br>x = np.linspace(-2, 1.2, 32)<br>print(&quot;x values:&quot;, x)<br><br># Define the cubic polynomial function<br>y = x**3 - 3*x # y is also called as f(x)<br>print(&quot;y values:&quot;, y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*pZJQb_C3ugqsxgKBr0Up4Q.png" /></figure><pre># Define the analytical derivative of the cubic polynomial function<br>y_prime = 3*x**2 - 3<br><br># Midpoints for finite difference derivative plotting<br>midpoints_x = (x[:-1] + x[1:]) / 2<br><br># Plotting the function and its derivatives<br>sns.set_style(&#39;darkgrid&#39;)<br>plt.figure(figsize=(24, 8))<br><br># Original function<br>plt.plot(x, y, label=&#39;y = x^3 - 3x&#39;, marker=&#39;o&#39;)<br># Analytical derivative<br>plt.plot(x, y_prime, label=&quot;Analytical Derivative (y&#39;)&quot;, linestyle=&#39;--&#39;, color=&#39;red&#39;)<br># Finite difference derivative<br>plt.scatter(midpoints_x, finite_diff_derivatives, label=&quot;Finite Difference Derivative&quot;, color=&#39;green&#39;)<br><br># Marking the points<br>plt.scatter(x, y, color=&#39;red&#39;)<br><br># Annotating the points and the slopes<br>for i, (px, py) in enumerate(zip(x, y)):<br>    plt.annotate(f&quot;({px:.1f}, {py:.2f})&quot;, (px, py), textcoords=&quot;offset points&quot;, xytext=(0,10), ha=&#39;center&#39;, fontsize=8)<br><br>for i in range(len(midpoints_x)):<br>    plt.annotate(f&quot;Slope: {finite_diff_derivatives[i]:.2f}&quot;, <br>                (midpoints_x[i], finite_diff_derivatives[i]), <br>                textcoords=&quot;offset points&quot;, <br>                xytext=(0,10 if i % 2 == 0 else -15), <br>                ha=&#39;center&#39;, <br>                color=&#39;blue&#39;, <br>                fontsize=8)<br><br>plt.xlabel(&#39;x values&#39;, fontsize=14)<br>plt.ylabel(&#39;y/f(x) values&#39;, fontsize=14)<br>plt.title(&#39;Cubic Polynomial Function and Derivatives&#39;, fontsize=16)<br>plt.legend()<br>plt.grid(True)<br>plt.show()<br><br># Displaying the values<br>print(&quot;Finite Difference Derivatives between all consecutive points:&quot;, finite_diff_derivatives)<br>print(&quot;Analytical Derivative values:&quot;, y_prime)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK5TJZownE2dW7b91EHdPw.png" /></figure><p><strong>Observation</strong></p><ul><li>Here we can observe, that when ever the adjacent two y values y1, y2 are flat or having zero angle to the x-axis, then its slope would be near to zero.</li><li>Similarly in y1-&gt;y2, when y2 &gt; y1, then results in positive slope and in vice-versa case i.e., y2 &lt; y1 results in negative slope. All these are based on gradient formula (Tangent/Hypotenuse line formed between two points and its angle to x-axis. In right angle triangle this methodology helps to find the angle / slope, which we are using same here).</li><li>Also computed using formula</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*sOWmbhmYhtsqSXQuhaV_EQ.png" /><figcaption>Gradient / Derivative / Slope Between Two Points</figcaption></figure><h3><strong>What are Minima, Maxima?</strong></h3><h4>Minima</h4><ul><li><strong>Definition</strong>: A minima is a point where the function’s value is lower than at all nearby points.</li><li><strong>In Gradient Descent</strong>: When performing gradient descent, you aim to find the minima of the loss function. This means you’re looking for the point where the function has the lowest possible value, indicating the best fit for your model.</li></ul><h4>Maxima</h4><ul><li><strong>Definition</strong>: A maxima is a point where the function’s value is higher than at all nearby points.</li><li><strong>In Gradient Descent</strong>: While gradient descent primarily focuses on finding minima (since we want to minimize the loss), understanding maxima is also important. Maxima represent points where the function reaches its highest value, which is useful in different contexts, like when performing gradient ascent for maximizing a function.</li></ul><p>Analogy</p><ul><li><strong>Minima</strong>: Think of it as the lowest point in a valley.</li><li><strong>Maxima</strong>: Think of it as the highest point on a hill.</li></ul><p><strong>Local Minima</strong>: In other words, local minima is the place where slope between current and next point comes to nearly to zero and then suddenly started increasing i.e., on this data point where first derivative is ~ 0 and second derivative i.e., again derivative this point with next point, the slope begins to increase again.</p><p><strong>Local Maxima</strong>: It is the place where slope between current and next point comes to nearly to zero and then suddenly started decreasing i.e., on this data point where first derivative is ~ 0 and second derivative i.e., again derivative this point with next point, the slope begins to decrease again.</p><p>Intuitively, seeing below plot w.r.t above makes understanding clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nt65kxoOhut66mn3DBQNmg.png" /><figcaption>Minima and Maxima</figcaption></figure><h3>What is Gradient Descent and Gradient Ascent algorithms?</h3><p>Gradient descent and gradient ascent are optimization algorithms commonly used in machine learning and other fields. They both rely on the concept of gradients to find the minimum or maximum of a function.</p><p><strong>Gradient Descent:</strong></p><ul><li><strong>Goal:</strong> Find the minimum value (lowest point) of a function.</li><li><strong>Concept:</strong> Imagine a hiker lost in a foggy mountain range. They want to reach the bottom of a valley (minimum point). Gradient descent helps them navigate by taking small steps in the direction that goes downhill the steepest (negative gradient).</li><li><strong>Applications:</strong> Training machine learning models like linear regression, logistic regression, and neural networks.</li></ul><p><strong>Gradient Ascent:</strong></p><ul><li><strong>Goal:</strong> Find the maximum value (highest point) of a function.</li><li><strong>Concept:</strong> Similar to the hiker analogy, but instead of finding the valley, they want to reach the mountain peak (maximum point).</li><li><strong>Applications:</strong> Less common than gradient descent, but can be used in certain optimization problems where maximizing a function is desired.</li></ul><h3><strong>Gradient Descent Algorithm</strong></h3><blockquote><strong>Linear Regression : Estimating Coefficients Using Squared Loss Function And Solving Loss Function with : GD[ Gradient Descent] Algorithm</strong></blockquote><p>For linear regression, considering the model with single predictor is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*f5YCy4l4toGImzNyVSlL5Q.png" /><figcaption>Simple Linear Regression</figcaption></figure><p>In case wanted to brush up the linear regression model, about the main regression concepts. Look below in my previous post, which covers all major topics in linear regression.</p><p><a href="https://medium.com/@rakesh.ganya28/from-data-to-predictions-understanding-linear-regression-94dbefb39c22">From Data to Predictions: Understanding Linear Regression</a></p><p>Gradient Descent is an optimization algorithm used to minimize a loss function by iteratively moving in the direction of steepest descent (i.e., achived by using negative the previous weights with small steps) as defined by the negative of the gradient. It’s commonly used to optimize machine learning algorithms, including linear regression.</p><p>In other words,</p><ul><li><strong>Concept</strong>: The fundamental algorithm. It iteratively moves in the direction of the steepest descent (negative gradient) of the function, adjusting parameters (weights and bias) to minimize error using weights and intercept update function.</li><li><strong>Update Formula</strong>:</li></ul><blockquote>parameter_new = parameter_old — learning_rate *(average_gradient_over_all_data)</blockquote><p>learning_rate controls step size, and gradient is the partial derivative of the error function with respect to the parameter.</p><ul><li><strong>Process</strong>: Considers the error for all training examples in each iteration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*_BxpXkXH7t5pbmoXpC2tNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*whY-XBzmdTNKrsgLSv6aWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*_QZrKWL3S9mP0Xbov8Db6w.png" /></figure><p><strong>Sample Data</strong></p><pre># Sample Data<br>data = {<br>    &quot;Product_Sell&quot;: [10, 15, 18, 22, 26, 30, 5, 31],<br>    &quot;Revenue_Generation&quot;: [1000, 1400, 1800, 2400, 2600, 2800, 700, 2900]<br>}<br><br>df = pd.DataFrame(data)<br>X = df[&#39;Product_Sell&#39;].values<br>y = df[&#39;Revenue_Generation&#39;].values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*knAXqpa21S5lo53c6Vlpmg.png" /></figure><p>Lets try different cases with random weights and understand how much loss initial weight provides and how initial rate of change value in loss function w.r.t initial weights helps in weight updation equation, in further reducing of rate of change in loss function.</p><blockquote>Note:</blockquote><blockquote>Less rate of change / slope in loss function w.r.t weights means, less prediction error occurring with these weights.</blockquote><blockquote>High rate of change / slope in loss function w.r.t weights means, higher prediction error occurring with these weights.</blockquote><p><strong>Case 1:</strong></p><blockquote><strong>Initial Weights, as</strong></blockquote><blockquote>m = 0 # coefficient (slope)</blockquote><blockquote>b = 0 # intercept (bias)</blockquote><pre># Standardize X for better optimization performance<br><br># Initialize Parameters<br>m = 0  # coefficient (slope)<br>b = 0  # intercept (bias)<br>n = len(X)  # number of data points<br><br># Function to compute the predictions<br>def predict(X, m, b):<br>    return m * X + b<br><br># Hyperparameters Constants<br>learning_rate = 0.001 # For slower steps size<br># iterations = 120<br>epochs = 100<br><br># Lists to store weights, losses<br>weights = []<br>intercepts = []<br>losses = []<br>preds = []<br><br>print(f&#39;Initial Weights and Intercept: m = {m:.4f}, b = {b:.4f}&#39;)<br><br># Gradient Descent (GD) Algorithm<br>for epoch in range(epochs):<br>    # Compute Prediction Error<br>    y_pred = predict(X, m, b)<br>    error = y - y_pred<br><br>    # Computer loss with weights and intercept<br>    loss = np.mean(error ** 2)<br><br>    m_gradient = (-2/n) * np.dot(error, X) # Dot Product (Matrix Multiplication, then summation) # As per above derived derivative formula <br>    b_gradient = (-2/n) * np.sum(error) # As per above derived derivative formula<br><br>    # Update latest weights and intercepts<br>    m = m - learning_rate * m_gradient # latest weights <br>    b = b - learning_rate * b_gradient # latest intercept<br><br>    # Collect weights, intercept and losses<br>    weights.append(m)<br>    intercepts.append(b)<br>    preds.append(y_pred)<br>    losses.append(loss)<br><br>    print(f&#39;Epoch {epoch}: m = {m:.4f}, b = {b:.4f}, Loss = {loss:.4f}&#39;)<br><br># Final parameters<br>print(f&#39;Final parameters: m = {m:.4f}, b = {b:.4f}&#39;)        </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*ELd2wAzN55vaAdsgY5c71w.png" /><figcaption>Parameter Estimation in Epochs in terms of reducing Loss</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI8__rqzpcwfCy-y6k8ZWw.png" /></figure><p><strong>Loss vs. Weight during Gradient Descent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuvyqviHVr-HzDbngt92Rg.png" /><figcaption>Initial weight location and then continuous updation in terms to reduce loss</figcaption></figure><p><strong>Case 2:</strong></p><blockquote><strong>Initial Weights, as</strong></blockquote><blockquote>m = -100 # coefficient (slope)</blockquote><blockquote>b = -100 # intercept (bias)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*jEepFDVMCJU9Hnwfh_Nnhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzRCJ2_-b33KN2UKpcQTwQ.png" /></figure><p><strong>Loss vs. Weight during Gradient Descent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeO-1w_UgJsVjBnMMym8qA.png" /><figcaption>Initial weight location and then continuous updation in terms to reduce loss</figcaption></figure><p><strong>Case 3:</strong></p><blockquote><strong>Initial Weights, as</strong></blockquote><blockquote>m = 300 # coefficient (slope)</blockquote><blockquote>b = 300 # intercept (bias)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*UYndqbVGThhAdIYUg9LKyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1N2_9ICTwpuIQoc2EIy_Q.png" /></figure><p><strong>Loss vs. Weight during Gradient Descent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHealABEbjcxVuBHy14mTA.png" /><figcaption>Initial weight location and then continuous updation in terms to reduce loss</figcaption></figure><p><strong>Key Observations</strong></p><ul><li>We can see above, that <strong>Gradient Descent </strong>algorithm properly estimated Linear Regression parameters i.e., coefficient and intercept to fit most of the data points.</li><li>When we assigned initial weights and intercepts, as m=0 and b=0. The initial loss rate of change/slope value w.r.t this given weight was high(it is single value). The first loss value using initial weight itself won’t mentioned the direction, using this weight and computing through update equation defines next step i.e., new weight, this tells the direction of the weights w.r.t optimal w*, in which it going to continue to decrease/increase in weights to reduce error. As mentioned in above sketch.</li><li>Then based on smart weight update function i.e., gradient descent(means it try to go in down direction irrespective of left/right side of the hill), then it slowly goes down by reducing slope height by minus its initial slope height * step size(meaning how much big jump we wanted to go down). Like this its go down to optimal w*. Where with w* the slope height/rate of change in loss function is near to zero. So prediction error doesn&#39;t have any huge potential errors.</li></ul><blockquote>Note: This is the simple curve is related to weights updation function, to see how each time weight update changes in loss function value. And helps to find optimal w*. Just like elbow curve in clustering. But here we go down direction by using its Initial rate of change/slope height and slowing reducing it.</blockquote><ul><li>In all case random weight cases, the weight update equation understood rate of change error / slope height in loss function and started decreasing/increasing the weight in order to reduce this rate of change/error close to zero in loss function. And it proves it is capable of handle initial random selection of weights and make it slowly correct to reduce error through small steps.</li><li>This is how, Gradient Descent works and helps to find optimal w* and intercept in regression model to make least loss value.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5efe72aec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis Efficiency: Manual Approaches vs. Hugging Face Pretrained Models]]></title>
            <link>https://medium.com/@rakesh.ganya28/sentiment-analysis-efficiency-manual-approaches-vs-hugging-face-pretrained-models-622212883263?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/622212883263</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 05:27:07 GMT</pubDate>
            <atom:updated>2024-06-22T05:27:07.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Sentiment Analysis</p><h3>What is Sentiment Analysis?</h3><p>Sentiment analysis is a natural language processing (NLP) technique used to determine the emotional tone behind a body of text. It aims to identify and extract subjective information from text, such as opinions, attitudes, and emotions. This technique is often used in various applications, such as analyzing customer feedback, monitoring social media, and evaluating product reviews.</p><h3><strong>What is Hugging Face?</strong></h3><ul><li>Hugging Face provides open-source libraries and tools, particularly the Transformers library, which is a popular toolkit for building applications using natural language processing (NLP). This library simplifies tasks like building chatbots or analyzing text. Even though it focuses on NLP, Hugging Face also offers tools for computer vision and audio processing.</li><li>These are like pre-made building blocks that you can use in your own projects. Imagine you want to build a system to classify spam emails. Instead of starting from scratch, you can use a pre-trained model that already knows the difference between spam and regular emails. Hugging Face offers a vast collection of these models for various tasks.</li></ul><h3>How to Setup Hugging Face?</h3><ul><li>Installation steps are mentioned in below official document path : <a href="https://huggingface.co/docs/transformers/en/installation">https://huggingface.co/docs/transformers/en/installation</a></li><li>Below are the main packages, which are used to make Hugging Face pretrained models run.</li></ul><blockquote><strong>Torch</strong></blockquote><blockquote>Torch is an open-source machine learning library originally developed by Facebook’s AI Research lab. It is designed for deep learning and is highly popular in the data science community, especially for tasks involving neural networks. The library provides a range of tools and functions to create and train complex models efficiently.</blockquote><blockquote><strong>NumPy</strong></blockquote><blockquote>NumPy (Numerical Python) is a fundamental library in Python for scientific computing and data science. It provides powerful tools for working with multidimensional arrays and matrices, which are essential building blocks for many data science tasks.</blockquote><blockquote><strong>TensorFlow</strong></blockquote><blockquote>TensorFlow is a powerful open-source library developed by Google for numerical computation and large-scale machine learning. It is designed for numerical computation using data flow graphs, where nodes represent mathematical operations, and edges represent the multidimensional data arrays (tensors) that flow between them. It provides a flexible framework for building, training, and deploying a wide range of machine learning models. TensorFlow is widely used for developing and training machine learning and deep learning models, particularly neural networks.</blockquote><blockquote><strong>tf-keras</strong></blockquote><blockquote>It also commonly referred to as Keras with TensorFlow, is a high-level API built on top of TensorFlow that simplifies the process of building and training deep learning models. Keras is a high-level deep learning API written in Python, which runs on top of lower-level deep learning frameworks such as TensorFlow, Theano, or Microsoft Cognitive Toolkit (CNTK). It was developed with a focus on enabling fast experimentation and easy implementation of neural networks.</blockquote><blockquote><strong>Flax</strong></blockquote><blockquote>Flax is a relatively new but powerful deep learning library built on top of JAX, a high-performance numerical computation library in Python.</blockquote><blockquote><strong>Transformers</strong></blockquote><blockquote>Transformers are a specific type of neural network architecture that have revolutionized the field of Natural Language Processing (NLP) in data science.</blockquote><blockquote>Sentiment Prediction: Hugging Face Pretrained Model</blockquote><h4><strong><em>Import Libraries</em></strong></h4><pre>import pandas as pd<br>import warnings<br>from transformers import pipeline<br>from IPython.display import display, HTML<br><br>warnings.filterwarnings(&quot;ignore&quot;)</pre><h4><strong><em>Sample Data</em></strong></h4><pre>df = pd.DataFrame({&quot;Restaurant_Reviews&quot;: [&quot;Food taste is good :-)&quot;, <br>                                        &quot;Food taste is bad :-(&quot;,<br>                                        &quot;Food served late.&quot;,<br>                                        &quot;Food is good, but price is expensive.&quot;, <br>                                        &quot;Staff are not friendly&quot;]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*IWchrr54Yg4jNk5MqddDHA.png" /></figure><h4><strong><em>Import Hugging Face: Pretrained Model</em></strong></h4><pre>classifier = pipeline(&quot;sentiment-analysis&quot;) # It loads default sentiment analysis model from Hugging Face Repo</pre><h4><strong><em>Predict Sentiment</em></strong></h4><pre>def get_setiment_analysis(data):<br>    res = classifier(data)<br>    return res<br><br>df[&quot;Sentiment_Prediction&quot;] = df[&quot;Restaurant_Reviews&quot;].apply(get_setiment_analysis)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*RzgHMnYVO5h92d4tKTpBlw.png" /><figcaption>Sentiment Predictions</figcaption></figure><p>Observation</p><ul><li>It predicted mostly correctly and given correct classification of sentiment on given restaurant reviews, but there are few wrong predictions too i.e., Food served late. [{‘label’: ‘POSITIVE’, ‘score’: 0.9620344042778015}]. Where we may need to take care little about data pre-processing steps or compare with other pretrained model.</li><li>Here, the pretrained model took care of the whole pre-processing and feature engineering tasks, which takes most of the time from manual training setup.</li><li>So, I believe, in small use cases like above, using readily available pretrained would be one of the better options to quickly start, which can be further customised based on our objectives.</li></ul><blockquote>Sentiment Prediction: Manual Approach Model</blockquote><p>In this approach we will be using below two special packages predominantly.</p><blockquote><strong>NLTK</strong></blockquote><blockquote>NLTK, or the Natural Language Toolkit, is a comprehensive library in Python used for working with human language data (text). It provides easy-to-use interfaces to over 50 corpora and lexical resources, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and more.</blockquote><blockquote><strong>Textblob</strong></blockquote><blockquote>TextBlob is a free, open-source Python library designed specifically for simplifying common Natural Language Processing (NLP) tasks. It offers a user-friendly interface built on top of NLTK (Natural Language Toolkit) to perform essential text analysis operations, tasks such as part-of-speech tagging, noun phrase extraction, sentiment analysis, classification, translation, and more.</blockquote><h4><strong><em>Import Libraries</em></strong></h4><pre>import pandas as pd<br>import numpy as np<br>import re<br>import nltk<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import warnings<br>from nltk.tokenize import word_tokenize<br>from nltk import pos_tag<br>from nltk.corpus import stopwords, wordnet<br>from nltk.stem import PorterStemmer, WordNetLemmatizer<br>from textblob import TextBlob<br>from wordcloud import WordCloud<br>from IPython.display import display, HTML<br><br># Loads pretrained models for tokenization<br>nltk.download(&#39;punkt&#39;)<br># Loads pretrained models for part-of-speech tagging<br>nltk.download(&#39;averaged_perceptron_tagger&#39;)<br># Stopwords are words that are frequently occurring in a language but do not carry significant meaning on their own in the context of text analysis, <br># such as &quot;the&quot;, &quot;a&quot;, &quot;an&quot;, &quot;in&quot;, &quot;on&quot;, &quot;of&quot;, etc. <br>nltk.download(&quot;stopwords&quot;)<br># WordNet is a lexical database designed to mimic the human lexical memory. It organizes English words into sets of Synonyms (Synsets), Antonyms, Hypernyms ...<br>nltk.download(&#39;wordnet&#39;)<br><br>warnings.filterwarnings(&quot;ignore&quot;)<br>%matplotlib inline</pre><h4><strong><em>Sample Data</em></strong></h4><pre>df = pd.DataFrame({&quot;Restuarant_Reviews&quot;: [&quot;Food taste is good :-)&quot;, <br>                                        &quot;Food taste is bad :-(&quot;,<br>                                        &quot;Food served late.&quot;,<br>                                        &quot;Food is good, but price is expensive.&quot;, <br>                                        &quot;Staff are not friendly&quot;]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Rl0TSmyRgHENOCsDF30egw.png" /></figure><h4><strong><em>Preprocessing</em></strong></h4><blockquote><strong><em>Step 1: Removing Special Characters and Symbols from String</em></strong></blockquote><pre>def clean_text(text):<br>    text = re.sub(&#39;[^A-Za-z]+&#39;, &#39; &#39;, text)<br>    return text<br><br>df[&quot;Cleaned_Data&quot;] = df[&quot;Restuarant_Reviews&quot;].apply(clean_text)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*q_nIUsyxSZ1wUYb4uyBzLQ.png" /></figure><blockquote><strong>Step 2: Tokenization</strong></blockquote><blockquote>Tokenization is the process of breaking the text into smaller pieces called Tokens.</blockquote><blockquote>It can be performed at sentences(sentence tokenization) or word level(word tokenization)</blockquote><pre>def tokenize(text):<br>    text = word_tokenize(text)<br>    return text<br><br>df[&quot;Tokenized_Data&quot;] = df[&quot;Cleaned_Data&quot;].apply(tokenize)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*ekNOCWsaqphIs-He1lrGhg.png" /></figure><blockquote><strong>Step 3: Stop Words Removal</strong></blockquote><blockquote>Stopwords in English are words that carry very little useful information.</blockquote><blockquote>We need to remove them as part of text preprocessing. nltk has a list of stopwords of every language.</blockquote><pre>stop_words_list = [x for x in stopwords.words(&#39;english&#39;) if x.lower() != &quot;not&quot;]<br><br>def remove_stop_words(text):<br>    text = [token for token in text if token.lower() not in stop_words_list]<br>    return text<br><br>df[&quot;Stop_Words_Removed_Data&quot;] = df[&quot;Tokenized_Data&quot;].apply(remove_stop_words)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-xl5oUjTcZ4cZlVYXFHNQ.png" /></figure><blockquote><strong>Step 4: Enrichment — POS tagging</strong></blockquote><blockquote>Parts of Speech (POS) tagging is a process of converting each token into a tuple having the form (word, tag).</blockquote><blockquote>POS tagging essential to preserve the context of the word and is essential for Lemmatization.</blockquote><pre>def pos_tagging(text):<br>    text = nltk.pos_tag(text)<br>    return text<br><br>df[&quot;POS_Tagged_Data&quot;] = df[&quot;Stop_Words_Removed_Data&quot;].apply(pos_tagging)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoGsOwlmXavNTHZNa5phrQ.png" /></figure><blockquote><strong>Step 5: Obtaining the stem words</strong></blockquote><blockquote>A stem is a part of a word responsible for its lexical meaning.</blockquote><blockquote>The two popular techniques of obtaining the root/stem words are</blockquote><blockquote>- Stemming</blockquote><blockquote>- Lemmatization.</blockquote><blockquote>The key difference is Stemming often gives some meaningless root words as it simply chops off some characters in the end.</blockquote><blockquote>Lemmatization gives meaningful root words, however, it requires POS tags of the words</blockquote><ul><li>Stemming</li></ul><pre># Intialise<br>stemmer = PorterStemmer()<br><br># Stemming<br>tokens_with_stems = [stemmer.stem(token) for token in sample_tokens]<br>tokens_with_stems</pre><ul><li>Lemmatization</li></ul><pre># POS tagger dictionary<br>pos_map = {<br>    &#39;NN&#39;: wordnet.NOUN,<br>    &#39;NNP&#39;: wordnet.NOUN,<br>    &#39;VBD&#39;: wordnet.VERB,<br>    &#39;JJ&#39;: wordnet.ADJ,<br>    &#39;RB&#39;: wordnet.ADV,<br>}<br><br># Intialize<br>lemmatizer = WordNetLemmatizer()<br><br># Lemmatization<br>lemmatizer.lemmatize(&quot;Food&quot;, wordnet.NOUN)<br><br>def lemmatize(data):<br>    lemmatited_tokens = []<br>    for word, pos_tag in data:<br>        # print(word, pos_tag)<br>        wordnet_pos = pos_map.get(pos_tag, wordnet.NOUN) # Default to NOUN if POS tag not in map<br>        lemmatized_word = lemmatizer.lemmatize(word, pos=wordnet_pos)<br>        lemmatited_tokens.append(lemmatized_word)<br>    # print(lemmatited_tokens)<br>    return &quot; &quot;.join(lemmatited_tokens)<br>        <br>df[&quot;Lemmatised_Data&quot;] = df[&quot;POS_Tagged_Data&quot;].apply(lemmatize)        </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtsrnAenWx-Qj5OSUamUQw.png" /></figure><blockquote><strong>Sentiment Prediction [Text Blob]</strong></blockquote><blockquote>TextBlob is a Python library for processing textual data.</blockquote><blockquote>It provides a consistent API for diving into common natural language processing (NLP) tasks such as part-of-speech tagging, noun phrase extraction, sentiment analysis, and more.</blockquote><blockquote>The two measures that are used to analyze the sentiment are:</blockquote><blockquote>- `Polarity` — talks about how positive or negative the opinion is</blockquote><blockquote>- `Subjectivity` — talks about how subjective the opinion is TextBlob(text).sentiment gives us the Polarity, Subjectivity values.</blockquote><blockquote>Polarity ranges from -1 to 1 (1 is more positive, 0 is neutral, -1 is more negative)</blockquote><blockquote>Subjectivity ranges from 0 to 1(0 being very objective and 1 being very subjective)</blockquote><pre># Sentiment Score Using : Polarity &amp; Subjectivity<br>def get_subjectivity_score(text):<br>    return TextBlob(text).sentiment.subjectivity<br><br>def get_polarity_score(text):<br>    return TextBlob(text).sentiment.polarity<br><br>def get_sentiment_score(score):<br>    if score &lt; 0:<br>        return &quot;Negative&quot;<br>    elif (score &gt; 0) and (score &lt; 0.3):<br>        return &quot;Neutral&quot;<br>    else:<br>        return &quot;Positive&quot;<br><br>df[&quot;Subjectivity&quot;] = df[&quot;Lemmatised_Data&quot;].apply(get_subjectivity_score)<br>df[&quot;Polarity&quot;] = df[&quot;Lemmatised_Data&quot;].apply(get_polarity_score)<br>df[&quot;Sentiment_Prediction&quot;] = df[&quot;Polarity&quot;].apply(get_sentiment_score)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdZhbwRYaM5iTcqQp-rYbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgGYjv7mDdVA3j7nkLuTrQ.png" /><figcaption>Predictions</figcaption></figure><pre># Combine all lemmatized text into a single string<br>text = &#39; &#39;.join(df[&#39;Lemmatised_Data&#39;].tolist())<br><br># Generate the word cloud<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(text)<br><br># Plot the word cloud<br>plt.figure(figsize=(10, 5))<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*Jb0DhQ-lzKqVcEDFYafoQQ.png" /><figcaption>Word Cloud: Predominant Words in Reviews Text</figcaption></figure><p>Observation</p><ul><li>In simple text data like above, after making all preprocessing steps.</li><li>Our model now can clearly predict the sentiment correctly.</li><li>In final, I believe both manual approach and pretrained model are important. So we can compare both or mix both to some extent, to get optimal predictions for our problem statement.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=622212883263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Data Handling: Pandas vs Polars with Apache Arrow Data Format Integration]]></title>
            <link>https://medium.com/@rakesh.ganya28/effective-data-handling-pandas-vs-polars-with-apache-arrow-data-format-integration-585898669325?source=rss-9055c60ca6a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/585898669325</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rakesh Ganya]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 20:10:00 GMT</pubDate>
            <atom:updated>2024-06-20T20:16:16.813Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Pandas vs Polars</strong></h4><h3>Pandas</h3><p>Pandas is one of the most widely used data manipulation libraries in Python. It provides data structures and functions needed to manipulate structured data seamlessly, especially for data analysis and data science.</p><blockquote><strong>Ease of Use:</strong></blockquote><ul><li>Intuitive and easy-to-use API for data manipulation.</li><li>Comprehensive indexing and slicing functionalities.</li><li>Handles missing data elegantly with fill and drop methods.</li></ul><blockquote><strong>Integration:</strong></blockquote><ul><li>Integrates well with other libraries like NumPy, SciPy, Matplotlib, and Scikit-learn.</li><li>Read/write support for various file formats (CSV, Excel, SQL, JSON, HDF5, etc.).</li></ul><blockquote><strong>Data Operations:</strong></blockquote><ul><li>Robust support for operations such as merging, joining, reshaping, pivoting, and aggregations.</li><li>Time series functionality, including date range generation and frequency conversion.</li></ul><blockquote><strong>Performance:</strong></blockquote><ul><li>Optimized for in-memory data structures but can struggle with very large datasets due to memory constraints.</li><li>Allows for custom types of operations via the apply method, which can be slower.</li></ul><h3>Polars</h3><p>Polars is a newer, high-performance DataFrame library designed for fast data processing. It is written in Rust and aims to provide efficient and parallelized data operations.</p><blockquote><strong>Performance:</strong></blockquote><ul><li>Built with performance in mind, leveraging Rust for low-level memory management and speed.</li><li>Excellent handling of large datasets that do not fit into memory.</li><li>Supports parallel execution of data operations, which can lead to significant speed improvements.</li></ul><blockquote><strong>Memory Efficiency:</strong></blockquote><ul><li>Uses Arrow’s in-memory format, which provides efficient memory use and interoperability with other systems.</li><li>Efficient handling of missing data and support for various data types, including nested types.</li></ul><blockquote><strong>Interoperability:</strong></blockquote><ul><li>Designed to work well with Arrow, allowing seamless integration with Arrow-compatible tools and formats.</li><li>Can interoperate with Pandas, allowing conversion between Polars and Pandas Data Frames.</li></ul><blockquote><strong>Use Cases:</strong></blockquote><ul><li>Particularly well-suited for tasks requiring high performance and efficient memory use.</li><li>Ideal for large-scale data processing and environments where speed is critical.</li></ul><h3>Apache Arrow Data Format</h3><p>Primarily used as a data exchange format for efficient data sharing between different tools in the data science ecosystem. Useful for transferring data between PySpark, Polars, Pandas, and other tools that support Arrow.</p><h3>Pandas Data Manipulation</h3><pre>import pandas as pd<br>import os<br><br># Input File Path<br>file_path = os.path.dirname(os.path.dirname(os.getcwd()))+&quot;\\EDA\\Data\\Play_Tennis.csv&quot;<br><br># Load Data<br>df = pd.read_csv(file_path)<br><br>print(df.info())<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzJZpoTdV-59ZQUnSV_BOw.png" /></figure><pre># Filter &amp; Select Columns<br>df_temp = df[df[&quot;Day&quot;].isin([&quot;D1&quot;, &quot;D2&quot;])][[&quot;Day&quot;,&quot;Play_Tennis&quot;]]<br>print(df_temp)<br><br># Group by Mean<br>df_temp = df.groupby([&quot;Outlook&quot;])[&quot;Ticket_Price&quot;].mean()<br>df_temp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*wnFSoJZnNUI9c4J7leDgbA.png" /></figure><h3>Polars Data Manipulation</h3><pre>import polars as pl<br>import pyarrow as pa<br>import pyarrow.parquet as pq<br><br>df = pl.read_csv(file_path)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5pQi9uB9i7wnoIExwkDBQ.png" /></figure><pre># Filter<br>df_temp = df.filter(pl.col(&quot;Day&quot;) == &quot;D1&quot;).select([pl.col(&quot;Day&quot;), pl.col(&quot;Play_Tennis&quot;)])<br>print(df_temp)<br><br># Group by<br># df_temp = df.groupby(&quot;Outlook&quot;).mean()[&quot;Ticket_Price&quot;]<br>df_temp = df.groupby(&quot;Outlook&quot;).agg(pl.col(&quot;Ticket_Price&quot;).mean())<br>df_temp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*jygov5xYbIJ-3ObeOtYmQA.png" /></figure><h3><strong>Convert Polars to Pandas Data Frame: [Using Backend Arrow Data Format]</strong></h3><pre># Convert the Polars DataFrame to an Arrow Table<br>arrow_table = df.to_arrow()<br># Convert the Arrow Table to a Pandas DataFrame<br>df_pandas = arrow_table.to_pandas()<br><br>print(df_pandas.info())<br>df_temp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*JuZja4wW2IWKSOTdLdOdsg.png" /></figure><h3><strong>Convert Pandas to Polars Data Frame: [Using Backend Arrow Data Format]</strong></h3><pre># Convert the Pandas DataFrame to an Arrow Table<br>arrow_table = pa.Table.from_pandas(df_pandas)<br><br># Convert the Arrow Table to a Polars DataFrame<br>df_polars = pl.from_arrow(arrow_table)<br><br>df_polars</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPc-ivBgrjhUnwzQIbpnZg.png" /></figure><h3>Final Take Aways</h3><ul><li>Like this, based on the project requirement, we can decide which processing library can be used.</li><li>And we can also mix some part of pre-processing or ETL process in polars and then shift less memory oriented tasks to pandas like above.</li><li>This way, we can able to use best features from all tools and can make Data Analytics solutions more robust.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=585898669325" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>