카테고리 없음2016. 5. 13. 14:10

오늘은 Kaggler 되기 두번째 날입니다. 금일 다루는 내용은 어려운 내용이 될듯.. 털썩.  brief하게 더듬고 넘어가는 걸로 하겠습니다.  문제는 3달전 있었던 한 competition에서 우승한 팀의 how to solvec입니다. 1764개의 팀(1925명 참가)중에서 우승을 차지한 팀의 내용을 가져왔습니다.  해설로는 600개의 베이스 모델을 멋지게 혼합하여 우승을 할거라고 확신했다 하는데 봅시다.


문제 요약

Homesite라는 Home Insurance회사에서 어떤 고객이 특정 보험 상품을 구매할거냐를 분석하여 마케팅에 활용하고자 competition을 연거구요.  데이터는 여기에 트레이닝/테스트 데이터가 주어진답니다. 그리고 분석 후 제출할 샘플 양식까지 주어집니다.  제출하면 여기에서 점수가 주어지고 랭킹까지 되네요. 하지만 소스코드를 볼려고 했더니... 코드는 비공개인거 같습니다. 하긴 1등이 천만원의 상금이 걸려 있고 뭔가 이 회사에서 실제로 분석 모델로 사용할 거라 당연히 비공개일듯.. 


하지만 how to solve는 제가 보기에 나름(?) 정리가 잘 되어져 있습니다.  봅시다!!



Feature Engineering라는 것은 ML이 작동하기 위해서 도메인 지식을 가지고 features를 만드는 과정이라고 볼수 있습니다. 그럼 여기에서 feature는 머냐고 하면 관찰하고 있는 object/phenomenon에 대한 individual measurable property를 말하구요.  하지만 이 feature engineering을 사용하기에는 어려웠다고 합니다. feature를 잡아내기 위한 과정을 통하여 feature를 선별하긴 했으나 결국엔 극수의 engineered features를 얻었다고 합니다.  

- Count of 0, 1 and N/A row-wise

- PCA top component features

- TSNE 2D

- Cluster ID generated with k-means

- Some differences among features (especially the “golden” features found in a public script)


TSNE과 마지막은은 이해가 잘 안가고. 나머지는 봅시다.  AUC가 처음부터 높게 나와서 신났다고 하네요. 


아래 그림은 PCA로  Red(부정)/Green(긍정)으로 Classification이 되서 말이죠.

Dataset plotted against the top 2 components of PCA (negative in green, positive in red)


그 다음 그림은 TSNE로 한거라고 합니다.


Dataset plotted against the top 2 dimensions of TSNE (negative in green, positive in red)



Dataset Modeling

Python Sklearn의 label encoder를 이용하여 categoriclal features를 인코딩하였다고 합니다. 간단하지만 막강한 이 녀석으로 트리 분류기에서도 작동이 꽤 잘 되었다고 합니다. 하지만 linear한 것들에게는 추천하지 안흔다고 합니다. 왜냐하면 우리 또한 one hot encoded features를 생성했기 때문이라고 합니다.. ( 이 말은.. 저도 이해가 안가네요) 결국 우리는 타겟에 영향을 주는 categorical features의 ratio를 구하기 위해서 target encoding도 시도했다고 합니다. 하지만 개선이 되지 않았다고 합니다.  <-- 결국 label encoding의 불편함을 얘기한거 같습니다 trial and error죠.



Training & Ensembling


여기에서부터 흥미진진한데요.  데이터셋의 다른 버젼들에다가 아래와 같은 ML 모델을 돌렸다고 합니다. 정말 잘 알려져있는것들 잔뜩이네요. 저한텐 밑에 3개는 또 모르지만..

- Logistic Regression

- Regularized Greedy Forest

- Neural Networks

- Extra Trees

- XGBoost

- H2O Random Forest (just 1 or 2 models into our first stage: not really important)

위의 3개는 알겠으나 그 밑에 3개는 모르겠습니다. 마지막껀 H20는 뭔가 RF의 새로운 버젼인거 같은데.. 좀 봐야겠고.. ^^ 여튼 약 600개의 모델로 1레벨이 이루어져 있다고 합니다. 100개는 수작업으로 위의 기술한 기술들의 different features와 hyperparameters를 가지고 만들어졌다고 합니다. 그리고 나서 다양성을 고려하여 500개의 나머지 모델을 만드는 로봇(?)을 만들었다고 합니다. 이 로봇은 자동으로 XGBoost, 로지스틱 회귀, NN가지고 임의로 선택된 features를 기반으로 하여 model을 훈련시킨다고 하네요...  -> 이부분은 신기하네요.. feature가 고정적인것도 아닌가봅니다.


여튼 우리의 모델은 5 fold stratified CV로 만들어졌으며(테스트한 train/test 데이터를 5개로 쪼개서 또 트레이닝 시킨다는 말입니다 CV= Cross Validation)  이로써 우리가 개선을 꾀하고 overfitting을 피할수 있게 도와준다 합니다. 게다가 CV로다가 앙상블 모델을 사용할 수 있었다 합니다(자세한 내용은 여기 뭔가 난해합니다. 여기까진 시간관계상 빠지는걸로..)



아래는 앙상블 예인거 같은데  RGF와 XGB의 관계도.. CORRELATION이 꽤 높죠?

Predictions of an RGF model plotted against predictions of a XGB model

그런데 전 이해가 잘안가네요... 그래서 어쩌라고?? 여튼  600개의 모델을 혼합하기 위해서 다양한 방법을 사용했고 몇번의 실패후에 3개의 멋진 조합을 발견했다고 합니다. 바로 고전적인 로지스틱 회귀와 XGB, NN의 조합이었다합니다.. 후아.. 끝....


