<?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 Mirza Abdul Rehman on Medium]]></title>
        <description><![CDATA[Stories by Mirza Abdul Rehman on Medium]]></description>
        <link>https://medium.com/@mirzaabdulrehman.ieee?source=rss-b9d68c20b1f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5iSugD8teBA0os52qhelfg.jpeg</url>
            <title>Stories by Mirza Abdul Rehman on Medium</title>
            <link>https://medium.com/@mirzaabdulrehman.ieee?source=rss-b9d68c20b1f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:48:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mirzaabdulrehman.ieee/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[Human Activity Recognition Using BiLSTM and Temporal Attention: A Deep Learning Approach]]></title>
            <link>https://medium.com/@mirzaabdulrehman.ieee/human-activity-recognition-using-bilstm-and-temporal-attention-a-deep-learning-approach-a1cbb793f3dd?source=rss-b9d68c20b1f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1cbb793f3dd</guid>
            <dc:creator><![CDATA[Mirza Abdul Rehman]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 17:29:35 GMT</pubDate>
            <atom:updated>2026-11-26T17:29:35.295Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How can a smartphone recognize whether a person is walking, sitting, standing, or climbing stairs?</strong> Modern smartphones contain motion sensors that continuously collect information about movement and orientation. By applying machine learning to these signals, it is possible to identify different human activities automatically.</p><p>In this project, we developed a Human Activity Recognition (HAR) system using a custom Bidirectional Long Short-Term Memory (BiLSTM) network with a temporal attention mechanism. The model was implemented using PyTorch and trained to classify six human activities from raw smartphone sensor data.</p><p>The main objective was not only to achieve good classification accuracy but also to understand which moments in a sensor window contribute most to the model’s predictions.</p><h3>1. Understanding the Human Activity Recognition Problem</h3><p>Human Activity Recognition is an important application of machine learning in wearable technology, healthcare monitoring, fitness tracking, and smart environments.</p><p>For example, a fitness application can use smartphone motion data to identify walking or running. Similarly, activity monitoring systems can distinguish between active and inactive periods.</p><p>In this project, the model receives a sequence of smartphone motion measurements and predicts one of six activities:</p><ul><li>WALKING</li><li>WALKING_UPSTAIRS</li><li>WALKING_DOWNSTAIRS</li><li>SITTING</li><li>STANDING</li><li>LAYING</li></ul><p>Each prediction is based on a 2.56-second window containing 128 time steps.</p><h3>2. Dataset and Sensor Signals</h3><p>We used the Human Activity Recognition Using Smartphones dataset from the UCI Machine Learning Repository.</p><p>The dataset was collected from 30 volunteers who performed different physical activities while wearing a Samsung Galaxy S II smartphone attached to their waist. The smartphone recorded motion signals at a sampling frequency of 50 Hz.</p><p>Instead of using the dataset’s pre-engineered features, we worked with nine raw sensor channels.</p><p>These channels are divided into three groups:</p><p><strong>Body Accelerometer:</strong> Measures body acceleration along the X, Y, and Z axes after removing gravity.</p><p><strong>Body Gyroscope:</strong> Measures angular velocity along the three axes and helps capture rotational movement.</p><p><strong>Total Accelerometer:</strong> Measures acceleration including gravitational effects, providing information about movement and orientation.</p><p>Each window contains 128 measurements from all nine channels, resulting in an input shape of 128 × 9.</p><h3>3. Data Preparation and Splitting</h3><p>Before training, the raw sensor data was loaded and converted into the required format. Activity labels were converted from values 1–6 into values 0–5.</p><p>We divided the training data into training and validation sets using subject-based splitting. Four volunteers were selected for validation, while the remaining training volunteers were used for model training. The original test subjects remained separate.</p><p>The final dataset distribution was:</p><p>DatasetNumber of WindowsTraining5,891Validation1,461Testing2,947<strong>Total10,299</strong></p><p>An important preprocessing step was standardization. We calculated the mean and standard deviation of each sensor channel using training data only. The same values were then applied to validation and test data.</p><p>This approach helps prevent information leakage from the validation and test sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RXYvfmLwgHA7iyrUEqUXg.png" /><figcaption><strong>Figure 1: Example Sensor Signals</strong></figcaption></figure><p>The signal plots show that walking and stair-related activities produce more noticeable motion patterns, while sitting, standing, and laying generally contain less dynamic movement.</p><h3>4. Building the Recurrent Neural Network</h3><p>One of the main objectives of this project was to understand how recurrent neural networks process sequential data.</p><p>Rather than using PyTorch’s built-in recurrent network layers, we implemented the recurrent components manually.</p><h3>RNN Cell</h3><p>The basic RNN cell updates its hidden state using the current input and the previous hidden state. It provides a foundation for understanding sequential information processing.</p><h3>LSTM Cell</h3><p>A Long Short-Term Memory cell improves upon a basic RNN by introducing four components: the input gate, forget gate, cell candidate, and output gate.</p><p>The cell state is updated using:</p><p>[<br>c_t=f_t\odot c_{t-1}+i_t\odot g_t<br>]</p><p>The forget gate controls which previous information is retained, while the input gate determines how much new information is added.</p><p>This structure helps preserve useful information over longer sequences.</p><h3>Bidirectional LSTM</h3><p>A standard LSTM processes a sequence in one direction. A Bidirectional LSTM processes the same sequence in both forward and backward directions.</p><p>The outputs from both directions are concatenated at every time step.</p><p>Since the complete 2.56-second sensor window is available before classification, using information from both directions is appropriate for this task.</p><h3>Temporal Attention</h3><p>The attention mechanism allows the model to assign different importance weights to different time steps.</p><p>Instead of treating every moment equally, it learns which parts of the sensor sequence are more useful for making a prediction.</p><p>The attention weights are normalized using softmax, meaning that their sum across all 128 time steps is equal to one.</p><p>The final context vector is calculated as a weighted combination of the BiLSTM outputs.</p><h3>Complete HARNet Architecture</h3><p>Our final model follows this structure:</p><p><strong>Input → Bidirectional LSTM → Temporal Attention → Fully Connected Layer → Six Activity Classes</strong></p><p>The network contains 46,982 trainable parameters.</p><h3>5. Model Training</h3><p>The model was trained using PyTorch with the following configuration:</p><p>ParameterSettingLoss FunctionCross EntropyOptimizerAdamLearning Rate0.001Batch Size64Epochs30Gradient Clipping1.0</p><p>During training, the model’s training loss, validation loss, and validation accuracy were recorded after every epoch.</p><p>The model checkpoint with the lowest validation loss was selected. The lowest validation loss was achieved at epoch 16, with a value of approximately 0.07927.</p><p>Gradient clipping was also applied with a maximum gradient norm of 1.0 to reduce the risk of exploding gradients during recurrent network training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-hwKy_l62eelZdnwVwafQ.png" /><figcaption><strong>Figure 2: Training and Validation Performance</strong></figcaption></figure><h3>6. Testing and Experimental Results</h3><p>After training, the selected model was evaluated on the separate test dataset containing 2,947 windows.</p><p>The model achieved an overall test accuracy of:</p><h3>89.35%</h3><p>Out of 2,947 test samples, 2,633 were classified correctly, while 314 were incorrectly classified.</p><p>The per-class accuracy was:</p><p>ActivityAccuracyWALKING88.10%WALKING_UPSTAIRS92.78%WALKING_DOWNSTAIRS88.33%SITTING85.13%STANDING81.39%LAYING100.00%</p><p>The model achieved its highest accuracy on LAYING, correctly classifying all 537 test windows.</p><p>The lowest accuracy was observed for STANDING. This indicates that distinguishing between stationary activities is more challenging than recognizing some of the movement-based activities.</p><h3>Confusion Matrix Analysis</h3><p>The confusion matrix provides a detailed view of actual and predicted activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjRDzcotbGtl-XNbLoVATg.png" /></figure><p>The most significant confusion occurred between SITTING and STANDING.</p><p>There were 61 SITTING windows predicted as STANDING and 99 STANDING windows predicted as SITTING. Together, these account for 160 classification errors.</p><p>This is understandable because a smartphone attached to the waist may record relatively similar motion patterns when a person is sitting or standing still.</p><h3>7. Understanding Temporal Attention</h3><p>One of the most interesting parts of this project was analyzing the attention mechanism.</p><p>Instead of looking only at classification accuracy, we investigated how the network distributed its attention across the 128 time steps.</p><p>For every activity, we calculated the mean of the maximum attention weight across its test windows.</p><p>The results were:</p><p>. Activity Mean Maximum</p><p>. AttentionWALKING0.228907</p><p>. WALKING_UPSTAIRS0.197192</p><p>. WALKING_DOWNSTAIRS0.252234</p><p>. SITTING0.015239</p><p>. STANDING0.023014</p><p>. LAYING0.009716</p><p>For comparison, perfectly uniform attention across 128 time steps would have a maximum weight of approximately 0.0078125.</p><p>The results show that moving activities generally have more concentrated attention distributions. In contrast, still activities tend to have more distributed attention weights.</p><p>Walking downstairs has the highest mean maximum attention value, suggesting that the model often focuses strongly on particular moments in those sensor sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoLXceKJZm3R51QrZBqYTw.png" /><figcaption><strong>Figure 3: Average Attention Across Activities</strong></figcaption></figure><p>Individual attention plots were also generated for all six activities to examine how attention changes throughout a sensor window.</p><h3>8. Important Observations and Learnings</h3><p>This project provided several important insights into recurrent neural networks and time-series classification.</p><p><strong>Why was validation split by person?</strong></p><p>The dataset contains windows with 50% overlap. Randomly distributing windows could place highly similar neighbouring windows from the same volunteer into both training and validation sets. Splitting by subject provides a more reliable evaluation of generalization to unseen people.</p><p><strong>Why are SITTING and STANDING difficult to distinguish?</strong></p><p>Both activities involve relatively little movement. Since the phone is attached to the waist, their acceleration and gyroscope patterns can appear similar, making classification difficult.</p><p><strong>Why was LAYING recognized so accurately?</strong></p><p>The acceleration channels contain useful information about gravity and body orientation. This helps the model recognize the characteristic orientation associated with laying down.</p><p><strong>Is attention more concentrated for moving activities?</strong></p><p>Yes. The moving activities generally showed higher maximum attention values. This suggests that particular moments of movement contain useful information for classification, whereas still activities may be identified using information distributed across a larger portion of the window.</p><p><strong>Why is Bidirectional LSTM suitable here?</strong></p><p>The entire sensor window is available before making a prediction. Therefore, the model can process information in both directions. However, this would not be suitable for strictly causal real-time prediction when future sensor measurements are not yet available.</p><p><strong>Why is LSTM better at retaining information than a basic RNN?</strong></p><p>The LSTM cell state provides a controlled path for information to pass across time steps. The forget and input gates regulate what information is removed or added. Gradient clipping helps protect training from excessively large gradients.</p><h3>9. Developing an Interactive Application</h3><p>To make the project more practical, we also developed a Streamlit-based web application.</p><p>The application allows users to select a test window or upload a CSV file containing 128 rows and 9 sensor channels.</p><p>It displays the sensor signals, predicted activity, probability distribution across all six classes, and temporal attention weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1TAMbxPNoXdEusLkkjw6w.png" /></figure><p>This interface provides a simple way to interact with the trained model and understand its predictions.</p><h3>10. Conclusion</h3><p>In this project, we developed a Human Activity Recognition system using a custom Bidirectional LSTM network with temporal attention.</p><p>The model achieved 89.35% test accuracy on 2,947 test windows. The attention analysis provided additional insight into how the network focuses on different time steps when identifying human activities.</p><p>One of the major findings was that SITTING and STANDING were the most frequently confused activities, while LAYING achieved 100% accuracy.</p><p>Beyond the final accuracy, this project provided practical experience in preparing multichannel time-series data, implementing recurrent neural network components, training deep learning models, analyzing attention weights, and developing an interactive application.</p><p>The work demonstrates how smartphone motion sensors and deep learning can be combined to build useful human activity recognition systems.</p><p><strong>Project Repository:</strong><br><a href="https://github.com/mirzaabdulrehmanieee-xyz/Human-Activity-Recognition-BiLSTM-Attention">https://github.com/mirzaabdulrehmanieee-xyz/Human-Activity-Recognition-BiLSTM-Attention</a></p><p><strong>Technologies:</strong> Python, PyTorch, NumPy, Matplotlib, Streamlit</p><p><strong>Team Members:</strong><br>Mirza Abdul Rehman<br>Muhammad Wasiq Aslam</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1cbb793f3dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECG Heartbeat Classification Using a Neural Network: From Scratch Implementation to 97.80%]]></title>
            <link>https://medium.com/@mirzaabdulrehman.ieee/ecg-heartbeat-classification-using-a-neural-network-from-scratch-implementation-to-97-80-ee82ffcdc3cb?source=rss-b9d68c20b1f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee82ffcdc3cb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ecg-test]]></category>
            <dc:creator><![CDATA[Mirza Abdul Rehman]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 21:40:52 GMT</pubDate>
            <atom:updated>2026-11-08T21:40:52.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>ECG Heartbeat Classification Using a Neural Network: From Scratch Implementation to 97.80% Test Accuracy</h3><h3>1. Introduction</h3><p>Electrocardiogram (ECG) signals are widely used to monitor the electrical activity of the human heart. Analyzing these signals helps identify different heartbeat patterns and abnormalities that may require medical attention.</p><p>In this project, I implemented a neural network for ECG heartbeat classification using the MIT-BIH heartbeat dataset. The main objective was to develop a model that could classify ECG heartbeat signals into five different categories.</p><p>Unlike using a complete machine learning framework for the entire model, this project involved implementing important components manually, including the neural network architecture, softmax cross-entropy loss, gradient verification, and evaluation metrics.</p><p>The final model achieved <strong>97.80% test accuracy</strong> and <strong>84.65% balanced accuracy</strong>.</p><h3>2. Dataset Description</h3><p>The project uses the MIT-BIH heartbeat dataset, which contains ECG heartbeat samples represented by numerical signal values.</p><p>Each heartbeat sample contains 187 input features, followed by its corresponding class label.</p><p>The dataset contains five heartbeat classes:</p><p>ClassDescriptionNNormal beatSSupraventricular ectopic beatVVentricular ectopic beatFFusion beatQUnknown beat</p><p>The dataset was divided into training and testing data:</p><ul><li>Training dataset: 87,554 samples</li><li>Testing dataset: 21,892 samples</li></ul><p>The original training dataset was further divided into training and validation sets using a 90:10 split with random seed 42.</p><p>After splitting:</p><ul><li>Training samples: 78,799</li><li>Validation samples: 8,755</li><li>Testing samples: 21,892</li></ul><p>The test dataset was kept separate for final model evaluation.</p><h3>3. Data Preparation and Visualization</h3><p>The dataset was loaded using Pandas and converted into numerical arrays.</p><p>The first 187 columns were used as input features, while the final column represented the target class.</p><p>The input features were converted into PyTorch float32 tensors, and the class labels were converted into int64 tensors.</p><p>To understand the dataset, sample ECG signals from all five classes were plotted.</p><p>These visualizations helped examine the differences in heartbeat patterns and understand the classification problem before training the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frABURY7a2sE1K5GSN50Yw.png" /></figure><p>Figure 1 — Sample ECG Heartbeat Signals</p><h3>4. Neural Network Architecture</h3><p>A fully connected feedforward neural network was implemented using PyTorch.</p><p>The architecture consists of three trainable layers:</p><p>LayerInput SizeOutput SizeActivationLayer 1187128ReLULayer 212864ReLUOutput Layer645Linear logits</p><p>The network uses:</p><ul><li>187 input features</li><li>128 neurons in the first hidden layer</li><li>64 neurons in the second hidden layer</li><li>5 output neurons representing the five heartbeat classes</li></ul><p>The model contains 32,645 trainable parameters.</p><h3>Weight Initialization</h3><p>Weights were initialized using He initialization, which is suitable for ReLU activation functions.</p><p>Biases were initialized to zero.</p><p>Random initialization was used instead of initializing all weights to zero because zero initialization would cause neurons in the same layer to learn identical features.</p><p>The output layer produces logits for all five classes. The class with the largest logit is selected as the predicted class.</p><h3>5. Loss Function and Gradient Verification</h3><p>A custom softmax cross-entropy loss function was implemented using PyTorch operations.</p><p>The loss function calculates the difference between the predicted class scores and the correct class labels.</p><p>The implementation uses the log-sum-exp operation for numerical stability.</p><p>To verify the correctness of the neural network’s gradients, a manual gradient calculation was performed for the output layer and compared with PyTorch automatic differentiation.</p><p>The maximum absolute differences were:</p><ul><li>Weight gradient difference: 5.96 × 10⁻⁸</li><li>Bias gradient difference: 1.19 × 10⁻⁷</li></ul><p>These very small differences confirmed that the manually calculated gradients closely matched PyTorch’s automatic differentiation results.</p><h3>6. Model Training and Optimization</h3><p>The network was trained using mini-batch gradient descent with momentum.</p><p>The training configuration was:</p><p>ParameterValueBatch Size128Number of Epochs30Momentum (β)0.9Weight Decay (λ)0.0001Learning Rates0.01, 0.1, 0.5Random Seed0</p><p>Training samples were shuffled at the beginning of every epoch.</p><p>Separate velocity values were maintained for each trainable parameter. Weight decay was applied to weights but not biases.</p><p>After each epoch, training and validation loss and accuracy were calculated. The model parameters corresponding to the lowest validation loss were retained.</p><h3>Learning Rate Comparison</h3><p>Three learning rates were tested:</p><ul><li>0.01</li><li>0.1</li><li>0.5</li></ul><p>The validation loss curves showed that a learning rate of 0.5 achieved the lowest validation loss among the three tested learning rates.</p><p>Therefore, 0.5 was selected for final model training.</p><p>The comparison demonstrated that learning rate selection has a significant impact on the convergence behavior and performance of a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbPY8PFbUvP_PNxs5V2hzg.png" /></figure><p>Figure 2 — Learning Rate Comparison</p><h3>7. Final Model and Loss Analysis</h3><p>The final model was trained using the selected learning rate of 0.5.</p><p>The best model parameters were saved in:</p><p>results/best_model.pth</p><p>Training and validation loss curves were also generated.</p><p>Both loss curves showed a decreasing trend throughout training. The validation loss remained slightly higher than the training loss, indicating a small generalization gap.</p><p>The curves suggest that the model learned useful patterns from the training data and achieved reasonable generalization performance, although slight overfitting may be present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*n_xq2hrV3_uMe3Y0RySHdA.png" /></figure><p>Figure 3 — Training vs Validation Loss</p><h3>8. Testing and Evaluation</h3><p>After training, the saved model parameters were loaded to evaluate the model on the complete test dataset.</p><p>The predicted class for each test sample was obtained by selecting the output neuron with the largest logit.</p><p>Accuracy, confusion matrix, per-class accuracy, and balanced accuracy were calculated manually without using sklearn.metrics.</p><h3>Overall Test Results</h3><p>MetricResultTotal Test Samples21,892Correct Predictions21,410Incorrect Predictions482Test Accuracy97.80%Balanced Accuracy84.65%</p><p>The model correctly classified 21,410 out of 21,892 test samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*6rLyweMjM4isaer6TcjTww.png" /></figure><p>Figure 4 — Training vs Validation Accuracy</p><h3>Confusion Matrix</h3><p>Actual</p><p>The following confusion matrix shows the actual and predicted heartbeat classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*rfrZy4qJHN1RcF2iM2E0Pg.png" /></figure><p>Per-Class Accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*23Hq5jX1fE9AtepAtnP5xw.png" /></figure><p>The model performed particularly well on classes N and Q.</p><p>However, class S achieved the lowest accuracy of 64.57%. The confusion matrix shows that 186 actual S samples were incorrectly classified as N.</p><p>This suggests that distinguishing some supraventricular ectopic beats from normal beats is challenging for the current model.</p><h3>9. Analysis and Observations</h3><h3>Majority-Class Baseline</h3><p>The test dataset contains 18,118 samples of class N out of 21,892 total samples.</p><p>A model that always predicts N would achieve:</p><p>Accuracy = (18,118 / 21,892) × 100 = <strong>82.76%</strong></p><p>Our model achieved 97.80%, which is approximately 15.04 percentage points higher.</p><p>This demonstrates why accuracy alone is not sufficient for evaluating a classifier trained on an imbalanced dataset.</p><h3>Balanced Accuracy</h3><p>The model achieved 84.65% balanced accuracy.</p><p>Balanced accuracy is the average of the individual class accuracies. It provides a better understanding of model performance across all five classes, particularly when some classes contain significantly fewer samples than others.</p><h3>Rare-Class Challenge</h3><p>Class F contains only 641 training samples.</p><p>One possible improvement is class-weighted cross-entropy loss. Assigning higher weights to minority classes would increase the penalty for incorrectly classifying their samples and could encourage the network to learn rare heartbeat patterns more effectively.</p><p>This is a proposed improvement and was not implemented in the current experiment.</p><h3>10. Conclusion</h3><p>This project demonstrated the implementation and evaluation of a neural network for ECG heartbeat classification using the MIT-BIH dataset.</p><p>The work covered dataset preparation, ECG visualization, neural network implementation, He initialization, custom softmax cross-entropy loss, gradient verification, mini-batch training with momentum, learning rate comparison, and manual evaluation metrics.</p><p>The final model achieved <strong>97.80% test accuracy</strong> and <strong>84.65% balanced accuracy</strong>.</p><p>Although the overall accuracy was high, the results also highlighted the challenges of class imbalance and the difficulty of classifying minority heartbeat categories, particularly class S.</p><p>Future improvements could include class-weighted loss functions and other techniques for improving minority-class classification.</p><p>This project provided practical experience in neural network implementation, optimization, evaluation, and understanding the limitations of classification models.</p><p><strong>Note:</strong> This project is an academic machine learning experiment and is not intended to replace professional medical diagnosis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee82ffcdc3cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Three-Phase Transmission Line Faults Using Machine Learning]]></title>
            <link>https://medium.com/@mirzaabdulrehman.ieee/detecting-three-phase-transmission-line-faults-using-machine-learning-0a20d08d9864?source=rss-b9d68c20b1f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a20d08d9864</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[three-phase]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <dc:creator><![CDATA[Mirza Abdul Rehman]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 14:05:04 GMT</pubDate>
            <atom:updated>2026-10-11T14:05:04.974Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Comparing Logistic Regression and Support Vector Machines for electrical fault detection</em></p><h3>Introduction</h3><p>Electrical power systems are an important part of everyday life. From industrial plants to homes, a reliable electricity supply depends on equipment that can detect abnormal conditions and respond quickly. One major challenge in power systems is identifying faults in transmission lines. If a fault is not detected on time, it can damage equipment, interrupt the power supply, and create safety risks.</p><p>In this project, I developed and evaluated machine learning models to detect faults in a three-phase transmission line. The main objective was to classify electrical measurements into two categories: fault and no fault. I compared Logistic Regression with Linear and Radial Basis Function (RBF) Support Vector Machines (SVMs). I also investigated whether adding squared electrical features could improve the performance of Logistic Regression.</p><p>The project focused on three important questions: how well can these models classify faults, which model produces fewer missed faults and false alarms, and how reliable are the results when applied to a real electrical protection system?</p><h3>Understanding the Dataset</h3><p>The dataset contains three-phase current measurements (Ia, Ib, and Ic), three-phase voltage measurements (Va, Vb, and Vc), and a target column indicating the fault condition. The original dataset contained 12,001 rows and nine columns. During preprocessing, two unnecessary columns were removed and the target column was renamed to fault, leaving seven columns.</p><p>The dataset contained 5,496 fault observations and 6,505 no-fault observations. I divided the data into training, validation, and test sets using a fixed random seed. The training set was used to learn the model parameters, the validation set was used to select model settings, and the test set was reserved for final evaluation.</p><p>I also standardized the input features using statistics calculated from the training data. This helped put measurements on comparable scales while avoiding the use of test-set information during preprocessing.</p><h3>Exploratory Data Analysis</h3><p>Before training the models, I examined the electrical measurements through exploratory plots. These plots helped me understand the data distribution and investigate whether fault conditions could be distinguished from normal conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKAKe2_7xsfpjvF02EP1Rg.png" /><figcaption><em>Figure 1: Three-phase current measurements under fault and no-fault conditions.</em></figcaption></figure><p>This plot helps examine how the current measurements behave across the two classes. Changes in current can provide useful information for identifying electrical faults. However, the exact patterns depend on the type and severity of the fault, so it is important to study the actual measurements rather than assume that all faults produce identical responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hYUvL8S3AYWSvrwsKR2dbw.png" /><figcaption><em>Figure 2: Scatter plot showing the relationship between current measurements and fault classes.</em></figcaption></figure><p>The scatter plot provides another way to examine whether the two classes form separate groups. If the points overlap, a simple linear decision boundary may struggle to classify every observation correctly. This makes feature engineering and nonlinear classification methods worth investigating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4ipgF9FZqtvbH8m-qzyaAQ.png" /><figcaption><em>Figure 3: Distribution of current measurements in the dataset.</em></figcaption></figure><p>The histogram provides additional information about the spread and distribution of current values. Together, these plots helped establish a starting point for the model-development stage.</p><h3>Logistic Regression: Set R and Set Q</h3><p>I first implemented Logistic Regression using gradient-based optimization. The model estimates the probability that an observation belongs to the fault class and assigns a class based on a threshold of 0.5.</p><p>Set R uses the six original electrical features: Ia, Ib, Ic, Va, Vb, and Vc. Set Q extends this feature set by adding the square of each original feature. This gives the model additional information about nonlinear relationships between electrical measurements and fault conditions.</p><p>For Set R, the selected learning rate was 1, producing a final cost of 0.677161 and validation accuracy of 73.08%. For Set Q, the selected learning rate was 10, producing a final cost of 0.053434 and validation accuracy of 97.83%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*m0kTMjKE3rgIZuto4mF_Yg.png" /><figcaption><em>Figure 4: Logistic Regression cost against iteration for Set R.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bbZrmHiLvEWzvhuGXdAA1w.png" /><figcaption><em>Figure 5: Logistic Regression cost against iteration for Set Q.</em></figcaption></figure><p>The comparison shows that adding squared features substantially improved the classification results. Set Q provided a better representation of the relationship between the electrical measurements and the fault label than the original features alone.</p><h3>Support Vector Machines</h3><p>I also evaluated two SVM kernels. The Linear SVM uses a linear decision boundary, while the RBF SVM can represent more complex nonlinear boundaries.</p><p>For the Linear SVM, I tested C values of 0.1, 1, 10, and 100. The best validation accuracy was 72.58%. For the RBF SVM, I tested the same C values with gamma values of 0.1 and 1. The best configuration was C = 100 and gamma = 1, achieving 99.67% validation accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hh0FdaPoQOSCDWjBvAhJyg.png" /><figcaption><em>Figure 6: Validation accuracy against C for the Linear SVM and RBF SVM configurations.</em></figcaption></figure><p>The validation plot allows us to compare the effect of C on the different models. C controls how strongly training classification errors are penalized. In the RBF model, gamma also affects how locally the decision boundary responds to the training observations.</p><h3>Final Test Results</h3><p>After selecting the models using validation data, I evaluated the four final models on the test set. I used test accuracy and the confusion matrix to examine not only correct predictions but also false alarms and missed faults.</p><p>ModelTest accuracyTNFalse alarms (FP)Missed faults (FN)TPLogistic Regression — Set R72.64%13050657439Logistic Regression — Set Q97.88%12996451051Linear SVM73.59%13050634462RBF SVM99.58%1301461090</p><p>TN represents correctly identified no-fault observations, while TP represents correctly identified faults. FP counts false alarms, and FN counts actual faults that the model failed to detect.</p><p>The results show a clear difference between the linear models and the nonlinear approaches. Set Q achieved 97.88% test accuracy, while the RBF SVM achieved 99.58%. The RBF SVM also had only six missed faults, compared with 45 for Set Q, 634 for the Linear SVM, and 657 for Set R.</p><h3>Discussion: What Do the Results Tell Us?</h3><p>The first observation is that Set R Logistic Regression and the Linear SVM achieved similar results. Both use the same six standardized features and learn linear decision boundaries. Their similar performance suggests that using the original features with a linear boundary limits the ability to separate some fault and no-fault observations.</p><p>The Set Q weights provide another perspective. The signs of the squared-current and squared-voltage coefficients should be interpreted together with the other coefficients and the intercept. A positive coefficient increases the model’s linear score as its corresponding standardized feature increases, while a negative coefficient decreases it. These signs do not, by themselves, establish a universal electrical relationship; the learned weights must be considered alongside the feature scaling and observed data.</p><p>The number of support vectors also differs considerably. The selected Linear SVM uses 5,836 support vectors, whereas the selected RBF SVM uses 266. Support vectors are training observations that influence the decision boundary. A large number means many observations contribute to defining that boundary, although the count alone does not determine model quality.</p><p>Another important consideration is the train-test split. The dataset contains consecutive time samples, but the split was random. Neighbouring samples can be very similar and may end up in different subsets. This can make the test accuracy optimistic compared with performance on genuinely unseen operating conditions. Testing on a separate time period or independent measurements would provide a more realistic assessment.</p><p>If I were choosing a candidate for further relay testing, the RBF SVM would be my first choice based on the current results. It achieved the fewest missed faults while maintaining high accuracy and a small number of false alarms. However, a real protection relay must be evaluated for reliability, response time, and safety under different fault conditions. The model should not be deployed in an actual power system based only on these results.</p><h3>Conclusion</h3><p>This project compared Logistic Regression, feature engineering, and two SVM kernels for three-phase transmission line fault detection. Adding squared features improved Logistic Regression considerably, while the RBF SVM achieved the strongest recorded test performance. The confusion-matrix results showed why accuracy alone is not enough: missed faults and false alarms are also important when assessing protection systems.</p><p>Although the results are promising, the random split may overestimate performance on new operating conditions. Further testing with independent measurements and realistic protection-system requirements is necessary before considering practical deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a20d08d9864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solar Plant AC Power Prediction: On-Site Sensors vs. Public Weather Data]]></title>
            <link>https://medium.com/@mirzaabdulrehman.ieee/solar-plant-ac-power-prediction-on-site-sensors-vs-public-weather-data-75271b8fac91?source=rss-b9d68c20b1f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/75271b8fac91</guid>
            <category><![CDATA[renewable-energy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[solar-energy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artficial-intelligence]]></category>
            <dc:creator><![CDATA[Mirza Abdul Rehman]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 16:20:28 GMT</pubDate>
            <atom:updated>2026-09-15T16:20:28.600Z</atom:updated>
            <content:encoded><![CDATA[<h4>How plant-level sensor measurements outperform public weather data in solar power forecasting</h4><h3>Introduction</h3><p>Solar energy is one of the most promising renewable energy sources, but its power output is highly dependent on changing environmental conditions such as solar irradiation, temperature, and cloud cover. Because of this variability, accurate solar power prediction is important for energy planning, monitoring, and efficient plant operation.</p><p>In this project, I explored whether public weather data can predict solar plant AC power as accurately as measurements collected directly from the plant. I compared two feature sets: one based on on-site sensor measurements and another based on public weather data obtained from Open-Meteo.</p><p>To build and evaluate the prediction models, I implemented Linear Regression using three optimization approaches: the Normal Equation, Batch Gradient Descent, and Stochastic Gradient Descent. The results provided a clear comparison between plant-specific measurements and publicly available weather information.</p><h3>Dataset &amp; Data Preparation</h3><p>The analysis focused on <strong>Plant 1</strong> of the solar power dataset. The available data included inverter-level power generation records and weather sensor measurements collected at the plant.</p><p>The generation data was aggregated to obtain plant-level AC power, while the weather data provided important environmental variables such as irradiation, module temperature, and ambient temperature.</p><p>To complement the plant sensor data, I also collected public weather information from <strong>Open-Meteo</strong>, including shortwave radiation, temperature at 2 metres, and cloud cover.</p><p>The data preparation process involved several steps:</p><ul><li>Merging generation and weather data using timestamps</li><li>Aggregating inverter-level measurements to plant-level AC power</li><li>Resampling the data to hourly intervals</li><li>Checking for missing values</li><li>Creating hour-based sine and cosine features</li><li>Standardizing the input features using statistics calculated only from the training data</li></ul><p>The final dataset was then divided chronologically into training and testing periods to preserve the time-series nature of the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uv8IPNZqIqwmjiHk19gWww.png" /><figcaption>Figure 1. Relationship between solar irradiation and AC power generation.</figcaption></figure><h3>Feature Sets</h3><p>To understand how the source of weather information affects prediction accuracy, I developed two different feature sets.</p><h4>Set A — On-Site Sensor Features</h4><p>Set A uses measurements collected directly from the solar plant:</p><ul><li>Irradiation</li><li>Module Temperature</li><li>Ambient Temperature</li><li>Hour Sine</li><li>Hour Cosine</li></ul><p>These features represent the actual environmental conditions experienced by the solar plant.</p><h4>Set B — Public Weather Features</h4><p>Set B uses publicly available weather information obtained from Open-Meteo:</p><ul><li>Shortwave Radiation</li><li>Temperature at 2 metres</li><li>Cloud Cover</li><li>Hour Sine</li><li>Hour Cosine</li></ul><p>The purpose of this comparison was to determine whether public weather information could provide prediction performance comparable to plant-specific sensor measurements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIV6xAqJTpbcNbpqAtJWRg.png" /><figcaption>Figure 2. Comparison of on-site sensor irradiation and Open-Meteo shortwave radiation across selected days.</figcaption></figure><h3>Methodology</h3><p>After preparing the data, I trained linear regression models using three different approaches: <strong>Normal Equation, Batch Gradient Descent, and Stochastic Gradient Descent (SGD)</strong>.</p><p>The dataset was split chronologically to avoid information leakage:</p><p><strong>Training period:</strong> 15 May — 10 June 2020<br> <strong>Testing period:</strong> 11 June — 17 June 2020</p><p>No shuffling was performed because the observations form a time series.</p><h4>Normal Equation</h4><p>The Normal Equation was used to obtain a direct analytical solution for the regression parameters. This approach is particularly convenient for relatively small datasets because it does not require iterative learning.</p><h4>Batch Gradient Descent</h4><p>Batch Gradient Descent updates the model parameters using the complete training dataset at every iteration. I evaluated multiple learning rates and monitored the cost function during training.</p><h4>Stochastic Gradient Descent</h4><p>Stochastic Gradient Descent updates the parameters one training example at a time. Although its optimization path is more variable, it is more practical for very large datasets because it does not require the complete dataset for every update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b26KK5ow8AR-DHdFsmutQg.png" /><figcaption>Figure 3. Batch Gradient Descent cost curves for different learning rates.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQh7V4lDeUB2E2qhEIcDDg.png" /><figcaption>Figure 4. Stochastic Gradient Descent cost curves for different learning rates.</figcaption></figure><h3>Results</h3><p>he model evaluation showed a clear difference between the two feature sets. Models trained using on-site sensor measurements performed substantially better than models based on public weather data.</p><h4>Overall Test Performance</h4><p><strong>Set A — On-Site Sensors</strong><br> <strong>539.46 kW RMSE</strong></p><p><strong>Set B — Public Weather</strong><br> <strong>2572.66 kW RMSE</strong></p><p>The best sensor-based model achieved an RMSE of <strong>539.46 kW</strong>, while the best public-weather model achieved an RMSE of <strong>2572.66 kW</strong>.</p><p>This represents a <strong>376.90% relative increase in RMSE</strong> when using public weather data instead of the best-performing sensor-based model.</p><h4>Daytime Performance</h4><p>The comparison was also performed specifically during daytime hours (06:00–18:00), when solar generation is most significant.</p><p><strong>Set A — On-Site Sensors</strong><br> <strong>704.46 kW RMSE</strong></p><p><strong>Set B — Public Weather</strong><br> <strong>3148.71 kW RMSE</strong></p><p>The daytime results show that the sensor-based model continued to outperform the public-weather model by a substantial margin.</p><p>The difference between the two daytime RMSE values was <strong>2444.25 kW</strong>, which is approximately <strong>8.94% of the plant’s peak hourly AC power</strong>.</p><h4>Peak Power</h4><p>The maximum hourly AC power observed in the plant data was:</p><p><strong>27,325.90 kW</strong></p><p>These results demonstrate that having weather measurements directly at the solar plant provides a major advantage for accurate AC power prediction.</p><h4>Actual vs. Predicted Power</h4><p>The predicted and actual AC power values were also compared over the test week. The sensor-based model was able to follow the actual generation pattern more closely, while the public-weather model showed larger deviations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLMrB85TPfX2FT3BeyBo6A.png" /><figcaption>Figure 5. Actual vs. predicted AC power during the test week using the Normal Equation for Set A and Set B.</figcaption></figure><h3>Residual Analysis</h3><p>After evaluating the overall prediction performance, I analyzed the residuals to understand when and why the model made its largest errors.</p><p>The largest residuals were mainly concentrated between <strong>10 AM and 3 PM</strong>, which corresponds to the period of high solar generation.</p><p>During these hours, solar irradiation can change rapidly because of passing clouds and other short-term environmental variations. These changes can cause the actual AC power output to differ from the value predicted by a simple linear model.</p><p>Other possible factors include <strong>local shading, temperature effects, short-term irradiation fluctuations, and inverter behaviour</strong> that are not fully captured by the selected features.</p><p>The residual analysis therefore suggests that the model performs best when the relationship between the input weather conditions and power output is relatively stable, while more complex conditions during peak generation hours can produce larger prediction errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5-2jrP-G_pfSOTTPN84Kw.png" /><figcaption>Figure 6. Residuals versus hour of day for the sensor-based model. Larger errors are concentrated during peak solar-generation hours.</figcaption></figure><h3>What Did We Learn?</h3><p>The comparison produced several important insights.</p><p><strong>First, data quality and location matter.</strong> On-site sensors provide measurements directly from the solar plant, making them more representative of the actual conditions affecting power generation.</p><p><strong>Second, public weather data can still be useful.</strong> Although it performed considerably worse in this experiment, public data can provide a practical alternative for preliminary estimation or situations where plant-level sensors are unavailable.</p><p><strong>Third, the choice of optimization method depends on the dataset size.</strong> The Normal Equation is convenient for relatively small datasets, while Stochastic Gradient Descent becomes more practical as the number of training samples grows.</p><p><strong>Finally, a simple linear model has limitations.</strong> Solar power generation is influenced by complex and rapidly changing physical conditions that may not be completely represented by a small set of linear features.</p><h3>Conclusion</h3><p>This project investigated the impact of using on-site sensor measurements versus public weather data for predicting hourly solar plant AC power.</p><p>The results showed a clear advantage for plant-specific sensor data. The best sensor-based model achieved an overall RMSE of <strong>539.46 kW</strong>, compared with <strong>2572.66 kW</strong> for the best public-weather model.</p><p>The findings highlight the importance of accurate, location-specific weather measurements for solar power forecasting. Public weather data remains useful when direct plant measurements are unavailable, but it may not capture local conditions with sufficient accuracy.</p><p>For this relatively small dataset, the <strong>Normal Equation</strong> provides a practical solution because it directly estimates the model parameters. For much larger datasets, <strong>Stochastic Gradient Descent</strong> would be a more scalable approach.</p><p>Overall, this experiment demonstrates that <strong>better data can lead to better predictions</strong>. On-site sensors provide a more reliable foundation for accurate plant-level solar power forecasting.</p><h3>Project Resources</h3><p>The complete implementation, datasets, trained model weights, visualizations, and Streamlit application are available in the project repository.</p><p><strong>GitHub Repository:</strong><br> <a href="https://github.com/mirzaabdulrehmanieee-xyz/Solar-Plant-AC-Power-Prediction.git">https://github.com/mirzaabdulrehmanieee-xyz/Solar-Plant-AC-Power-Prediction</a></p><h3>Technologies Used</h3><p><strong>Python • NumPy • Pandas • Matplotlib • Streamlit • Open-Meteo API • GitHub</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75271b8fac91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>