LAB 03 | المختبر 03

Machine Learning Load Forecasting

التنبؤ بالحمل الكهربائي باستخدام التعلم الآلي
Linear Regression, Training, Prediction, and Error Evaluation
الانحدار الخطي والتدريب والتنبؤ وتقييم الخطأ

🎯 Lab Objectives

  • Understand load forecasting as a supervised-learning problem.
  • Construct a simple electrical-load dataset.
  • Understand linear regression mathematically.
  • Estimate model parameters in MATLAB.
  • Predict electrical load from temperature.
  • Calculate MAE, MSE, and RMSE.
  • Visualize actual and predicted load.

🎯 أهداف المختبر

  • فهم التنبؤ بالحمل كمسألة تعلم خاضع للإشراف.
  • إنشاء مجموعة بيانات بسيطة للحمل الكهربائي.
  • فهم الانحدار الخطي رياضيًا.
  • تقدير معاملات النموذج باستخدام MATLAB.
  • التنبؤ بالحمل اعتمادًا على درجة الحرارة.
  • حساب MAE وMSE وRMSE.
  • رسم الحمل الحقيقي والمتنبأ به.

1. Load Forecasting Problem

Electrical load forecasting estimates future power demand using historical measurements and explanatory variables.

Future Load = f(Historical Data, Weather, Time, ...)

In this first example, we intentionally use only one input:

Temperature → Electrical Load

1. مسألة التنبؤ بالحمل

يهدف التنبؤ بالحمل الكهربائي إلى تقدير الطلب المستقبلي على القدرة اعتمادًا على البيانات التاريخية والعوامل المؤثرة.

الحمل المستقبلي = f(البيانات السابقة، الطقس، الزمن، ...)

سنبدأ بنموذج بسيط يستخدم درجة الحرارة كدخل واحد.

2. Supervised Learning

For each training sample, we know both the input and the desired output.

x → t

In this laboratory:

x = Temperature [°C]
t = Electrical Load [MW]
The model learns the relationship between temperature and load from examples.

2. التعلم الخاضع للإشراف

لكل عينة تدريب نعرف قيمة الدخل والقيمة الصحيحة المطلوبة.

درجة الحرارة → الحمل الكهربائي
يتعلم النموذج العلاقة الرياضية من الأمثلة المتوفرة في بيانات التدريب.

3. Example Dataset

Sample Temperature [°C] Load [MW]
110105
212110
314116
416121
518128
620134
722141
824147
926154
1028162

3. مجموعة البيانات

تمثل كل عينة درجة حرارة مقاسة والحمل الكهربائي المقابل لها.

هذه البيانات تعليمية ومبسطة لفهم الخوارزمية، وليست بيانات شبكة حقيقية.

4. Enter the Data in MATLAB

temperature = [10 12 14 16 18 20 22 24 26 28]';

loadMW = [105 110 116 121 128 134 141 147 154 162]';

The apostrophe converts each vector into a column vector.

4. إدخال البيانات إلى MATLAB

نخزن درجات الحرارة والحمل في متجهين عموديين بحيث تمثل كل صفّة عينة تدريب واحدة.

5. Linear Regression Model

Assume a linear relationship:

ŷ = β₀ + β₁x

where:

  • ŷ = predicted electrical load
  • x = temperature
  • β₀ = intercept
  • β₁ = slope

5. نموذج الانحدار الخطي

ŷ = β₀ + β₁x

حيث β₀ هو الجزء الثابت، وβ₁ يمثل مقدار تغير الحمل المتوقع عند تغير درجة الحرارة بمقدار درجة واحدة.

6. Prediction Error

For sample i:

eᵢ = tᵢ - ŷᵢ

A good model should make these residual errors small.

6. خطأ التنبؤ

eᵢ = tᵢ - ŷᵢ

يمثل الخطأ الفرق بين الحمل الحقيقي والحمل الذي تنبأ به النموذج.

7. Least-Squares Principle

Linear regression selects the parameters that minimize the sum of squared errors:

J(β₀,β₁) = Σ [tᵢ-(β₀+β₁xᵢ)]²

Therefore:

min J(β₀,β₁)

7. مبدأ المربعات الصغرى

نبحث عن β₀ وβ₁ بحيث يصبح مجموع مربعات أخطاء التنبؤ أصغر ما يمكن.

min Σ [tᵢ-(β₀+β₁xᵢ)]²
هنا تحدث عملية التعلم: نحدد معاملات النموذج من البيانات بدل اختيارها يدويًا.

8. Matrix Form

Write the model for all samples:

ŷ = Xβ

with:

β = [β₀ β₁]ᵀ

and:

X = [1 x₁; 1 x₂; ... ; 1 xₙ]

