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๋…„๊ฐ„ ๊ตฌ๋งค ๋ฐ์ดํ„ฐ์ด๋‹ค.![image.png](attachment:291e1ffc-e949-4bc0-98fe-69e2a04d8546.png) ๊ฒฐ๊ณผ : 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 ... Attaching to tmp815252o0_algo-1-n7amc_12mdone algo-1-n7amc_1 | ------- [STARTING TRAINING] ------- algo-1-n7amc_1 | ------- [TRAINING COMPLETE!] ------- algo-1-n7amc_1 | ------- [STARTING EVALUATION] ------- algo-1-n7amc_1 | 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) .........................  * 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