0Pricing
Machine Learning Academy · درس

معادلة الخط: الميل والجزء المقطوع والتنبؤات

استرجع صيغة y=mx+b، وارسم خط انحدار على بيانات حقيقية، وافهم كيف يربط النموذج المدخلات بالمخرجات

معادلة الخط: الميل والجزء المقطوع والتنبؤات درس مجاني في Machine Learning Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Machine Learning Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Machine Learning Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Linear Relationships in Data

Many real-world relationships are approximately linear: as square footage increases, house price increases proportionally; as advertising spend rises, sales rise. Linear regression models these relationships by finding the straight line that best fits the data.

Before tackling the algorithm, you need to deeply understand the mathematical object it is trying to find: the equation of a line. Every linear regression model is ultimately a line (in 2D) or a hyperplane (in higher dimensions), and the two parameters that define it — slope and intercept — carry meaningful interpretations for the problem you are solving.

The Equation y = mx + b

The equation of a line in 2D is y = mx + b, where:

  • y — the dependent variable (what we want to predict, e.g., house price)
  • x — the independent variable or feature (e.g., square footage)
  • m — the slope: how much y changes for each one-unit increase in x
  • b — the intercept: the value of y when x is zero

In machine learning notation, this is often written as ŷ = w₁x + w₀ or ŷ = θ₁x + θ₀, where w or θ are the weights (parameters) the model learns.

import numpy as np
import matplotlib.pyplot as plt

# Define a line: y = 2x + 5
m = 2.0   # slope
b = 5.0   # intercept

x = np.linspace(0, 10, 100)
y = m * x + b  # vectorised — computes all 100 points at once

plt.plot(x, y, color='blue', linewidth=2)
plt.xlabel('x (square footage / 100)')
plt.ylabel('y (price in $1000s)')
plt.title('Line: y = 2x + 5')
plt.grid(True, alpha=0.3)
plt.show()

Interpreting the Slope

The slope m tells you the rate of change: for every one-unit increase in x, y changes by m units. The sign matters: a positive slope means x and y move together (positive correlation), a negative slope means they move in opposite directions.

In a house-price model where x is square footage and y is price in dollars, a slope of 150 means each additional square foot adds $150 to the predicted price. This interpretability is one of linear regression's biggest strengths — you can explain exactly what drives the prediction.

import numpy as np

# Example: house price model
# y = 150 * sqft + 50000

def predict_price(sqft, slope=150, intercept=50000):
    return slope * sqft + intercept

print('Price for 1000 sqft:', predict_price(1000))  # $200,000
print('Price for 1500 sqft:', predict_price(1500))  # $275,000
print('Price for 2000 sqft:', predict_price(2000))  # $350,000

# Each 500 sqft increase adds:
delta = predict_price(1500) - predict_price(1000)
print(f'Adding 500 sqft increases price by: ${delta:,}')

Interpreting the Intercept

The intercept b is the value of y when x equals zero. It anchors the line at a specific y-value on the vertical axis. Interpreting the intercept requires care — sometimes it makes physical sense, and sometimes it does not.

In the house-price example, an intercept of $50,000 would mean a house with zero square footage costs $50,000, which is physically meaningless. The intercept is best thought of as a calibration constant that shifts the entire line up or down to fit the data, rather than a quantity with direct real-world meaning in every context.

import numpy as np
import matplotlib.pyplot as plt

x = np.array([500, 800, 1000, 1200, 1500, 2000])
y = np.array([125000, 170000, 200000, 230000, 275000, 350000])

# The intercept shifts the line vertically
for intercept in [0, 50000, 100000]:
    y_line = 150 * np.linspace(0, 2000, 100) + intercept
    plt.plot(np.linspace(0, 2000, 100), y_line,
             label=f'b = {intercept:,}')

plt.scatter(x, y, color='black', zorder=5, label='Data')
plt.xlabel('Square Footage')
plt.ylabel('Price ($)')
plt.legend()
plt.show()

Plotting Data and a Regression Line

Before fitting a model, always plot your data to confirm a linear relationship actually exists. If the scatter plot shows a curved or non-linear pattern, a linear model is the wrong choice. Visualising the fitted line on top of the scatter plot is the first validation step after training.

