Machine Learning Academy · 강의

고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기

학습자는 전자상거래 데이터셋을 전처리하고, 지출액과 구매 빈도로 고객을 클러스터링한 다음, 각 세그먼트의 특성을 분석해 비즈니스 인사이트를 도출합니다.

레슨 4/413개 단계

고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Business Goal: Segment Customers

Customer segmentation groups buyers by behaviour so that marketing, product, and customer-success teams can tailor their actions to each group. Typical signals include recency (days since last purchase), frequency (number of purchases), and monetary value (total spend) — the RFM framework. Clustering discovers these segments from data without needing predefined categories.

Loading and Inspecting the Dataset

We use the classic Online Retail dataset (UCI ML Repository). It contains ~500k transactions with invoice date, customer ID, quantity, and unit price. Our first task is to load the data, drop rows with missing customer IDs, filter out returns (negative quantity), and compute the RFM features for each customer.

import pandas as pd

df = pd.read_csv('online_retail.csv', encoding='latin1')

# Drop missing customers and returns
df = df.dropna(subset=['CustomerID'])
df = df[df['Quantity'] > 0]
df['Revenue'] = df['Quantity'] * df['UnitPrice']
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])

print(df.shape)
print(df.dtypes)

Engineering RFM Features

Recency: days since the customer's last purchase (smaller = more recent = better). Frequency: number of unique invoices. Monetary: total revenue generated. We compute these relative to a snapshot date (one day after the last transaction in the dataset) so recency increases with inactivity.

snapshot_date = df['InvoiceDate'].max() + pd.Timedelta(days=1)

rfm = df.groupby('CustomerID').agg(
    Recency=('InvoiceDate', lambda x: (snapshot_date - x.max()).days),
    Frequency=('InvoiceNo', 'nunique'),
    Monetary=('Revenue', 'sum')
).reset_index()

print(rfm.describe())

Treating Outliers and Skewness

RFM features are often highly right-skewed: a handful of VIP customers dominate the monetary axis. Before scaling, apply a log transform (np.log1p) to compress the long tail. Clip extreme outliers beyond the 99th percentile to prevent a single whale customer from distorting all centroids.

import numpy as np

for col in ['Recency', 'Frequency', 'Monetary']:
    cap = rfm[col].quantile(0.99)
    rfm[col] = rfm[col].clip(upper=cap)
    rfm[col + '_log'] = np.log1p(rfm[col])

print(rfm[['Recency_log', 'Frequency_log', 'Monetary_log']].describe())

Scaling Features for K-Means

K-Means uses Euclidean distance, so features must be on the same scale. After log-transforming, apply StandardScaler to centre each feature at zero with unit variance. Always fit the scaler on training data only — here the full RFM table since there is no separate test set for unsupervised learning.

from sklearn.preprocessing import StandardScaler

features = ['Recency_log', 'Frequency_log', 'Monetary_log']
X = rfm[features].values

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print('Mean after scaling:', X_scaled.mean(axis=0).round(4))
print('Std after scaling:', X_scaled.std(axis=0).round(4))

Selecting k with Elbow and Silhouette

Run the elbow and silhouette diagnostics on the RFM dataset to select k. For a typical e-commerce dataset you might see the elbow around k=4 or k=5, which corresponds to intuitive segments: champions, loyal customers, at-risk customers, and churned customers.

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

results = []
for k in range(2, 9):
    km = KMeans(n_clusters=k, n_init=10, random_state=42)
    labels = km.fit_predict(X_scaled)
    results.append({'k': k, 'inertia': km.inertia_,
                    'silhouette': silhouette_score(X_scaled, labels)})

import pandas as pd
print(pd.DataFrame(results))

Fitting the Final Clustering Model

After selecting k, fit the final K-Means model and add the cluster labels back to the RFM DataFrame. This makes it easy to compute segment profiles and build customer-facing reports. The fit_predict method fits and returns labels in one call.

from sklearn.cluster import KMeans

k = 4
km = KMeans(n_clusters=k, n_init=20, random_state=42)
rfm['Segment'] = km.fit_predict(X_scaled)

print('Cluster sizes:')
print(rfm['Segment'].value_counts())

Profiling Each Segment

Compute the mean of the original (untransformed) RFM values for each cluster. This gives interpretable business profiles: Champions have low recency, high frequency, high monetary; Churned have high recency, low frequency, low monetary. Naming segments based on their profiles makes reports actionable.

profile = rfm.groupby('Segment')[['Recency', 'Frequency', 'Monetary']].mean()
print(profile.round(1))

# Optional: label segments by profile
segment_names = {
    0: 'Champions',
    1: 'At-Risk',
    2: 'Loyal',
    3: 'Churned'
}
rfm['SegmentName'] = rfm['Segment'].map(segment_names)
print(rfm['SegmentName'].value_counts())

Visualising Segments with Scatter Plots

Plot Frequency vs Monetary with colour coding for each segment. Add recency as point size to encode the third dimension visually. This chart is the deliverable that a marketing team can use to identify which customers to target for reactivation campaigns vs upselling campaigns.

import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5))
for seg in rfm['Segment'].unique():
    mask = rfm['Segment'] == seg
    plt.scatter(rfm.loc[mask, 'Frequency'],
                rfm.loc[mask, 'Monetary'],
                s=rfm.loc[mask, 'Recency'] + 5,
                label=f'Segment {seg}', alpha=0.5)
plt.xlabel('Frequency')
plt.ylabel('Monetary')
plt.legend()
plt.title('RFM Customer Segments')
plt.show()

Assigning New Customers to Segments

After deploying the model, new customers get assigned by passing their scaled RFM vector through the same scaler and then calling km.predict. Never refit the scaler on new data — use the scaler fitted on the training RFM table to avoid shifting the feature space. The centroid positions remain fixed after fitting.

import numpy as np

# Simulate a new customer: recency=10, frequency=15, monetary=600
new_customer = np.array([[10, 15, 600]])
new_log = np.log1p(new_customer)
new_scaled = scaler.transform(new_log)

segment = km.predict(new_scaled)[0]
print('New customer segment:', segment)

Business Insights and Next Steps

Clustering is a starting point, not an end. After profiling segments, the team should design targeted actions: send re-engagement emails to At-Risk customers, offer loyalty rewards to Champions, present upsell offers to Loyal customers. Track conversion rates per segment to measure the ROI of segmentation. Periodically retrain the model as customer behaviour evolves over time.

Quick Check

Test your understanding of customer segmentation with clustering from this lesson.

Lesson Recap

In this lesson you learned: RFM (Recency, Frequency, Monetary) features are the standard building blocks for customer segmentation, log transformation and StandardScaler make skewed RFM features suitable for K-Means, and segment profiling translates cluster numbers into actionable business labels like Champions and At-Risk. Next up we explore PCA — a technique for reducing high-dimensional data to its most informative components.

무료로 시작

AI 튜터와 함께 Python을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
30
레슨
120

자주 묻는 질문

“고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기” 강의는 무료인가요?

네 — “고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기”에서 뭘 배우나요?

학습자는 전자상거래 데이터셋을 전처리하고, 지출액과 구매 빈도로 고객을 클러스터링한 다음, 각 세그먼트의 특성을 분석해 비즈니스 인사이트를 도출합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. K-Means: 중심점, 할당 및 갱신 단계
  2. K 선택하기: 엘보 방법과 실루엣 점수
  3. DBSCAN: 핵심 점, 경계 점 및 잡음
  4. 고객 세분화를 위한 클러스터링: 처음부터 끝까지 살펴보기
← Machine Learning Academy(으)로 돌아가기