Kaggle/Titanic : Machine Learning from disaster

Getting Started With Python

표독's 2016. 3. 19. 20:07

Getting Started With Python

파이썬으로 시작하기

Getting Started with Python: Kaggle's Titanic Competition

케글의 타이타닉 경연대회

Recapping our work with Excel: we have been able to successfully download the competition data and submit 2 models: one based on just the gender and another on the gender, class, and price of ticket. 

엑셀로 했던 일을 반복해보자. 우리는 경연 대회 성공적으로 데이터를 받고 2개의 모델을 제출 했다 : 하나는 단순히 성별에 관한 것이었고, 다른 하나는 성, 등급, 그리고 표의 가격이다. 

This is good for an initial submission, however problems arise when we move to slightly more complicated models and the time taken to formulate approaches in Excel takes longer.

처음 제출하기엔 좋았지만, 이것은 우리가 좀 더 복잡한 모델을 하고자 할 때, 그리고 Excel로 계산하기에는 시간을 잡아 먹는다는 문제가 생긴다.

 What do you do if you want to make a more complicated model but don’t have the time to manually find the proportion of survivors for a given variable? We should make the computer do the hard work for us!

당신이 당장 좀 더 복잡한 모델을 만들고자 하는데, 주어진 변수를 통해 생존자의 비율을 수동적으로 찾을 시간이 없을 때, 당신은 무엇을 하겠는가? 우리는 컴퓨터가 우리를 위해 이 힘든일을 하게 해야만 한다!

I want to add more variables but it takes so much time!

나는 더 많은 변수를 만들고 싶지만 이것은 시간을 많이 잡아 먹는다!

Programming scripts are a great way to speed up your calculations and avoid the arduous task of manually calculating the pivot table ratios. 

프로그래밍 스트립트는 당신의 계산을 더 빠르게 하는데 좋은 요소이며, 피벗 테이블 비율을 수동적으로 계산하는 모호한 일을 피하게 한다.

There are many languages out there, each with its own advantages and disadvantages. Here we are going to use Python version 2.7, which is an easy to use scripting language. 

여기엔 많은 언어들이 있으며, 각각 장 단점을 가지고 있다. 우리는 여기서 Python 2.7 이라는 스크립팅 언어로 사용하기 쉬운 언어를 사용할 것이다.

If you do not have this installed, please visit the Python web site and folllow the instructions there -- or, you could install one specific distribution of Python called Anaconda that already bundles the most useful libraries for data science. (Another advantage of Anaconda is that it includes iPython (Interactive Python) which makes the interface easier for stepping through lines of programming one by one.) 

만약 당신이 파이썬을 가지고 있지 않다면, 파이썬 웹사이트를 통해, 다운받고 안내를 따르길 바란다, 또는 당신은 Anaconda라는 특정한 파이썬 배포판을 받을 수 있는데, 이것은 데이터 과학에 관한 대부분의 다양한 라이브러리를 가지고 있다. (Anaconda의 다른 장점으로는 이것은 iPyhthon(Interactive Python)을 가지고 있다는 것인데, 이것은 한줄 한줄 단계적으로 프로그래밍하기 쉽게한다.)

NOTE in either case: if you use Python version 3.x, you may discover some Python syntax has changed in that version, which can cause errors on this tutorial as people point out in the forum.

다음과 같은 사항을 생각하라 : 당신이 만약 파이썬 3 버전대를 쓴다면, 다른 사람들이 지적하는 것 처럼, 당신은 이 버전에서 syntax 오류를 찾을수 있습니다.

When you have things installed, to begin just type  python , or  ipython , or ipython notebook.

인스톨을 완료했을 때, 이제 당신은 python, Ipython 또는 Ipython notebook에 타이핑할 준비가 된것 입니다.

One of the great advantages of Python is its packages. Of these packages, the most useful (for Kaggle competitions) are the Numpy, Scipy, Pandas, matplotlib and csv package. In order to check whether you have these, just go to your python command line and type  import numpy  (and so on). If you don’t you will need them! This tutorial is going to guide you through making the same submissions as before, only this time using Python.


Python의 정말 큰 장점중의 하나는 이것의 패키지들입니다. 이들 패키지중에서 가장 유용한 것들은 (Kaggle 경연대회에서) Numpy, Scipy, Pandas, matplotlib 그리고 scv package입니다. 당신이 이것들을 가지고 있는지 확인하기 위해 당신의 command line(명령줄)에 가서 import numpy(등등)을 쳐 보세요. 만약 안된다면, 그것이 필요하다는 것입니다. 이 튜토리얼은 전과 같이 그대로 제출하기만 하면됩니다만, 이번에는 파이썬만을 이용합니다.

