0Pricing
Machine Learning Academy · 강의

직선의 방정식: 기울기, 절편, 예측

y=mx+b 공식을 복습하고, 실제 데이터에 회귀선을 그리며, 모델이 입력을 출력으로 매핑하는 방식을 이해합니다.

직선의 방정식: 기울기, 절편, 예측은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“직선의 방정식: 기울기, 절편, 예측”에서 뭘 배우나요?

y=mx+b 공식을 복습하고, 실제 데이터에 회귀선을 그리며, 모델이 입력을 출력으로 매핑하는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“직선의 방정식: 기울기, 절편, 예측” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 직선의 방정식: 기울기, 절편, 예측
  2. 비용 함수와 최소제곱법
  3. scikit-learn으로 LinearRegression 훈련
  4. 다중 선형 회귀와 특성 중요도
← Machine Learning Academy(으)로 돌아가기