๐ Data Engineering
Jupyter
Jupyter Notebook
An interactive computing environment. Code, results, and documentation in a single notebook. The standard tool of data science.
Jupyter Notebook
An interactive computing environment. Code, results, and documentation in a single notebook. The standard tool of data science.
Jupyter is an open-source platform for interactive computing that integrates code, visualizations, and Markdown documents into a single notebook. It is the de facto standard tool in data science, machine learning, and education.
| Kernel | Language | Use case |
|---|---|---|
| IPython | Python | Data Science, ML |
| IRkernel | R | Statistical Analysis |
| IJulia | Julia | Scientific Computing |
| Scala Kernel | Scala/Spark | Big Data Processing |
| IJavascript | JavaScript | Web Development |
# =============================================================================
# ๋
ธํธ๋ถ ์ ๋ชฉ: ๊ณ ๊ฐ ์ดํ ๋ถ์
# ์์ฑ์: Data Team
# ์์ฑ์ผ: 2024-01-15
# ๋ชฉ์ : ๊ณ ๊ฐ ์ดํ ์์ธก ๋ชจ๋ธ ๊ฐ๋ฐ ๋ฐ ์ธ์ฌ์ดํธ ๋์ถ
# =============================================================================
# %% [markdown]
# ## 1. ํ๊ฒฝ ์ค์ ๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ํฌํธ
# ๋
ธํธ๋ถ ์์ ์ ํ์ํ ๋ชจ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ํ ๊ณณ์์ ์ํฌํธํฉ๋๋ค.
# %%
# ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ
import os
import sys
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')
# ๋ฐ์ดํฐ ์ฒ๋ฆฌ
import numpy as np
import pandas as pd
# ์๊ฐํ
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('seaborn-v0_8-whitegrid')
plt.rcParams['figure.figsize'] = (12, 6)
plt.rcParams['font.family'] = 'NanumGothic'
# ๋จธ์ ๋ฌ๋
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
# ์ค์
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 100)
# ๋๋ค ์๋ ๊ณ ์ (์ฌํ์ฑ)
RANDOM_STATE = 42
np.random.seed(RANDOM_STATE)
print(f"Python ๋ฒ์ : {sys.version}")
print(f"Pandas ๋ฒ์ : {pd.__version__}")
print(f"์คํ ์๊ฐ: {datetime.now()}")
# %% [markdown]
# ## 2. ๋ฐ์ดํฐ ๋ก๋ ๋ฐ ๊ธฐ๋ณธ ํ์
# %%
# ๋ฐ์ดํฐ ๊ฒฝ๋ก ์ค์ (ํ๊ฒฝ ๋ณ์ ๋๋ ์ค์ ํ์ผ ์ฌ์ฉ ๊ถ์ฅ)
DATA_PATH = os.getenv('DATA_PATH', '../data')
# ๋ฐ์ดํฐ ๋ก๋
df = pd.read_csv(f'{DATA_PATH}/customer_data.csv')
# ๊ธฐ๋ณธ ์ ๋ณด ํ์ธ
print(f"๋ฐ์ดํฐ ํฌ๊ธฐ: {df.shape}")
print(f"\n๋ฐ์ดํฐ ํ์
:\n{df.dtypes}")
print(f"\n๊ฒฐ์ธก์น:\n{df.isnull().sum()}")
df.head()
# %% [markdown]
# ## 3. ํ์์ ๋ฐ์ดํฐ ๋ถ์ (EDA)
# %%
# ์์นํ ๋ณ์ ๊ธฐ์ ํต๊ณ
df.describe()
# %%
# ํ๊ฒ ๋ณ์ ๋ถํฌ
fig, ax = plt.subplots(1, 2, figsize=(14, 5))
df['churn'].value_counts().plot(kind='bar', ax=ax[0])
ax[0].set_title('์ดํ ์ฌ๋ถ ๋ถํฌ')
ax[0].set_xlabel('์ดํ (1: ์ดํ, 0: ์ ์ง)')
df['churn'].value_counts().plot(kind='pie', autopct='%1.1f%%', ax=ax[1])
ax[1].set_title('์ดํ ๋น์จ')
plt.tight_layout()
plt.show()
# %% [markdown]
# ## 4. ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ
# %%
def preprocess_data(df):
"""๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ ํจ์ - ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ๊ฒ ํจ์ํ"""
df_processed = df.copy()
# ๊ฒฐ์ธก์น ์ฒ๋ฆฌ
df_processed['tenure'].fillna(df_processed['tenure'].median(), inplace=True)
# ๋ฒ์ฃผํ ์ธ์ฝ๋ฉ
label_cols = ['gender', 'contract_type']
for col in label_cols:
le = LabelEncoder()
df_processed[col] = le.fit_transform(df_processed[col])
return df_processed
df_processed = preprocess_data(df)
df_processed.head()
# %% [markdown]
# ## 5. ๋ชจ๋ธ ํ์ต ๋ฐ ํ๊ฐ
# %%
# ํน์ฑ๊ณผ ํ๊ฒ ๋ถ๋ฆฌ
feature_cols = ['tenure', 'monthly_charges', 'total_charges', 'gender', 'contract_type']
X = df_processed[feature_cols]
y = df_processed['churn']
# ํ์ต/ํ
์คํธ ๋ถํ
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y
)
# ์ค์ผ์ผ๋ง
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# ๋ชจ๋ธ ํ์ต
model = RandomForestClassifier(n_estimators=100, random_state=RANDOM_STATE)
model.fit(X_train_scaled, y_train)
# ์์ธก ๋ฐ ํ๊ฐ
y_pred = model.predict(X_test_scaled)
print(classification_report(y_test, y_pred))
# %% [markdown]
# ## 6. ๊ฒฐ๋ก ๋ฐ ๋ค์ ๋จ๊ณ
# - ๋ชจ๋ธ ์ ํ๋: XX%
# - ์ฃผ์ ์ดํ ์์ธ: tenure, monthly_charges
# - ๋ค์ ๋จ๊ณ: ํ์ดํผํ๋ผ๋ฏธํฐ ํ๋, ์์๋ธ ๋ชจ๋ธ ์๋
# papermill์ ์ฌ์ฉํ ๋
ธํธ๋ถ ํ๋ผ๋ฏธํฐํ ๋ฐ ์๋ ์คํ
import papermill as pm
from datetime import datetime
# ํ๋ผ๋ฏธํฐํ๋ ๋
ธํธ๋ถ ์คํ
pm.execute_notebook(
input_path='analysis_template.ipynb',
output_path=f'outputs/analysis_{datetime.now().strftime("%Y%m%d")}.ipynb',
parameters={
'data_path': '/data/sales_2024.csv',
'start_date': '2024-01-01',
'end_date': '2024-01-31',
'target_metric': 'revenue'
},
kernel_name='python3'
)
# ๋ฐฐ์น ์คํ (์ฌ๋ฌ ํ๋ผ๋ฏธํฐ ์กฐํฉ)
regions = ['์์ธ', '๋ถ์ฐ', '๋๊ตฌ', '์ธ์ฒ']
for region in regions:
pm.execute_notebook(
input_path='regional_analysis.ipynb',
output_path=f'outputs/analysis_{region}.ipynb',
parameters={'region': region}
)
print(f"{region} ๋ถ์ ์๋ฃ")
# ์ ์ฉํ Jupyter ๋งค์ง ์ปค๋งจ๋
# ์
์คํ ์๊ฐ ์ธก์
%%time
df.groupby('category').agg({'sales': ['sum', 'mean', 'count']})
# ์์ธ ํ๋กํ์ผ๋ง
%%timeit -n 10 -r 3
result = df.query('sales > 1000')
# ์ธ๋ถ ์คํฌ๋ฆฝํธ ์คํ
%run utils/data_processing.py
# ํ๊ฒฝ ๋ณ์ ์ค์
%env DATABASE_URL=postgresql://localhost/mydb
# ๋๋ฒ๊น
%debug # ์๋ฌ ๋ฐ์ ํ ๋๋ฒ๊ฑฐ ์ง์
# SQL ์ฟผ๋ฆฌ (ipython-sql ํ์ฅ)
%load_ext sql
%sql postgresql://user:pass@localhost/db
%%sql
SELECT * FROM customers LIMIT 10;
# ํ์ผ ์ฐ๊ธฐ
%%writefile utils/helper.py
def clean_data(df):
return df.dropna()
# ๋
ธํธ๋ถ ํ์คํ ๋ฆฌ
%history -n 1-10
# ๋ณ์ ๋ชฉ๋ก
%who_ls DataFrame
# ์์คํ
๋ช
๋ น
!pip install pandas --upgrade
!ls -la data/
# pre-commit hooks for Jupyter notebooks
repos:
- repo: https://github.com/kynan/nbstripout
rev: 0.6.1
hooks:
- id: nbstripout
name: Strip notebook outputs
- repo: https://github.com/nbQA-dev/nbQA
rev: 1.7.0
hooks:
- id: nbqa-black
name: Format notebook code with black
- id: nbqa-isort
name: Sort imports in notebooks
- id: nbqa-flake8
name: Lint notebooks with flake8
- repo: local
hooks:
- id: jupyter-nb-clear-output
name: Clear Jupyter notebook outputs
entry: jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace
files: \.ipynb$
language: system
# JupyterHub ๋ค์ค ์ฌ์ฉ์ ํ๊ฒฝ ์ค์
c = get_config()
# ์ธ์ฆ ์ค์ (LDAP)
from ldapauthenticator import LDAPAuthenticator
c.JupyterHub.authenticator_class = LDAPAuthenticator
c.LDAPAuthenticator.server_address = 'ldap.company.com'
c.LDAPAuthenticator.bind_dn_template = 'uid={username},ou=users,dc=company,dc=com'
# Spawner ์ค์ (Docker)
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.DockerSpawner.image = 'jupyter/datascience-notebook:latest'
c.DockerSpawner.network_name = 'jupyterhub-network'
# ๋ฆฌ์์ค ์ ํ
c.DockerSpawner.mem_limit = '4G'
c.DockerSpawner.cpu_limit = 2
# ์ฌ์ฉ์๋ณ ๋ณผ๋ฅจ ๋ง์ดํธ
c.DockerSpawner.volumes = {
'jupyterhub-user-{username}': '/home/jovyan/work',
'/data/shared': {'bind': '/home/jovyan/shared', 'mode': 'ro'}
}
# ๊ด๋ฆฌ์ ์ค์
c.Authenticator.admin_users = {'admin', 'dataadmin'}
# SSL ์ค์
c.JupyterHub.ssl_cert = '/etc/ssl/certs/jupyterhub.crt'
c.JupyterHub.ssl_key = '/etc/ssl/private/jupyterhub.key'