Python: Reading in your train.csv

train.csv를 읽자.

Python has a nice csv reader, which reads each line of a file into memory. You can read in each row and just append a list. From there, you can quickly turn it into an array. 

파이썬은 csv 파일의 각 줄을 읽어 메모리로 전송하는 괜찮은 csv 리더기를 가지고 있습니다. 당신은 각 행을 읽을 수 있고 리스트에 추가시킬 수 있습니다. 이것으로 부터, 당신은 이것을 배열로 바꿔낼 수 있습니다.

# The first thing to do is to import the relevant packages
# 첫번째로 관련된 패키지들을 부른다
# that I will need for my script,
# 그 다음에는 나의 스크립트가 필요하다.
# these include the Numpy (for maths and arrays)
#수학과 배열을 위해 Numpy가 필요하다.
# and csv for reading and writing csv files
# csv 파일들을 읽고 쓰기 위해 csv가 필요하다.
# If i want to use something from this I need to call
# csv.[function] or np.[function] first
# 만약 내가 이것들로 부터 뭔가를 사용하고 싶다면 우리는 csv.[함수] 또는 np.[함수]을 사용한다.
In[2]: import csv as csv 
In[3]: import numpy as np
In[4]: csv_file_object = csv.reader(open('E:\\kaggle\\titanic\\train.csv', 'rb'))
# csv_file_object에 train.csv 파일을 읽는다.
In[5]: header = csv_file_object.next()
#next()는 첫번째 줄을 건너뛰게 해주는 문법이다. 첫번 째 줄은 header라고 불린다.
In[6]: data=[] # 빈 사전형 리스트 생성
In[7]: for row in csv_file_object:
... data.append(row) #한 줄씩 읽어주는 과정
In[8]: data = np.array(data) #data를 array배열로 바꿔준다.


Although you've seen this data before in Excel, just to be sure let's look at how it is stored now in Python.  Type  print data  and the output should be something like

당신이 Excel안에서 이러한 데이터를 봤더라도, 지금은 파이썬에서 어떻게 저장되는지 봐두는 겁니다. print data를 타이프하면 결과물은 다음과 같을 겁니다.


In[9]: print data
[['1' '0' '3' ..., '7.25' '' 'S']
['2' '1' '1' ..., '71.2833' 'C85' 'C']
['3' '1' '3' ..., '7.925' '' 'S']
...,
['889' '0' '3' ..., '23.45' '' 'S']
['890' '1' '1' ..., '30' 'C148' 'C']
['891' '0' '3' ..., '7.75' '' 'Q']]

You can see this is an array with just values (no descriptive header). And you can see that each value is being shown in quotes, which means it is stored as a string. Unfortunately in the output above, the full set of columns is being obscured with "...," so let's print the first row to see it clearly.  Type  print data[0]

당신은 설명적인 header가 없는 이런 값만 가진 배열을 불 수 있습니다. 그리고 당신은 각 값들이 따옴표 안에 있는 것을 보게 될 것인데 이것은 문자열임을 의미합니다. 불행하게도 위의 결과는 "....."에 의해 전체 열들이 보여지지 않습니다. 따라서 이것들을 명확하게 바꿔줘 봅시다. print data[0]을 쳐보세요.

In[10]: print data[0]
['1' '0' '3' 'Braund, Mr. Owen Harris' 'male' '22' '1' '0' 'A/5 21171'
'7.25' '' 'S']

and to see the last row, type  print data[-1]

print data[-1]을 치면 마지막 행을 볼 수 있습니다.


and to see the 1st row, 4th column, type  print data[0,3]

첫번째 행의 네번째 열을 보기 위해서 print data[0,3]을 쳐봅니다.

In[11]: print data[0,3]
Braund, Mr. Owen Harris


I have my data now I want to play with it

Now if you want to call a specific column of data, say, the gender column, I can just typedata[0::,4], remembering that "0::" means all (from start to end), and Python starts indices from 0 (not 1). You should be aware that the csv reader works by default with strings, so you will need to convert to floats in order to do numerical calculations. For example, you can turn the Pclass variable into floats by usingdata[0::,2].astype(np.float). Using this, we can calculate the proportion of survivors on the Titanic: 

