<?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 Rajpootmujtaba on Medium]]></title>
        <description><![CDATA[Stories by Rajpootmujtaba on Medium]]></description>
        <link>https://medium.com/@rajpootmujtaba537?source=rss-06ab6d86fbd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BfDKiCgD6eB6lWX4</url>
            <title>Stories by Rajpootmujtaba on Medium</title>
            <link>https://medium.com/@rajpootmujtaba537?source=rss-06ab6d86fbd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:24:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajpootmujtaba537/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[Classifying Heartbeats from ECG Signals]]></title>
            <link>https://medium.com/@rajpootmujtaba537/classifying-heartbeats-from-ecg-signals-eae214c779e7?source=rss-06ab6d86fbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae214c779e7</guid>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ecg-signals]]></category>
            <category><![CDATA[medical-devices]]></category>
            <dc:creator><![CDATA[Rajpootmujtaba]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 18:39:45 GMT</pubDate>
            <atom:updated>2026-11-09T18:39:45.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>A neural network built and trained from scratch in PyTorch</h3><h3>1. Introduction</h3><p>Electrocardiography (ECG) is an important medical technique used to monitor the electrical activity of the human heart. Each heartbeat produces a characteristic waveform, and changes in this waveform can indicate different types of cardiac abnormalities. Correctly identifying these heartbeats is important because it can help healthcare professionals detect irregular heart rhythms and make better clinical decisions.</p><p>In this project, we developed a fully connected neural network using PyTorch to classify ECG heartbeat signals into five categories: Normal (N), Supraventricular Ectopic (S), Ventricular Ectopic (V), Fusion (F), and Unknown or Paced (Q).</p><p>The network takes 187 ECG signal samples as input and predicts one of the five heartbeat categories. During this project, we implemented the network architecture, weight initialization, softmax cross-entropy loss, backpropagation, momentum-based gradient descent, and weight decay.</p><p>An important part of this project was analysing how well the network performs on different heartbeat categories, particularly because the dataset contains an unequal number of samples for each class.</p><h3>2. Understanding Class Imbalance and Overall Accuracy</h3><p>One of the main challenges in ECG heartbeat classification is class imbalance. The dataset contains significantly more normal heartbeats than abnormal heartbeats. For example, the training dataset contains 72,471 normal heartbeat samples, whereas the Fusion (F) category contains only 641 samples.</p><p>To understand why this imbalance matters, we considered a simple example: what would happen if a model always predicted every heartbeat as Normal (N)?</p><p>The test dataset contains 21,892 heartbeat samples, including 18,118 normal heartbeats.</p><p>The accuracy of this model would be:</p><p>Accuracy = (Number of Correct Predictions / Total Predictions) × 100</p><p>Accuracy = (18,118 / 21,892) × 100</p><p><strong>Always-N accuracy = 82.76%</strong></p><p>This result shows that a model could achieve approximately 82.76% accuracy without identifying even a single abnormal heartbeat correctly.</p><p>Therefore, overall accuracy alone is not a reliable measure of performance when a dataset is highly imbalanced. A model may appear successful because it correctly identifies the majority class while performing poorly on less common categories.</p><p>For this reason, we also evaluated per-class accuracy and balanced accuracy. These metrics provide a better understanding of how effectively the network recognises each heartbeat category.</p><h3>3. Per-Class Accuracy and Confusion Matrix Analysis</h3><p>To evaluate the network’s classification performance, we used a 5 × 5 confusion matrix. The rows of the confusion matrix represent the actual heartbeat categories, while the columns represent the categories predicted by the neural network.</p><p>The diagonal elements represent correctly classified heartbeats, whereas the off-diagonal elements represent incorrect predictions.</p><p>Per-class accuracy was calculated using:</p><p>Per-Class Accuracy = Correct Predictions for a Class / Total Actual Samples of That Class</p><p>We calculated this value separately for N, S, V, F, and Q.</p><p>The class with the lowest per-class accuracy represents the most difficult heartbeat category for our neural network to recognise.</p><p>According to the confusion matrix, this class was most frequently misclassified as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*VWwlBN6peR-I-LJZ.png" /></figure><p>One possible reason for this classification difficulty is that some abnormal heartbeat categories have similar waveform characteristics. Their ECG signals may contain overlapping patterns, making it difficult for a relatively small fully connected neural network to distinguish between them.</p><p>The limited number of training examples for certain heartbeat categories can also affect the model’s ability to learn their distinguishing features.</p><p>Therefore, analysing the confusion matrix provides more useful information than looking at overall accuracy alone.</p><h3>4. Training Performance: Overfitting and Underfitting</h3><p>During the training process, we monitored both training loss and validation loss over 30 epochs.</p><p>Training loss measures how well the neural network performs on the data used to train it, while validation loss measures how well it performs on previously unseen validation samples.</p><p>Comparing these two values helps us understand whether the network is learning useful patterns or simply memorising the training data.</p><p>There are three important possibilities:</p><p><strong>Overfitting:</strong> Overfitting occurs when training loss continues to decrease while validation loss starts increasing. This indicates that the network is learning the training examples very well but is not generalising effectively to new data.</p><p><strong>Underfitting:</strong> Underfitting occurs when both training and validation losses remain relatively high. This suggests that the network has not learned the underlying patterns in the ECG signals sufficiently.</p><p><strong>Good Generalisation:</strong> When both training and validation losses decrease and remain reasonably close, it suggests that the network is learning useful features and performing consistently on unseen data.</p><p>In our project, we used training and validation loss curves to investigate the network’s learning behaviour.</p><p><strong>Our observation:</strong></p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*tD2uLC0OxPPVT3mT.png" /></figure><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*0lGlk5hzFi4edoAO.png" /></figure><p>Monitoring validation loss was also important when selecting the learning rate and saving the model. We selected the model parameters from the epoch with the lowest validation loss to obtain the best validation performance.</p><h3>5. Importance of Weight Initialization and He Initialization</h3><p>Weight initialization plays an important role in training neural networks. We did not initialize every weight to zero because doing so would create a symmetry problem.</p><p>If all neurons in the same layer start with identical weights and biases, they will produce identical outputs and receive identical gradients during backpropagation. As a result, these neurons will continue learning the same features instead of developing different representations of the input data.</p><p>To avoid this problem, we used random weight initialization.</p><p>Specifically, we implemented He initialization, which is suitable for neural networks that use the ReLU activation function.</p><p>The standard deviation used for initialization is:</p><p>σ = √(2 / n_in)</p><p>Here, n_in represents the number of input neurons connected to the layer.</p><p>He initialization helps maintain the variance of activations as information passes through the network. This is particularly useful with ReLU because negative input values are converted to zero.</p><p>By using this initialization method, we aimed to improve the stability of training and reduce the possibility of activation values becoming excessively small or large across layers.</p><h3>6. Role of Momentum and Weight Decay in Training</h3><p>In addition to gradient descent, we implemented momentum and L2 weight decay to improve the training process.</p><h3>6.1 Momentum</h3><p>Momentum helps make gradient descent smoother and can reduce unnecessary fluctuations during training.</p><p>Instead of updating the weights using only the current gradient, momentum considers the previous velocity.</p><p>The update equation is:</p><p>v = βv + (1 − β)g</p><p>Here, v represents velocity, β is the momentum coefficient, and g represents the current gradient.</p><p>In our assignment, the momentum coefficient was set to 0.9.</p><p>When two consecutive mini-batch gradients point in opposite directions, the previous velocity helps reduce the sudden effect of the new gradient. Depending on their magnitudes, the velocity may decrease, reverse direction, or continue in its previous direction.</p><p>This makes the updates smoother and can help the network converge more consistently.</p><h3>6.2 Weight Decay</h3><p>Weight decay is a regularization technique used to discourage excessively large weight values.</p><p>In our implementation, the gradient for each weight was modified as follows:</p><p>g = ∂J/∂P + λP</p><p>Here, λ represents the weight decay coefficient, which was set to 0.0001.</p><p>If a weight receives no other gradient, weight decay still produces a gradient proportional to its current value. Consequently, the update moves the weight towards zero.</p><p>This helps control the size of the network weights and can reduce overfitting.</p><p>Importantly, we applied weight decay to the weight matrices but not to the bias parameters, as required by the assignment.</p><h3>7. Improving Performance on Rare Heartbeat Categories</h3><p>The Fusion (F) category presents a particular challenge because it contains only 641 training samples, compared with 72,471 samples in the Normal category.</p><p>This difference makes it difficult for the network to learn the characteristics of rare heartbeat categories effectively.</p><p>One possible improvement is <strong>oversampling</strong>.</p><p>Oversampling increases the representation of minority classes in the training dataset. This can be achieved by repeating existing minority-class examples or generating additional realistic examples using suitable data augmentation techniques.</p><p>By increasing the number of Fusion heartbeat examples, the network would receive more opportunities to learn their waveform characteristics.</p><p>Another possible approach is class-weighted cross-entropy loss. This method assigns greater importance to classification errors involving underrepresented classes.</p><p>As a result, the network would be encouraged to pay more attention to rare heartbeat categories instead of focusing primarily on the majority Normal category.</p><p>These approaches could potentially improve balanced accuracy and minority-class recognition.</p><p>However, any additional training strategy would need to be evaluated using the validation dataset before being considered an improvement.</p><h3>8. Conclusion</h3><p>This project demonstrated how a fully connected neural network can be developed from scratch using PyTorch for ECG heartbeat classification.</p><p>We implemented the network using manually created weight matrices and biases, ReLU activation, He initialization, softmax cross-entropy loss, backpropagation, mini-batch gradient descent, momentum, and weight decay.</p><p>The analysis also demonstrated why overall accuracy is not sufficient for evaluating a classifier trained on an imbalanced dataset. In particular, the always-N baseline achieves approximately 82.76% accuracy despite completely ignoring abnormal heartbeat categories.</p><p>Per-class accuracy, balanced accuracy, and the confusion matrix provide a more meaningful evaluation of classification performance.</p><p>Finally, techniques such as oversampling and class-weighted loss could help improve the recognition of rare heartbeat categories, particularly the Fusion class.</p><p>Overall, this project provided practical experience in neural network implementation, optimization, performance evaluation, and understanding the challenges of applying machine learning to medical signal classification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae214c779e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Faults on a Three-Phase Transmission Line]]></title>
            <link>https://medium.com/@rajpootmujtaba537/detecting-faults-on-a-three-phase-transmission-line-94bb1f1a64bc?source=rss-06ab6d86fbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/94bb1f1a64bc</guid>
            <category><![CDATA[fault-detection]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rajpootmujtaba]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 13:02:55 GMT</pubDate>
            <atom:updated>2026-10-11T13:02:55.851Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Author : Muhammad Mujtaba</em></p><h3>Introduction</h3><p>Electrical transmission lines are essential for delivering power safely and reliably. When a fault occurs, such as a phase-to-ground fault or a phase-to-phase fault, the electrical currents and voltages can change rapidly. Protective relays must identify these conditions and initiate the appropriate protection response.</p><p>Traditional protection systems use carefully designed electrical measurements and protection logic. In this project, we investigate whether machine learning can classify electrical measurements as either a fault or a no-fault condition.</p><p>The main objective is to compare linear and nonlinear classification methods and determine whether engineering features can improve fault detection.</p><h3>Dataset and Preparation</h3><p>The project uses the Electrical Fault Detection and Classification dataset from Kaggle. The dataset was generated through MATLAB/Simulink power-system simulations.</p><p>Each observation contains six measurements: phase currents Ia, Ib and Ic, and phase voltages Va, Vb and Vc. The target variable, named fault, indicates whether the observation represents a fault. A value of 1 represents a fault, while 0 represents a no-fault condition.</p><p>After loading the CSV file, two empty columns were removed. The label column was renamed, and the measurement columns were checked for numeric values and missing data.</p><p>The cleaned dataset contained 12,001 observations, including 5,496 fault observations and 6,505 no-fault observations.</p><p>The data was randomly divided into training, validation and test sets using the required seed of 42. The resulting sets contained 7,200, 2,400 and 2,401 observations, respectively.</p><p>Feature standardisation used the training-set means and standard deviations. The same statistics were then applied to the validation and test sets to prevent data leakage.</p><h3>Exploratory Data Analysis</h3><p>Three plots were produced to investigate the relationship between electrical measurements and fault conditions.</p><p>The first plot showed the three phase currents across the first 2,000 observations, with fault regions shaded. This allowed us to compare current behaviour with the recorded fault labels.</p><p>The second plot compared Ia against Ib. The two classes did not form a clearly separable pattern using a single straight line. Fault conditions can affect the phase currents differently, producing overlapping and nonlinear relationships.</p><p>The third plot compared the distribution of Ia during fault and no-fault conditions. Differences between the distributions showed that phase current contains useful information for classification. However, overlapping current values indicated that a single measurement would not be sufficient to classify every observation correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7rNuoAiOYk_byhdu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*NSkXQ1BF5Qjz39tP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_1KRyHJU5TGc7LQN.png" /></figure><h3>Logistic Regression</h3><p>Logistic regression was implemented from scratch using NumPy. The implementation included the sigmoid function, hypothesis, binary cross-entropy cost, batch gradient descent and prediction function.</p><p>Two feature sets were evaluated. Set R contained the six original measurements. Set Q contained those measurements and their six squared values.</p><p>The learning rate was selected by comparing cost curves for 0.01, 0.1, 1 and 10 over 2,000 iterations. The selected learning rates were 1 for Set R and 10 for Set Q.</p><p>Set R achieved approximately 72.58% training accuracy and 73.08% validation accuracy. Set Q achieved approximately 97.88% training accuracy and 97.83% validation accuracy.</p><p>This improvement demonstrates that feature engineering can significantly improve a linear classifier. Although logistic regression remains linear in its expanded feature space, the squared terms allow it to represent nonlinear relationships in the original measurements.</p><h3>Support Vector Machines</h3><p>Support Vector Machines were trained using scikit-learn’s SVC implementation. Four C values were evaluated for the linear kernel. Eight combinations of C and gamma were evaluated for the RBF kernel.</p><p>The linear SVM achieved approximately 72.58% validation accuracy across the tested C values. The best RBF model used C = 100 and gamma = 1, achieving approximately 99.67% validation accuracy.</p><p>The difference between the linear and RBF models suggests that a nonlinear decision boundary is better suited to these simulated observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SMxiczUnoqgLyMmY.png" /></figure><p><strong>Q1 Logistic regression on Set R and the linear SVM should score almost the same. Why?<br>What does that tell you about the data?</strong></p><p>A. Both models use the same six standardised measurements and learn a linear decision boundary. Logistic regression learns weights by minimising log-loss, whereas a linear SVM learns a maximum-margin boundary. Their objectives differ, but both are limited to linear separation in the original feature space. Their similar results suggest that a linear boundary is insufficient to capture the more complicated fault patterns in this dataset.</p><p><strong>Q2 Look at your Set Q weights. What sign do the weights on I² terms have, and what sign do the weights on V² terms have? Explain both signs using what happens to current and voltage during a fault?</strong></p><p>A. The positive current-square weights mean that larger squared current measurements tend to increase the predicted fault probability, holding the other features fixed. The negative voltage-square weights mean that larger squared voltage measurements tend to reduce that probability, holding the other features fixed. This is broadly consistent with faults causing elevated currents and voltage sags. However, the coefficients are learned associations, not proof of causation, and individual linear terms also affect the prediction.</p><p><strong>Q3 Compare the number of support vectors of your best linear SVM with your best RBF SVM. What does a very large number of support vectors mean?</strong></p><ul><li>Best linear SVM: <strong>5,835 support vectors.</strong></li><li>Best RBF SVM: <strong>266 support vectors.</strong></li><li>A support vector is a training sample that helps determine the SVM’s decision boundary. A large number of support vectors means the decision boundary depends on many training observations. The linear model’s much larger count is consistent with its difficulty separating these classes using a straight boundary.</li></ul><p>The number alone is not a universal measure of model quality.</p><p><strong>Q4 From your validation table, what happens to accuracy and to the number of support vectors as C increases? Explain using what C controls?</strong></p><p>The linear SVM’s validation accuracy stays approximately 72.58% across all four values of C. Its support-vector count changes only slightly.</p><p>For the RBF SVM, validation accuracy generally improves as C increases, although it is not strictly monotonic for every gamma. The support-vector count generally decreases as C increases in these results, but not at every step.</p><p>A larger C penalises training errors more strongly and allows a tighter fit to the training data. This can improve classification, but it can also increase overfitting risk. Gamma controls the shape and local influence of the RBF kernel, so its effect must be considered alongside C.</p><p><strong>Q5 The rows are consecutive time samples, and the split was random, so neighbouring samples (which look almost identical) land in both training and test sets. Do you think your test accuracy is optimistic or pessimistic for a real relay? Why?</strong></p><p>It is likely to be optimistic. The rows are consecutive time samples, and neighbouring samples can be highly correlated. Randomly splitting rows means very similar observations may appear in both training and test sets. The test score can therefore overestimate performance on genuinely unseen faults, operating conditions, or time periods. A chronological or event-based split would provide a stronger test of generalisation.</p><p><strong>Q6 If you were designing the relay, which model would you deploy? Base your answer on missed faults and false alarms, not only accuracy.</strong></p><p>Based on these results, I would select the RBF SVM for further validation because it has only six missed faults and four false alarms on the test set. Set Q logistic regression is a simpler alternative, but it misses 45 faults.</p><p>However, I would not deploy either model directly on a real power system based only on this experiment. I would test it on independent fault events, different operating conditions, and a time-separated dataset, then assess missed-fault rates, false trips, response time and fail-safe behaviour. A real protective relay must satisfy the relevant protection and safety requirements.</p><h3>Test Results</h3><p>After selecting hyperparameters using validation data, the four final models were evaluated on the held-out test set.</p><p>Logistic regression using Set R achieved approximately 72.64% accuracy and missed 657 faults. The linear SVM achieved approximately 73.64% accuracy and missed 633 faults.</p><p>Set Q logistic regression achieved approximately 97.88% accuracy and missed 45 faults. The RBF SVM achieved approximately 99.58% accuracy, with four false alarms and six missed faults.</p><p>These results highlight the importance of examining the confusion matrix rather than accuracy alone. In power-system protection, a missed fault may prevent the system from responding when protection is required. False alarms also matter because unnecessary trips can interrupt the power supply.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7pO9_r0TYOBmwMN8.png" /></figure><h3>Limitations and Conclusion</h3><p>The experiment demonstrates that nonlinear feature engineering and the RBF kernel can improve classification performance on this dataset. It also shows how logistic regression can be implemented mathematically without using a prebuilt logistic regression estimator.</p><p>However, the results must be interpreted carefully. The dataset consists of consecutive simulated time samples, and random splitting can place highly correlated observations in both training and test sets. This may make the reported test accuracy optimistic compared with performance on unseen fault events.</p><p>Future work should evaluate the models using chronological or event-based splits, additional operating conditions and independently generated fault scenarios. Detection latency, false-trip rates and performance under measurement noise should also be investigated.</p><p>The project provides a useful foundation for machine-learning-based fault detection, but further validation and protection engineering are necessary before any model could be considered for real-world relay deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94bb1f1a64bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Solar Power Plant Output from Weather Data]]></title>
            <link>https://medium.com/@rajpootmujtaba537/predicting-solar-power-plant-output-from-weather-data-015e039e652c?source=rss-06ab6d86fbd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/015e039e652c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[electrical-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[paython]]></category>
            <dc:creator><![CDATA[Rajpootmujtaba]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 16:28:54 GMT</pubDate>
            <atom:updated>2026-09-15T16:28:54.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Building linear regression from scratch — normal equation, batch gradient descent, and stochastic gradient descent — to answer a question every installer without a monitoring budget actually cares about.</p><p><em>Author : Muhammad Mujtaba</em></p><h3>Introduction</h3><p>Solar photovoltaic power generation depends strongly on weather conditions. The amount of sunlight reaching the panels directly affects the amount of electricity produced, while temperature also influences the performance of photovoltaic modules. Solar plants normally use on-site sensors to measure conditions such as irradiation and temperature. However, installing and maintaining these sensors may not always be practical, especially for a rooftop installer or a small solar installation.</p><p><strong>How much prediction accuracy is lost when on-site irradiation and temperature sensors are replaced by free public weather data?</strong></p><p>To answer this question, a linear regression model was developed using three different optimization methods: the Normal Equation, Batch Gradient Descent, and Stochastic Gradient Descent. The objective was to predict the hourly AC power output of Plant 1 using weather-related features.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DU0OqYwkNou0eK83.png" /></figure><p>Figure 1</p><h3>The Data</h3><p>The core dataset comes from Kaggle’s <em>Solar Power Generation Data</em>: two grid-connected photovoltaic plants in India, with readings every 15 minutes over 34 days (15 May — 17 June 2020). This project used <strong>Plant 1</strong>, which ships as two files — a generation log (68,778 rows across 22 inverters) and a weather-sensor log (3,182 rows) — that had to be cleaned and merged before anything else could happen.</p><p>The pipeline looked like this:</p><ol><li><strong>Parse timestamps.</strong> The generation file and the sensor file don’t store dates in the same format, so each needed its own parsing rule.</li><li><strong>Aggregate to plant level.</strong> AC power is logged per inverter, so all 22 inverters were summed at each timestamp to get total plant output.</li><li><strong>Merge.</strong> Plant-level power was joined to the sensor readings (irradiation, module temperature, ambient temperature) on timestamp.</li><li><strong>Resample to hourly.</strong> Averaging down from 15-minute readings to hourly gives roughly 34 days × 24 hours ≈ 816 rows. After dropping rows with missing sensor values, <strong>796 hourly rows</strong> remained — a clean, small, well-behaved dataset for hand-rolled linear algebra.</li></ol><p>For the “public weather” half of the comparison, hourly historical weather was pulled directly from the <strong>Open-Meteo</strong> archive API for the plant’s approximate coordinates (14.82°N, 78.28°E), covering the same date range, giving shortwave radiation and 2-meter air temperature with no API key required.</p><h3>Location Check</h3><p>The public weather data was selected according to the location of Plant 1. The plant location used for the weather query was approximately <strong>14.82° latitude and 78.28° longitude</strong>, with the local timezone set to Asia/Kolkata.</p><p>The historical weather data was requested for the same period as the generation dataset, from <strong>15 May 2020 to 17 June 2020</strong>. The public solar radiation values were converted from W/m² to kW/m² so that they could be compared with the plant’s irradiation measurements.</p><p>Matching the location and time period is important because weather data from a different location could produce misleading predictions even if the regression method itself is correct.</p><h3>The Model</h3><p>Following the lecture notation, the hypothesis is a plain linear function of the features, hθ(x)=θ⊤xh_\theta(x) = \theta^\top x hθ​(x)=θ⊤x, fit by minimizing the least-squares cost J(θ)=12∑(hθ(x(i))−y(i))2J(\theta) = \frac{1}{2}\sum (h_\theta(x^{(i)}) — y^{(i)})² J(θ)=21​∑(hθ​(x(i))−y(i))2. Three solvers were implemented from scratch and compared against each other:</p><ul><li><strong>Normal equation</strong> — the closed-form solution θ=(X⊤X)−1X⊤y\theta = (X^\top X)^{-1}X^\top y θ=(X⊤X)−1X⊤y, computed in a single matrix operation.</li><li><strong>Batch gradient descent</strong> — repeatedly stepping every weight in the direction that reduces the cost over the <em>entire</em> training set.</li><li><strong>Stochastic gradient descent</strong> — the same idea, but updating weights after looking at <em>one</em> training row at a time.</li></ul><p>Two feature sets were compared:</p><ul><li><strong>Set A (on-site sensors):</strong> irradiation, module temperature, ambient temperature.</li><li><strong>Set B (public weather only):</strong> downloaded shortwave radiation and temperature.</li></ul><h3>The Results</h3><p>Test RMSE and R²</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*3HJyCCHDh8-W2353.png" /></figure><h3>Optimization Decision</h3><p>For the current dataset, the <strong>Normal Equation</strong> is the preferred method because the dataset is relatively small and it provides a direct solution with excellent accuracy.</p><p>For a dataset containing approximately <strong>10 million rows</strong>, an iterative gradient-based method would be more suitable. Stochastic Gradient Descent would be attractive because it processes individual samples and does not require the complete dataset to be used for every parameter update. This makes it more suitable for very large datasets.</p><p>The Batch Gradient Descent cost curve is expected to be smoother because each update uses the complete training dataset. In contrast, the SGD cost curve is noisier because each update is based on one sample.</p><h3>Actual vs. predicted AC power over the test week, Public Weather model</h3><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1g4YIXstPT0PC98D.png" /></figure><p>The value of RMSE of Public Weather model is <strong>3206.469623</strong></p><h3>Actual vs. predicted AC power over the test week, On site weather model</h3><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7bAtBxG2XVtpeYM.png" /></figure><p>The value of RMSE of On site Weather model is <strong>658.016060</strong></p><h3>Conclusion</h3><p>This project demonstrates the trade-off between local sensor measurements and free public weather data for solar power prediction. On-site sensor measurements provide more direct information about the actual conditions at the PV plant, while public weather data provides a low-cost alternative.</p><p>The current results show that the local-sensor model performs better than the public-weather model. Therefore, public weather data can be useful for a rooftop installer when the objective is preliminary estimation and system planning. However, its suitability depends on how large the daytime RMSE is compared with the plant’s peak hourly AC power.</p><p>Overall, the experiment shows that the choice of weather data can have a significant effect on solar power prediction accuracy, while the choice of optimization method also depends on dataset size. The Normal Equation is convenient for smaller datasets, whereas gradient-based methods become more attractive as the dataset grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=015e039e652c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>