markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
`**d` represents any number of keyword parameters | def dconcat(sep = ":", **dic):
for k in dic.keys():
print("{}{}{}".format(k, sep, dic[k]))
dconcat(hello = "world", python = "rocks", sep = "~") | hello~world
python~rocks
| MIT | Notebooks/Arguments-and-Unpacking.ipynb | gtavasoli/PyTips |
UnpackingThe new feature [PEP 448](https://www.python.org/dev/peps/pep-0448/) added in **Python 3.5** allows `*a` and `**d` to be used outside of function parameters: | print(*range(5))
lst = [0, 1, 2, 3]
print(*lst)
a = *range(3), # The comma here cannot be omitted
print(a)
d = {"hello": "world", "python": "rocks"}
print({**d}["python"])
print(*d)
print([*d][0]) | 0 1 2 3 4
0 1 2 3
(0, 1, 2)
rocks
hello python
hello
| MIT | Notebooks/Arguments-and-Unpacking.ipynb | gtavasoli/PyTips |
The so-called unpacking (Unpacking) can actually be regarded as removing the tuple of `()` or removing the dictionary of `{}`. This syntax also provides a more Pythonic way to merge dictionaries: | user = {'name': "Trey", 'website': "http://treyhunner.com"}
defaults = {'name': "Anonymous User", 'page_name': "Profile Page"}
print({**defaults, **user}) | {'name': 'Trey', 'page_name': 'Profile Page', 'website': 'http://treyhunner.com'}
| MIT | Notebooks/Arguments-and-Unpacking.ipynb | gtavasoli/PyTips |
Using this unpacking method when calling a function is also available in **Python 2.7**: | print(concat(*"ILovePython")) | I/L/o/v/e/P/y/t/h/o/n
| MIT | Notebooks/Arguments-and-Unpacking.ipynb | gtavasoli/PyTips |
Average speed of earth is 29.93 km/s, so looks good. | vr0 = earth_diff['r'] / (24*3600) * km
vr0
vtheta0 = earth_diff['theta']
vtheta0
vphi0 = earth_diff['phi']
vphi0 | _____no_output_____ | MIT | code/notebooks/eph-earth-velocity.ipynb | GandalfSaxe/letomes |
Librairies | from typing import List, Union, Tuple, Callable, Dict
from os import environ
from random import seed
from numpy.random import seed as np_seed
from numpy import ndarray, zeros
from pandas import DataFrame, read_csv
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import ... | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
WandB | user_secrets = UserSecretsClient()
api_key = user_secrets.get_secret("WANDB")
wandb.login(key=api_key)
run = wandb.init(
project="pet_finder",
entity="leopoldavezac",
config={
'learning_rate':0.001,
'epochs':20,
'batch_size':24,
'loss_func':'mse',
'img_width':224,
... | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
Constants | DATA_PATH = '../input/petfinder-pawpularity-score'
ID_VAR_NM = 'Id'
TARGET_VAR_NM = 'Pawpularity'
AUTOTUNE = tf.data.experimental.AUTOTUNE
CONFIG = wandb.config | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
Load & Preprocess Data |
def get_datasets() -> List[tf.data.Dataset]:
df_train = load_df(set_nm='train')
df_test = load_df(set_nm='test')
df_train[TARGET_VAR_NM] /= 100
df_train = create_img_path_var(df_train, 'train')
df_test = create_img_path_var(df_test, 'test')
df_train, df_val = split(df_train)
ds_train =... | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
Img Dims Visualization | img_paths = ('{}/{}/'.format(DATA_PATH, 'train') + load_df('train')[ID_VAR_NM] + '.jpg').values
img_dims = zeros((len(img_paths), 2))
for i, img_path in enumerate(img_paths):
img_dims[i,:] = load_img(img_path).shape[:-1]
fig = go.Figure()
fig.add_trace(go.Histogram(x=img_dims[:,0], histnorm='probability... | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
Model | def get_model(efficient_net_model_nm:str, dense_layers_post_eff_net:List[int], dropout: float) -> tf.keras.Model:
efficient_net = tf.keras.models.load_model('../input/keras-applications-models/{efficient_net_model_nm}.h5')
if CONFIG.efficient_net_trainable:
unfreeze_layers(efficient_net)
... | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
Submissions |
def save_test_pred(pred: ndarray) -> None:
df_test = load_df_test()
df_test[TARGET_VAR_NM] = pred
df_test[[ID_VAR_NM, TARGET_VAR_NM]].to_csv('submission.csv', index=False)
def load_df_test() -> DataFrame:
return read_csv('{}/test.csv'.format(DATA_PATH), usecols=[ID_VAR_NM])
test_pred = model.pr... | _____no_output_____ | MIT | pet-finder.ipynb | leopoldavezac/PetFinder |
๋น
๋ฐ์ดํฐ ๋ถ์ ๊ธฐ์ฌ ์ค๊ธฐ ์ํ ์์ ํ์ด 1. ์์
ํ ์ 1์ ํ : ๋ฐ์ดํฐ ์ฒ๋ฆฌ ์์ญ* mtcars ๋ฐ์ดํฐ์
(mtcars.csv)์ qsec ์ปฌ๋ผ์ ์ต์์ต๋ ์ฒ๋(Min-Max Scale)๋ก ๋ณํํ ํ 0.5๋ณด๋ค ํฐ ๊ฐ์ ๊ฐ์ง๋ ๋ ์ฝ๋ ์๋ฅผ ๊ตฌํ์์ค. | import pandas as pd # pandas import
df = pd.read_csv('mtcars.csv') # df์ mtcars.csv๋ฅผ ์ฝ์ด ๋ฐ์ดํฐํ๋ ์์ผ๋ก ์ ์ฅ
df.head() # df์ ์์์ 5๊ฐ ๋ฐ์ดํฐ ์ถ๋ ฅ | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ๋ฐฉ๋ฒ 1 sklearn์ MinMaxScaler๋ฅผ ์ด์ฉํด์ ๋ณํ | from sklearn.preprocessing import MinMaxScaler # sklearn์ min-max scaler import
scaler = MinMaxScaler() # MinMaxScaler ๊ฐ์ฒด ์์ฑ
# scaler์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ด์ ๋ชจ๋ธ์ ๋ง๋ค๊ณ ๊ฐ์ ๋ฎ์ด์จ์
df['qsec'] = scaler.fit_transform(df[['qsec']])
# qsec๊ฐ 0.5๋ณด๋ค ํฐ ๋ฐ์ดํฐ๋ง ์์ธํด์ ๊ธธ์ด๋ฅผ ๊ตฌํจ
answer = len(df[df['qsec']>0.5])
print(answer) | 9
| MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ๋ฐฉ๋ฒ 2 Min-Max Scale์ ์์์ผ๋ก ๋ง๋ค์ด์ ๋ณํ์ํด | df['qsec'] = (df['qsec'] - df['qsec'].min()) / (df['qsec'].max() - df['qsec'].min())
answer = len(df[df['qsec']>0.5])
print(answer) | 9
| MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
2. ์์
ํ ์ 2์ ํ : ๋ชจํ ๊ตฌ์ถ ๋ฐ ํ๊ฐ ์์ญ* ์๋๋ ๋ฐฑํ์ ๊ณ ๊ฐ์ 1๋
๊ฐ ๊ตฌ๋งค ๋ฐ์ดํฐ์ด๋ค. ๊ฒฐ๊ณผ : X_test๋ฐ์ดํฐ๋ก ๋จ์์ผ ํ๋ฅ ์ ๊ตฌํด์ cust_id์ ๋จ์์ผ ํ๋ฅ ๋ง ๊ฐ์ง csv๋ก ์์ฑ ํ๊ฐ์งํ : ROC-AUC Curve ํ์ธ ์ฌํญ* ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ* Feature Engineering* ๋ถ๋ฅ ๋ชจ๋ธ* ์ต์ ํ* ์์๋ธ 1. EDA | import pandas as pd
import numpy as np
X_train = pd.read_csv('X_train.csv', encoding='euc-kr') # ํ๊ธ์ด ์์ด ์ธ์ฝ๋ฉํ์ฌ ์ฝ๋ฏ
y_train = pd.read_csv('y_train.csv')
X_test = pd.read_csv('X_test.csv', encoding='euc-kr') # ํ๊ธ์ด ์์ด ์ธ์ฝ๋ฉํ์ฌ ์ฝ๋ฏ
display(X_train.head())
display(y_train.head())
display(X_test.head())
train_data = X_train.merg... | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ์นผ๋ผ ๋ณ ๋ฐ์ดํฐ ํ์
๊ณผ ํํ ํ์ธ * ํ๋ถ๊ธ์ก์ ๊ฒฐ์ธก์น ์์ * ์ฃผ๊ตฌ๋งค์ํ๊ณผ ์ฃผ๊ตฌ๋งค์ง์ ๋ง ๋ฒ์ฃผํ ๋ฐ์ดํฐ : ํ์์ one-hot encoding | train_data.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 3500 entries, 0 to 3499
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 cust_id 3500 non-null int64
1 ์ด๊ตฌ๋งค์ก 3500 non-null int64
2 ์ต๋๊ตฌ๋งค์ก 3500 non-null int64
3 ํ๋ถ๊ธ์ก 1205 non-... | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ๊ฒฐ์ธก์น ํ์ธ * ํ๋ถ๊ธ์ก์ ๊ฒฐ์ธก์น๊ฐ ๋๋ถ๋ถ(2295 / 3500) | train_data.isnull().sum() | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ํ
์คํธ ๋ฐ์ดํฐ์ ํ๋ถ๊ธ์ก๋ ๊ฒฐ์ธก์น๊ฐ ๋ง์ | X_test.isnull().sum() | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ์ซ์ํ ๋ฐ์ดํฐ์ ๋ถํฌ ํ์ธ * ์ปฌ๋ผ๋ง๋ค์ ์ค์ผ์ผ ์ฐจ์ด๊ฐ ์ปค์ ๋ณํ ํ์ | train_data.describe() | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ๋ฌธ์ ๋ฐ์ดํฐ ๋ถํฌ ํ์ธ | train_data.describe(include=[object])
display(train_data['์ฃผ๊ตฌ๋งค์ํ'].unique(), len(train_data['์ฃผ๊ตฌ๋งค์ํ'].unique()))
display(X_test['์ฃผ๊ตฌ๋งค์ํ'].unique(), len(X_test['์ฃผ๊ตฌ๋งค์ํ'].unique()))
display(train_data['์ฃผ๊ตฌ๋งค์ง์ '].unique(), len(train_data['์ฃผ๊ตฌ๋งค์ง์ '].unique()))
display(X_test['์ฃผ๊ตฌ๋งค์ง์ '].unique(), len(X_test['์ฃผ๊ตฌ๋งค์ง์ '].unique())) | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ์ฃผ๊ตฌ๋งค์ํ์์ ์ฐจ์ด๋๋ ์ํ ํ์ธ | for i in train_data['์ฃผ๊ตฌ๋งค์ํ'].unique():
if i not in X_test['์ฃผ๊ตฌ๋งค์ํ'].unique():
print(i) | ์ํ๊ฐ์
| MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* train_data์ ์ํ ๊ฐ์ ๋ฐ์ดํฐ ํ์ธ | train_data[train_data['์ฃผ๊ตฌ๋งค์ํ']=='์ํ๊ฐ์ ']
2/3500 # 0.05% ์ํ๊ฐ์ ๋ฐ์ดํฐ | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ์ด๊ตฌ๋งค์ก๊ณผ ์ต๋๊ตฌ๋งค์ก์ ์์๊ฐ ํ์ธ๋์ด ํด๋น ๋ฐ์ดํฐ ์ถ๋ ฅ * ๋ชจ๋ ์ฌ์์ ๊ฒฝ์ฐ๋ก ํ์ธ๋จ * ํ๋ถ ๊ธ์ก์ด ์ต๋๊ตฌ๋งค์ก๋ณด๋ค ๋ง์ ๊ฒ์ ์๋ฏธ? * ์ต๋๊ตฌ๋งค์ก์ด ์์๋ ๋ญ๊ฐ? | train_data[(train_data['์ด๊ตฌ๋งค์ก']<=0) | (train_data['์ต๋๊ตฌ๋งค์ก']<=0)] | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ํ
์คํธ ๋ฐ์ดํฐ๋ ํ์ธ * 0๊ณผ ์์์ ๊ฐ์ ์ด๋ป๊ฒ ์ฒ๋ฆฌํ ๊ฒ์ธ๊ฐ? | X_test[(X_test['์ด๊ตฌ๋งค์ก']<=0) | (X_test['์ต๋๊ตฌ๋งค์ก']<=0)] | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* train_data์์ gender์ ๋ฐ๋ฅธ ๊ฐ๋ค ๋น๊ต | display(train_data.groupby('gender').min())
display(train_data.groupby('gender').mean())
display(train_data.groupby('gender').max()) | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* train_data๋ผ๋ฆฌ์ ์๊ด๊ณ์ ํ์ธ * gender์ ์๊ด๊ด๊ณ๊ฐ ๋์ ๋ฐ์ดํฐ๊ฐ ์์ | train_data.corr() | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ์ฑ๋ณ์ ๋ฐ๋ฅธ ํน์ด์ ์ด ๋ณด์ด์ง ์์* ์ ์ฒด ๋ฐ์ดํฐ์ ์ฑ๋ณ ๋ฐ์ดํฐ ์ ํ์ธ | print('์ ์ฒด ๋ฐ์ดํฐ :', len(train_data))
print('์ฌ์ ๋ฐ์ดํฐ ์ :', len(train_data[train_data['gender']==0]))
print('๋จ์ ๋ฐ์ดํฐ ์ :', len(train_data[train_data['gender']==1]))
print('๋ฐ์ดํฐ์์ ๋จ์์ผ ํ๋ฅ : {}%'.format(round((len(train_data[train_data['gender']==1]) / len(train_data))*100, 1))) | ์ ์ฒด ๋ฐ์ดํฐ : 3500
์ฌ์ ๋ฐ์ดํฐ ์ : 2184
๋จ์ ๋ฐ์ดํฐ ์ : 1316
๋ฐ์ดํฐ์์ ๋จ์์ผ ํ๋ฅ : 37.6%
| MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
2. ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ * ํ๋ถ๊ธ์ก์ ๊ฒฐ์ธก์น๋ฅผ 0์ผ๋ก ๋์ฒด | train_data['ํ๋ถ๊ธ์ก'].fillna(0, inplace=True)
X_test['ํ๋ถ๊ธ์ก'].fillna(0, inplace=True)
display(train_data.isnull().sum())
display(X_test.isnull().sum()) | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ์ฃผ๊ตฌ๋งค์ํ์ด ์ํ๊ฐ์ ์ธ ๋ฐ์ดํฐ ์ญ์ | train_data.drop(train_data[train_data['์ฃผ๊ตฌ๋งค์ํ']=='์ํ๊ฐ์ '].index, inplace=True)
train_data[train_data['์ฃผ๊ตฌ๋งค์ํ']=='์ํ๊ฐ์ '] | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
3. Feature Engineering * ์ฐ์ํ ๋ฐ์ดํฐ : ํ์ค ์ ๊ท ๋ถํฌ๋ก ๋ณํ * ๋ด์ ๋น๊ตฌ๋งค๊ฑด์, ๊ตฌ๋งค์ฃผ๊ธฐ๋ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๊ณ ์ญ์ ๋ ๊ฒํ (์๊ด๊ณ์ ๋ฎ์) | train_data.head()
conti_cols = ['์ด๊ตฌ๋งค์ก', '์ต๋๊ตฌ๋งค์ก', 'ํ๋ถ๊ธ์ก','๋ด์ ์ผ์', '๋ด์ ๋น๊ตฌ๋งค๊ฑด์', '์ฃผ๋ง๋ฐฉ๋ฌธ๋น์จ', '๊ตฌ๋งค์ฃผ๊ธฐ']
# ํ์ค ์ ๊ท ๋ถํ scaler ์ฌ์ฉํ์ฌ train๋ฐ์ดํฐ์์ ๋ง๋ค scaler๋ฅผ test์ ๋์ผํ๊ฒ ์ ์ฉํ์ฌ ๋ณํ
from sklearn.preprocessing import StandardScaler
for col in conti_cols:
scaler = StandardScaler()
scaler.fit(train_data[[col]])
train_data[col] ... | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
* ๋ฒ์ฃผํ ๋ฐ์ดํฐ ์ํซ์ธ์ฝ๋ฉ | categorical_cols = ['์ฃผ๊ตฌ๋งค์ํ', '์ฃผ๊ตฌ๋งค์ง์ ']
for col in categorical_cols:
temp = pd.get_dummies(train_data[col])
train_data = pd.concat([train_data, temp], axis=1)
del train_data[col]
temp = pd.get_dummies(X_test[col])
X_test = pd.concat([X_test, temp], axis=1)
del X_test[col]
display(train_... | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
4. ๋ถ๋ฅ ์๊ณ ๋ฆฌ์ฆ | from sklearn.ensemble import RandomForestClassifier # ๋๋คํฌ๋ ์คํธ
from sklearn.linear_model import LogisticRegression # ๋ก์ง์คํฑํ๊ท
from sklearn.metrics import roc_auc_score # ์์ ์ ํ๊ฐ์งํ์ธ ROC_AUC score
x_cols = list(train_data.columns)
x_cols.remove('cust_id')
x_cols.remove('gender')
X = train_data[x_cols]
y = train_data['gender... | RF ROCAUC Score: 0.7546568802481672
LR ROCAUC Score: 0.6955802615788438
| MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
5. ๊ฒฐ๊ณผ ์ ์ถ | # ROC_AUC score๊ฐ ๋์ ๋๋คํด์คํธ๋ก ํ
์คํธ ๋ฐ์ดํฐ๋ก ๊ฒฐ๊ณผ ์์ธก๊ฐ ์ ๋ฆฌ
pred_result = pd.DataFrame(model_rf.predict_proba(test_x))
result = pd.concat([X_test['cust_id'], pred_result[[1]]], axis=1)
result.columns = [['cust_id', 'gender']] # ์์ธก๊ฒฐ๊ณผ์ ์ปฌ๋ผ์ด 1์ด๋ฏ๋ก ๋ฌธ์ ์ ๋์ผํ๊ฒ ์ปฌ๋ผ ๋ณ๊ฒฝ
result
result.to_csv('result.csv', index=False) # ๋ณ๋์ ์ธ๋ฑ์ค ์์ด csv๋ก ์ ์ฅ | _____no_output_____ | MIT | ๋น
๋ถ๊ธฐ ์ค๊ธฐ ์์ ํ์ด.ipynb | kamzzang/ADPStudy |
A K-means clustering project The purpose of this exercise is to implement the K-means clustering module of pyspark and find how many hacker groups were involved in the data brach of a certain technology firm. The forensic engineers of the firm were able to collect some meta data of each brach. The firm suspects that t... | import findspark
findspark.init('/home/yohannes/spark-2.4.7-bin-hadoop2.7')
%config Completer.use_jedi = False
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('Kmeans').getOrCreate()
data = spark.read.csv('hack_data.csv',header=True,inferSchema=True) | _____no_output_____ | MIT | K-means clustering_pyspark.ipynb | Molla80/K-means-clustering-using-pyspark |
Data exploration | data.printSchema()
data.head(1) | _____no_output_____ | MIT | K-means clustering_pyspark.ipynb | Molla80/K-means-clustering-using-pyspark |
Creating features vector | from pyspark.ml.feature import VectorAssembler
data.columns
assembler = VectorAssembler(inputCols=['Session_Connection_Time',
'Bytes Transferred',
'Kali_Trace_Used',
'Servers_Corrupted',
'Pages_Corrupted',
'WPM_Typing_Speed'], outputCol='features')
final_data = assembler.transform(data)
final_data.printSchema() | root
|-- Session_Connection_Time: double (nullable = true)
|-- Bytes Transferred: double (nullable = true)
|-- Kali_Trace_Used: integer (nullable = true)
|-- Servers_Corrupted: double (nullable = true)
|-- Pages_Corrupted: double (nullable = true)
|-- Location: string (nullable = true)
|-- WPM_Typing_Speed: doub... | MIT | K-means clustering_pyspark.ipynb | Molla80/K-means-clustering-using-pyspark |
Scaling the data | from pyspark.ml.feature import StandardScaler
scaler = StandardScaler(inputCol='features',outputCol='scaledFeat')
final_data = scaler.fit(final_data).transform(final_data)
final_data.printSchema() | root
|-- Session_Connection_Time: double (nullable = true)
|-- Bytes Transferred: double (nullable = true)
|-- Kali_Trace_Used: integer (nullable = true)
|-- Servers_Corrupted: double (nullable = true)
|-- Pages_Corrupted: double (nullable = true)
|-- Location: string (nullable = true)
|-- WPM_Typing_Speed: doub... | MIT | K-means clustering_pyspark.ipynb | Molla80/K-means-clustering-using-pyspark |
K-means clustering model | from pyspark.ml.clustering import KMeans
# let's try with the assumption that there were two hacker groups
kmeans = KMeans(featuresCol='scaledFeat',k=2)
model = kmeans.fit(final_data)
results = model.transform(final_data)
centers = model.clusterCenters()
print(centers)
results.printSchema()
results.describe().show()
re... | +----------+-----+
|prediction|count|
+----------+-----+
| 1| 167|
| 0| 167|
+----------+-----+
| MIT | K-means clustering_pyspark.ipynb | Molla80/K-means-clustering-using-pyspark |
Graphical visualization of the clusters | results_pd = results.toPandas()
results_pd
import matplotlib.pyplot as plt
%matplotlib inline
plot = plt.scatter(data=results_pd, x=results_pd.index, y=results_pd['Bytes Transferred'],c=results_pd['prediction'])
plt.ylabel('Bytes Transferred') | _____no_output_____ | MIT | K-means clustering_pyspark.ipynb | Molla80/K-means-clustering-using-pyspark |
Credit Risk ClassificationCredit risk poses a classification problem thatโs inherently imbalanced. This is because healthy loans easily outnumber risky loans. In this Challenge, youโll use various techniques to train and evaluate models with imbalanced classes. Youโll use a dataset of historical lending activity from ... | # Import the modules
import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import confusion_matrix
from imblearn.metrics import classification_report_imbalanced
import warnings
warnings.filterwarnings('ignore') | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
--- Split the Data into Training and Testing Sets Step 1: Read the `lending_data.csv` data from the `Resources` folder into a Pandas DataFrame. | # Read the CSV file from the Resources folder into a Pandas DataFrame
# Using the read_csv function and Path module, create a DataFrame
lending_data_df = pd.read_csv(
Path('./Resources/lending_data.csv'),
).dropna()
# Review the DataFrame
display(lending_data_df.head())
display(lending_data_df.tail()) | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 2: Create the labels set (`y`) from the โloan_statusโ column, and then create the features (`X`) DataFrame from the remaining columns. | # Separate the data into labels and features
y = lending_data_df['loan_status']
# Separate the X variable, the features
X = lending_data_df[['loan_size','interest_rate','borrower_income','debt_to_income','num_of_accounts','derogatory_marks','total_debt']]
# Review the y variable Series
display(y[:5])
# Review t... | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 3: Check the balance of the labels variable (`y`) by using the `value_counts` function. | # Check the balance of our target values
y.value_counts() | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 4: Split the data into training and testing datasets by using `train_test_split`. | # Import the train_test_learn module
from sklearn.model_selection import train_test_split
# Split the data using train_test_split
# Assign a random_state of 1 to the function
X_train, X_test,y_train,y_test= train_test_split(X, y,random_state=1)
| _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
--- Create a Logistic Regression Model with the Original Data Step 1: Fit a logistic regression model by using the training data (`X_train` and `y_train`). | # Import the LogisticRegression module from SKLearn
from sklearn.linear_model import LogisticRegression
# Instantiate the Logistic Regression model
# Assign a random_state parameter of 1 to the model
logistic_regression_model = LogisticRegression(random_state=1)
# Fit the model using training data
logistic_re... | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 2: Save the predictions on the testing data labels by using the testing feature data (`X_test`) and the fitted model. | # Make a prediction using the testing data
y_predict = logistic_regression_model.predict(X_test) | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 3: Evaluate the modelโs performance by doing the following:* Calculate the accuracy score of the model.* Generate a confusion matrix.* Print the classification report. | # Print the balanced_accuracy score of the model
balanced_accuracy = balanced_accuracy_score(y_test,y_predict)
print(balanced_accuracy)
# Generate a confusion matrix for the model
logistic_regression_matrix =confusion_matrix(y_test, y_predict)
print(logistic_regression_matrix)
# Print the classification report for ... | pre rec spe f1 geo iba sup
0 1.00 0.99 0.91 1.00 0.95 0.91 18765
1 0.85 0.91 0.99 0.88 0.95 0.90 619
avg / total 0.99 0.99 0.91 0.99 0.95 0... | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 4: Answer the following question.
**Question:** How well does the logistic regression model predict both the `0` (healthy loan) and `1` (high-risk loan) labels?
**Answer:** The model performed better for the 0 class of samples than it did for the 1 class of samples. The precision and the recall for the 0 class... | # Import the RandomOverSampler module form imbalanced-learn
from imblearn.over_sampling import RandomOverSampler
# Instantiate the random oversampler model
# # Assign a random_state parameter of 1 to the model
random_oversampler_model = RandomOverSampler(random_state=1)
# Fit the original training data to the ... | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 2: Use the `LogisticRegression` classifier and the resampled data to fit the model and make predictions. | # Instantiate the Logistic Regression model
# Assign a random_state parameter of 1 to the model
logistic_regression_resample_model = LogisticRegression(random_state=1)
# Fit the model using the resampled training data
logistic_regression_resample_model.fit(X_resampled, y_resampled)
# Make a prediction using th... | _____no_output_____ | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Step 3: Evaluate the modelโs performance by doing the following:* Calculate the accuracy score of the model.* Generate a confusion matrix.* Print the classification report. | # Print the balanced_accuracy score of the model
balanced_accuracy = balanced_accuracy_score(y_test,y_resampled_perdict)
print(balanced_accuracy)
# Generate a confusion matrix for the model
logistic_regression_resample_matrtix = confusion_matrix(y_test, y_resampled_perdict)
print(logistic_regression_resample_matrt... | pre rec spe f1 geo iba sup
0 1.00 0.99 0.99 1.00 0.99 0.99 18765
1 0.84 0.99 0.99 0.91 0.99 0.99 619
avg / total 0.99 0.99 0.99 0.99 0.99 0... | MIT | credit_risk_resampling.ipynb | douglasg-fintec/Credit_Risk_Resampling |
Imports | import os
import time
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from collections import OrderedDict
import PIL
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
dataset_... | _____no_output_____ | MIT | PyTorchNN/1610_PT_FCU.ipynb | marcinbogdanski/ai-sketchpad |
CamVid Dataset | def download(url, dest, md5sum):
import os
import urllib
import hashlib
folder, file = os.path.split(dest)
if folder != '':
os.makedirs(folder, exist_ok=True)
if not os.path.isfile(dest):
print('Downloading', file, '...')
urllib.request.urlretrieve(url, dest)
else:
... | _____no_output_____ | MIT | PyTorchNN/1610_PT_FCU.ipynb | marcinbogdanski/ai-sketchpad |
United States - Crime Rates - 1960 - 2014 Introduction:This time you will create a data Special thanks to: https://github.com/justmarkham for sharing the dataset and materials. Step 1. Import the necessary libraries | import numpy as np
import pandas as pd | _____no_output_____ | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv). Step 3. Assign it to a variable called crime. | url = "https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv"
crime = pd.read_csv(url)
crime.head() | _____no_output_____ | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Step 4. What is the type of the columns? | crime.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 55 entries, 0 to 54
Data columns (total 12 columns):
Year 55 non-null int64
Population 55 non-null int64
Total 55 non-null int64
Violent 55 non-null int64
Property 55 non-null int64
Murder ... | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Have you noticed that the type of Year is int64. But pandas has a different type to work with Time Series. Let's see it now. Step 5. Convert the type of the column Year to datetime64 | # pd.to_datetime(crime)
crime.Year = pd.to_datetime(crime.Year, format='%Y')
crime.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 55 entries, 0 to 54
Data columns (total 12 columns):
Year 55 non-null datetime64[ns]
Population 55 non-null int64
Total 55 non-null int64
Violent 55 non-null int64
Property 55 non-null int64
Murder ... | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Step 6. Set the Year column as the index of the dataframe | crime = crime.set_index('Year', drop = True)
crime.head() | _____no_output_____ | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Step 7. Delete the Total column | del crime['Total']
crime.head() | _____no_output_____ | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Step 8. Group the year by decades and sum the values Pay attention to the Population column number, summing this column is a mistake | # To learn more about .resample (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html)
# To learn more about Offset Aliases (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases)
# Uses resample to sum each decade
crimes = crime.resample('10AS').sum()
# Uses resa... | _____no_output_____ | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Step 9. What is the mos dangerous decade to live in the US? | # apparently the 90s was a pretty dangerous time in the US
crime.idxmax(0) | _____no_output_____ | BSD-3-Clause | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | chisus089/3_pandas_exercises |
Exercise1.1Plot $f(x) = 1 - e ^ (2 * x)$ over $[-1, 1]$ with intervals $.01$ | """
Exercise1.1
Plot f(x) = 1 - e ^ (2 * x) over [-1, 1] with intervals .01
"""
x_range = arange(-1, 1, .01)
y_range = array([1 - exp(2 * x) for x in x_range])
plot(x_range, y_range, 'k-', label = "Exercise1.1")
ylabel("y")
xlabel("x")
legend(loc='upper right') | _____no_output_____ | MIT | Exercise01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Exercise1.2Solve matrix multiplication of$$AB = \left[\begin{array}{ccc} 0 &-1& 2\\-2& -1& 4\\2& 7& -2\end{array}\right]\left[\begin{array}{ccc} -7& 1& 1\\ 7& -3& -2\\3& 5& 0\end{array}\right]$$ $$y = [3, -1, 2] $$Solve $C = A*B$, $$Cx = y$$. | """
Exercise1.2
Solve matrix multiplication
"""
#from numpy import array, linalg
A = array([[0, -1, 2], [-2, -1, 4], [2, 7, -2]])
B = array([[-7, 1, 1], [7, -3, -2], [3, 5, 0]])
y = array([3, -1, 2])
# part_a():
"""
Solve Cx = y using standard matrix multiplication for A and B
"""
C = A.dot(B)
x = linalg.solve(C, y... |
The element-by-element matrix product C:
[[ 0 -1 2]
[-14 3 -8]
[ 6 35 0]]
Solution from Element-wise multiplication:
[-0.79958678 0.19421488 1.59710744]
| MIT | Exercise01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Exercise1.3calculate the time series$$yt = 5 + .05 * t + Et$$ (Where E is epsilon)for years $1960, 1961, ..., 2016$ assuming $Et$ independently and identically distributed with mean $0$ and sigma $0.2$. | # Setting a random seed for reproducibility
rnd = np.random.RandomState(seed=123)
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html
"""
Exercise1.3
calculate the time series
"""
#from numpy import random, array, polyfit, poly1d
mu = -0.2
sigma = 0.2
"""
Create the time series, yt,... | _____no_output_____ | MIT | Exercise01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Exercise1.4Consider the original example with the farmer where acreage planted will be$$a = 0.5 + 0.5 * Ep$$ (Ep is expected price)Quantity q is equivalent to$$q = a * y$$ (y is yield)Clearing price p is$$p = 3 - 2 * q$$Assume in our case that yield will be a random two point distribution s.t.```y = array([0.7, 1.3])`... |
#from math import exp, fabs
#from numpy import array, var
#part_a():
"""
Compute the variance in price
"""
a = 1
y, w = array([0.7, 1.3]), array([0.5, 0.5])
for _ in range(100):
a_previous = a
p = 3 - 2 * a * y
f = w.dot(p)
a = 0.5 + 0.5 * f
if fabs(a_previous - a) < exp(-8):
brea... | _____no_output_____ | MIT | Exercise01.ipynb | lnsongxf/Applied_Computational_Economics_and_Finance |
Model | xb, yb = dls_feat.one_batch(); xb.shape
from torch.nn import TransformerEncoder, TransformerEncoderLayer
class SeqHead(nn.Module):
def __init__(self):
super().__init__()
# d_model = 2048+6+1
d_model = 1024
n_head = 4
self.flat = nn.Sequential(AdaptiveConcatPool2d(), ... | _____no_output_____ | Apache-2.0 | 03_train3d_experiments/03_train3d_02d_train_transformer_head.ipynb | bearpelican/rsna_retro |
Training | learn.lr_find()
do_fit(learn, 10, 1e-4)
learn.save(f'runs/{name}-1') | _____no_output_____ | Apache-2.0 | 03_train3d_experiments/03_train3d_02d_train_transformer_head.ipynb | bearpelican/rsna_retro |
Testing | sub_fn = f'subm/{name}'
learn.load(f'runs/{name}-1')
learn.validate()
learn.dls = get_3d_dls_feat(Meta.df_tst, path=path_feat_tst_384avg, bs=32, test=True)
preds,targs = learn.get_preds()
preds.shape, preds.min(), preds.max()
pred_csv = submission(Meta.df_tst, preds, fn=sub_fn)
api.competition_submit(f'{sub_fn}.csv', n... | _____no_output_____ | Apache-2.0 | 03_train3d_experiments/03_train3d_02d_train_transformer_head.ipynb | bearpelican/rsna_retro |
1. Create Train Script | %%file train
#!/usr/bin/env python
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
import pickle
import os
np.random.seed(123)
# Define paths for Model Training inside Container.
INPUT_PATH = '/opt/ml/input/data'
OUTPUT_PATH = '/opt/ml/output'
MODEL_PATH = '/opt/ml/model'
P... | Overwriting train
| Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
2. Create Serve Script | %%file serve
#!/usr/bin/env python
from flask import Flask, Response, request
from io import StringIO
import pandas as pd
import logging
import pickle
import os
app = Flask(__name__)
MODEL_PATH = '/opt/ml/model'
# Singleton Class for holding the Model
class Predictor:
model = None
@classmethod
def... | Overwriting serve
| Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
3. Build a Docker Image and Push to ECR | %%sh
# Assign a name for your Docker image.
image_name=byoc-sklearn
echo "Image Name: ${image_name}"
# Retrieve AWS Account.
account=$(aws sts get-caller-identity --query Account --output text)
# Get the region defined in the current configuration (default to us-east-1 if none defined).
region=$(aws configure get r... | Image Name: byoc-sklearn
Account: 892313895307
Region: us-east-1
Repository: 892313895307.dkr.ecr.us-east-1.amazonaws.com
Image URI: 892313895307.dkr.ecr.us-east-1.amazonaws.com/byoc-sklearn:latest
Login Succeeded
Sending build context to Docker daemon 80.38kB
Step 1/8 : FROM python:3.7
---> 5b86e11778a2
Step 2/8 :... | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Imports | from sagemaker.predictor import csv_serializer
import pandas as pd
import sagemaker | _____no_output_____ | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Essentials | role = sagemaker.get_execution_role()
session = sagemaker.Session()
account = session.boto_session.client('sts').get_caller_identity()['Account']
region = session.boto_session.region_name
image_name = 'byoc-sklearn'
image_uri = f'{account}.dkr.ecr.{region}.amazonaws.com/{image_name}:latest' | _____no_output_____ | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Train (Local Mode) | model = sagemaker.estimator.Estimator(
image_name=image_uri,
role=role,
train_instance_count=1,
train_instance_type='local',
sagemaker_session=None
)
model.fit({'train': 'file://.././DATA/train/train.csv', 'test': 'file://.././DATA/test/test.csv'}) | Creating tmp815252o0_algo-1-n7amc_1 ...
[1BAttaching to tmp815252o0_algo-1-n7amc_12mdone[0m
[36malgo-1-n7amc_1 |[0m ------- [STARTING TRAINING] -------
[36malgo-1-n7amc_1 |[0m ------- [TRAINING COMPLETE!] -------
[36malgo-1-n7amc_1 |[0m ------- [STARTING EVALUATION] -------
[36malgo-1-n7amc_1 |[0m Accura... | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Deploy (Locally) | predictor = model.deploy(1, 'local', endpoint_name='byoc-sklearn', serializer=csv_serializer) | Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
| Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Evaluate Real Time Inference (Locally) | df = pd.read_csv('.././DATA/test/test.csv', header=None)
test_df = df.sample(1)
test_df
test_df.drop(test_df.columns[[0]], axis=1, inplace=True)
test_df
test_df.values
prediction = predictor.predict(test_df.values).decode('utf-8').strip()
prediction | _____no_output_____ | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Train (using SageMaker) | WORK_DIRECTORY = '.././DATA'
train_data_s3_pointer = session.upload_data(f'{WORK_DIRECTORY}/train', key_prefix='byoc-sklearn/train')
test_data_s3_pointer = session.upload_data(f'{WORK_DIRECTORY}/test', key_prefix='byoc-sklearn/test')
train_data_s3_pointer
test_data_s3_pointer
model = sagemaker.estimator.Estimator(
... | 's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
| Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Deploy Trained Model as SageMaker Endpoint | predictor = model.deploy(1, 'ml.m5.xlarge', endpoint_name='byoc-sklearn', serializer=csv_serializer) | Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
| Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Real Time Inference using Deployed Endpoint | df = pd.read_csv('.././DATA/test/test.csv', header=None)
test_df = df.sample(1)
test_df.drop(test_df.columns[[0]], axis=1, inplace=True)
test_df
test_df.values
prediction = predictor.predict(test_df.values).decode('utf-8').strip()
prediction | _____no_output_____ | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Batch Transform (Batch Inference) using Trained SageMaker Model | bucket_name = session.default_bucket()
output_path = f's3://{bucket_name}/byoc-sklearn/batch_test_out'
transformer = model.transformer(instance_count=1,
instance_type='ml.m5.xlarge',
output_path=output_path,
assemble_wit... | .Gracefully stopping... (press Ctrl+C again to force)
.........................
[34m * Serving Flask app "serve" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http:/... | Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
Inspect Batch Transformed Output | s3_client = session.boto_session.client('s3')
s3_client.download_file(bucket_name,
'byoc-sklearn/batch_test_out/batch_test.csv.out',
'.././DATA/batch_test/batch_test.csv.out')
with open('.././DATA/batch_test/batch_test.csv.out', 'r') as f:
results = f.readlines() ... | Transform results:
1
3
0
1
1
3
1
3
0
0
0
3
0
0
2
| Apache-2.0 | SageMaker/Training-Inference/6. BYOC Sklearn/BYOC Sklearn.ipynb | arunprsh/AI-ML-Examples |
11์ฅ ์์ฐ์ด์ฒ๋ฆฌ 1๋ถ **๊ฐ์ฌ๋ง**: ํ๋์์ ์๋ ์ [Deep Learning with Python, Second Edition](https://www.manning.com/books/deep-learning-with-python-second-edition?a_aid=keras&a_bid=76564dff) 10์ฅ์ ์ฌ์ฉ๋ ์ฝ๋์ ๋ํ ์ค๋ช
์ ๋ด๊ณ ์์ผ๋ฉฐ ํ
์ํ๋ก์ฐ 2.6 ๋ฒ์ ์์ ์์ฑ๋์์ต๋๋ค. ์์ค์ฝ๋๋ฅผ ๊ณต๊ฐํ ์ ์์๊ฒ ๊ฐ์ฌ๋๋ฆฝ๋๋ค.**tensorflow ๋ฒ์ ๊ณผ GPU ํ์ธ**- ๊ตฌ๊ธ ์ฝ๋ฉ ์ค์ : '๋ฐํ์ -> ๋ฐํ์ ์ ํ ๋ณ๊ฒฝ' ๋ฉ๋ด์์ GPU ์ง์ ํ ์๋... | from tensorflow.keras.layers import TextVectorization
text_vectorization = TextVectorization(
output_mode="int",
) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
`TextVectorization` ์ธต ๊ตฌ์ฑ์ ์ฌ์ฉ๋๋ ์ฃผ์ ๊ธฐ๋ณธ ์ค์ ์ ๋ค์๊ณผ ๊ฐ๋ค.- ํ์คํ: ์๋ฌธ์ํ์ ๋ง์นจํ ๋ฑ ์ ๊ฑฐ - `standardize='lower_and_strip_punctuation'`- ํ ํฐํ: ๋จ์ด ๊ธฐ์ค ์ชผ๊ฐ๊ธฐ - `ngrams=None` - `split='whitespace'`- ์ถ๋ ฅ ๋ชจ๋: ์ถ๋ ฅ ํ
์์ ํ์ - `output_mode="int"` ํ์คํ์ ํ ํฐํ ๋ฐฉ์์ ์์๋ก ์ง์ ํด์ ํ์ฉํ ์๋ ์๋ค.๋ค๋ง, ํ์ด์ฌ์ ๊ธฐ๋ณธ ๋ฌธ์์ด ์๋ฃํ์ธ `str` ๋์ ์ `tf.string` ํ
์๋ฅผ ํ์ฉํด์ผ ํจ์ ์ฃผ์ํด์ผ ํ๋ค. ํ... | import re
import string
import tensorflow as tf
# ํ์คํ: ์๋ฌธ์ํ ๋ฐ ๋ง์นจํ ์ ๊ฑฐ
def custom_standardization_fn(string_tensor):
lowercase_string = tf.strings.lower(string_tensor)
return tf.strings.regex_replace(
lowercase_string, f"[{re.escape(string.punctuation)}]", "")
# ๊ณต๋ฐฑ ๊ธฐ์ค์ผ๋ก ์ชผ๊ฐ๊ธฐ
def custom_split_fn(string_te... | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**์์ ** ์๋ ๋ฐ์ดํฐ์
์ ๋์์ผ๋ก ํ
์คํธ ๋ฒกํฐํ๋ฅผ ์งํํด๋ณด์. | dataset = [
"I write, erase, rewrite",
"Erase again, and then",
"A poppy blooms.",
]
text_vectorization.adapt(dataset) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
์์ฑ๋ ์ดํ ์์ธ์ ๋ค์๊ณผ ๊ฐ๋ค. | vocabulary = text_vectorization.get_vocabulary()
vocabulary | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
์์ฑ๋ ์ดํ ์์ธ์ ํ์ฉํ์ฌ ์๋ก์ด ๋ฌธ์ฅ์ ๋ฒกํฐํ ํด๋ณด์. | test_sentence = "I write, rewrite, and still rewrite again"
encoded_sentence = text_vectorization(test_sentence)
print(encoded_sentence) | tf.Tensor([ 7 3 5 9 1 5 10], shape=(7,), dtype=int64)
| MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
๋ฒกํฐํ๋ ํ
์๋ก๋ถํฐ ๋ฌธ์ฅ์ ๋ณต์ํ๋ฉด ํ์คํ๋ ๋ฌธ์ฅ์ด ์์ฑ๋๋ค. | inverse_vocab = dict(enumerate(vocabulary))
decoded_sentence = " ".join(inverse_vocab[int(i)] for i in encoded_sentence)
print(decoded_sentence) | i write rewrite and [UNK] rewrite again
| MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**`TextVectorization` ์ธต ์ฌ์ฉ๋ฒ** `TextVectorization` ์ธต์ GPU ๋๋ TPU์์ ์ง์๋์ง ์๋๋ค.๋ฐ๋ผ์ ๋ชจ๋ธ ๊ตฌ์ฑ์ ์ง์ ์ฌ์ฉํ๋ ๋ฐฉ์์ ๋ชจ๋ธ์ ํ๋ จ์๋ฆ์ถ ์ ์๊ธฐ์ ๊ถ์ฅ๋์ง ์๋๋ค.์ฌ๊ธฐ์๋ ๋์ ์ ๋ฐ์ดํฐ์
์ ์ฒ๋ฆฌ๋ฅผ ๋ชจ๋ธ ๊ตฌ์ฑ๊ณผ ๋
๋ฆฝ์ ์ผ๋ก ์ฒ๋ฆฌํ๋ ๋ฐฉ์์ ์ด์ฉํ๋ค.ํ์ง๋ง ํ๋ จ์ด ์์ฑ๋ ๋ชจ๋ธ์ ์ค์ ์ ๋ฐฐ์นํ ๊ฒฝ์ฐ `TextVectorization` ์ธต์์์ฑ๋ ๋ชจ๋ธ์ ์ถ๊ฐํด์ ์ฌ์ฉํ๋ ๊ฒ ์ข๋ค.์ด์ ๋ํ ์์ธํ ์ค๋ช
์ ์ ์ ๋ค์ ๋ถ๋ก์์ ์ค๋ช
ํ๋ค. 11.3 ๋จ์ด ๋ชจ์ ํํ๋ฒ: ์งํฉ๊ณผ ์ํ์ค ์์ ์ธ๊ธํ ๋๋ก ์์ฐ์ด์ฒ๋ฆฌ ๋ชจ๋ธ์ ๋ฐ๋ผ ... | !curl -O https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
!tar -xf aclImdb_v1.tar.gz | % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 80.2M 100 80.2M 0 0 26.1M 0 0:00:03 0:00:03 --:--:-- 26.1M
| MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
`aclImdb/train/unsup` ์๋ธ๋๋ ํ ๋ฆฌ๋ ํ์ ์๊ธฐ์ ์ญ์ ํ๋ค. | if 'google.colab' in str(get_ipython()):
!rm -r aclImdb/train/unsup
else:
import shutil
unsup_path = './aclImdb/train/unsup'
shutil.rmtree(unsup_path) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
๊ธ์ ๋ฆฌ๋ทฐ ํ๋์ ๋ด์ฉ์ ์ดํด๋ณด์.๋ชจ๋ธ ๊ตฌ์ฑ ์ด์ ์ ํ๋ จ ๋ฐ์ดํฐ์
์ ์ดํด ๋ณด๊ณ ๋ชจ๋ธ์ ๋ํ ์ง๊ด์ ๊ฐ๋ ๊ณผ์ ์ด ํญ์ ํ์ํ๋ค. | if 'google.colab' in str(get_ipython()):
!cat aclImdb/train/pos/4077_10.txt
else:
with open('aclImdb/train/pos/4077_10.txt', 'r') as f:
text = f.read()
print(text) | I first saw this back in the early 90s on UK TV, i did like it then but i missed the chance to tape it, many years passed but the film always stuck with me and i lost hope of seeing it TV again, the main thing that stuck with me was the end, the hole castle part really touched me, its easy to watch, has a great story, ... | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
์ค๋น ๊ณผ์ 2: ๊ฒ์ฆ์
์ค๋นํ๋ จ์
์ 20%๋ฅผ ๊ฒ์ฆ์
์ผ๋ก ๋ผ์ด๋ธ๋ค.์ด๋ฅผ ์ํด `aclImdb/val` ๋๋ ํ ๋ฆฌ๋ฅผ ์์ฑํ ํ์๊ธ์ ๊ณผ ๋ถ์ ํ๋ จ์
๋ชจ๋ ๋ฌด์์๋ก ์์ ํ ๊ทธ์ค 20%๋ฅผ ๊ฒ์ฆ์
๋๋ ํ ๋ฆฌ๋ก ์ฎ๊ธด๋ค. | import os, pathlib, shutil, random
base_dir = pathlib.Path("aclImdb")
val_dir = base_dir / "val"
train_dir = base_dir / "train"
for category in ("neg", "pos"):
os.makedirs(val_dir / category) # val ๋๋ ํ ๋ฆฌ ์์ฑ
files = os.listdir(train_dir / category)
random.Random(1337).shuffle(files) ... | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
์ค๋น ๊ณผ์ 3: ํ
์ ๋ฐ์ดํฐ์
์ค๋น`text_dataset_from_directory()` ํจ์๋ฅผ ์ด์ฉํ์ฌ ํ๋ จ์
, ๊ฒ์ฆ์
, ํ
์คํธ์
์ ์ค๋นํ๋ค. ์๋ฃํ์ ๋ชจ๋ `Dataset`์ด๋ฉฐ, ๋ฐฐ์น ํฌ๊ธฐ๋ 32๋ฅผ ์ฌ์ฉํ๋ค. | from tensorflow import keras
batch_size = 32
train_ds = keras.utils.text_dataset_from_directory(
"aclImdb/train", batch_size=batch_size
)
val_ds = keras.utils.text_dataset_from_directory(
"aclImdb/val", batch_size=batch_size
)
test_ds = keras.utils.text_dataset_from_directory(
"aclImdb/test", ba... | Found 20000 files belonging to 2 classes.
Found 5000 files belonging to 2 classes.
Found 25000 files belonging to 2 classes.
| MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
๊ฐ ๋ฐ์ดํฐ์
์ ๋ฐฐ์น๋ก ๊ตฌ๋ถ๋๋ฉฐ์
๋ ฅ์ `tf.string` ํ
์์ด๊ณ , ํ๊น์ `int32` ํ
์์ด๋ค.ํฌ๊ธฐ๋ ๋ชจ๋ 32์ด๋ฉฐ ์ง์ ๋ ๋ฐฐ์น ํฌ๊ธฐ์ด๋ค.์๋ฅผ ๋ค์ด, ์ฒซ์งธ ๋ฐฐ์น์ ์
๋ ฅ๊ณผ ํ๊น ๋ฐ์ดํฐ์ ์ ๋ณด๋ ๋ค์๊ณผ ๊ฐ๋ค. | for inputs, targets in train_ds:
print("inputs.shape:", inputs.shape)
print("inputs.dtype:", inputs.dtype)
print("targets.shape:", targets.shape)
print("targets.dtype:", targets.dtype)
# ์์ : ์ฒซ์งธ ๋ฐฐ์น์ ์ฒซ์งธ ๋ฆฌ๋ทฐ
print("inputs[0]:", inputs[0])
print("targets[0]:", targets[0])
break | inputs.shape: (32,)
inputs.dtype: <dtype: 'string'>
targets.shape: (32,)
targets.dtype: <dtype: 'int32'>
inputs[0]: tf.Tensor(b'The film begins with a bunch of kids in reform school and focuses on a kid named \'Gabe\', who has apparently worked hard to earn his parole. Gabe and his sister move to a new neighborhood to ... | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
11.3.2 ๋จ์ด์ฃผ๋จธ๋ ๊ธฐ๋ฒ ๋จ์ด์ฃผ๋จธ๋์ ์ฑ์ธ ํ ํฐ์ผ๋ก ์ด๋ค N-๊ทธ๋จ์ ์ฌ์ฉํ ์ง ๋จผ์ ์ง์ ํด์ผ ํ๋ค. - ์ ๋๊ทธ๋จ(unigrams): ํ๋์ ๋จ์ด๊ฐ ํ์ ํ ํฐ- N-๊ทธ๋จ(N-grams): ์ต๋ N ๊ฐ์ ์ฐ์ ๋จ์ด๋ก ์ด๋ฃจ์ด์ง ํ ํฐ **๋ฐฉ์ 1: ์ ๋๊ทธ๋จ ๋ฐ์ด๋๋ฆฌ ์ธ์ฝ๋ฉ** ์๋ฅผ ๋ค์ด "the cat sat on the mat" ๋ฌธ์ฅ์ ์ ๋๊ทธ๋จ์ผ๋ก ์ฒ๋ฆฌํ๋ฉด ๋ค์ ๋จ์ด์ฃผ๋จธ๋๊ฐ ์์ฑ๋๋ค.์งํฉ์ผ๋ก ์ฒ๋ฆฌ๋๊ธฐ์ ๋จ์ด๋ค์ ์์๋ ์์ ํ ๋ฌด์๋๋ค.```{"cat", "mat", "on", "sat", "the"}```์ด์ ๋ชจ๋ ๋ฌธ์ฅ์ ์ดํ์์ธ์ ํฌํจ๋ ๋จ์ด๋ค์ ์๋งํผ ๊ธด 1์ฐจ์ ์ด... | from tensorflow.keras.layers import TextVectorization
text_vectorization = TextVectorization(
max_tokens=20000,
output_mode="multi_hot",
)
# ์ดํ์์ธ ์์ฑ
text_only_train_ds = train_ds.map(lambda x, y: x)
text_vectorization.adapt(text_only_train_ds) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
์์ฑ๋ ์ดํ์์ธ์ ์ด์ฉํ์ฌ ํ๋ จ์
, ๊ฒ์ฆ์
, ํ
์คํธ์
๋ชจ๋ ๋ฒกํฐํํ๋ค. | binary_1gram_train_ds = train_ds.map(lambda x, y: (text_vectorization(x), y))
binary_1gram_val_ds = val_ds.map(lambda x, y: (text_vectorization(x), y))
binary_1gram_test_ds = test_ds.map(lambda x, y: (text_vectorization(x), y)) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
๋ณํ๋ ์ฒซ์งธ ๋ฐฐ์น์ ์
๋ ฅ๊ณผ ํ๊น ๋ฐ์ดํฐ์ ์ ๋ณด๋ ๋ค์๊ณผ ๊ฐ๋ค.`max_tokens=20000`์ผ๋ก ์ง์ ํ์๊ธฐ์ ๋ชจ๋ ๋ฌธ์ฅ์ ๊ธธ์ด๊ฐ 2๋ง์ธ ๋ฒกํฐ๋ก ๋ณํ๋์๋ค. | for inputs, targets in binary_1gram_train_ds:
print("inputs.shape:", inputs.shape)
print("inputs.dtype:", inputs.dtype)
print("targets.shape:", targets.shape)
print("targets.dtype:", targets.dtype)
print("inputs[0]:", inputs[0])
print("targets[0]:", targets[0])
break | inputs.shape: (32, 20000)
inputs.dtype: <dtype: 'float32'>
targets.shape: (32,)
targets.dtype: <dtype: 'int32'>
inputs[0]: tf.Tensor([1. 1. 1. ... 0. 0. 0.], shape=(20000,), dtype=float32)
targets[0]: tf.Tensor(0, shape=(), dtype=int32)
| MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**๋ฐ์ง ๋ชจ๋ธ ์ง์ ** ๋จ์ด์ฃผ๋จธ๋ ๋ชจ๋ธ๋ก ์ฌ๊ธฐ์๋ ๋ฐ์ง ๋ชจ๋ธ์ ์ฌ์ฉํ๋ค. `get_model()` ํจ์๊ฐ ์ปดํ์ผ ๋ ๋จ์ํ ๋ฐ์ง ๋ชจ๋ธ์ ๋ฐํํ๋ค.๋ชจ๋ธ์ ์ถ๋ ฅ๊ฐ์ ๊ธ์ ์ผ ํ๋ฅ ์ด๋ฉฐ, ์ต์์ ์ธต์ ํ์ฑํ ํจ์๋ก `sigmoid`๋ฅผ ์ฌ์ฉํ๋ค. | from tensorflow import keras
from tensorflow.keras import layers
def get_model(max_tokens=20000, hidden_dim=16):
inputs = keras.Input(shape=(max_tokens,))
x = layers.Dense(hidden_dim, activation="relu")(inputs)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(1, activation="sigmoid")(x) # ๊ธ์ ์ผ ํ๋ฅ ๊ณ์ฐ
... | Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 20000)] 0
... | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**๋ชจ๋ธ ํ๋ จ** ๋ฐ์ง ๋ชจ๋ธ ํ๋ จ๊ณผ์ ์ ํน๋ณํ ๊ฒ ์๋ค.ํ๋ จ ํ ํ
์คํธ์
์ ๋ํ ์ ํ๋๊ฐ 89% ๋ณด๋ค ์กฐ๊ธ ๋ฎ๊ฒ ๋์จ๋ค.์ต๊ณ ์ฑ๋ฅ์ ๋ชจ๋ธ์ด ํ
์คํธ์
์ ๋ํด 95% ์ ๋ ์ ํ๋๋ฅผ ๋ด๋ ๊ฒ๋ณด๋ค๋ ๋ฎ์ง๋ง๋ฌด์์๋ก ์ฐ๋ ๋ชจ๋ธ๋ณด๋ค๋ ํจ์ฌ ์ข์ ๋ชจ๋ธ์ด๋ค. | callbacks = [
keras.callbacks.ModelCheckpoint("binary_1gram.keras",
save_best_only=True)
]
model.fit(binary_1gram_train_ds.cache(),
validation_data=binary_1gram_val_ds.cache(),
epochs=10,
callbacks=callbacks)
model = keras.models.load_model("binary... | Epoch 1/10
625/625 [==============================] - 10s 16ms/step - loss: 0.4074 - accuracy: 0.8277 - val_loss: 0.2792 - val_accuracy: 0.8908
Epoch 2/10
625/625 [==============================] - 3s 5ms/step - loss: 0.2746 - accuracy: 0.8981 - val_loss: 0.2774 - val_accuracy: 0.8964
Epoch 3/10
625/625 [==============... | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
**๋ฐฉ์ 2: ๋ฐ์ด๊ทธ๋จ ๋ฐ์ด๋๋ฆฌ ์ธ์ฝ๋ฉ** ๋ฐ์ด๊ทธ๋จ(2-grams)์ ์ ๋๊ทธ๋จ ๋์ ์ด์ฉํด๋ณด์. ์๋ฅผ ๋ค์ด "the cat sat on the mat" ๋ฌธ์ฅ์ ๋ฐ์ด๊ทธ๋จ์ผ๋ก ์ฒ๋ฆฌํ๋ฉด ๋ค์ ๋จ์ด์ฃผ๋จธ๋๊ฐ ์์ฑ๋๋ค.```{"the", "the cat", "cat", "cat sat", "sat", "sat on", "on", "on the", "the mat", "mat"}````TextVectorization` ํด๋์ค์ `ngrams=N` ์ต์
์ ์ด์ฉํ๋ฉดN-๊ทธ๋จ๋ค๋ก ์ด๋ฃจ์ด์ง ์ดํ์์ธ์ ์์ฑํ ์ ์๋ค. | text_vectorization = TextVectorization(
ngrams=2,
max_tokens=20000,
output_mode="multi_hot",
) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
์ดํ์์ธ ์์ฑ๊ณผ ํ๋ จ์
, ๊ฒ์ฆ์
, ํ
์คํธ์
์ ๋ฒกํฐํ ๊ณผ์ ์ ๋์ผํ๋ค. | text_vectorization.adapt(text_only_train_ds)
binary_2gram_train_ds = train_ds.map(lambda x, y: (text_vectorization(x), y))
binary_2gram_val_ds = val_ds.map(lambda x, y: (text_vectorization(x), y))
binary_2gram_test_ds = test_ds.map(lambda x, y: (text_vectorization(x), y)) | _____no_output_____ | MIT | notebooks/dlp11_part01_introduction.ipynb | codingalzi/dlp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.