Content-Based Filtering
Content-Based Filtering
Recommendation based on item attributes. Uses a user preference profile.
Content-Based Filtering
Recommendation based on item attributes. Uses a user preference profile.
Content-Based Filtering is an algorithm that analyzes the attributes (features) of items and recommends items similar to those a user liked in the past. For example, if a user has watched many action movies, other action movies are recommended. Because this approach uses the items' own metadata (genre, keywords, description, etc.), it can make reasonably good recommendations even without behavioral data from a new user.
Content-Based Filtering developed out of Information Retrieval research in the 1990s, and it is built on traditional text analysis techniques such as TF-IDF and cosine similarity. Since the 2010s, with the advancement of deep learning, embedding techniques such as Word2Vec and BERT have been introduced, making it possible to capture semantic similarity more accurately. In 2024-2025, LLM-based embeddings (OpenAI Embeddings, Cohere Embed) are significantly improving the quality of recommender systems.
The core working principle consists of three steps. First, in the item profiling step, the features of each item are represented as vectors. Second, in the user profiling step, the features of the items the user has interacted with are aggregated to generate a user preference vector. Third, in the matching step, the similarity between the user profile and candidate items is calculated to rank them. Cosine similarity, Euclidean distance, Jaccard similarity, and others are used to measure similarity.
In practice, hybrid systems combined with Collaborative Filtering are common. Netflix uses both content features and users' viewing history, while Spotify combines audio feature analysis with listening patterns. The advantage of Content-Based Filtering is that it is robust against the cold start (new item) problem, and its disadvantage is the Filter Bubble phenomenon, in which only the types of items the user already knows are recommended.
This is an example of a content-based recommender system using TF-IDF and cosine similarity.
# 콘텐츠 기반 영화 추천 시스템
# pip install scikit-learn pandas numpy
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# 샘플 영화 데이터
movies = pd.DataFrame({
'movie_id': [1, 2, 3, 4, 5],
'title': ['인셉션', '인터스텔라', '다크나이트', '어벤져스', '아이언맨'],
'genres': ['SF 액션 스릴러', 'SF 드라마 우주', '액션 범죄 스릴러', 'SF 액션 히어로', 'SF 액션 히어로'],
'description': [
'꿈 속의 꿈 레벨 잠재의식 추출 미션',
'웜홀 블랙홀 시간팽창 인류구원 우주탐사',
'고담시티 조커 배트맨 범죄와의 전쟁',
'어벤져스 어셈블 히어로팀 지구방위',
'토니스타크 아크리액터 슈트 히어로탄생'
]
})
# 장르와 설명을 결합하여 콘텐츠 특징 생성
movies['content'] = movies['genres'] + ' ' + movies['description']
# TF-IDF 벡터화
tfidf = TfidfVectorizer(max_features=100)
tfidf_matrix = tfidf.fit_transform(movies['content'])
# 아이템 간 유사도 행렬 계산
similarity_matrix = cosine_similarity(tfidf_matrix, tfidf_matrix)
def recommend_movies(movie_title, top_n=3):
"""특정 영화와 유사한 영화 추천"""
# 영화 인덱스 찾기
idx = movies[movies['title'] == movie_title].index[0]
# 해당 영화와 다른 영화들의 유사도
sim_scores = list(enumerate(similarity_matrix[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# 자기 자신 제외하고 top_n개 추천
sim_scores = sim_scores[1:top_n+1]
recommendations = []
for i, score in sim_scores:
recommendations.append({
'title': movies.iloc[i]['title'],
'similarity': round(score, 3)
})
return recommendations
# 테스트: 인셉션과 유사한 영화 추천
print("'인셉션'을 좋아한다면:")
for rec in recommend_movies('인셉션'):
print(f" - {rec['title']} (유사도: {rec['similarity']})")
This is an example of an embedding-based content recommender system (using Sentence Transformers).
# 시맨틱 임베딩 기반 추천
# pip install sentence-transformers numpy
from sentence_transformers import SentenceTransformer
import numpy as np
# 다국어 임베딩 모델 로드
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
# 아이템 설명
items = [
{"id": 1, "name": "Python 입문서", "desc": "초보자를 위한 파이썬 프로그래밍 기초"},
{"id": 2, "name": "Django 가이드", "desc": "파이썬 웹 프레임워크 장고 실무 튜토리얼"},
{"id": 3, "name": "React 실전", "desc": "자바스크립트 리액트 프론트엔드 개발"},
{"id": 4, "name": "머신러닝 기초", "desc": "파이썬으로 배우는 인공지능 알고리즘"},
{"id": 5, "name": "SQL 마스터", "desc": "데이터베이스 쿼리 작성과 최적화"},
]
# 아이템 임베딩 생성
descriptions = [item["desc"] for item in items]
embeddings = model.encode(descriptions)
def find_similar_items(query, top_k=3):
"""검색 쿼리와 유사한 아이템 찾기"""
query_embedding = model.encode([query])
# 코사인 유사도 계산
similarities = np.dot(embeddings, query_embedding.T).flatten()
top_indices = np.argsort(similarities)[::-1][:top_k]
results = []
for idx in top_indices:
results.append({
"name": items[idx]["name"],
"score": float(similarities[idx])
})
return results
# 사용자 관심사 기반 추천
user_interest = "파이썬 AI 학습하고 싶어요"
print(f"'{user_interest}'에 대한 추천:")
for item in find_similar_items(user_interest):
print(f" - {item['name']} (점수: {item['score']:.3f})")
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
The performance of Content-Based Filtering is directly tied to the quality of item metadata. Incomplete or inconsistent tags and missing descriptions significantly degrade recommendation quality. Data cleaning comes first.
Recommending only items too similar to those the user has viewed reduces diversity. If you "recommend only action because they've only watched action movies," user satisfaction and long-term engagement decrease.
Build a metadata standardization pipeline, and apply Multi-Armed Bandit or diversity scores to balance Exploration-Exploitation. Use A/B testing to find the optimal point between recommendation diversity and click-through rate.