from google.colab import drive # 패키지 불러오기
from os.path import join
ROOT = "/content/drive" # 드라이브 기본 경로
print(ROOT) # print content of ROOT (Optional)
drive.mount(ROOT) # 드라이브 기본 경로 Mount
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/inflearn_kaggle/' # 프로젝트 경로
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH) # 프로젝트 경로
print(PROJECT_PATH)
/content/drive
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/
필자는 inflearn_kaggle 폴더안에 data, docs, source 등의 하위 폴더를 추가로 만들었다.
즉, data 안에 다운로드 받은 파일이 있을 것이다.
III. 캐글 데이터 수집 및 EDA
우선 데이터를 수집하기에 앞서서 EDA에 관한 필수 패키지를 설치하자.
import pandas as pd
import pandas_profiling
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import seaborn as sns
from IPython.core.display import display, HTML
from pandas_profiling import ProfileReport
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
from google.colab import drive # 패키지 불러오기
from os.path import join
ROOT = "/content/drive" # 드라이브 기본 경로
print(ROOT) # print content of ROOT (Optional)
drive.mount(ROOT) # 드라이브 기본 경로 Mount
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/inflearn_kaggle/' # 프로젝트 경로
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH) # 프로젝트 경로
print(PROJECT_PATH)
/content/drive
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/
필자는 inflearn_kaggle 폴더안에 data, docs, source 등의 하위 폴더를 추가로 만들었다.
즉, data 안에 다운로드 받은 파일이 있을 것이다.
III. 캐글 데이터 수집 및 EDA
우선 데이터를 수집하기에 앞서서 EDA에 관한 필수 패키지를 설치하자.
import pandas as pd
import pandas_profiling
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import seaborn as sns
from IPython.core.display import display, HTML
from pandas_profiling import ProfileReport
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.
I. 개요
Functions와 Decorators에 관해 나누려고 한다.
function는 우리가 생각하는 그 함수가 맞다.
decorator도 함수인데, 일종의 확장 개념으로 생각하면 좋다.
II. Simple Tutorial
먼저 간단한 함수를 만들자.
defadd_one(number):
return number +1add_one(2)
3
일반적으로 파이썬의 함수들은 단지 입출력에 대한 단순한 내용 보다는 side effects 또한 함의하고 있다.
print()함수가 대표적인 예인데, 코드에 print()를 실행하면 아무것도 출력되지 않는다.
decorator를 이해하기 위해서 필요한 가설 1개는 arguments를 value로 바꾸는 것이다.
print()
III. First-Class Objects
파이썬에서 함수는 first-class objects이다.
이것은 다른 객체(문자열, int, float, list 등)와 마찬가지로 기능들이 다양한 경로로 전달되어 인수로 사용될 수 있다는 것을 의미한다.
다음 예제를 확인해보자.
def_hello(name):
returnf"안녕하세요 {name}"def_friend(name):
returnf"와~ {name}, 우리는 이제 친구야"defwill_greet(greeter_func):
return greeter_func("Chloe")
여기에서 will_greet() 함수만 사용할 것이다.
그런데, _greet() 함수 안에는 다른 함수들 _hello()나 _friend()만 사용할 것이다.
will_greet(_hello)
'안녕하세요 Chloe'
will_greet(_friend)
'와~ Chloe, 우리는 이제 친구야'
will_greet(_hello)는 두개의 함수가 사용되었지만, 조금 작동법이 다르다.
먼저 _hello는 인수값이 사용된 것은 아니며 그저 참조된 것이지만, will_greet()함수는 인수값이 사용되었다는 차이점이 있다.
IV. Inner Functions
Inner functions는 정의된 함수안에 또다른 함수를 정의하는 것이다.
defmother():
print("저는 두 아이의 엄마입니다.")
defchild_1st():
print("저는 첫째이며 3살입니다.")
defchild_2nd():
print("저는 둘째이며 2살입니다.")
child_1st()
child_2nd()
mother()
저는 두 아이의 엄마입니다.
저는 첫째이며 3살입니다.
저는 둘째이며 2살입니다.
위 내용은 매우 간단하지만, mother()를 불러야 첫째와 둘째를 같이 볼 수 있다. 이유는 첫째와 둘째 모두 엄마 없이는 살 수 없기 때문이다.
만약에 child_1st()만 호출해보자. 엄마 없이 아이를 불러서는 안된다.
child_1st()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-8d46572507ad> in <module>()
----> 1 child_1st()
NameError: name 'child_1st' is not defined
V. Returning Functions from Functions
함수의 return 값으로 inner function을 사용할 수 있다.
defmother(num):
defchild_1st():
return"안녕하세요, 저는 첫째, Chloe입니다."defchild_2nd():
return"안녕하세요, 저는 둘째, Evan입니다."if num==1:
print("저는 첫째 아이의 엄마입니다.")
return child_1st
else:
print("저는 둘째 아이의 엄마입니다.")
return child_2nd
괄호 없이 child_1st와 child_2nd를 반환한다는 점에 주목한다.
이는 함수에 대한 참조를 먼저 반환함을 의미한다.
my1stBaby = mother(1)
my2ndBaby = mother(2)
저는 첫째 아이의 엄마입니다.
저는 둘째 아이의 엄마입니다.
여기에서 각각의 객체를 출력해보고 어떤 결과가 나오는지 확인해보자.
my1stBaby
<function __main__.mother.<locals>.child_1st>
my2ndBaby
<function __main__.mother.<locals>.child_2nd>
mother 함수 안에 필요한 함수들만 호출되는 것을 볼 수 있다.
이 때, my1stBaby()와 my2ndBaby() 함수를 호출하면 어떤 결과가 나타내는지 확인해보자.
my1stBaby()
'안녕하세요, 저는 첫째, Chloe입니다.'
my2ndBaby()
'안녕하세요, 저는 둘째, Evan입니다.'
마지막으로, 앞의 예에서 상위 함수 mother() 내에서 inner function(예: child_1st()) 함수를 실행했다는 점에 유의한다.
그러나 이 마지막 예에서는 결과값을 반환할 때 내부 함수인 child_1st 괄호를 하지 않았다는 것도 확인한다.
That way, you got a reference to each function that you could call in the future.
from google.colab import drive # 패키지 불러오기
from os.path import join
ROOT = "/content/drive" # 드라이브 기본 경로
print(ROOT) # print content of ROOT (Optional)
drive.mount(ROOT) # 드라이브 기본 경로 Mount
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/inflearn_kaggle/' # 프로젝트 경로
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH) # 프로젝트 경로
print(PROJECT_PATH)
/content/drive
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/
필자는 inflearn_kaggle 폴더안에 data, docs, source 등의 하위 폴더를 추가로 만들었다.
즉, data 안에 다운로드 받은 파일이 있을 것이다.
III. 캐글 데이터 수집 및 EDA
우선 데이터를 수집하기에 앞서서 EDA에 관한 필수 패키지를 설치하자.
import pandas as pd
import pandas_profiling
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import seaborn as sns
from IPython.core.display import display, HTML
from pandas_profiling import ProfileReport
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
from google.colab import drive # 패키지 불러오기 from os.path import join
ROOT ="/content/drive"# 드라이브 기본 경로print(ROOT) # print content of ROOT (Optional)drive.mount(ROOT) # 드라이브 기본 경로 MountMY_GOOGLE_DRIVE_PATH ='My Drive/Colab Notebooks/inflearn_kaggle/'# 프로젝트 경로PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH) # 프로젝트 경로print(PROJECT_PATH)
/content/drive
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/
필자는 inflearn_kaggle 폴더안에 data, docs, source 등의 하위 폴더를 추가로 만들었다.
즉, data 안에 다운로드 받은 파일이 있을 것이다.
III. 캐글 데이터 수집 및 EDA
우선 데이터를 수집하기에 앞서서 EDA에 관한 필수 패키지를 설치하자.
import pandas as pd
import pandas_profiling
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import seaborn as sns
from IPython.core.display import display, HTML
from pandas_profiling import ProfileReport
from google.colab import drive # 패키지 불러오기
from os.path import join
ROOT = "/content/drive" # 드라이브 기본 경로
print(ROOT) # print content of ROOT (Optional)
drive.mount(ROOT) # 드라이브 기본 경로 Mount
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/inflearn_kaggle/' # 프로젝트 경로
PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH) # 프로젝트 경로
print(PROJECT_PATH)
/content/drive
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
/content/drive/My Drive/Colab Notebooks/inflearn_kaggle/
필자는 inflearn_kaggle 폴더안에 data, docs, source 등의 하위 폴더를 추가로 만들었다.
즉, data 안에 다운로드 받은 파일이 있을 것이다.
III. 캐글 데이터 수집 및 EDA
우선 데이터를 수집하기에 앞서서 EDA에 관한 필수 패키지를 설치하자.
import pandas as pd
import pandas_profiling
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.core.display import display, HTML
from pandas_profiling import ProfileReport
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
(1) 데이터 수집
지난 시간에 받은 데이터가 총 4개임을 확인했다.
data_description.txt
sample_submission.csv
test.csv
train.csv
여기에서는 우선 test.csv & train.csv 파일을 받도록 한다.
train = pd.read_csv('data/train.csv')
test = pd.read_csv('data/test.csv')
print("data import is done")
data import is done
(2) 데이터 확인
Kaggle 데이터를 불러오면 우선 확인해야 하는 것은 데이터셋의 크기다.
변수의 갯수
Numeric 변수 & Categorical 변수의 개수 등을 파악해야 한다.
Point 1 - train데이터에서 굳이 훈련데이터와 테스트 데이터를 구분할 필요는 없다.
이 강의의 목적이 Kaggle 데이터를 활용한 Python 포트폴리오 제작 강의임을 잊지 말자.
이번 시간에는 Kaggle 데이터를 구글 드라이브로 다운로드 받는 방법에 대해 작성하였다.
II. Kaggle KPI 설치
Google Colab에서 Kaggle API를 불러오려면 다음 소스코드를 실행한다.
!pip install kaggle
Requirement already satisfied: kaggle in /usr/local/lib/python3.6/dist-packages (1.5.6)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.23.0)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.24.3)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.0.0)
Requirement already satisfied: python-dateutil in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.8.1)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.41.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle) (2020.4.5.1)
Requirement already satisfied: six>=1.10 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.12.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (2.9)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (3.0.4)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle) (1.3)
III. Kaggle Token 다운로드
Kaggle에서 API Token을 다운로드 받는다.
[Kaggle]-[My Account]-[API]-[Create New API Token]을 누르면 kaggle.json 파일이 다운로드 된다.
이 파일을 바탕화면에 옮긴 뒤, 아래 코드를 실행 시킨다.
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
# kaggle.json을 아래 폴더로 옮긴 뒤, file을 사용할 수 있도록 권한을 부여한다.
!mkdir -p ~/.kaggle/ && mv kaggle.json ~/.kaggle/ && chmod 600 ~/.kaggle/kaggle.json
Saving kaggle.json to kaggle.json
uploaded file "kaggle.json" with length 64 bytes
ls -1ha ~/.kaggle/kaggle.json
ls: cannot access '/root/.kaggle/kaggle.json': No such file or directory
에러 메시지가 없으면 성공적으로 json 파일이 업로드 되었다는 뜻이다.
IV. 구글 드라이브 연동
데이터를 불러오기 전에 구글 드라이브와 연동하는 작업을 우선 진행한다.
매우 쉽다. 그러니 천천히 따라와주시기를 바란다.
(1) 구글 드라이브 마운트
다음 소스코드를 통해서 구글 드라이브와 마운트를 진행한다.
쉽게 표현하면 구글 코랩에서 드라이브로 접근을 하겠다는 뜻이다.
아래 소스 코드를 실행 하면 본인 인증 절차를 진행하면 된다.
from google.colab import drive # 패키지 불러오기
ROOT = "/content/drive" # 드라이브 기본 경로
print(ROOT) # print content of ROOT (Optional)
drive.mount(ROOT) # 드라이브 기본 경로 Mount
/content/drive
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
(2) 프로젝트 파일 생성 및 다운받을 경로 이동
구글 코랩을 실행하면 Drive에 Colab Notebooks 폴더가 생성이 된다.
일종의 Colab Project 폴더로 생각하자.
이 때 본인만의 프로젝트 폴더를 만들자. (주의: 폴더 이름은 반드시 영어명과 공백없이 만든다)
보안 그룹은 클러스터에 대한 인바운드 및 아웃바운드 트래픽을 제어하는 가상 방화벽 역할을 한다.
첫 번째 클러스터를 생성하면 Amazon EMR은 마스터 인스턴스, ElasticMapReduce-master와 연결된 기본 Amazon EMR 관리 Security Group 및 핵심 노드 및 태스크 노드와 연결된 Security Group ElasticMapReduce-slave를 생성한다.
Warning: 공용 서브넷의 마스터 인스턴스에 대한 기본 EMR 관리 보안 그룹 ElasticMapReduce-master는 모든 소스(IPv4 0.0.0/0)에서 포트 22의 인바운드 트래픽을 허용하는 규칙으로 사전 구성된다. 이는 마스터 노드에 대한 초기 SSH 클라이언트 연결을 단순화하기 위한 것이다. 보안 이슈가 생길 우려가 있기 때문에 AWS는 이 인바운드 규칙을 편집하여 신뢰할 수 있는 소스의 트래픽만 제한하거나 액세스를 제한하는 사용자 지정 보안 그룹을 지정해야 한다.