머신러닝 작업 흐름: 데이터에서 예측까지
원시 데이터 수집과 정제부터 모델 훈련, 평가, 배포까지 전체 pipeline을 단계별로 살펴봅니다.
머신러닝 작업 흐름: 데이터에서 예측까지은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The End-to-End ML Pipeline
Building ML is more than training a model — it's a full pipeline. Knowing all the stages keeps you from rushing straight to modelling too soon.
Stage 1: Define the Problem
Stage one is to define the problem: what are you predicting, why does it matter, and how will you measure success? Vague goals make vague models.
Stage 2: Collect and Load Data
Next, collect and load your data from files, databases, or APIs — Pandas is the go-to tool. Always inspect the raw data before doing anything else.
import pandas as pd
# Load data from a CSV file
df = pd.read_csv('housing.csv')
# First inspection
print(df.shape) # (rows, columns)
print(df.dtypes) # data types per column
print(df.head()) # first 5 rows
print(df.describe()) # summary statisticsStage 3: Exploratory Data Analysis
Exploratory Data Analysis is the detective work: plot distributions, check correlations, and hunt for outliers before you build any model.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.read_csv('housing.csv')
# Distribution of target variable
df['price'].hist(bins=50)
plt.title('House Price Distribution')
plt.show()
# Correlation heat map
sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.show()
# Check for missing values
print(df.isnull().sum())Stage 4: Preprocess the Data
Preprocessing turns messy data into a clean feature matrix — filling gaps, scaling, and encoding. Golden rule: fit only on training data to avoid leakage.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
df = pd.read_csv('housing.csv')
X = df.drop('price', axis=1)
y = df['price']
# Split first, then fit scaler ONLY on train
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # fit + transform on train
X_test_scaled = scaler.transform(X_test) # transform only on testStage 5: Train the Model
Now train the model: in scikit-learn it's one fit() call. Start simple with a baseline like a linear model before reaching for anything complex.
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
# Simple baseline first
linear_model = LinearRegression()
linear_model.fit(X_train_scaled, y_train)
# More complex model
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train_scaled, y_train)
print('Linear model trained.')
print('Random Forest trained.')Stage 6: Evaluate the Model
Evaluate on held-out test data the model never saw. Pick the right metric — MAE and RMSE for numbers, accuracy and F1 for categories.
from sklearn.metrics import mean_absolute_error, r2_score
import numpy as np
y_pred = linear_model.predict(X_test_scaled)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
rmse = np.sqrt(((y_test - y_pred) ** 2).mean())
print(f'MAE: {mae:.2f}')
print(f'RMSE: {rmse:.2f}')
print(f'R2: {r2:.3f}')Stage 7: Iterate and Improve
The first model is rarely the best. ML is iterative: based on your results, gather more data, engineer features, or tune settings — then try again.
Stage 8: Deploy the Model
Deployment makes your trained model available to real users — often as a web API, a batch job, or an on-device model in an app. A notebook alone adds no value.
import joblib
# Save the trained model
joblib.dump(linear_model, 'house_price_model.pkl')
print('Model saved.')
# Later, load and predict in production
loaded_model = joblib.load('house_price_model.pkl')
prediction = loaded_model.predict(X_test_scaled[:1])
print(f'Prediction: ${prediction[0]:,.0f}')Stage 9: Monitor and Retrain
Deployment isn't the finish line. Data shifts over time, so you need monitoring to catch silent performance drops and trigger retraining when needed.
The Workflow as a Scikit-learn Pipeline
A scikit-learn Pipeline chains preprocessing and modelling into one object. It prevents leakage and makes deployment cleaner — save and load just one thing.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
# Chain preprocessing and model in one object
pipeline = Pipeline([
('scaler', StandardScaler()),
('model', LinearRegression())
])
# fit() applies scaler then trains the model
pipeline.fit(X_train, y_train)
# predict() applies scaler then predicts
y_pred = pipeline.predict(X_test)
print('Pipeline prediction done.')Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
Great progress! The ML workflow runs from problem definition to monitoring, preprocessing fits on training data only, and deployment is the start, not the end.
자주 묻는 질문
“머신러닝 작업 흐름: 데이터에서 예측까지” 강의는 무료인가요?
네 — “머신러닝 작업 흐름: 데이터에서 예측까지” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“머신러닝 작업 흐름: 데이터에서 예측까지”에서 뭘 배우나요?
원시 데이터 수집과 정제부터 모델 훈련, 평가, 배포까지 전체 pipeline을 단계별로 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“머신러닝 작업 흐름: 데이터에서 예측까지” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 전통적 프로그래밍과 머신러닝
- 지도 학습, 비지도 학습, 강화 학습
- 머신러닝 작업 흐름: 데이터에서 예측까지
- 현실 세계의 머신러닝: 활용 사례와 한계