빅데이터
실전기술
IT가맹점개발팀
이태영
2014.12.23
Recommendation System
using Mahout
Mahout 설치
1) Mahout 0.9 다운로드
http://mahout.apache.org 접속 후 다운로드
2) 계정 홈 디렉토리로 mv
$ mv mahout-distribution-0.9.tar.gz ~
3) 압축을 풀고 mahout 심볼릭 링크를 생성
$ ln -s mahout-distribution-0.9 mahout
4) .bash_profile에 MAHOUT_HOME과 PATH 추가
1 # .bash_profile
2
3 # Get the aliases and functions
4 if [ -f ~/.bashrc ]; then
5 . ~/.bashrc
6 fi
7
8 # User specific environment and startup programs
9
10 export JAVA_HOME=$HOME/java
11 export HADOOP_HOME=$HOME/hadoop
12 export PYTHON_HOME=$HOME/python
13 export MAHOUT_HOME=$HOME/mahout
14
15 PATH=$PATH:$HOME/bin:$JAVA_HOME/bin:$HADOOP_HOME/bin:$HADOOP_HOME/sbin:$PYTHON_HOME/:$MAHOUT_HOME/bin
16
17 export PATH
협업 필터링 알고리즘
Collarborative filtering
1. User based – (첫째, 비슷한 사용자 찾음)
• 취향이 비슷한 유저 B가 어떤 아이템을 구매했는지 확인 후 B가 구매했던 상품으로 추천
2. Item based – (첫째, 비슷한 아이템 찾음)
• 내가 구매했던 상품들을 기반으로, 연관성이 있는 상품을 추천
User based Recommendation Item based Recommendation
유사도
Similarity
1. Euclidean Distance
• 두 객체 간의 선호도 거리를 계산하여, 작을 수록 비슷한 성향을 가짐
2. Cosine Similarity (=Pearson Similarity)
• 두 객체 간의 선호도를 벡터화 하여, 벡터 사이의 각도가 적을 수록 유사
3. Jaccard Similarity
• 두 객체 간의 요소들의 전체 요소들 중 교집합되는 요소가 차지하는 비중
Mahout
What is Mahout?
The Apache Mahout™ project's goal is to build a scalable machine learning library.
• Clustering (군집화)
• Classification (분류)
• Recommendation (추천 및 협업필터링)
• Pattern Mining (패턴 마이닝)
• Regression (회귀 분석)
• Evolutionary Algorithms (진화 알고리즘)
• Dimension reduction (차원 리덕션)
Mahout is made by JAVA
• We can use Mahout core libarary for java programming.
• NO HADOOP ONLY.
Mahout 프로그래밍
Recommendation
1. MovieLens 데이터 셋 ( http://grouplens.org/datasets/movielens )
• 10만개 / 1백만개 / 1천만개 별로 평가 데이터 셋 제공
• 미국 내 상영된 영화를 사용자들이 평가한 결과물 1997/9/19 ~ 1998/4/22간
• 미네소타 대학 컴퓨터과학 연구실에서 수집한 추천 알고리즘을 위한 학습데이터
다운로드(약 4.8MB)
2. SLF4J 라이브러리 (http://www.slf4j.org )
• mahout 라이브러리 호환성 필요
Mahout 프로그래밍
Recommendation
다운로드(약 4.3MB)
3. GUAVA 라이브러리 ( https://code.google.com/p/guava-libraries )
• mahout의 데이터 객체는 guava 라이브러리 의존
Mahout 프로그래밍
Recommendation
다운로드(약 4.3MB)
다운로드(약 2.2MB)
4. Apache commons Math 라이브러리 (http://commons.apache.org/proper/commons-math )
• 수치 계산용 라이브러리
Mahout 프로그래밍
Recommendation
다운로드(약 14.3MB)
 최종 라이브러리 리스트
• commons-math3-3.4.jar
• guava-18.0.jar
• mahout-core-0.9.jar
• mahout-integration-0.9.jar
• mahout-math-0.9.jar
• slf4j-api-1.7.7.jar
• slf4j-nop-1.7.7.jar
Mahout 프로그래밍
Recommendation
Mahout 프로그래밍
Item Based Recommendation
 프로젝트 생성
• ItemRecommender
• Java 5 SDK 이상
Mahout 프로그래밍
Item Based Recommendation
 프로젝트 개발 준비
• Libraries는 모두 lib 폴더 밑으로 복사
• ml-100k.zip(MovieLens 데이터)를 압축을 푼 뒤 data 폴더로 u.data를 복사
README 파일 내 설명
u.data -- The full u data set, 100000 ratings by 943 users
on 1682 items. Each user has rated at least 20 movies.
Users and items are numbered consecutively from 1. The
data is randomly ordered. This is a tab separated list of
user id | item id | rating | timestamp. The time stamps are
unix seconds since 1/1/1970 UTC
Mahout 프로그래밍
Recommendation
 프로젝트 개발 준비
• u.data 파일을 csv 파일 형태로 변경하여 movies.csv로 저장
• u.data 파일의 각 요소별 구분자인 t 을 콤마(,)로 치환
Mahout 프로그래밍
User Based Recommendation
 클래스 추가
• 패키지 : recommend.item
• 클래스 : UserRecommend
 Java Build Path 추가
Mahout 프로그래밍
UserRecommend 클래스
public class UserRecommend {
public static void main(String[] args) throws Exception{
/* 데이터 모델 생성 */
DataModel dm = new FileDataModel(new File("data/movies.csv"));
/* 유사도 모델 생성 */
UserSimilarity sim = new PearsonCorrelationSimilarity(dm);
/* 모든 유저들로부터 주어진 유저와 특정 임계값을 충족하거나 초과하는 neighborhood 기준 */
UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, sim, dm);
/* 사용자 추천기 생성 */
UserBasedRecommender recommender = new GenericUserBasedRecommender(dm, neighborhood, sim);
int x= 1;
/* 데이터 모델 내의 유저들의 iterator를 단계별로 이동하며 추천 아이템들 제공 */
for(LongPrimitiveIterator users = dm.getUserIDs(); users.hasNext();){
long userID = users.nextLong(); /* 현재 유저 ID */
/* 현재 유저 ID에 해당되는 5개 아이템 추천 */
List<RecommendedItem> recommendations = recommender.recommend(userID, 5);
for(RecommendedItem recommenation : recommendations){
System.out.println(userID +","+ recommenation.getItemID()+","+recommenation.getValue());
}
if(++x > 5) break; /* 유저 ID 5까지만 출력 */
}
}
}
Mahout 프로그래밍
UserRecommend 클래스 실행 결과
1,1558,5.0
1,1500,5.0
1,1467,5.0
1,1189,5.0
1,1293,5.0
2,1643,5.0
2,1467,5.0
2,1500,5.0
2,1293,5.0
2,1189,5.0
3,1189,5.0
3,1500,5.0
3,1302,5.0
3,1368,5.0
3,1398,4.759591
4,1104,4.7937207
4,853,4.729132
4,169,4.655577
4,1449,4.60582
4,408,4.582672
5,1500,5.0
5,1233,5.0
5,851,5.0
5,1189,5.0
5,119,5.0
1,1500,5.0
1,1467,5.0
1,1189,5.0
1,1293,5.0
1,1367,4.7517056
2,1500,5.0
2,1293,5.0
2,1189,5.0
2,1449,4.608227
2,1594,4.5082903
3,1500,5.0
3,1189,5.0
3,1293,5.0
3,1449,4.76954
3,1450,4.686902
4,1467,5.0
4,1500,5.0
4,1189,5.0
4,1293,5.0
4,1594,4.566541
5,1500,5.0
5,1467,5.0
5,1189,5.0
5,1293,5.0
5,1642,4.66432
sim = new PearsonCorrelationSimilarity(dm); sim = new LogLikelihoodSimilarity(dm);
<유저ID, 추천 아이템ID, 연결 강도>
Mahout 프로그래밍
Item Based Recommendation
 클래스 추가
• 패키지 : recommend.item
• 클래스 : ItemRecommend
 Java Build Path 추가
Mahout 프로그래밍
ItemRecommend 클래스
public class ItemRecommend {
public static void main(String args[]){
DataModel dm;
try {
/* 데이터 모델 생성 */
dm = new FileDataModel(new File("data/movies.csv"));
/* 유사도 모델 선택 */
ItemSimilarity sim = new PearsonCorrelationSimilarity(dm);
/* 추천기 선택 : ItemBased */
GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim);
int x=1;
/* 데이터 모델 내의 item들의 iterator를 단계별 이동하며 추천 아이템들 제공 */
for(LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();){
long itemID = items.nextLong(); /* 현재 item ID */
/*현재 item ID와 가장 유사한 5개 아이템 추천 */
List<RecommendedItem> recommendations = recommender.mostSimilarItems(itemID, 5);
/* 유사한 아이템 출력 = "현재 아이템 ID | 추천된 아이템 ID | 유사도" */
for(RecommendedItem recommendation : recommendations){
System.out.println(itemID + ","+recommendation.getItemID() + "," + recommendation.getValue());
}
x++;/* 아이템 ID 5까지 유사한 아이템들 5개씩 */
if(x>5) System.exit(0);
}
} catch (IOException | TasteException e) {
e.printStackTrace();
}
}
}
Mahout 프로그래밍
ItemRecommend 클래스 실행 결과
1,973,1.0
1,885,1.0
1,920,1.0
1,757,1.0
1,341,1.0
2,341,1.0
2,119,1.0
2,308,1.0
2,75,1.0
2,74,1.0
3,560,1.0
3,422,1.0
3,344,1.0
3,400,1.0
3,115,1.0
4,1038,1.0
4,868,1.0
4,927,1.0
4,643,1.0
4,360,1.0
5,348,1.0
5,34,1.0
5,113,1.0
5,35,1.0
5,6,1.0
1,117,0.9953521
1,151,0.9953065
1,121,0.9952347
1,405,0.99500656
1,50,0.99491894
2,403,0.9964998
2,233,0.9964557
2,161,0.9961404
2,231,0.9960143
2,385,0.9959657
3,405,0.99037176
3,235,0.9893157
3,121,0.9880421
3,250,0.9880041
3,100,0.98773706
4,56,0.99627966
4,174,0.99601305
4,204,0.9959589
4,202,0.99582237
4,385,0.9957967
5,218,0.99432045
5,98,0.9922024
5,234,0.99179345
5,56,0.99115413
5,53,0.9909523
sim = new PearsonCorrelationSimilarity(dm); sim = new LogLikelihoodSimilarity(dm);
<기준 아이템 ID, 비교 아이템ID, 유사도>
References
1. Apache Mahtout Recommender Quick Start
• http://mahout.apache.org/users/recommender/quickstart.html
2. Recommendation System : 협업 필터링을 중심으로
• http://rosaec.snu.ac.kr/meet/file/20120728b.pdf
3. Apache Mahout 맛보기 (30분만에 추천 시스템 만들기)
• http://www.slideshare.net/pitzcarraldo/mahout-cook-book
4. Mahout를 활용한 영화 추천 샘플링
• http://www.mimul.com/pebble/default/2012/03/23/1332494169544.html
5. Recommendation: 추천 – 알고리즘 : Item-Based Filtering
• http://hochul.net/blog/recommendation-daisy/

20141223 머하웃(mahout) 협업필터링_추천시스템구현

  • 1.
  • 2.
    Mahout 설치 1) Mahout0.9 다운로드 http://mahout.apache.org 접속 후 다운로드 2) 계정 홈 디렉토리로 mv $ mv mahout-distribution-0.9.tar.gz ~ 3) 압축을 풀고 mahout 심볼릭 링크를 생성 $ ln -s mahout-distribution-0.9 mahout 4) .bash_profile에 MAHOUT_HOME과 PATH 추가 1 # .bash_profile 2 3 # Get the aliases and functions 4 if [ -f ~/.bashrc ]; then 5 . ~/.bashrc 6 fi 7 8 # User specific environment and startup programs 9 10 export JAVA_HOME=$HOME/java 11 export HADOOP_HOME=$HOME/hadoop 12 export PYTHON_HOME=$HOME/python 13 export MAHOUT_HOME=$HOME/mahout 14 15 PATH=$PATH:$HOME/bin:$JAVA_HOME/bin:$HADOOP_HOME/bin:$HADOOP_HOME/sbin:$PYTHON_HOME/:$MAHOUT_HOME/bin 16 17 export PATH
  • 3.
    협업 필터링 알고리즘 Collarborativefiltering 1. User based – (첫째, 비슷한 사용자 찾음) • 취향이 비슷한 유저 B가 어떤 아이템을 구매했는지 확인 후 B가 구매했던 상품으로 추천 2. Item based – (첫째, 비슷한 아이템 찾음) • 내가 구매했던 상품들을 기반으로, 연관성이 있는 상품을 추천 User based Recommendation Item based Recommendation
  • 4.
    유사도 Similarity 1. Euclidean Distance •두 객체 간의 선호도 거리를 계산하여, 작을 수록 비슷한 성향을 가짐 2. Cosine Similarity (=Pearson Similarity) • 두 객체 간의 선호도를 벡터화 하여, 벡터 사이의 각도가 적을 수록 유사 3. Jaccard Similarity • 두 객체 간의 요소들의 전체 요소들 중 교집합되는 요소가 차지하는 비중
  • 5.
    Mahout What is Mahout? TheApache Mahout™ project's goal is to build a scalable machine learning library. • Clustering (군집화) • Classification (분류) • Recommendation (추천 및 협업필터링) • Pattern Mining (패턴 마이닝) • Regression (회귀 분석) • Evolutionary Algorithms (진화 알고리즘) • Dimension reduction (차원 리덕션) Mahout is made by JAVA • We can use Mahout core libarary for java programming. • NO HADOOP ONLY.
  • 6.
    Mahout 프로그래밍 Recommendation 1. MovieLens데이터 셋 ( http://grouplens.org/datasets/movielens ) • 10만개 / 1백만개 / 1천만개 별로 평가 데이터 셋 제공 • 미국 내 상영된 영화를 사용자들이 평가한 결과물 1997/9/19 ~ 1998/4/22간 • 미네소타 대학 컴퓨터과학 연구실에서 수집한 추천 알고리즘을 위한 학습데이터 다운로드(약 4.8MB)
  • 7.
    2. SLF4J 라이브러리(http://www.slf4j.org ) • mahout 라이브러리 호환성 필요 Mahout 프로그래밍 Recommendation 다운로드(약 4.3MB)
  • 8.
    3. GUAVA 라이브러리( https://code.google.com/p/guava-libraries ) • mahout의 데이터 객체는 guava 라이브러리 의존 Mahout 프로그래밍 Recommendation 다운로드(약 4.3MB) 다운로드(약 2.2MB)
  • 9.
    4. Apache commonsMath 라이브러리 (http://commons.apache.org/proper/commons-math ) • 수치 계산용 라이브러리 Mahout 프로그래밍 Recommendation 다운로드(약 14.3MB)
  • 10.
     최종 라이브러리리스트 • commons-math3-3.4.jar • guava-18.0.jar • mahout-core-0.9.jar • mahout-integration-0.9.jar • mahout-math-0.9.jar • slf4j-api-1.7.7.jar • slf4j-nop-1.7.7.jar Mahout 프로그래밍 Recommendation
  • 11.
    Mahout 프로그래밍 Item BasedRecommendation  프로젝트 생성 • ItemRecommender • Java 5 SDK 이상
  • 12.
    Mahout 프로그래밍 Item BasedRecommendation  프로젝트 개발 준비 • Libraries는 모두 lib 폴더 밑으로 복사 • ml-100k.zip(MovieLens 데이터)를 압축을 푼 뒤 data 폴더로 u.data를 복사 README 파일 내 설명 u.data -- The full u data set, 100000 ratings by 943 users on 1682 items. Each user has rated at least 20 movies. Users and items are numbered consecutively from 1. The data is randomly ordered. This is a tab separated list of user id | item id | rating | timestamp. The time stamps are unix seconds since 1/1/1970 UTC
  • 13.
    Mahout 프로그래밍 Recommendation  프로젝트개발 준비 • u.data 파일을 csv 파일 형태로 변경하여 movies.csv로 저장 • u.data 파일의 각 요소별 구분자인 t 을 콤마(,)로 치환
  • 14.
    Mahout 프로그래밍 User BasedRecommendation  클래스 추가 • 패키지 : recommend.item • 클래스 : UserRecommend  Java Build Path 추가
  • 15.
    Mahout 프로그래밍 UserRecommend 클래스 publicclass UserRecommend { public static void main(String[] args) throws Exception{ /* 데이터 모델 생성 */ DataModel dm = new FileDataModel(new File("data/movies.csv")); /* 유사도 모델 생성 */ UserSimilarity sim = new PearsonCorrelationSimilarity(dm); /* 모든 유저들로부터 주어진 유저와 특정 임계값을 충족하거나 초과하는 neighborhood 기준 */ UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, sim, dm); /* 사용자 추천기 생성 */ UserBasedRecommender recommender = new GenericUserBasedRecommender(dm, neighborhood, sim); int x= 1; /* 데이터 모델 내의 유저들의 iterator를 단계별로 이동하며 추천 아이템들 제공 */ for(LongPrimitiveIterator users = dm.getUserIDs(); users.hasNext();){ long userID = users.nextLong(); /* 현재 유저 ID */ /* 현재 유저 ID에 해당되는 5개 아이템 추천 */ List<RecommendedItem> recommendations = recommender.recommend(userID, 5); for(RecommendedItem recommenation : recommendations){ System.out.println(userID +","+ recommenation.getItemID()+","+recommenation.getValue()); } if(++x > 5) break; /* 유저 ID 5까지만 출력 */ } } }
  • 16.
    Mahout 프로그래밍 UserRecommend 클래스실행 결과 1,1558,5.0 1,1500,5.0 1,1467,5.0 1,1189,5.0 1,1293,5.0 2,1643,5.0 2,1467,5.0 2,1500,5.0 2,1293,5.0 2,1189,5.0 3,1189,5.0 3,1500,5.0 3,1302,5.0 3,1368,5.0 3,1398,4.759591 4,1104,4.7937207 4,853,4.729132 4,169,4.655577 4,1449,4.60582 4,408,4.582672 5,1500,5.0 5,1233,5.0 5,851,5.0 5,1189,5.0 5,119,5.0 1,1500,5.0 1,1467,5.0 1,1189,5.0 1,1293,5.0 1,1367,4.7517056 2,1500,5.0 2,1293,5.0 2,1189,5.0 2,1449,4.608227 2,1594,4.5082903 3,1500,5.0 3,1189,5.0 3,1293,5.0 3,1449,4.76954 3,1450,4.686902 4,1467,5.0 4,1500,5.0 4,1189,5.0 4,1293,5.0 4,1594,4.566541 5,1500,5.0 5,1467,5.0 5,1189,5.0 5,1293,5.0 5,1642,4.66432 sim = new PearsonCorrelationSimilarity(dm); sim = new LogLikelihoodSimilarity(dm); <유저ID, 추천 아이템ID, 연결 강도>
  • 17.
    Mahout 프로그래밍 Item BasedRecommendation  클래스 추가 • 패키지 : recommend.item • 클래스 : ItemRecommend  Java Build Path 추가
  • 18.
    Mahout 프로그래밍 ItemRecommend 클래스 publicclass ItemRecommend { public static void main(String args[]){ DataModel dm; try { /* 데이터 모델 생성 */ dm = new FileDataModel(new File("data/movies.csv")); /* 유사도 모델 선택 */ ItemSimilarity sim = new PearsonCorrelationSimilarity(dm); /* 추천기 선택 : ItemBased */ GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim); int x=1; /* 데이터 모델 내의 item들의 iterator를 단계별 이동하며 추천 아이템들 제공 */ for(LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();){ long itemID = items.nextLong(); /* 현재 item ID */ /*현재 item ID와 가장 유사한 5개 아이템 추천 */ List<RecommendedItem> recommendations = recommender.mostSimilarItems(itemID, 5); /* 유사한 아이템 출력 = "현재 아이템 ID | 추천된 아이템 ID | 유사도" */ for(RecommendedItem recommendation : recommendations){ System.out.println(itemID + ","+recommendation.getItemID() + "," + recommendation.getValue()); } x++;/* 아이템 ID 5까지 유사한 아이템들 5개씩 */ if(x>5) System.exit(0); } } catch (IOException | TasteException e) { e.printStackTrace(); } } }
  • 19.
    Mahout 프로그래밍 ItemRecommend 클래스실행 결과 1,973,1.0 1,885,1.0 1,920,1.0 1,757,1.0 1,341,1.0 2,341,1.0 2,119,1.0 2,308,1.0 2,75,1.0 2,74,1.0 3,560,1.0 3,422,1.0 3,344,1.0 3,400,1.0 3,115,1.0 4,1038,1.0 4,868,1.0 4,927,1.0 4,643,1.0 4,360,1.0 5,348,1.0 5,34,1.0 5,113,1.0 5,35,1.0 5,6,1.0 1,117,0.9953521 1,151,0.9953065 1,121,0.9952347 1,405,0.99500656 1,50,0.99491894 2,403,0.9964998 2,233,0.9964557 2,161,0.9961404 2,231,0.9960143 2,385,0.9959657 3,405,0.99037176 3,235,0.9893157 3,121,0.9880421 3,250,0.9880041 3,100,0.98773706 4,56,0.99627966 4,174,0.99601305 4,204,0.9959589 4,202,0.99582237 4,385,0.9957967 5,218,0.99432045 5,98,0.9922024 5,234,0.99179345 5,56,0.99115413 5,53,0.9909523 sim = new PearsonCorrelationSimilarity(dm); sim = new LogLikelihoodSimilarity(dm); <기준 아이템 ID, 비교 아이템ID, 유사도>
  • 20.
    References 1. Apache MahtoutRecommender Quick Start • http://mahout.apache.org/users/recommender/quickstart.html 2. Recommendation System : 협업 필터링을 중심으로 • http://rosaec.snu.ac.kr/meet/file/20120728b.pdf 3. Apache Mahout 맛보기 (30분만에 추천 시스템 만들기) • http://www.slideshare.net/pitzcarraldo/mahout-cook-book 4. Mahout를 활용한 영화 추천 샘플링 • http://www.mimul.com/pebble/default/2012/03/23/1332494169544.html 5. Recommendation: 추천 – 알고리즘 : Item-Based Filtering • http://hochul.net/blog/recommendation-daisy/