Seaborn's regplot() computes and plots the regression line with a confidence interval in one call, making it a quick sanity check during EDA.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Simulate house price data
np.random.seed(42)
sqft = np.random.uniform(500, 3000, 100)
price = 150 * sqft + 50000 + np.random.normal(0, 20000, 100)

# Quick regression plot with seaborn
plt.figure(figsize=(8, 5))
sns.regplot(x=sqft, y=price, scatter_kws={'alpha': 0.5},
            line_kws={'color': 'red', 'linewidth': 2})
plt.xlabel('Square Footage')
plt.ylabel('Price ($)')
plt.title('House Price vs Square Footage')
plt.show()

Making Predictions with a Line

Once you have a line (slope m and intercept b), making a prediction for a new input x is just arithmetic: plug x into the equation and compute y. This is called inference or prediction.

The key insight is that the model does not know the true output for a new input — it estimates it based on the patterns it learned from training data. The quality of these predictions depends entirely on how well the training data represents the new inputs and how linear the true relationship actually is.

import numpy as np

# Learned parameters (from training, simplified here)
slope = 150.0
intercept = 52000.0

def predict(x_new, m, b):
    return m * x_new + b

# Single prediction
new_house_sqft = 1800
predicted_price = predict(new_house_sqft, slope, intercept)
print(f'Predicted price for {new_house_sqft} sqft: ${predicted_price:,.0f}')

# Batch prediction (multiple houses)
houses = np.array([1000, 1200, 1500, 2000, 2500])
prices = predict(houses, slope, intercept)
for sqft, price in zip(houses, prices):
    print(f'{sqft} sqft -> ${price:,.0f}')

Residuals: The Gap Between Prediction and Reality

No real dataset falls perfectly on a line. The residual for each data point is the difference between the actual value and the model's predicted value: residual = y_actual - y_predicted. A positive residual means the model under-predicted; a negative residual means it over-predicted.

Residuals are the raw material for evaluating and improving a linear model. If residuals show a systematic pattern (e.g., always positive for large x values), that is evidence the true relationship is non-linear and a more complex model is needed.

import numpy as np

y_actual = np.array([200000, 250000, 310000, 180000, 420000])

# Model predictions
m, b = 150.0, 52000.0
x = np.array([1000, 1300, 1700, 850, 2400])
y_pred = m * x + b

residuals = y_actual - y_pred

for i, (actual, pred, res) in enumerate(zip(y_actual, y_pred, residuals)):
    print(f'House {i+1}: Actual=${actual:,}  Predicted=${pred:,.0f}  Residual=${res:,.0f}')

print(f'\nMean residual: ${residuals.mean():,.0f}')
print(f'Std of residuals: ${residuals.std():,.0f}')

Negative Slope: Inverse Relationships

A negative slope models an inverse relationship: as x increases, y decreases. For example, the older a car, the lower its resale value. Or the more competitors a business has, the lower its market share.

Linear regression handles negative slopes naturally — the algorithm will find whatever slope (positive, negative, or zero) best fits the training data. A slope of exactly zero would mean x provides no information about y, and the best prediction for every input would just be the mean of y.

import numpy as np
import matplotlib.pyplot as plt

# Car age vs resale value (inverse relationship)
np.random.seed(0)
age = np.random.uniform(1, 15, 50)
value = -1500 * age + 25000 + np.random.normal(0, 2000, 50)
value = np.clip(value, 1000, 30000)  # clip to realistic range

plt.scatter(age, value, alpha=0.6)
plt.plot([1, 15], [-1500*1+25000, -1500*15+25000],
         color='red', linewidth=2, label='y = -1500x + 25000')
plt.xlabel('Car Age (years)')
plt.ylabel('Resale Value ($)')
plt.title('Inverse Relationship: Age vs Resale Value')
plt.legend()
plt.show()

From Line to Hyperplane

In reality, we almost always have multiple input features, not just one. When you extend the line equation to multiple features, the model becomes a hyperplane in high-dimensional space:

ŷ = w₁x₁ + w₂x₂ + ... + wₙxₙ + b