만약 당신이 데이터의 특정한 열만을 호출하고 싶다면, gender 열같은경우에, 나는 data[0::,4]라고 칠 것입니다, 기억하세요 "0::"은 처음부터 끝까지를 가르키며 파이썬은 (1이 아니라) 0부터 시작한다는 것을요!. csv은 기본적으로 문자열에 작동합니다. 그래서 우리는 수학적 계산을 하기위해 정수로 바꾸어 줄 필요가 있습니다. 예를 들어 우리는 Pclass변수를 정수(floats)로 바꿔주고 싶습니다. data[0::, 2].astype(np.float) 을 사용해서 말이죠. 우린 이것을 이용해서 타이타닉에서의 생존자 비율을 계산할 수 있습니다. 

In[13]: number_passengers = np.size(data[0::,1].astype(np.float))
 #passengers의 수를 구하기 위한

In[14]: number_survived = np.sum(data[0::,1].astype(np.float))  

#산 사람은 1이므로 총합은 생존자 수

In[15]: proportion_survivors = number_survived / number_passengers 

# 비율 구하기

Numpy has some lovely functions. For example, we can search the gender column, find where any elements equal female (and for males, 'do not equal female'), and then use this to determine the number of females and males that survived: 


Numpy는 몇 개의 사랑스러운 기능을 가지고 있습니다. 예를 들어, 우리는 gender 열을 찾을 수있습니다, 그리고 female 값을 가진 요소들을 찾을 수 있고('female'이 아닌 값, 즉 male 값도 가능합니다', 그리고 이것을 이용해 생존한 남성과 여성의 수를 알 수 있겠습니다.


women_only_stats = data[0::,4] == "female" # This finds where all
# gender 변수에서
# the elements in the gender
# 'female'값을 가진
# column that equals “female”
# 요소들만 찾기
men_only_stats = data[0::,4] != "female" # This finds where all the
# gender 변수에서
# elements do not equal
# female이 아닌 변수들만

We use these two new variables as a "mask" on our original train data, so we can select only those women, and only those men on board, then calculate the proportion of those who survived:


우리는 이 두가지 새로운 변수를 이용할 수 있습니다. 그럼으로써 우리는 여자만을 선택할 수 있고, 남자 탑승객만을 사용할 수 있습니다. 그래서 우리는 살아남은 이 사람들의 비율을 알 수 있습니다.


# Using the index from above we select the females and males separately
# 위에서 남성과 여성을 분리했던 것을 인덱싱 한다.
women_onboard = data[women_only_stats,1].astype(np.float)
#women_onboard에 여성중 생존자인 경우를 찾아 float 형태로 바꿔줌
men_onboard = data[men_only_stats,1].astype(np.float)
#men_onboard에 남성중 생존자인 경우를 찾아 float형태로 바꿔줌
# Then we finds the proportions of them that survived
# 그러면 우리는 살아남은 사람들의 비율을 알 수 있다. (남 , 여)
proportion_women_survived = \
np.sum(women_onboard) / np.size(women_onboard)
# 여성의 살아 남은 비율
proportion_men_survived = \
np.sum(men_onboard) / np.size(men_onboard)
# 남성의 살아 남은 비율

# and then print it out
# 프린팅 해보자.
In[25]: print 'Proportion of women who survived is %s' % proportion_women_survived
Proportion of women who survived is 0.742038216561
In[27]: print 'Proportion of men who survived is %s' % proportion_men_survived
Proportion of men who survived is 0.347133757962

Now that I have my indication that women were much more likely to survive, I am done with the training set.

이제 우리는 여자들의 살아날 확률에 대해 알았고, training set은 끝났다.


Reading the test data and writing the gender model as a csv

test data를 읽고 gender 모델을 csv로 하기.


As before, we need to read in the test file by opening a python object to read and another to write. First, we read in the test.csv file and skip the header line:

지금까지 우리는 test file에서 새로운 python object를 읽기 위해 열고 다른 것을 쓰기 위해 열었습니다. 첫째로, 우리는 test.csv 파일을 읽고 header라인을 넘겨 봅시다.

test_file = open('E:\\kaggle\\titanic\\test.csv', 'rb')
test_file_object = csv.reader(test_file)
header = test_file_object.next()

Now, let's open a pointer to a new file so we can write to it (this file does not exist yet). Call it something descriptive so that it is recognizable when we upload it:

이제, 새로운 파일을 열도록 해봄으로서 여기에 뭔가 쓸 수 있습니다. 이것을 뭔가 묘사적으로 할 수 있게 하여 우리가 업로드 할 때 인식 가능하도록 만듭시다.

prediction_file = open("genderbasedmodel.csv", "wb") #새로운 csv모델 만들기
prediction_file_object = csv.writer(prediction_file) # prediction_file에 쓰기형태.

 

We now want to read in the test file row by row, see if it is female or male, and write our survival prediction to a new file. 

우리는 이제 test file을 한줄 한줄 읽고, 만약 여성인지 남성인지에 따라서 우리의 생존 예측이 새로운 파일에 쓰여지도록 하고 싶다.

prediction_file_object.writerow(["PassengerId", "Survived"])
#써주는 객체에 "Passengerld"와 "Survived"를 적는다
for row in test_file_object: # For each row in test.csv
# test_file_object 파일에서 한줄씩 불러와서
if row[3] == 'female': # is it a female, if yes then
#'female'인 경우에
prediction_file_object.writerow([row[0],'1']) # predict 1
# row[0]과 '1'을 적어라
else: # or else if male,
prediction_file_object.writerow([row[0],'0']) # predict 0
#아니면 row[0]과 '0'을 적어라
test_file.close()
prediction_file.close()

Think : female이었을 경우 살았을 확률이 높았으니, 모두 살았다고 가정하는 것.

Pythonising the second submission

두 번째 미션을 파이서나이징(파이선으로해보자)

By now you have created your first python submission. Let's complicate things and try and submit the same submission as before, binning up the ticket price into the four bins and modeling the outcome on class, gender, and ticket price. This part assumes that you have completed the section 'Reading in your train.csv' and you have a data array as before.  On the Data page you will find a python script named 'genderclassmodel.py' to follow along... but be sure to type (or paste) each line of code yourself, to help you learn what is happening.

우리는 파이썬으로 첫 번째 제출거리를 만들었다. 이제 좀 더 복잡한 것을 시도해보고 전과 같은 제출을 해보자, 표 가격은 4개의 그룹으로 나누고 등급, 성, 표 가격을 결과물로 한 모델링을 해보자. 이 부분에서는 당신이 Reading in your train.csv를 끝냈다고 가정한다. 그리고 전에 했던 data array을 가지고 있다고 생각한다. Data page에서 'genderclassmodel.py'를 찾을 수 있을 것이지만, 무슨 일어나는지 알기 위해 코드 한줄 한줄씩 직접 쳐보길 바랍니다.

The idea is to create an table which contains just 1's and 0's. The array will be a survival reference table, whereby you read in the test data, find out passenger attributes, look them up in the survival table, and determine if they should be predicted to survive or not. In the case of a model that uses gender, class, and ticket price, you will need an array of 2x3x4 ( [female/male] , [1st / 2nd / 3rd class], [4 bins of prices] ). 

아이디어는 1과 0 값만을 테이블을 만드는 것입니다. 이 배열은 생존에 대한 것일 것인데 이 것으로 우리는 test data를 읽고 passenger 속성에 대해 찾아 냅니다, 생존 테이블에서 그들을 찾고 생존했는지 아닌지에 대해 결정해야 합니다. 우리는 이 성별, 등급, 티켓 가격을 사용한 모델에서 2x3x4의 배열이 필요합니다(남/여, 1,2,3,등급, 가격의 4 항목)

The script will systematically will loop through each combination and use the 'where' function in python to search the passengers that fit that combination of variables. Just like before, you can ask what indices in your data equals female, 1st class, and paid more than $30. The problem is that looping through requires bins of equal sizes, i.e. $0-9,  $10-19,  $20-29,  $30-39.  For the sake of binning let's say everything equal to and above 40 "equals" 39 so it falls in this bin. So then you can set the bins:

이 스크립트는 각각의 조합들을 반복하고 변수들의 조합에 부합되는 passengers를 찾는 기능인 'where'을 사용합니다. 이전과 같이, 당신의 데이터에서 여성, 1등급, 그리고 30달러 이상의 조건에 부합되는 것들을 명시할 수 있습니다. 이 문제는 같은 크기의 범주들이 필요하다는 것입니다. 즉 $0-9, $10-19, $20-29, $30-39처럼 말이죠. 묶기 위해서 우리는 40 이상을 모두 39로 같게 할 것입니다. 그러면 당신은 이제 통(범주)들을 설정할 수 있습니다.


# So we add a ceiling
#그래서 우리는 상한을 정해줍니다.
fare_ceiling = 40 #40으로 정했다.
# then modify the data in the Fare column to = 39, if it is greater or equal to the ceiling
#그 다음 데이터를 39까지 맞추어 주는 작업을 한다. 만약 이것이 40보다 높거나 같다면 말이다.
data[ data[0::,9].astype(np.float) >= fare_ceiling, 9 ] = fare_ceiling - 1.0
#array[a, b ] 에서 a는 행, b는 열 indexing!

fare_bracket_size = 10
# bins의 크기를 설정해주고
number_of_price_brackets = fare_ceiling / fare_bracket_size
# 상한을 나눠주면 bins의 갯수 = 4개

# I know there were 1st, 2nd and 3rd classes on board
#우리는 classes에 1,2,3 등급들이 있는 것을 알고 있다.
number_of_classes = 3 # 3개

# But it's better practice to calculate this from the data directly
# 그러나 데이터로 부터 직접 계산하는 것이 좀 더 좋은 연습이 될것이다.
# Take the length of an array of unique values in column index 2
# 2번째 열에서 고유 값들의 배열 길이를 알아내 보자.
number_of_classes = len(np.unique(data[0::,2]))
# unique(x) 메서드는 배열 x에서 중복된 원소를 제거한 후 정렬하여 반환
# Initialize the survival table with all zeros
# 생존자 열을 모두 0으로 만들자 zeros는 모두 0으로 만든다.
survival_table = np.zeros((2, number_of_classes, number_of_price_brackets))
# 여기서는 3차원 2 x 등급개수(3) x 티켓 범주 갯수
In[50]: survival_table
Out[50]:
array([[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],

[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]])

Now that these are set up, you can loop through each variable and find all those passengers that agree with the statements:


이제 설정을 마쳤습니다, 이제 각각의 변수를 반복하고 모든 탑승객들이 이 구문에 맞추어진것을 볼 수 있습니다.


for i in xrange(number_of_classes): #loop through each class
#각 클래스안에서 반복문 , xrange는 이 자체 객체를 리턴, 리스트를 만들지 않고 작동
for j in xrange(number_of_price_brackets): #loop through each price bin

women_only_stats = data[ \ #which element
(data[0::,4] == "female") \
&(data[0::,2].astype(np.float) \#and was ith class
== i+1) \
&(data[0:,9].astype(np.float) \#was greater
>= j*fare_bracket_size) \#than this bin
&(data[0:,9].astype(np.float) \#and less than
< (j+1)*fare_bracket_size)\#the next bin
, 1] #in the 2nd col
#women_only_stats 변수에는 여성이면서 등급별, 티켓 가격 범주별로 생존 유무 반환


men_only_stats = data[ \#Which element
(data[0::,4] != "female") \#is a male
&(data[0::,2].astype(np.float) \#and was ith class
== i+1) \
&(data[0:,9].astype(np.float) \#was greater
>= j*fare_bracket_size) \#than this bin
&(data[0:,9].astype(np.float) \#and less than
< (j+1)*fare_bracket_size)\#the next bin

#men_only_stats 변수에는 남성이면서 등급별, 티켓 가격 범주별로 생존 유무 반환

, 1]Notice that  data[ where function, 1]  means it is finding the Survived column for the conditional criteria which is being called. As the loop starts with i=0 and j=0, the first loop will return the Survived values for all the 1st-class females (i + 1) who paid less than 10 ((j+1)*fare_bracket_size) and similarly all the 1st-class males who paid less than 10.  Before resetting to the top of the loop, we can calculate the proportion of survivors for this particular combination of criteria and record it to our survival table:


data[where 함수, 1]은 생존자 열에서 호출된 조건 기준에 부합하는 것을 찾습니다. 반복문이 i=0, j=0으로 시작하게 되고, 첫 번째 반복문은 첫번째 등급 여성(i+1)에서 10달러 미만의 티켓가격을 낸 사람의 생존 값을 반환하고 이처럼 모든 1등급 클래스에서 10달러 미만의 가격을 지불 한 사람들의 생존값을 반환합니다. 반복문의 꼭대기를 재 설정하기 전에, 이러한 특정 기준들의 조합에 관한 사망자의 비율에 대해 계산가능하고 이것을 생존자 테이블에 기록할 수 있습니다


At the end we will get a matrix which will be shaped as a 2x3x4 array-- or think of this as two 3x4 arrays: The first corresponding to females, with the rows giving the class and columns giving the fare bracket, and the second corresponding similarly to the males.


결국 2x3x4 배열의 행렬을 가지게 될 것입니다. 아니면 2개의 3x4행렬 이라고 할 수 있습니다. 첫 번째는 여성에 해당될 것이며 등급에 관한 행과 요금 범주에 관한 열을 가질 것이고 다음은 남성에 해당합니다.


 Female

0-9 

10-19 

20-29 

30-39 

 

 

 

 

 

 

 

 

 

 

 

 



Male 

0-9 

10-19 

20-29 

30-39 

 

 

 

 

 2

 

 

 

 

 3

 

 

 

 


각 칸안에는 생존자의 수가 기록 될 것이다.








'Kaggle > Titanic : Machine Learning from disaster' 카테고리의 다른 글

Getting Started With Python II  (0) 2016.04.07