Colab이란?
Colaboratory(줄여서 'Colab'이라고 함)을 통해 브라우저 내에서 Python 스크립트를 작성하고 실행할 수 있습니다.
구성이 필요하지 않음
무료로 GPU 사용
간편한 공유
학생이든, 데이터과학자든, AI 연구원이든 Colab으로 업무를 더욱 간편하게 처리할 수 있습니다.
지금 읽고 계신 문서는 정적 웹페이지가 아니라 코드를 작성하고 실행할 수 있는 대화형 환경인 Colab 메모장.
예를 들어 다음은 값을 계산하여 변수로 저장하고 결과를 출력하는 간단한 Python 스크립트가 포함된 코드 셀.
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day
Output
86400
위 셀의 코드를 실행하려면 셀을 클릭하여 선택한 후 코드 왼쪽의 실행 버튼을 누르거나,
단축키 'Command/Ctrl+Enter'를 사용하세요.
셀을 클릭하면 코드 수정을 바로 시작할 수 있습니다.
특정 셀에서 정의한 변수를 추후 다른 셀에서 사용할 수 있습니다.
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week
Output
99792000
Colab 메모장을 사용하면 실행 코드와 서식 있는 텍스트를 이미지, HTML, LaTeX 등과 함께 하나의 문서로 통합할 수 있습니다. Colab 메모장을 만들면 Google Drive 계정에 저장됩니다.
Colab 메모장을 간편하게 공유하여 동료나 친구들이 댓글을 달거나 수정하도록 할 수 있습니다.
자세히 알아보려면 Colab 개요를 참조하세요.
새 Colab 메모장을 만들려면 위의 파일 메뉴를 사용하거나 다음 링크로 이동하세요.
새 Colab 메모장 만들기
Colab 메모장은 Colab에서 호스팅하는 Jupyter 메모장입니다. Jupyter 프로젝트에 관해 자세히 알아보려면 jupyter.org를 참조하세요.
데이터과학
Colab을 통해 인기 있는 Python 라이브러리를 최대한 활용하여 데이터를 분석하고 시각화할 수 있습니다.
아래 코드 셀에서는 Numpy를 사용하여 임의의 데이터를 생성하고 matplotlib으로 이를 시각화합니다.
셀을 클릭하면 코드 수정을 바로 시작할 수 있습니다.
import numpy as np
from matplotlib import pyplot as plt
ys = 200 + np.random.randn(100)
x = [x for x in range(len(ys))]
plt.plot(x, ys, '-')
plt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha=0.6)
plt.title("Sample Visualization")
plt.show()
Output
![](https://blog.kakaocdn.net/dn/BM5QH/btsB3tD2QvB/r9fuF9gfKPxKXK0gvSTl7k/img.png)
Google Drive 계정에서 스프레드시트를 비롯한 데이터를 Colab 메모장으로 가져오거나 GitHub 등의 여러 다른 소스에서 데이터를 가져올 수 있습니다.
Colab을 데이터과학에 활용하는 방법과 데이터 가져오기에 관해 자세히 알아보려면 데이터 사용하기 아래 링크를 참조하세요.
머신러닝
Colab 사용하면 코드 몇 줄만으로 이미지 데이터세트를 가져오고, 이 데이터세트로 이미지 분류기를 학습시키며, 모델을 평가할 수 있습니다.
Colab 메모장은 Google 클라우드 서버에서 코드를 실행하므로 사용 중인 컴퓨터 성능과 관계없이 GPU 및 TPU를 포함한 Google 하드웨어의 성능을 활용할 수 있습니다.
브라우저만 있으면 사용 가능합니다.
Colab은 다음 같은 분야의 머신러닝 커뮤니티에서 널리 쓰이고 있습니다.
TensorFlow 시작하기
신경망 개발 및 학습시키기
TPU로 실험하기
AI 연구 보급하기
튜토리얼 만들기
머신러닝 적용 사례를 보여 주는 Colab 메모장 샘플을 확인하려면 아래 머신러닝 예시를 참조하세요.
Cells
노트북은 셀 목록입니다.
셀에는 설명텍스트나 실행코드 및 해당출력이 포함됩니다.
셀을 클릭하여 선택합니다.
A notebook is a list of cells. Cells contain either explanatory text or executable code and its output. Click a cell to select it.
Code cells
코드 셀
아래는 코드 셀입니다.
toolbar button에 CONNECTED가 표시되면, 셀을 클릭하여 선택하고 다음과 같은 방법으로 내용을 실행:
Below is a code cell. Once the toolbar button indicates CONNECTED, click in the cell to select it and execute the contents in the following ways:
셀의 왼쪽 여백에 있는 Play 아이콘을 클릭 Click the Play icon in the left gutter of the cell;
셀을 제자리에서 실행하려면 Cmd/Ctrl+Enter를 입력; Type Cmd/Ctrl+Enter to run the cell in place;
셀을 실행하고 포커스를 다음 셀로 이동하려면 Shift+Enter를 입력합니다(아무것도 없는 경우 셀 추가). 또는Type Shift+Enter to run the cell and move focus to the next cell (adding one if none exists); or
Alt+Enter를 눌러 셀을 실행하고 바로 아래에 새 코드 셀을 삽입. Type Alt+Enter to run the cell and insert a new code cell immediately below it.
런타임 메뉴에는 일부 또는 모든 셀을 실행하기 위한 추가 옵션이 있습니다.
There are additional options for running some or all cells in the Runtime menu.
a = 10
a
Output
10
Text cells 텍스트 셀
이것은 텍스트 셀입니다.
이 셀을 두 번 클릭하여 편집할 수 있습니다.
텍스트 셀은 마크다운 구문을 사용합니다.
자세한 내용은 마크다운 가이드를 참조하세요.
LaTeX를 사용, 텍스트 셀에 수학을 추가하여 MathJax로 렌더링할 수도 있습니다.
This is a text cell. You can double-click to edit this cell. Text cells use markdown syntax. To learn more, see our markdown guide.
You can also add math to text cells using LaTeX to be rendered by MathJax.
한 쌍의 $ 기호 안에 명령문을 넣으세요.
Just place the statement within a pair of $ signs.
예를 들어 For example
$\sqrt{3x-1}+(1+x)^2$는 √3x−1+(1+x)2이 됨
$\sqrt{3x-1}+(1+x)^2$ becomes √3x−1+(1+x)2.
Anne Klein Women's Genuine Diamond Dial Bangle Watch
Anne Klein Women's Genuine Diamond Dial Bangle Watch
Adding and moving cells
셀 추가 및 이동
셀 사이에 마우스를 가져가면 표시되는 + CODE 및 + TEXT 버튼을 사용하여 새 셀을 추가할 수 있습니다.
이러한 버튼은 현재 선택한 셀 아래에 셀을 추가하는 데 사용할 수 있는 노트북 위의 toolbar에도 있습니다.
셀을 선택하고 상단 toolbar에서 셀 위로 또는 셀 아래로를 클릭하여 셀을 이동할 수 있습니다.
한 셀 외부에서 그룹 전체를 드래그하여 "올가미 선택 lasso selection" 을 통해 연속 셀을 선택할 수 있습니다.
하나를 클릭한 다음 Ctrl 키를 누른 채 다른 셀을 클릭하면 인접하지 않은 셀을 동시에 선택할 수 있습니다.
마찬가지로 Ctrl 대신 Shift를 사용하면 모든 중간 셀이 선택됩니다.
You can add new cells by using the + CODE and + TEXT buttons that show when you hover between cells. These buttons are also in the toolbar above the notebook where they can be used to add a cell below the currently selected cell.
You can move a cell by selecting it and clicking Cell Up or Cell Down in the top toolbar.
Consecutive cells can be selected by "lasso selection" by dragging from outside one cell and through the group. Non-adjacent cells can be selected concurrently by clicking one and then holding down Ctrl while clicking another. Similarly, using Shift instead of Ctrl will select all intermediate cells.
Working with python
파이썬으로 작업하기
Colaboratory는 Jupyter Notebook을 기반으로 구축되었습니다.
다음은 제공되는 편의 기능의 예시.
장기 실행 Python 프로세스가 중단될 수 있습니다.
다음 셀을 실행하고 Runtime -> Interrupt execution(단축키: Cmd/Ctrl-M I)을 선택하여 실행을 중지합니다.
Colaboratory is built on top of Jupyter Notebook. Below are some examples of convenience functions provided.
Long running python processes can be interrupted. Run the following cell and select Runtime -> Interrupt execution (hotkey: Cmd/Ctrl-M I) to stop execution.
import time
print("Sleeping")
time.sleep(30) # sleep for a while; interrupt me!
print("Done Sleeping")
output
Sleeping
Done Sleeping
System aliases
시스템 별칭
Jupyter에는 ls와 같은 일반적 작업에 대한 shortcuts가 포함되어 있습니다:
Jupyter includes shortcuts for common operations, such as ls:
!ls /bin
Output
그 !ls는 아마도 큰 출력을 생성했을 것입니다.
다음 중 하나를 수행하여 셀을 선택하고 출력을 지울 수 있습니다:
That !ls probably generated a large output. You can select the cell and clear the output by either:
1. 셀 위의 toolbar에서 clear output button(x)을 클릭; Clicking on the clear output button (x) in the toolbar above the cell; or 또는
2. 출력 영역 왼쪽 여백을 마우스 오른쪽 버튼으로 클릭하고 상황에 맞는 메뉴에서 "Clear output"를 선택. Right clicking the left gutter of the output area and selecting "Clear output" from the context menu.
!를 사용하여 다른 프로세스를 실행하십시오.
Python 변수에서 문자열 보간을 사용하면 결과가 변수에 할당될 수 있습니다:
Execute any other process using ! with string interpolation from python variables, and note the result can be assigned to a variable:
# In https://github.com/ipython/ipython/pull/10545, single quote strings are ignored
message = 'Colaboratory is great!'
foo = !unset message && echo -e '{message}\n{message}\n'$message"\n$message"
foo
Magics 마술
Colaboratory는 Jupyter의 마법 개념을 공유합니다.
셀의 텍스트가 실행되는 방식을 변경하는 단축 주석이 있습니다. 자세한 내용은 Jupyter의 매직 페이지를 참조하세요.
Colaboratory shares the notion of magics from Jupyter. There are shorthand annotations that change how a cell's text is executed. To learn more, see Jupyter's magics page.
%%html
<marquee style='width: 30%; color: blue;'><b>Whee!</b></marquee>
%%html
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 450 400" width="200" height="200">
<rect x="80" y="60" width="250" height="250" rx="20" style="fill:red; stroke:black; fill-opacity:0.7" />
<rect x="180" y="110" width="250" height="250" rx="40" style="fill:blue; stroke:black; fill-opacity:0.5;" />
</svg>
Automatic completions and exploring code
자동 완성 및 코드 탐색
Colab은 Python 객체의 속성을 탐색하고 문서 문자열을 빠르게 볼 수 있는 자동완성 기능을 제공합니다.
예를 들어 먼저 다음 셀을 실행하여 numpy 모듈을 가져옵니다.
Colab provides automatic completions to explore attributes of Python objects, as well as to quickly view documentation strings. As an example, first run the following cell to import the numpy module.
import numpy as np
이제 np 뒤에 커서를 삽입하고 마침표(.)를 누르면 np 모듈 내에서 사용가능한 완성 목록이 표시됩니다.
Ctrl+Space를 사용하면 Completions을 다시 열 수 있습니다.
If you now insert your cursor after np and press Period(.), you will see the list of available completions within the np module. Completions can be opened again by using Ctrl+Space.
np
모듈의 함수나 클래스 뒤에 여는 괄호를 입력하면 해당 문서 문자열의 팝업이 표시됩니다:
If you type an open parenthesis after any function or class in the module, you will see a pop-up of its documentation string:
np.ndarray
Ctrl+Shift+Space를 사용하여 문서를 다시 열거나 메서드 이름 위에 마우스를 올려 메서드에 대한 문서를 볼 수 있습니다.
메서드 이름 위로 마우스를 가져가면 탭에서 열기 링크를 클릭하면 영구 창에서 문서가 열립니다.
소스 보기 링크는 메소드의 소스 코드로 이동합니다.
The documentation can be opened again using Ctrl+Shift+Space or you can view the documentation for method by mouse hovering over the method name.
When hovering over the method name the Open in tab link will open the documentation in a persistent pane. The View source link will navigate to the source code for the method.
Exception Formatting
예외 형식
예외는 Colab 출력에서 적절하게 형식화됩니다:
Exceptions are formatted nicely in Colab outputs:
x = 1
y = 4
z = y/(1-x)
Output
ZeroDivisionError Traceback (most recent call last)
<ipython-input-14-dc39888fd1d2> in <module>()
1 x = 1
2 y = 4
----> 3 z = y/(1-x)
ZeroDivisionError: integer division or modulo by zero
division by zero
스택 추적:
> File "C:\Users\user\source\repos\PythonApplication1\PythonApplication1.py", line 3, in <module> (Current frame)
> z = y/(1-x)
> ~^^~~~~
>ZeroDivisionError: division by zero
Rich, interactive outputs
풍부한 대화형 출력
지금까지 생성된 모든 출력은 텍스트였지만 아래 차트 같이 더 흥미로울 수 있습니다.
Until now all of the generated outputs have been text, but they can be more interesting, like the chart below.
import numpy as np
from matplotlib import pyplot as plt
ys = 200 + np.random.randn(100)
x = [x for x in range(len(ys))]
plt.plot(x, ys, '-')
plt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha=0.6)
plt.title("Fills and Alpha Example")
plt.show()
![](https://blog.kakaocdn.net/dn/TqAAI/btsB2sZKQwW/xbKDb3wQ6nTNqa8ZuLdfrK/img.png)
Integration with Drive
드라이브와의 통합
Colaboratory는 Google 드라이브와 통합되어 있습니다.
이를 통해 여러 사람과 동일한 문서를 공유하고, 댓글을 달고, 공동 작업할 수 있습니다.
Colaboratory is integrated with Google Drive. It allows you to share, comment, and collaborate on the same document with multiple people:
공유 버튼(도구 모음 오른쪽 상단)을 사용하면 노트북을 공유하고 노트북에 설정된 권한을 제어할 수 있습니다.
The SHARE button (top-right of the toolbar) allows you to share the notebook and control permissions set on it.
File->Make a Copy 는 드라이브에 노트북의 복사본을 만듭니다.
File->Make a Copy creates a copy of the notebook in Drive.
File->Save은 파일을 드라이브에 저장합니다. File->Save 및 체크포인트는 버전을 고정하여 개정 기록에서 삭제되지 않도록 합니다.
File->Save saves the File to Drive. File->Save and checkpoint pins the version so it doesn't get deleted from the revision history.
File->Revision history에는 노트북의 수정 기록이 표시됩니다.
File->Revision history shows the notebook's revision history.
Commenting on a cell
셀에 댓글 달기
Google 문서에서처럼 Colaboratory 노트북에 댓글을 달 수 있습니다.
설명은 셀에 첨부되며 참조하는 셀 옆에 표시됩니다.
댓글 전용 권한이 있는 경우 셀 위로 마우스를 가져가면 셀 오른쪽 상단에 댓글 버튼이 표시됩니다.
편집 또는 댓글 권한이 있는 경우, 다음 3가지 방법 중 하나로 셀에 댓글을 달 수 있습니다.
셀을 선택하고 셀 오른쪽 상단에 있는 도구 모음에서 주석 버튼을 클릭합니다.
텍스트 셀을 마우스 오른쪽 버튼으로 클릭하고 상황에 맞는 메뉴에서 댓글 추가를 선택합니다.
단축키 Ctrl+Shift+M을 사용하여 현재 선택한 셀에 설명을 추가합니다.
댓글을 해결하고 회신할 수 있으며, +[이메일 주소](예: +user@domain.com)를 입력하여 특정 공동작업자에게 댓글을 타겟팅할 수 있습니다.
주소가 지정된 공동작업자에게 이메일이 전송됩니다.
페이지 오른쪽 상단에 있는 댓글 버튼은 노트북에 첨부된 모든 댓글을 표시합니다.
You can comment on a Colaboratory notebook like you would on a Google Document. Comments are attached to cells, and are displayed next to the cell they refer to. If you have comment-only permissions, you will see a comment button on the top right of the cell when you hover over it.
If you have edit or comment permissions you can comment on a cell in one of three ways:
Select a cell and click the comment button in the toolbar above the top-right corner of the cell.
Right click a text cell and select Add a comment from the context menu.
Use the shortcut Ctrl+Shift+M to add a comment to the currently selected cell.
You can resolve and reply to comments, and you can target comments to specific collaborators by typing +[email address] (e.g., +user@domain.com). Addressed collaborators will be emailed.
The Comment button in the top-right corner of the page shows all comments attached to the notebook.
댓글