Each wᵢ is a separate coefficient (weight) for the corresponding feature xᵢ. The prediction is still just a linear combination of inputs plus a bias. This extension — from a line to a hyperplane — is all that changes when you go from simple to multiple linear regression.

import numpy as np

# Multiple linear regression prediction
# y = w1*sqft + w2*bedrooms + w3*age + b

def predict_multi(features, weights, bias):
    # features shape: (n_features,) or (n_samples, n_features)
    return np.dot(features, weights) + bias

weights = np.array([150.0, 5000.0, -200.0])  # sqft, bedrooms, age
bias = 30000.0

# One house: 1500 sqft, 3 bedrooms, 10 years old
house = np.array([1500, 3, 10])
price = predict_multi(house, weights, bias)
print(f'Predicted price: ${price:,.0f}')
# = 150*1500 + 5000*3 + (-200)*10 + 30000 = $282,000

Correlation vs Causation in Linear Models

Linear regression finds statistical correlations, not causal relationships. A high slope between ice cream sales and drowning deaths does not mean ice cream causes drowning — both are caused by hot weather. A model's slope tells you about the relationship in training data, not about the underlying causal mechanism.

This distinction matters enormously when deploying ML models for decision-making. A model that predicts loan defaults might find that zip code is a strong predictor — but using zip code as a decision factor may encode racial discrimination rather than genuine credit risk. Always interrogate why a feature has high predictive power.

Setting Up for scikit-learn

Now that you understand what a line is and what its parameters mean, you are ready to use scikit-learn to automatically learn the optimal slope and intercept from data. The algorithm will minimise the total prediction error across all training examples, finding the best-fit line without you manually tuning m and b.

In the next lesson you will learn exactly how this optimisation works — what 'best fit' means mathematically, and how the Mean Squared Error cost function turns fitting a line into a problem of minimising a mathematical expression.

from sklearn.linear_model import LinearRegression
import numpy as np

# scikit-learn finds the optimal slope and intercept automatically
np.random.seed(42)
sqft = np.random.uniform(500, 3000, 100).reshape(-1, 1)
price = 150 * sqft.ravel() + 50000 + np.random.normal(0, 20000, 100)

model = LinearRegression()
model.fit(sqft, price)

print(f'Learned slope (coef_):     {model.coef_[0]:.1f}')
print(f'Learned intercept (b):     {model.intercept_:.1f}')
print(f'Prediction for 1500 sqft: ${model.predict([[1500]])[0]:,.0f}')

Quick Check

Test your understanding of Machine Learning with Python concepts from this lesson.

Lesson Recap

In this lesson you learned: the equation y=mx+b defines a line with slope m (rate of change) and intercept b (y-value at x=0), residuals measure the gap between actual and predicted values, and multiple linear regression extends the line to a hyperplane with one weight per feature. Next up we explore cost functions and least squares — the mathematical framework that defines what 'best fit' means and how the algorithm finds the optimal parameters.

الأسئلة الشائعة

هل درس «معادلة الخط: الميل والجزء المقطوع والتنبؤات» مجاني؟

نعم — نص درس «معادلة الخط: الميل والجزء المقطوع والتنبؤات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Machine Learning Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Machine Learning Academy 4 دروس في المجموع.

ماذا ستتعلم في «معادلة الخط: الميل والجزء المقطوع والتنبؤات»؟

استرجع صيغة y=mx+b، وارسم خط انحدار على بيانات حقيقية، وافهم كيف يربط النموذج المدخلات بالمخرجات تتمرن على Machine Learning Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Machine Learning Academy؟

لا تُشترط خبرة سابقة. Machine Learning Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «معادلة الخط: الميل والجزء المقطوع والتنبؤات»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Machine Learning Academy هذا؟

نعم. كل درس في Machine Learning Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. معادلة الخط: الميل والجزء المقطوع والتنبؤات
  2. دوال التكلفة والمربعات الصغرى
  3. تدريب الانحدار الخطي باستخدام scikit-learn
  4. الانحدار الخطي المتعدد وأهمية السمات
← العودة إلى Machine Learning Academy