003 Google Colab에서 FLAML 시작하기
키워드: Colab, 시작하기
개요
Google Colab은 무료로 사용할 수 있는 클라우드 기반 Jupyter 노트북 환경입니다. FLAML의 큰 장점 중 하나는 Google Colab에서 완벽하게 지원된다는 것입니다. 별도의 설치나 환경 설정 없이 브라우저에서 바로 FLAML을 실습할 수 있습니다.
이 글에서는 Google Colab에서 FLAML을 설정하고 첫 번째 모델을 학습하는 방법을 알아보겠습니다.
실습 환경
- 플랫폼: Google Colab (colab.research.google.com)
- 필요 계정: Google 계정
- 비용: 무료 (GPU 사용 시 제한 있음)
Google Colab 시작하기
1단계: Colab 접속
- 브라우저에서 colab.research.google.com 접속
- Google 계정으로 로그인
- "새 노트북" 클릭
2단계: FLAML 설치
Colab 셀에서 다음 명령어를 실행합니다:
!pip install flaml[automl] -q
-q옵션은 설치 로그를 최소화합니다.
설치 확인
import flaml
print(f"FLAML 버전: {flaml.__version__}")
출력 예시
FLAML 버전: 2.1.0
Colab에서 첫 번째 FLAML 모델
전체 코드
# 1. 패키지 설치 (최초 1회)
!pip install flaml[automl] -q
# 2. 라이브러리 임포트
from flaml import AutoML
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
# 3. 데이터 준비 (유방암 진단 데이터)
data = load_breast_cancer()
X, y = data.data, data.target
# 003 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(f"학습 데이터: {X_train.shape}")
print(f"테스트 데이터: {X_test.shape}")
# 4. FLAML AutoML 실행
automl = AutoML()
automl.fit(
X_train, y_train,
task="classification",
time_budget=30, # 30초 동안 탐색
metric="accuracy",
verbose=1
)
# 5. 결과 확인
print("\n" + "="*50)
print("FLAML 학습 결과")
print("="*50)
print(f"최적 모델: {automl.best_estimator}")
print(f"최적 하이퍼파라미터: {automl.best_config}")
print(f"검증 정확도: {1 - automl.best_loss:.4f}")
# 6. 테스트 세트 평가
predictions = automl.predict(X_test)
test_accuracy = accuracy_score(y_test, predictions)
print(f"테스트 정확도: {test_accuracy:.4f}")
# 7. 상세 분류 리포트
print("\n분류 리포트:")
print(classification_report(y_test, predictions,
target_names=['악성', '양성']))
실행 결과
학습 데이터: (455, 30)
테스트 데이터: (114, 30)
[flaml.automl.logger: INFO] Iteration 1, ...
[flaml.automl.logger: INFO] Iteration 2, ...
...
==================================================
FLAML 학습 결과
==================================================
최적 모델: lgbm
최적 하이퍼파라미터: {'n_estimators': 11, 'num_leaves': 4, ...}
검증 정확도: 0.9714
테스트 정확도: 0.9737
분류 리포트:
precision recall f1-score support
악성 0.98 0.95 0.96 43
양성 0.97 0.99 0.98 71
accuracy 0.97 114
macro avg 0.97 0.97 0.97 114
weighted avg 0.97 0.97 0.97 114
Colab 활용 팁
팁 1: GPU 런타임 사용
FLAML은 CPU만으로도 빠르지만, 대규모 데이터에서는 GPU가 도움됩니다:
- 메뉴에서 "런타임" → "런타임 유형 변경" 클릭
- 하드웨어 가속기를 "GPU"로 선택
- "저장" 클릭
# 003 GPU 확인
import torch
print(f"GPU 사용 가능: {torch.cuda.is_available()}")
팁 2: 구글 드라이브 연동
데이터 파일을 구글 드라이브에서 불러오기:
from google.colab import drive
drive.mount('/content/drive')
# 003 드라이브의 파일 읽기
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/data.csv')
팁 3: 결과 저장
학습된 모델을 저장하고 다운로드:
import pickle
# 003 모델 저장
with open('flaml_model.pkl', 'wb') as f:
pickle.dump(automl, f)
# 003 Colab에서 다운로드
from google.colab import files
files.download('flaml_model.pkl')
팁 4: 세션 유지
Colab은 일정 시간 후 세션이 끊깁니다. 긴 학습 시 주의:
# 003 진행 상황을 중간중간 저장
automl.fit(
X_train, y_train,
task="classification",
time_budget=300,
log_file_name="flaml_log.log" # 로그 파일 저장
)
Colab vs 로컬 환경
| 항목 | Google Colab | 로컬 환경 |
|---|---|---|
| 설치 | 매번 필요 | 한 번만 |
| 무료 GPU | 제공 (제한적) | 별도 구매 필요 |
| 메모리 | 12GB (무료) | PC 사양에 따름 |
| 세션 유지 | 최대 12시간 | 무제한 |
| 파일 저장 | 드라이브 연동 필요 | 로컬에 직접 저장 |
| 적합한 용도 | 학습, 실험 | 프로덕션, 대규모 학습 |
실습: 다양한 데이터세트로 연습
회귀 문제 예제
from sklearn.datasets import load_diabetes
# 003 당뇨병 데이터 (회귀)
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
automl = AutoML()
automl.fit(
X_train, y_train,
task="regression", # 회귀 태스크
time_budget=30,
metric="r2"
)
print(f"최적 모델: {automl.best_estimator}")
print(f"R² 점수: {1 - automl.best_loss:.4f}")
다중 분류 예제
from sklearn.datasets import load_wine
# 003 와인 품질 데이터 (다중 분류)
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
automl = AutoML()
automl.fit(
X_train, y_train,
task="classification",
time_budget=30,
metric="accuracy"
)
print(f"최적 모델: {automl.best_estimator}")
print(f"정확도: {1 - automl.best_loss:.4f}")
Colab 노트북 템플릿
매번 사용할 수 있는 템플릿 코드:
#@title FLAML 기본 템플릿 {display-mode: "form"}
# 003 설치
!pip install flaml[automl] -q
# 003 임포트
from flaml import AutoML
import pandas as pd
from sklearn.model_selection import train_test_split
#@markdown ### 설정
task = "classification" #@param ["classification", "regression"]
time_budget = 60 #@param {type:"slider", min:10, max:300, step:10}
# 003 데이터 로드 (여기에 본인 데이터 경로 입력)
# 003 df = pd.read_csv('your_data.csv')
# 003 X = df.drop('target', axis=1)
# 003 y = df['target']
# 003 학습 실행
automl = AutoML()
# 003 automl.fit(X_train, y_train, task=task, time_budget=time_budget)
정리
- Google Colab에서 FLAML을 무료로 사용할 수 있습니다.
!pip install flaml[automl]로 간단히 설치됩니다.- 브라우저만 있으면 어디서든 FLAML을 실습할 수 있습니다.
- 구글 드라이브 연동으로 데이터와 모델을 저장/관리할 수 있습니다.
- 세션 제한(12시간)이 있으므로 중간 저장을 권장합니다.
다음 글 예고
다음 글에서는 FLAML vs 다른 AutoML 도구 비교에 대해 알아보겠습니다. PyCaret, Auto-sklearn, H2O 등과의 차이점과 각 도구의 장단점을 비교합니다.
FLAML AutoML 마스터 시리즈 #003