كل المقررات

الرئيسية / مقرر Machine Learning / الفصل 4 الجزء 1

الفصل 4 (الجزء 1): Training Models

Linear regression, the Normal Equation and gradient descent

في الجزء ده هنفتح الصندوق: نفهم إزاي الـ Linear Regression بتتدرّب فعلاً، بالمعادلة المباشرة (Normal Equation) وبالـ Gradient Descent بأنواعه.

فيديو المحاضرة

فيديو المحاضرة

بعد الفيديو: الأمثلة والاختبار والتمارين والمشروع الصغير تحت.

أمثلة Python

أمثلة صغيرة بالـ scikit-learn

الكود والنتيجة معروضين هنا كنص ثابت (النتائج اتجرّبت فعلاً). لتشغيل الكود بنفسك انسخه في Google Colab المجاني. تقدر كمان تفتح الدفتر الرسمي للكتاب (ترخيص Apache-2.0) من الرابط تحت.

المثال ١: Normal Equation بإيدينا

Sample output (press Run to produce your own):
by hand: bias 4.00, weight 2.98
sklearn: bias 4.00, weight 2.98

المثال ٢: Gradient Descent بسيط

Sample output (press Run to produce your own):
after 1000 steps: bias 4.00, weight 2.98

المثال ٣: SGDRegressor وتأثير الـ scaling

Sample output (press Run to produce your own):
SGD R2   : 0.326
Linear R2: 0.332

افتح الدفتر الرسمي في Colab

اختبار قصير

اختبر فهمك

1. What does the Normal Equation give you?

2. The learning rate in gradient descent is:

3. Which version uses one random example per step?

4. Why scale the features before gradient descent?

5. With a huge number of features, which is usually the better choice?

تمارين برمجة

جرّب بإيدك

التمرين 1

في المثال ٢ غيّر learning rate إلى 0.5 ثم 0.001 واطبع الأوزان بعد ١٠٠٠ خطوة. إيه الفرق؟

In example 2 try lr = 0.5 and then 0.001 and print the weights after 1000 steps. What changes?

(output appears here)

التمرين 2

درّب LinearRegression على feature واحدة (bmi) من داتا diabetes واطبع الميل (coef_) والـ R2 على الـ test.

Train LinearRegression on one feature (bmi) from the diabetes data and print the slope and the test R2.

(output appears here)

مشروع صغير في آخر المحاضرة

ابني Gradient Descent بنفسك على داتا حقيقية

الداتا: Diabetes dataset: 442 patients, target = disease progression. Source: Efron et al., 2004.

License / source: Ships with scikit-learn. Dataset page

الخطوات

  1. خد feature الـ bmi وعمل لها standardization (اطرح المتوسط واقسم على الانحراف).
  2. جهّز مصفوفة فيها عمود 1 للـ bias.
  3. اكتب loop من ٢٠٠ خطوة للـ gradient descent بـ lr=0.1 على الـ MSE.
  4. قارن الأوزان بتاعتك بأوزان LinearRegression على نفس البيانات.
  5. اطبع الفرق بينهم (لازم يكون صغير جداً).
Expected output (press Run to produce your own):
mine  : [152.13  45.16]
sklearn: [152.13  45.16]

Credits: topic order follows the public chapter list of Aurélien Géron's book "Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow" (3rd ed.). All explanations and code here are original.