그래서 요약하자면...


Model ensemble


그리고 노하우를 알려주네요. 저는 아래 팁들이 상당히 공유가 꺼려질정도로 마음에 듭니다. 내 머리속에만 넣어두고 나만 활용하고 싶다는...

데이터 사이언스의 영역은 쉬운길이 아니고 어렵습니다. 하지만 아래와 같은 방식과 마인드셋으로 하면 언젠가.. 나도 FAMOUS DATA EXPERT가 될겁니다. 그럼 오늘 연재 끝..


  • Read forums, there are lots of useful insights
  • Use the best script as a benchmark
  • Don’t be afraid to generate lot of models and keep all the data created this way. You could still select them later in order to blend them… Or let the blender take the decision for you 🙂
  • Validate the behavior of your CV. If you have a huge jump in local score that doesn’t reflect on the leaderboard there is something wrong
  • Grid search in order to find hyperparameters works fine
  • Blending is a powerful tool. Please read the following post if you haven't have already: http://mlwave.com/kaggle-ensembling-guide/
  • Be aware of the standard deviation when blending. Increasing the metric is good but not that much if the SD increases
  • Neural nets are capricious 🙁 bag them if necessary
  • Merging is totally fine and helps each teammates to learn from others
  • If you are a team, use collaborative tools: Skype, Slack, svn, git...

Recommendations to those just starting out

As written just above, read the forums. There are nice tips, starter codes or even links to great readings. Don’t hesitate to download a dataset and test lot of things on it. Even if most of the tested methods fail or give poor results, you will acquire some knowledge about what is working and what is not.

Merge! Seriously, learning from others is what makes you stronger. We all have different insights, backgrounds or techniques which can be beneficial for your teammates. Last but not least, do not hesitate to discuss your ideas. This way you can find some golden thoughts that can push you to the top!









Posted by 억사마
데이터분석2016. 5. 12. 18:49

난 일주일에 세번!!!! Kaggle에 올라온 Famous Script를 따라서 해보고 감상평과 내용요약을 하고자 한다.


1. 주제

Kaggle에서는 사용자들이 Public Dataset을 가지고 분석한 스크립트와 보고서를 보고 Voting을 한다. 그중 가장 많은 아마존의 Find Food의 리뷰 분석 실습이다.. 데이터는 스탠포드에서 제공하고 2012년 10월에 아마존 사용자들의 568,454 리뷰 데이터를 모은것이다.

데이터 구성은 csv로 아래와 같다.

  • Id
  • ProductId - unique identifier for the product
  • UserId - unqiue identifier for the user
  • ProfileName
  • HelpfulnessNumerator - number of users who found the review helpful
  • HelpfulnessDenominator - number of users who indicated whether they found the review helpful
  • Score - rating between 1 and 5
  • Time - timestamp for the review
  • Summary - brief summary of the review
  • Text - text of the review

그리고 내가 선정한 스크립트는 바로 Ben Hamner이란 분이 올린 script가 되시겠다. 참고로 8개의 voting을 받았다. 


library(RSQLite)
library(tm)
library(wordcloud)

library(RSQLite)
db <- dbConnect(dbDriver("SQLite"), "../input/database.sqlite")

reviews <- dbGetQuery(db, "
SELECT *
FROM Reviews
LIMIT 10000")

make_word_cloud <- function(documents) {
  corpus = Corpus(VectorSource(tolower(documents)))
  corpus = tm_map(corpus, removePunctuation)
  corpus = tm_map(corpus, removeWords, stopwords("english"))
  
  frequencies = DocumentTermMatrix(corpus)
  word_frequencies = as.data.frame(as.matrix(frequencies))
  
  words <- colnames(word_frequencies)
  freq <- colSums(word_frequencies)
  wordcloud(words, freq,
            min.freq=sort(freq, decreasing=TRUE)[[400]],
            colors=brewer.pal(8, "Dark2"),
            random.color=TRUE)  
}

png("wordcloud.png")
make_word_cloud(reviews$Text) 
dev.off()


분명 데이터도 sqlite에서 잘 뽑아와서 corpus를 munging하고 wordcloud함수도 잘 생성되었으나... 쉬운예제임에도불구하고 그림이 안 나옴.. 

실패되시겠습니다. 그래도 여튼 원래장소에서 가져와서붙이고 내가 한걸로.. ㅡ.ㅡ

'데이터분석' 카테고리의 다른 글

Kaggler's Day #8  (0) 2016.06.10
Kaggler's Day #7  (0) 2016.06.08
Kaggler's Day #6  (0) 2016.05.31
Kaggler's Day #5  (0) 2016.05.27
Kaggler's Day #3  (0) 2016.05.16
Posted by 억사마
카테고리 없음2015. 5. 6. 18:58

파워셀을 이용하면 되고 스크립트는 다음과 같다.


아래 &match는 바꿀 문자열  &replacement는 변환할 문자열로 입력하되 하위에도 *slf* 라고 되어있는 부분은 직접 넣어줘야하는듯.


$match = "swtichstr" 

$replacement = "convertedstr"


$files = Get-ChildItem $(get-location) -filter *sif* -Recurse


$files |

    Sort-Object -Descending -Property { $_.FullName } |

    Rename-Item -newname { $_.name -replace $match, $replacement } -force




$files = Get-ChildItem $(get-location) -include *.* -Recurse 


foreach($file in $files) 

    ((Get-Content $file.fullname) -creplace $match, $replacement) | set-content $file.fullname 

}


read-host -prompt "Done! Press any key to close."

Posted by 억사마