8. الصيغة المصفوفية

يمكن كتابة جميع معادلات عينات التدريب بصورة مختصرة:

ŷ = Xβ

العمود الأول من X يخص المعامل الثابت β₀، والعمود الثاني يحتوي على قيم درجة الحرارة.

9. Deriving the Optimal Parameters

The squared-error function is:

J(β) = (t-Xβ)ᵀ(t-Xβ)

Differentiate with respect to β:

∂J/∂β = -2Xᵀ(t-Xβ)

At the minimum:

∂J/∂β = 0

therefore:

XᵀXβ = Xᵀt

which gives the normal-equation solution:

β = (XᵀX)⁻¹Xᵀt

9. اشتقاق معاملات النموذج

نشتق دالة الخطأ بالنسبة إلى معاملات النموذج، ثم نساوي المشتقة بالصفر لأننا نبحث عن القيمة الدنيا.

∂J/∂β = -2Xᵀ(t-Xβ)=0

ومنها:

XᵀXβ=Xᵀt
β=(XᵀX)⁻¹Xᵀt
هذه المعادلة توضح رياضيًا كيف يتعلم الانحدار الخطي معاملاته من البيانات.

10. MATLAB Implementation

X = [ones(size(temperature)) temperature];

beta = X \ loadMW;

MATLAB's backslash operator solves the least-squares problem directly and is generally preferable to explicitly computing a matrix inverse.

beta0 = beta(1);
beta1 = beta(2);

10. التنفيذ في MATLAB

نبني المصفوفة X ثم نستخدم العامل \ لحساب معاملات الانحدار بطريقة عددية مستقرة.

