<?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 F on Medium]]></title>
        <description><![CDATA[Stories by F on Medium]]></description>
        <link>https://medium.com/@f236066?source=rss-ef9f3513eff9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g0qcTqlPdlK6Tliy</url>
            <title>Stories by F on Medium</title>
            <link>https://medium.com/@f236066?source=rss-ef9f3513eff9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:55:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@f236066/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 Smartphone Sensors: A BiLSTM and Attention-Based Deep Learning…]]></title>
            <link>https://medium.com/@f236066/human-activity-recognition-using-smartphone-sensors-a-bilstm-and-attention-based-deep-learning-11eb623acb5b?source=rss-ef9f3513eff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/11eb623acb5b</guid>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[numpy-tutorial]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[F]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 16:40:35 GMT</pubDate>
            <atom:updated>2026-11-25T16:40:35.400Z</atom:updated>
            <content:encoded><![CDATA[<h3>Human Activity Recognition Using Smartphone Sensors: A BiLSTM and Attention-Based Deep Learning Model</h3><p><strong>Authors: Abdul Rehman Khan (23F-6066) and Bilawal Shahzad (23F-6058)</strong></p><h3>Introduction</h3><p>Have you ever wondered how your smartphone recognises whether you are walking, sitting, standing, or climbing stairs?</p><p>Modern smartphones contain motion sensors that collect information about body movement. By analysing these signals, machine learning models can automatically identify different human activities.</p><p>In our Applied Machine Learning Assignment, we developed a Human Activity Recognition (HAR) system using PyTorch. The main objective was to classify six human activities from raw smartphone sensor data using recurrent neural networks and an attention mechanism.</p><p>We manually implemented RNN, LSTM, Bidirectional LSTM (BiLSTM), and Attention rather than using built-in recurrent layers.</p><h3>1. Dataset Overview</h3><p>We used the <strong>UCI Human Activity Recognition Using Smartphones Dataset</strong>, which contains recordings from 30 volunteers aged between 19 and 48.</p><p>Participants performed six activities while wearing a Samsung Galaxy S II smartphone around their waist.</p><p>The six activities were:</p><ul><li>Walking</li><li>Walking Upstairs</li><li>Walking Downstairs</li><li>Sitting</li><li>Standing</li><li>Laying</li></ul><p>Our model uses nine raw sensor channels:</p><ul><li>Body acceleration: X, Y, Z</li><li>Body gyroscope: X, Y, Z</li><li>Total acceleration: X, Y, Z</li></ul><p>The sensor sampling frequency is <strong>50 Hz</strong>. Each input window contains <strong>128 time steps</strong>, representing <strong>2.56 seconds</strong> of movement.</p><p>The dataset uses 50% overlapping windows, with an overlap of 64 samples or 1.28 seconds.</p><h3>Dataset distribution</h3><p>ActivityTraining windowsTest windowsWalking1,226496Walking Upstairs1,073471Walking Downstairs986420Sitting1,286491Standing1,374532Laying1,407537<strong>Total7,3522,947</strong></p><p><strong>Figure 1: Dataset distribution across six activities</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB-kfYDJ4A8BYLIWn8oUWg.png" /><figcaption>Figure 1</figcaption></figure><h3>2. Data Preprocessing</h3><p>Data preprocessing is an important step before training a deep learning model.</p><p>We converted the original activity labels from 1–6 into 0–5 and separated the validation data using the four specified volunteers: 3, 15, 25, and 30.</p><p>We used a subject-based validation split instead of randomly selecting windows. This helps prevent overlapping and highly similar windows from the same person appearing in both training and validation sets.</p><p>We also standardised all nine sensor channels using the training data’s mean and standard deviation. The same standardisation values were applied to validation and test data.</p><p>The final input shape was:</p><p><strong>128 time steps × 9 sensor channels</strong></p><p>This allowed our network to process multichannel time-series data.</p><h3>3. Proposed Model Architecture</h3><p>Our model, called HARNet, combines a Bidirectional LSTM, an attention mechanism, and a final classification layer.</p><p><strong>Figure 2: HARNet model architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XG6OyINJaoPY1DspngEl0g.png" /><figcaption>Figure 2</figcaption></figure><h3>Recurrent Neural Network (RNN)</h3><p>The RNN processes sequential data by maintaining information from previous time steps. We implemented the RNN cell manually to understand how hidden states are updated.</p><h3>Long Short-Term Memory (LSTM)</h3><p>LSTM improves the handling of long sequences through four gates: input, forget, cell candidate, and output.</p><p>These gates control how information is stored, updated, and passed through the network.</p><h3>Bidirectional LSTM (BiLSTM)</h3><p>The BiLSTM processes the input sequence in both forward and backward directions.</p><p>Our architecture uses 64 hidden units in each direction, producing a combined output of <strong>128 features per time step</strong>.</p><p>This allows the network to learn from both earlier and later parts of the same sensor window.</p><h3>Attention Mechanism</h3><p>Attention helps the model focus on the most informative moments in a sequence.</p><p>Instead of treating all 128 time steps equally, the attention layer assigns a weight to each time step. These weights are then used to create a context representation for the final classification.</p><p>The model’s final linear layer produces six output scores, one for each activity.</p><h3>4. Model Parameters</h3><p>Our architecture contains the following trainable parameters:</p><p>Model componentTrainable parametersBidirectional LSTM37,888Attention layer8,320Final classification layer774<strong>Total46,982</strong></p><p><strong>Figure 3: Trainable parameter distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVy4OP4vlGYXxUyD8axuew.png" /><figcaption>Figure 3</figcaption></figure><p>The complete network contains <strong>46,982 trainable parameters</strong>, matching the expected architecture specified in the assignment.</p><h3>5. Model Training</h3><p>We trained the model using PyTorch with the following configuration:</p><p>Training settingValueOptimizerAdamLearning rate0.001Loss functionCross-EntropyBatch size64Training epochs30Gradient clipping1.0Hidden units64</p><p>During training, we recorded training loss, validation loss, and validation accuracy after every epoch.</p><p>We also saved the model checkpoint with the lowest validation loss to use for final testing.</p><p><strong>Figure 4: Training and validation performance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8F7AhWL8O5A9yWRu0OjiA.png" /><figcaption>Figure 4</figcaption></figure><p>[Insert your actual training loss, validation loss, and validation accuracy graphs here.]</p><p>These graphs help us understand how the model learns and whether its performance improves across training epochs.</p><h3>6. Model Evaluation</h3><p>After training, we evaluated the saved model using the separate test dataset containing <strong>2,947 windows</strong>.</p><p>We used three main evaluation measures:</p><ul><li><strong>Accuracy:</strong> Measures the percentage of correctly classified test windows.</li><li><strong>Confusion matrix:</strong> Shows the relationship between actual and predicted activity labels.</li><li><strong>Per-class accuracy:</strong> Measures how accurately the model recognises each individual activity.</li></ul><p><strong>Figure 5: Test confusion matrix</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Gjy0k7yB8OB5hQFMUzJfg.png" /><figcaption>Figure 5</figcaption></figure><p>Our final experimental results:</p><p>Evaluation metricResultTest accuracy[Insert actual result]%Best training epoch[Insert actual epoch]Best validation accuracy[Insert actual result]%Training time[Insert actual time]</p><p>The assignment provides approximately <strong>92% test accuracy</strong> as a reference for its specified architecture. This is not a measured result from our experiment, so we will report our own test accuracy after running the model.</p><h3>7. Understanding the Attention Mechanism</h3><p>One of the most interesting parts of this project is understanding which moments the model focuses on when recognising an activity.</p><p>We visualised attention weights across all 128 time steps for correctly classified examples from each activity.</p><p>We also calculated average attention curves for all six activities.</p><p>For reference, perfectly uniform attention across 128 time steps has a weight of approximately <strong>0.0078 per time step</strong>.</p><p>A higher maximum attention value indicates that the model places more emphasis on particular moments.</p><p><strong>Figure 6: Attention visualisation for all six activities</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrxmsDJOnwmatzbYdIIOJA.png" /><figcaption>Figure 6</figcaption></figure><p><strong>Figure 7: Average attention curves for all activities</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6BagmtLBhFPM5T5Swgk6Q.png" /><figcaption>Figure 7</figcaption></figure><p>These visualisations help us investigate how the network uses sensor information when distinguishing between different human activities.</p><h3>8. Key Observations</h3><p><strong>Why did we split the data by volunteer?</strong></p><p>Because the dataset contains 50% overlapping windows, random splitting could create similarities between training and validation samples. Splitting by volunteer provides a better evaluation of generalisation to unseen people.</p><p><strong>Why use BiLSTM?</strong></p><p>A BiLSTM processes the complete sensor window in both directions. This is appropriate for our task because the entire window is available before the activity is predicted.</p><p><strong>Why can sitting and standing be difficult to distinguish?</strong></p><p>Both activities involve relatively little movement. Their sensor signals may therefore have similar patterns, making classification more challenging.</p><p><strong>Why is attention useful?</strong></p><p>Attention provides a way to examine which time steps receive more importance during the model’s decision-making process.</p><p><strong>Why use gradient clipping?</strong></p><p>Gradient clipping limits the gradient norm to 1.0 and helps prevent excessively large gradients during recurrent network training.</p><h3>9. Conclusion</h3><p>In this project, we developed a Human Activity Recognition system using raw smartphone motion sensor data.</p><p>We implemented recurrent neural network components manually, built a Bidirectional LSTM architecture, and integrated an attention mechanism for time-series classification.</p><p>The final architecture contains 46,982 trainable parameters and classifies six different human activities.</p><p>This assignment gave us practical experience in data preprocessing, recurrent neural networks, deep learning model training, evaluation, and attention visualisation.</p><p>It also demonstrated how everyday smartphone sensors can be used to recognise human movement through machine learning.</p><h3>Project Team</h3><p><strong>Abdul Rehman Khan — 23F-6066</strong></p><p><strong>Bilawal Shahzad — 23F-6058</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11eb623acb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching a Neural Network to Read Heartbeats: Building NEUROCARD AI from Scratch]]></title>
            <link>https://medium.com/@f236066/teaching-a-neural-network-to-read-heartbeats-building-neurocard-ai-from-scratch-40570b4d877b?source=rss-ef9f3513eff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/40570b4d877b</guid>
            <category><![CDATA[medical-education]]></category>
            <category><![CDATA[heart-health]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[electrocardiography]]></category>
            <category><![CDATA[cardiology]]></category>
            <dc:creator><![CDATA[F]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 18:20:24 GMT</pubDate>
            <atom:updated>2026-11-10T18:20:24.432Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Suggested subtitle: How we built an ECG heartbeat classifier in PyTorch with a hand-written loss, a hand-written optimizer and a 97.8% test accuracy, and why that number alone is misleading.</em></p><p>Every heartbeat leaves an electrical signature. A cardiologist reading an electrocardiogram (ECG) looks at the shape of each beat to decide whether it is healthy or a sign of something worth a closer look. For our deep learning course project, we asked a simple question: <strong>can a small neural network learn to do the same thing?</strong></p><p>The result is <strong>NEUROCARD AI</strong>, an ECG heartbeat classifier built in PyTorch. We did not just call model.fit(). We wrote the network&#39;s forward pass, the loss function and the optimizer ourselves, verified our gradients against PyTorch&#39;s autograd, and wrapped everything in an interactive Streamlit app.</p><p>This post walks through what we built, what we found, and what we learned.</p><h3>The Dataset: MIT-BIH Heartbeats</h3><p>We used the MIT-BIH heartbeat dataset. Each sample is one heartbeat, represented by <strong>187 signal values</strong> (scaled between 0 and 1) plus a class label. The original training file has 87,554 beats, and the test file has 21,892.</p><p>Every beat falls into one of five classes:</p><ul><li><strong>N</strong>: Normal beat</li><li><strong>S</strong>: Supraventricular ectopic beat</li><li><strong>V</strong>: Ventricular ectopic beat</li><li><strong>F</strong>: Fusion beat</li><li><strong>Q</strong>: Unknown beat</li></ul><p>We split the original training data 90:10 into <strong>78,799 training</strong> and <strong>8,755 validation</strong> samples. The test set stayed untouched until the very end.</p><p>The first thing we noticed was the imbalance. The test set has 18,118 normal beats out of 21,892. That detail ends up shaping the whole story.</p><h3>The Architecture: A Small, Honest Network</h3><p>We kept the model deliberately simple: a fully connected network called <strong>ECGNet</strong>.</p><ul><li><strong>Input:</strong> 187 values</li><li><strong>Hidden layer 1:</strong> 128 neurons with ReLU</li><li><strong>Hidden layer 2:</strong> 64 neurons with ReLU</li><li><strong>Output:</strong> 5 raw logits, one per class</li></ul><p>That comes to <strong>32,645 trainable parameters</strong>, which is tiny by modern standards. Weights use <strong>He initialization</strong>, with variance 2/n_in, because it keeps activations at a healthy scale in ReLU networks. Biases start at zero.</p><p>Instead of using nn.Linear, we defined the weight matrices and biases as raw nn.Parameter tensors and wrote the forward pass ourselves:</p><pre>z1 = x @ self.W1.T + self.b1<br>a1 = torch.clamp(z1, min=0)      # ReLU<br>z2 = a1 @ self.W2.T + self.b2<br>a2 = torch.clamp(z2, min=0)      # ReLU<br>z3 = a2 @ self.W3.T + self.b3    # logits</pre><p>Writing it this way forced us to understand every matrix shape in the network.</p><h3>Custom Loss: Softmax Cross-Entropy</h3><p>We implemented softmax cross-entropy manually using the numerically stable log-sum-exp form:</p><pre>losses = torch.logsumexp(logits, dim=1) - logits[torch.arange(B), y]<br>return losses.mean()</pre><p>This avoids computing raw exponentials that could overflow, and it gives the same result as the textbook formula.</p><h3>Checking Our Math: Gradient Verification</h3><p>How do you know your backpropagation math is right? You compare it with something you trust.</p><p>For the output layer, we derived the gradients by hand. For softmax cross-entropy, the gradient with respect to the logits is simply (Ŷ − Y), where Ŷ is the predicted probability matrix and Y is the one-hot label matrix. From that:</p><ul><li><strong>dW3 = (Ŷ − Y)ᵀ · A2 / B</strong></li><li><strong>db3 = sum(Ŷ − Y) / B</strong></li></ul><p>We then compared these values with the gradients PyTorch computed using autograd on a batch of 64 training samples. The largest absolute differences were:</p><ul><li><strong>W3:</strong> 5.96 × 10⁻⁸</li><li><strong>b3:</strong> 1.19 × 10⁻⁷</li></ul><p>Those are float32 rounding-level differences, so our manual derivation matches autograd.</p><h3>Training: Momentum and Weight Decay, Written by Hand</h3><p>We wrote the optimizer ourselves rather than using torch.optim.SGD. Our training setup:</p><ul><li><strong>Batch size:</strong> 128</li><li><strong>Epochs:</strong> 30</li><li><strong>Momentum:</strong> 0.9</li><li><strong>Weight decay:</strong> 0.0001, applied to weights only, not biases</li><li><strong>Data:</strong> reshuffled every epoch</li></ul><p>The update for each parameter is:</p><pre>velocity = 0.9 * velocity + 0.1 * gradient   # gradient includes weight decay<br>param = param - learning_rate * velocity</pre><p>This form averages recent gradients, so noisy mini-batch gradients that point in opposite directions partly cancel out and training becomes smoother. Weight decay gently pulls weights toward zero, which helps limit overfitting. After every epoch we measured validation loss and kept a copy of the model with the <strong>lowest validation loss</strong>.</p><h3>Picking a Learning Rate</h3><p>We trained the same network with three learning rates and compared validation results:</p><ul><li><strong>0.01:</strong> best validation loss 0.1618, validation accuracy 95.79%</li><li><strong>0.1:</strong> best validation loss 0.0860, validation accuracy 97.64%</li><li><strong>0.5:</strong> best validation loss 0.0698, validation accuracy 98.02%</li></ul><p>The learning rate of <strong>0.5</strong> won. It looks large, but with the averaged-gradient update above, the effective step size is smaller than it appears.</p><h3>The Results</h3><p>We evaluated the final model once on the 21,892 unseen test beats:</p><ul><li><strong>Correct predictions:</strong> 21,410</li><li><strong>Incorrect predictions:</strong> 482</li><li><strong>Test accuracy: 97.80%</strong></li><li><strong>Balanced accuracy: 84.65%</strong></li></ul><p>The training loss dropped from about 0.176 to 0.050, and the validation loss from about 0.177 to 0.072. The validation loss stayed slightly above the training loss, which indicates mild overfitting but nothing severe.</p><h3>Why 97.8% Is Not the Whole Story</h3><p>Here is the catch. A “model” that ignores the input and always predicts <em>Normal</em> would score 18,118 / 21,892 = <strong>82.76%</strong> on this test set. Our network beats that baseline by about 15 percentage points, which is real progress, but the headline accuracy hides what happens in the rare classes.</p><p>Per-class accuracy tells the real story:</p><ul><li><strong>N:</strong> 99.61%</li><li><strong>Q:</strong> 97.70%</li><li><strong>V:</strong> 91.02%</li><li><strong>F:</strong> 70.37%</li><li><strong>S:</strong> 64.57%</li></ul><p>The weakest class is <strong>S (supraventricular beats)</strong>. Of 556 actual S beats, only 359 were identified correctly, and 186 were mistaken for normal beats. Two things likely contribute: S beats can look similar to N beats in shape, and the network sees far fewer S examples during training.</p><p>This is why we also report <strong>balanced accuracy</strong>, the average of the per-class accuracies. It comes to 84.65%, a more honest summary of how the model treats every class equally.</p><h3>How We Would Improve It</h3><p>The most direct fix for rare classes such as F, which has only 641 training samples, is <strong>class-weighted cross-entropy</strong>. Giving rare classes a larger weight makes mistakes on them more costly during training, which pushes the network to pay attention to them. We proposed this as future work and did not implement it in this project. Other natural next steps would be 1D convolutional layers that exploit the sequential nature of ECG signals, and oversampling or data augmentation for the minority classes.</p><h3>The Streamlit App</h3><p>To make the model tangible, we built an interactive dashboard with a space-themed interface. You can:</p><ul><li>Pick a sample from the MIT-BIH test set, or upload your own ECG as a CSV</li><li>See the ECG waveform plotted</li><li>Get the model’s prediction with a five-class probability distribution</li><li>Browse model architecture and dataset details</li></ul><p>The app loads the trained weights from results/best_model.pth and runs real inference. Nothing is mocked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40570b4d877b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can a Straight Line Detect a Power-Line Fault? Logistic Regression vs SVM]]></title>
            <link>https://medium.com/@f236066/can-a-straight-line-detect-a-power-line-fault-logistic-regression-vs-svm-c40aa23e8f9c?source=rss-ef9f3513eff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c40aa23e8f9c</guid>
            <dc:creator><![CDATA[F]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 20:14:38 GMT</pubDate>
            <atom:updated>2026-10-10T20:14:38.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. The problem</h3><p>When a wire in a power system touches the ground, or two wires touch each other, the line current jumps and the voltage drops. A protective relay has only a few milliseconds to notice this and trip the breaker. If it misses a fault, equipment can burn and people can get hurt.</p><p>We looked at one single instant of three line currents (Ia, Ib, Ic) and three line voltages (Va, Vb, Vc) and asked: <strong>fault or no fault?</strong> Our big question was: can a straight-line decision boundary do this from raw instantaneous numbers? If not, what is the easiest fix: better features, or a better classifier?</p><h3>2. The data</h3><p>We used the Kaggle dataset “Electrical Fault Detection and Classification”, a three-phase power system simulated in MATLAB/Simulink. The file has 12,001 rows. Each row is one instant of the six measurements, with a label: 1 for fault and 0 for no fault. We removed two completely empty columns (Unnamed: 7 and Unnamed: 8), renamed the label column to fault, and checked that all six measurement columns are numeric. There were no missing values. The data has 5,496 fault rows and 6,505 no-fault rows, so the two classes are reasonably balanced.</p><p>We split the rows 60% / 20% / 20% into train, validation and test sets with a fixed random seed (42). Then we standardised every feature using only the training mean and the training standard deviation, so nothing leaks from the validation or test rows.</p><p>ItemValueRaw rows / raw columns12001 / 9Columns removedUnnamed: 7, Unnamed: 8Missing values after cleaning0Fault rows / no-fault rows5496 / 6505Train / validation / test rows7200 / 2400 / 2401Fault fraction in train / validation / test0.4607 / 0.4512 / 0.4565</p><h3>3. What the data looks like</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqTgrGzlj-g4lFbfk7ENYg.png" /></figure><p>Figure 1: Line currents for the first 2000 rows. The red zone is a fault.</p><p>The rows are consecutive time samples. Outside the red zone the three currents are small, smooth waves of about 60 A. When the fault starts (around row 505), phase A shakes for a moment and then swings between about -875 A and +875 A, roughly fifteen times bigger than normal. The fault lasts about three cycles, then the currents return to normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*0y2Juqxn5SQGLVpk52mEaQ.png" /></figure><p>Figure 2: Ia against Ib, coloured by fault.</p><p>The no-fault points form one small blob in the centre, where both currents stay below about 80 A. The fault points trace huge ellipses around that blob, and a few scattered points sit far to the left. Some fault points also pass through the middle of the blob, because the wave crosses zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdKn0ESV7jdTZxk98mcuiw.png" /></figure><p>Figure 3: Histogram of Ia for fault and no-fault rows.</p><p>The no-fault values of Ia are packed in a narrow band around zero (about -75 A to +75 A). The fault values are spread over the whole range from -880 A to +880 A, with long tails on both the positive and the negative side. In the middle there is a noticeable pile of fault rows (roughly one in five) hiding inside the no-fault band.</p><p><strong>Could a single straight line in the (Ia, Ib) plane separate the two classes?</strong> No. A straight line cuts the plane into two halves, so it can only say “big on this side, small on the other side”. But the faulty points surround the normal points on every side. The reason is that current is an AC wave. During a fault its size becomes large, but at any single instant the value can be big and positive, big and negative, or close to zero while the wave crosses zero. What we need is a rule like “far from zero on either side”, which a straight line cannot give.</p><h3>4. Logistic regression by hand</h3><p>We wrote logistic regression ourselves in NumPy: the sigmoid, the hypothesis, the cost J(theta), and batch gradient descent for 2000 iterations. The cost starts at 0.693 when theta is zero, as it should. We tried four learning rates (0.01, 0.1, 1 and 10) and chose the largest one for which the cost went down at every iteration.</p><p>We used two feature sets. <strong>Set R</strong> is the six raw numbers. <strong>Set Q</strong> is the six raw numbers plus their six squares (12 features).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eh0OAWFPOkrEbJpCfHiLg.png" /></figure><p>Figure 4: Cost against iteration for Set R.</p><p>For Set R, the rates 0.01, 0.1 and 1 all go down smoothly and settle at the same cost (about 0.677). The rate 10 is too big: the cost jumps up and down forever and never settles. So we chose alpha = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlppnHsStmXeDfzKsA1TYQ.png" /></figure><p>Figure 5: Cost against iteration for Set Q.</p><p>For Set Q, all four rates go down at every step, and the biggest one is the fastest. So we chose alpha = 10. Its final cost (0.053) is far lower than Set R’s.</p><p>Feature setChosen alphaFinal J(theta)Train accuracyValidation accuracySet R10.6771672.58%73.08%Set Q100.0534397.88%97.83%</p><h3>5. Support vector machines</h3><p>We then trained support vector machines (scikit-learn SVC) on the six raw standardised features. We tried a linear SVM and an RBF-kernel SVM, with C in {0.1, 1, 10, 100} and gamma in {0.1, 1}, and kept the best setting of each kernel based on validation accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ae_-smulfwJla4h9V6ReEA.png" /></figure><p>Figure 6: SVM validation accuracy against C.</p><p>KernelCgammaValidation accuracySupport vectorslinear0.1–72.58%5849linear1–72.58%5834linear10–72.58%5837linear100–72.58%5839rbf0.10.195.00%1347rbf0.1198.04%848rbf10.197.50%723rbf1199.17%482rbf100.199.21%381rbf10199.62%342rbf1000.199.54%174rbf100199.67%266</p><p>The linear SVM stays flat at 72.6% whatever C we pick. The RBF SVM climbs from 95% to almost 99.7%. The best linear model is C = 1; the best RBF model is C = 100 with gamma = 1.</p><h3>6. Final test results</h3><p>We used the test rows only once, at the very end. A missed fault means the breaker does not trip,</p><p>ModelAccuracyTNFalse alarmsMissed faultsTPLogistic regression, Set R72.64%13050657439Logistic regression, Set Q97.88%12996451051Linear SVM (C = 1)73.64%13050633463RBF SVM (C = 100, gamma = 1)99.58%1301461090</p><p>The test set has 1,096 real faults. The two straight-line models missed more than half of them (657 and 633). Adding squares cut the misses to 45, and the RBF SVM missed only 6.</p><p>The Set Q weights, learned by gradient descent:</p><p>WeightValuetheta0 (intercept)24.9209Ia2.3273Ib-5.3581Ic-1.7365Va-0.5336Vb0.4167Vc0.0986Ia²¹⁸.8912Ib²⁴.7543Ic²¹³.9569Va²-6.0276Vb²-6.4643Vc²-6.1407</p><h3>7. Answers to our analysis questions</h3><p><strong>Why do logistic regression on Set R and the linear SVM score almost the same?</strong> Both draw one flat boundary through the six raw features, so they land on almost the same line: 72.64% and 73.64%, both with hundreds of missed faults. This tells us the data is not linearly separable.</p><p><strong>What do the signs of the Set Q weights mean?</strong> The weights on the squared currents are positive (+18.89, +4.75, +13.96) and the weights on the squared voltages are negative (-6.03, -6.46, -6.14). In a fault the current becomes big, and squaring removes its sign, so a big I² means “fault”. In a fault the voltage sags, so V² becomes small, and a small V² also means “fault”.</p><p><strong>What does the number of support vectors tell us?</strong> The best linear SVM uses 5,834 support vectors, 81% of the 7,200 training rows. The best RBF SVM uses only 266 (3.7%). Support vectors are points on the margin or on the wrong side of it. A huge number means the boundary does not fit the data, as happens when a straight line is forced on data that is not linearly separable.</p><p><strong>What does C do?</strong> C is the penalty for a wrong or too-close point. A small C gives a wide, relaxed margin with many support vectors. A large C is strict: the margin narrows and the model tries hard to get every training point right. For the RBF SVM, as C goes from 0.1 to 100, accuracy rises (95.00% to 99.54% for gamma = 0.1) and support vectors fall (1347 to 174). The linear SVM does not change at all, because the straight line is the real problem, not C.</p><p><strong>Is our test accuracy realistic?</strong> Probably optimistic. The rows are consecutive time samples that look almost identical, and we split them randomly, so many test rows have a near-twin in the training set. A real relay sees new fault events with different places, types and noise, so its true accuracy would be lower than our 99.58%. A fairer test would split by whole time blocks or fault events.</p><p><strong>Which model would we deploy?</strong> The RBF SVM (C = 100, gamma = 1). It has only 6 missed faults and 4 false alarms. A missed fault is the dangerous mistake, so we rank models by missed faults first and false alarms second. Set Q logistic regression is simpler and faster (a sum and a sigmoid) and reaches 97.88%, but it misses 45 faults, about seven times more. It could be a backup if the relay had very little computing power.</p><h3>8. The front end</h3><p>We also built a small Streamlit web page. You type Ia, Ib, Ic, Va, Vb and Vc, press Predict, and see the Set Q logistic regression and the RBF SVM side by side. In the example below, both models say FAULT, and the logistic regression gives a fault probability of 0.894.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oyeZagxj7915aI8hUXfWw.png" /></figure><p>Figure 7: The Streamlit front end.</p><h3>9. What we learned</h3><ol><li>A straight line cannot detect faults from raw instantaneous values (both stopped at about 73%).</li><li>Two easy fixes work: add squared features (97.88%) or use an RBF-kernel SVM (99.58%).</li><li>In protection, a missed fault is worse than a false alarm, so we must read the confusion matrix and not only the accuracy.</li><li>A random split of time-series data can make the test accuracy look better than reality.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c40aa23e8f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>