beta = X \ loadMW;
من الأفضل عدديًا استخدام العامل \ بدل حساب inv(X'*X) بصورة مباشرة.

11. Make Predictions

Once β₀ and β₁ are known:

ŷᵢ = β₀ + β₁xᵢ

MATLAB:

predictedLoad = X * beta;

11. إجراء التنبؤ

بعد تعلم معاملات النموذج يمكن حساب الحمل المتوقع لكل درجة حرارة.

predictedLoad = X * beta;

12. Mean Absolute Error — MAE

MAE = (1/n) Σ |tᵢ-ŷᵢ|
MAE = mean(abs(loadMW - predictedLoad));

MAE gives the average magnitude of the prediction error in MW.

12. متوسط الخطأ المطلق MAE

MAE = (1/n) Σ |tᵢ-ŷᵢ|

إذا كان MAE=2 MW مثلًا، فهذا يعني أن مقدار خطأ التنبؤ المتوسط يقارب 2 MW.

13. Mean Squared Error — MSE

MSE = (1/n) Σ (tᵢ-ŷᵢ)²
MSE = mean((loadMW - predictedLoad).^2);

Squaring makes larger errors more influential.

13. متوسط مربع الخطأ MSE

يتم تربيع الخطأ قبل حساب المتوسط، ولذلك تحصل الأخطاء الكبيرة على وزن أكبر.

MSE = (1/n) Σ (tᵢ-ŷᵢ)²

14. Root Mean Squared Error — RMSE

RMSE = √MSE
RMSE = sqrt(MSE);
RMSE has the same physical unit as the electrical load: MW.

14. الجذر التربيعي لمتوسط مربع الخطأ RMSE

RMSE = √MSE

الميزة المهمة أن وحدة RMSE هي MW نفسها، مما يجعل تفسيرها أسهل.

15. Actual vs Predicted Load

figure

plot(temperature,loadMW,'o','LineWidth',1.6)
hold on

plot(temperature,predictedLoad,'-','LineWidth',1.8)

grid on

xlabel('Temperature [°C]')
ylabel('Electrical Load [MW]')

legend('Actual Load','Predicted Load','Location','best')

title('Electrical Load Forecasting')
The distance between each measured point and the regression line represents the prediction residual.

15. الحمل الحقيقي مقابل الحمل المتنبأ به

تمثل النقاط الحمل الحقيقي، بينما يمثل الخط خرج نموذج الانحدار الخطي.

كلما اقترب الخط من نقاط القياس، كانت أخطاء النموذج أصغر.

16. Forecast a New Operating Point

Suppose tomorrow's expected temperature is:

Tnew = 30°C

The predicted load is:

P̂new = β₀ + β₁Tnew
Tnew = 30;

forecastLoad = beta0 + beta1*Tnew;

fprintf('Forecast at %.1f C = %.2f MW\n', ...
        Tnew,forecastLoad);

16. التنبؤ بحالة جديدة

إذا كانت درجة الحرارة المتوقعة غدًا 30°C، يمكن استخدام النموذج المتعلم للتنبؤ بالحمل دون وجود قيمة الحمل مسبقًا.

P̂new = β₀ + β₁(30)
هذه هي الفكرة الأساسية للتنبؤ: التعلم من بيانات معروفة ثم استخدام النموذج مع بيانات جديدة.

17. Complete MATLAB Program

clear; clc; close all;

% -----------------------------------------------
% Machine Learning Load Forecasting
% Linear Regression
% -----------------------------------------------

% Dataset
temperature = [10 12 14 16 18 20 22 24 26 28]';

loadMW = [105 110 116 121 128 134 141 147 154 162]';

% -----------------------------------------------
% Build regression matrix
% y = beta0 + beta1*x
% -----------------------------------------------

X = [ones(size(temperature)) temperature];

% Least-squares training
beta = X \ loadMW;

beta0 = beta(1);
beta1 = beta(2);

% -----------------------------------------------
% Prediction on training data
% -----------------------------------------------

predictedLoad = X * beta;

% Residual error
error = loadMW - predictedLoad;

% -----------------------------------------------
% Performance indices
% -----------------------------------------------

MAE = mean(abs(error));

MSE = mean(error.^2);

RMSE = sqrt(MSE);

% -----------------------------------------------
% Display model
% -----------------------------------------------

fprintf('Learned model:\n')
fprintf('Load = %.4f + %.4f * Temperature\n\n', ...
        beta0,beta1)

fprintf('MAE  = %.4f MW\n',MAE)
fprintf('MSE  = %.4f MW^2\n',MSE)
fprintf('RMSE = %.4f MW\n\n',RMSE)

% -----------------------------------------------
% Forecast new temperature
% -----------------------------------------------

Tnew = 30;

forecastLoad = beta0 + beta1*Tnew;

fprintf('Forecast for T = %.1f C: %.2f MW\n', ...
        Tnew,forecastLoad)

% -----------------------------------------------
% Plot actual and predicted load
% -----------------------------------------------

figure

plot(temperature,loadMW,'o','LineWidth',1.6)
hold on

plot(temperature,predictedLoad,'-','LineWidth',1.8)

grid on

xlabel('Temperature [°C]')
ylabel('Electrical Load [MW]')

legend('Actual Load','Predicted Load', ...
       'Location','best')

title('Machine Learning Load Forecasting')

% -----------------------------------------------
% Plot prediction errors
% -----------------------------------------------

figure

stem(temperature,error,'LineWidth',1.5)

grid on

xlabel('Temperature [°C]')
ylabel('Prediction Error [MW]')

title('Load Forecasting Residuals')

17. البرنامج الكامل في MATLAB

ينفذ البرنامج جميع مراحل المسألة:

Data
Training
Model
Prediction
Evaluation

أي: البيانات ← التدريب ← النموذج ← التنبؤ ← تقييم الأداء.

18. What Does β₁ Mean Physically?

β₁ = ΔLoad / ΔTemperature

Its approximate unit is:

MW / °C

For this educational dataset, a positive β₁ means that load tends to increase as temperature increases.

18. ماذا يعني β₁ فيزيائيًا؟

β₁ = ΔLoad / ΔTemperature

أي أنه يمثل حساسية الحمل تجاه تغير درجة الحرارة، ووحدته التقريبية:

MW / °C
هذا مثال مهم على الربط بين معامل رياضي داخل نموذج التعلم الآلي ومعناه الهندسي.

19. Training Data vs Test Data

Evaluating a model only on the same data used for training can give an overly optimistic impression.

Dataset
Training Set
+
Test Set
Training data are used to learn the parameters. Test data should be used to evaluate the model on unseen examples.

19. بيانات التدريب وبيانات الاختبار

لا يكفي اختبار النموذج على البيانات نفسها التي استخدمناها في التدريب.

بيانات التدريب تستخدم لتعلم معاملات النموذج، بينما تستخدم بيانات الاختبار لقياس قدرة النموذج على التنبؤ بقيم لم يرها أثناء التدريب.

20. Simple Train/Test Experiment

Use the first seven samples for training and the last three for testing:

xTrain = temperature(1:7);
yTrain = loadMW(1:7);

xTest = temperature(8:10);
yTest = loadMW(8:10);

Xtrain = [ones(size(xTrain)) xTrain];

betaTest = Xtrain \ yTrain;

Xtest = [ones(size(xTest)) xTest];

yPrediction = Xtest * betaTest;

testError = yTest - yPrediction;

RMSEtest = sqrt(mean(testError.^2));

fprintf('Test RMSE = %.4f MW\n',RMSEtest)

20. تجربة بسيطة للتدريب والاختبار

نستخدم العينات السبع الأولى لتدريب النموذج، ثم نختبره على ثلاث عينات لم تدخل في عملية التدريب.

هذه الخطوة أقرب إلى الطريقة الصحيحة لتقييم نموذج تعلم آلي.

21. Extending the Model

Real load forecasting rarely depends on temperature alone.

A more realistic input vector may be:

x = [Temperature, Hour, Day, Previous Load, Solar Irradiance, ...]

The model becomes:

P̂ = β₀ + β₁T + β₂H + β₃D + β₄Pprevious + ...

21. تطوير النموذج

في التطبيقات الحقيقية لا يعتمد الحمل عادةً على درجة الحرارة وحدها.

يمكن إضافة الساعة، ونوع اليوم، والحمل السابق، والطقس وغيرها من المتغيرات.

P̂ = β₀ + β₁T + β₂H + β₃D + β₄Pprevious + ...

22. Experiment 1 — Add Measurement Noise

Replace the original load data by:

loadNoisy = loadMW + 3*randn(size(loadMW));

Train the model again and observe how the regression line and RMSE change.

22. التجربة 1 — إضافة ضجيج للقياسات

أضف ضجيجًا عشوائيًا إلى بيانات الحمل، ثم أعد التدريب وقارن النتائج.

هذه التجربة توضح تأثير جودة القياسات على أداء التعلم الآلي.

23. Experiment 2 — Remove Training Samples

Train using only a small number of samples and compare the prediction.

For example:

temperatureSmall = temperature(1:4);
loadSmall = loadMW(1:4);
Ask: Does having fewer training examples affect confidence in the model?

23. التجربة 2 — تقليل بيانات التدريب

استخدم أربع عينات فقط في التدريب ثم قارن النموذج بالنموذج الأصلي.

الهدف هو فهم أهمية كمية البيانات المستخدمة في التعلم.

24. Experiment 3 — Nonlinear Load Behavior

Suppose the real relationship becomes nonlinear:

Load = 80 + 1.2T + 0.05T²

A straight line may no longer represent the relationship sufficiently well.

This motivates more advanced machine-learning models and neural networks.

24. التجربة 3 — علاقة غير خطية

Load = 80 + 1.2T + 0.05T²

إذا أصبحت العلاقة غير خطية، فقد لا يكون الانحدار الخطي كافيًا لتمثيلها.

وهنا تظهر الحاجة إلى نماذج أكثر تقدمًا مثل الانحدار غير الخطي والشبكات العصبية.

25. Lab Tasks

  1. Enter the temperature and load dataset.
  2. Plot the raw data.
  3. Construct the regression matrix X.
  4. Calculate β₀ and β₁.
  5. Explain the physical meaning of β₁.
  6. Calculate predicted load values.
  7. Calculate MAE, MSE, and RMSE.
  8. Forecast the load at 30°C.
  9. Perform the train/test experiment.
  10. Add measurement noise and repeat the training.
  11. Explain when linear regression may become inadequate.

25. مهام المختبر

  1. أدخل بيانات درجة الحرارة والحمل.
  2. ارسم البيانات الأصلية.
  3. أنشئ مصفوفة الانحدار X.
  4. احسب β₀ وβ₁.
  5. اشرح المعنى الفيزيائي للمعامل β₁.
  6. احسب قيم الحمل المتنبأ بها.
  7. احسب MAE وMSE وRMSE.
  8. تنبأ بالحمل عند 30°C.
  9. نفذ تجربة التدريب والاختبار.
  10. أضف ضجيجًا إلى القياسات وأعد التدريب.
  11. اشرح متى يصبح الانحدار الخطي غير كافٍ.

📝 Review Questions

  1. Why is load forecasting a supervised-learning problem?
  2. What do β₀ and β₁ represent?
  3. Why do we minimize squared errors?
  4. How is the least-squares solution obtained?
  5. What is the difference between MAE, MSE, and RMSE?
  6. Why should test data not be used for training?
  7. What does a large test RMSE indicate?
  8. Why can temperature alone be insufficient for realistic load forecasting?
  9. When would a nonlinear model be preferable?

📝 أسئلة المراجعة

  1. لماذا يعد التنبؤ بالحمل مسألة تعلم خاضع للإشراف؟
  2. ماذا يمثل β₀ وβ₁؟
  3. لماذا نقلل مجموع مربعات الأخطاء؟
  4. كيف نحصل على حل المربعات الصغرى؟
  5. ما الفرق بين MAE وMSE وRMSE؟
  6. لماذا لا يجب استخدام بيانات الاختبار في التدريب؟
  7. ماذا تعني قيمة RMSE كبيرة على بيانات الاختبار؟
  8. لماذا لا تكفي درجة الحرارة وحدها في التنبؤ الحقيقي بالحمل؟
  9. متى نحتاج إلى نموذج غير خطي؟