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
В словарях отображать можно не только начала натурального ряда, а произвольные объекты. Представьте себе настоящий словарь или телефонную книжку. Имени человека соответствует номер телефона.Классическое использование словарей в анализе данных: хранить частоту слова в тексте.кот $\rightarrow$ 10и $\rightarrow$ 100Тейлор...
a = dict() type(a) a['chapter1'] = 'ghfdlksgrjkasgdjkagrdjksargs' a a[1] = 'hrjegrejk' x = (3,4,5) a[x] = 'hrjekwslerw' x = (1,2,3,'str') a[x] = 'fuidaslt' a a = dict() a[(2,3)] = [2,3] # кортеж может быть ключом, потому что он неизменямый a b = dict() b[[2,3]] = [2,3] # а список уже нет, получим ошибку print(b)
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Создание словаряВ фигурных скобках (как множество), через двоеточие ключ:значение
d = dict() d d1 = {"кот": 10, "и": 100, "Тейлора": 2} print(d1) d1["кот"]
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Через функцию dict(). Обратите внимание, что тогда ключ-значение задаются не через двоеточие, а через знак присваивания. А строковые ключи пишем без кавычек - по сути мы создаем переменные с такими названиями и присваиваим им значения (а потом функция dict() уже превратит их в строки).
d2 = dict(кот=10, и=100, Тейлора=2) print(d2) # получили тот же результат, что выше
{'кот': 10, 'и': 100, 'Тейлора': 2}
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
И третий способ - передаем функции dict() список списков или кортежей с парами ключ-значение.
d3 = dict([("кот", 10), ("и", 100), ("Тейлора", 2)]) # перечисление (например, список) tuple print(d3)
{'кот': 10, 'и': 100, 'Тейлора': 2}
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Помните, когда мы говорили про списки, мы обсуждали проблему того, что важно создавать именно копию объекта, чтобы сохранять исходный список. Копию словаря можно сделать так
d4 = dict(d3) # фактически, копируем dict который строчкой выше print(d4) d1 == d2 == d3 == d4 # Содержание всех словарей одинаковое
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Пустой словарь можно создать двумя способами.
d2 = {} # это пустой словарь (но не пустое множество) d4 = dict() print(d2, d4) x = {} type(x)
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Операции со словарями Как мы уже говорили, словари неупорядоченные структуры и обратиться по индексу к объекту уже больше не удастся.
d1[1] # выдаст ошибку во всех случах кроме того, если в вашем словаре вдруг есть ключ 1
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Но можно обращаться к значению по ключу.
d3 = dict([("кот", 10), ("и", 100), ("Тейлора", 2)]) print(d1['кот']) d1[1]
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Можно создать новую пару ключ-значение. Для этого просто указываем в квадратных скобках название нового ключа.
d1[1] = 'test' print(d1[1]) # теперь работает!
test
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Внимание: если элемент с указанным ключом уже существует, новый с таким же ключом не добавится! Ключ – это уникальный идентификатор элемента. Если мы добавим в словарь новый элемент с уже существующим ключом, мы просто изменим старый – словари являются изменяемыми объектами.
d3 = dict([("кот", 10), ("и", 100), ("Тейлора", 2)]) d1["кот"] = 11 # так же как в списке по индексу - можно присвоить новое значение по ключу d1 d1["кот"] += 1 # или даже изменить его за счет арифметической операции d1
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
А вот одинаковые значения в словаре могут быть.
d1['собака'] = 13 print(d1)
{'кот': 13, 'и': 100, 'Тейлора': 2, 1: 'test', 'собака': 13}
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Кроме обращения по ключу, можно достать значение с помощью метода .get(). Отличие работы метода в том, что если ключа еще нет в словаре, он не генерирует ошибку, а возвращает объект типа None ("ничего"). Это очень полезно в решении некоторых задач.
d1 print(d1['кот']) print(d1.get("ктоо")) # вернут None
None
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Удобство метода .get() заключается в том, что мы сами можем установить, какое значение будет возвращено, в случае, если пары с выбранным ключом нет в словаре. Так, вместо None мы можем вернуть строку Not found, и ломаться ничего не будет:
print(d1.get("ктоо", 'Not found')) # передаем вторым аргументом, что возвращать print(d1.get("ктоо", False)) # передаем вторым аргументом, что возвращать
Not found False
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Также со словарями работают уже знакомые нам операции - проверка количества элементов, проверка на наличие объектов.
d1 print(d1) print("кот" in d1) # проверка на наличие ключа print("ктоо" not in d1) # проверка на отстуствие ключа
{'кот': 13, 'и': 100, 'Тейлора': 2, 1: 'test', 'собака': 13} True True
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Удалить отдельный ключ или же очистить весь словарь можно специальными операциями.
del d1["кот"] d1 d1.clear() d1 del d1["кот"] # удалить ключ со своим значением print(d1) d1.clear() # удалить все print(d1) d1 = dict([("кот", 10), ("и", 10), ("Тейлора", 2)])
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
У словарей есть три метода, с помощью которых мы можем сгенерировать список только ключей, только значений и список пар ключ-значения (на самом деле там несколько другая структура, но ведет себя она очень похоже на список).
print(d1.values()) # только значения print(d1.keys()) # только ключи print(d1.items()) # только ключ-значение
dict_values([10, 10, 2]) dict_keys(['кот', 'и', 'Тейлора']) dict_items([('кот', 10), ('и', 10), ('Тейлора', 2)])
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Ну, и раз уж питоновские словари так похожи на обычные, давайте представим, что у нас есть словарь, где все слова многозначные. Ключом будет слово, а значением ‒ целый список.
my_dict = {'swear' : {'swear' : ['клясться', 'ругаться'], 'dream' : ['спать', 'мечтать']}, 'dream' : ['спать', 'мечтать']}
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
По ключу мы получим значение в виде списка:
my_dict['swear']['swear'][0]
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Так как значением является список, можем отдельно обращаться к его элементам:
my_dict['swear'][0] # первый элемент
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Можем пойти дальше и создать словарь, где значениями являются словари! Например, представим, что в некотором сообществе проходят выборы, и каждый участник может проголосовать за любое число кандидатов. Данные сохраняются в виде словаря, где ключами являются имена пользователей, а значениями – пары *кандидат-голос*.
votes = {'user1': {'cand1': '+', 'cand2': '-'}, 'user2' : {'cand1': 0, 'cand3' : '+'}} # '+' - за, '-' - против, 0 - воздержался votes
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
По аналогии с вложенными списками по ключам мы сможем обратиться к значению в словаре, который сам является значением в `votes` (да, эту фразу нужно осмыслить):
votes['user1']['cand1'] # берем значение, соответствующее ключу user1, в нем – ключу cand1 dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} dict3 = dict1.copy() dict3.update(dict2) print(dict3) dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} dict3 = {**dict1, **dict2} print(dict3)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
def warn(*args, **kwargs): pass import warnings warnings.warn = warn import pandas as pd from sklearn.model_selection import train_test_split from sklearn import tree from sklearn.ensemble import RandomForestClassifier #import csv to pandas dataframe income_data=pd.read_csv("income.csv",header=0, delimiter = ", ")...
0.8258199238422799 White 27816 Black 3124 Asian-Pac-Islander 1039 Amer-Indian-Eskimo 311 Other 271 Name: race, dtype: int64
MIT
income.ipynb
bibekuchiha/Predicting-Income-with-Random-Forests
Part 3 - Analyzing the Data Kiran TIRUMALE LAKSHMANA RAO Importing the Necessary Libraries
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns #install seaborn using 'pip intall seaborn' %matplotlib inline plt.style.use('seaborn-whitegrid')
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Loading the Cleaned Dataset
paris = pd.read_csv(r"C:\Users\ktirumalelakshmana\Desktop\Paris_Airbnb_Final.csv") paris.head() # Checking the data types etc paris.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 280 entries, 0 to 279 Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Hotel_Type_with_Location 280 non-null object 1 Hote_Type 280 non-null obj...
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Analyzing the Data The data from Airbnb for Paris location has been scraped for the dates `01-Dec-2020` to `31-Dec-2020` with 2 People or more Different locations where accommodations are available
Locations = paris['Location_in_Paris'].unique() Locations.sort() Locations # Total number of locations in Paris len(Locations)
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Visualizations Ratings and Discount
# Defining the x and y axis variables x = paris['Discount'] y = paris['Ratings'] r_colors = paris['No_of_Reviews'] # Plotting using matplotlib plt.scatter(x, y, alpha=0.2, c=r_colors, cmap='viridis') # Adding Title plt.title('Discount vs Ratings') # Adding X-Label plt.xlabel('Discount') # Adding Y-Label plt.ylabel(...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Price and Ratings
# Defining the x and y axis variables x = paris['Previous_Price'] y = paris['Ratings'] r_colors = paris['Discount'] # Plotting using matplotlib plt.scatter(x, y, alpha=0.2, c=r_colors, cmap='viridis') # Adding Title plt.title('Price vs Ratings') # Adding X-Label plt.xlabel('Previous Price') # Adding Y-Label plt.yla...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Ratings and No. of Reviews
# Defining the x and y axis variables x = paris['No_of_Reviews'] y = paris['Ratings'] # Plotting using matplotlib plt.scatter(x, y, alpha=0.2, cmap='viridis') # Adding Title plt.title('Ratings vs No. of Reviews') # Adding X-Label plt.xlabel('No. of Reviews') # Adding Y-Label plt.ylabel('Ratings');
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Discount and Price Correlation between `Discounted_Price` and `Previous_Price`
#Same plot as above, but using matplotlib x = paris['Discounted_Price'] y = paris['Previous_Price'] plt.scatter(x, y, alpha=0.2, cmap='viridis') m, b = np.polyfit(x, y, 1) plt.plot(x, m*x+b) plt.title('Discount vs Previous Price - Trend') plt.xlabel('Discounted Price') plt.ylabel('Previous Price') #Plotting using ...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Correlation between `Discount` and `Previous_Price`
#Plotting using seaborn scatterplot and hue sns.scatterplot(x = 'Discount', y = 'Previous_Price',data=paris, hue='Type_Bed_Studio', alpha=0.5) #Adding Trendline m, b = np.polyfit(x, y, 1) plt.plot(x, m*x+b) # Set title plt.title('Discount vs Previous Price - Trend') # Set x-axis label plt.xlabel('Discount') # Set y...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Discount and Price Distributions
# Plot histogram sns.distplot(paris['Discount'],kde = False, color='g') # Set title plt.title('Distribution of Discount') plt.show() # Plot histogram distribution sns.distplot(paris['Previous_Price'],kde = False) # Set title plt.title('Previous Price Distribution') plt.xlabel('Previous Price') plt.show() sns.distp...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Location wise information
location = paris.groupby('Location_in_Paris').mean() location # Location - lineplot for Discounted Price sns.set_style("whitegrid", {'axes.grid' : False}) g1 = sns.lineplot(x = location.index.values, y = 'Discounted_Price', data = location, palette = 'hls', alpha = 0.5 )...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Would have loved to plot the Ratings and Discount on a Paris map. However, unable to do it! `Type_Bed_Studio` wise Information
Bed_Studio = paris[['Type_Bed_Studio', 'Ratings', 'No_of_Reviews', 'Previous_Price', 'Discount', 'No_of_Guests']].groupby('Type_Bed_Studio').mean() Bed_Studio
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Studio vs Bedroom - Discount
# Plotting a barplot sns.set_style("whitegrid", {'axes.grid' : False}) sns.barplot(x = Bed_Studio.index.values, y = 'Discount', data = Bed_Studio, palette = 'hls', order = ['Studio', 'Bedroom'], alpha = 0.5 ) plt.title('Studio vs Bedroom - Discount'...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Studio vs Bedroom - Ratings
# Plotting a barplot sns.set_style("whitegrid", {'axes.grid' : False}) sns.barplot(x = Bed_Studio.index.values, y = 'Ratings', data = Bed_Studio, palette = 'hls', order = ['Studio', 'Bedroom'], alpha = 0.5 ) plt.title('Studio vs Bedroom - Ratings') ...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Studio vs Bedroom - Previous Price
# Plotting a barplot sns.set_style("whitegrid", {'axes.grid' : False}) sns.barplot(x = Bed_Studio.index.values, y = 'Previous_Price', data = Bed_Studio, palette = 'hls', order = ['Studio', 'Bedroom'], alpha = 0.5 ) plt.title('Studio vs Bedroom - Pri...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
`No_of_Guests` wise Information
guests = paris.groupby('No_of_Guests').mean() guests
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Guests vs Ratings
# Plotting a lineplot for guests vs rating sns.set_style("whitegrid", {'axes.grid' : False}) sns.barplot(x = guests.index.values, y = 'Ratings', data = guests, palette = 'PuBu', alpha = 0.5 ) plt.title('Guests vs Ratings') plt.plot()
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Guests vs Previous Price
# Plotting a lineplot for guests vs previous price sns.set_style("whitegrid", {'axes.grid' : False}) sns.lineplot(x = guests.index.values, y = 'Previous_Price', data = guests, palette = 'PuBu', alpha = 0.5 ) plt.title('Guests vs Previous Price') plt.plot()
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Guests vs Discount
# Plotting a lineplot for guests vs discount sns.set_style("whitegrid", {'axes.grid' : False}) sns.lineplot(x = guests.index.values, y = 'Discount', data = guests, color = 'g', alpha = 0.5 ) plt.title('Guests vs Discount') plt.plot()
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Guests vs Discounted Price
# Plotting a lineplot for guests vs discounted price sns.set_style("whitegrid", {'axes.grid' : False}) sns.lineplot(x = guests.index.values, y = 'Discounted_Price', data = guests, color = 'r', alpha = 0.5 ) plt.title('Guests vs Discounted Price') plt.plot()
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
Overlaying above 3 graphs
# Plotting a lineplot of above graphs - overlaying them together sns.set_style("whitegrid", {'axes.grid' : False}) sns.lineplot(x = guests.index.values, y = 'Previous_Price', data = guests, palette = 'PuBu', alpha = 0.5 ) sns.lineplot(x = guests.index.values, y = '...
_____no_output_____
MIT
Part 3 - Analyzing the Data.ipynb
kirantl/Airbnb_WebScraping
I. DATA Processinghttps://www.kaggle.com/henriqueyamahata/bank-marketing
def remove_duplicated_row(df): df = df.drop(df[df.duplicated()].index).reset_index(drop=True) return(df) def remove_features(df,col_lst): for col in col_lst: df.pop(col) return(df) def replace_missing_by_value(df,column,replaced_value,missing_value='unknown'): df[column] = df[column].apply...
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
L O A D data
#### L O A D Data file_path = "data/bank-additional-full.csv" marketing_df = pd.read_csv(file_path,sep = ";")
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
P R O C E S S I N G data
process_mkt_df = marketing_df.copy() test_size = 0.2 target = 'y' ## Processing data process_mkt_df = data_processing_pipeline(process_mkt_df) cat_cols = process_mkt_df.dtypes[process_mkt_df.dtypes == 'object'].index num_cols = process_mkt_df.dtypes[process_mkt_df.dtypes != 'object'].index ## label encoding process_...
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
R U N with the whole data set
## split train set and test_set X_train, X_test, y_train, y_test = train_test_split(process_mkt_df.drop('y',axis=1), process_mkt_df['y'], test_size=test_size, random_state = 101) ## standardize data scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_t...
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
U N D E R S A M P L E D Dataset
# main data set for training under_mkt_df = under_resample_data(process_mkt_df, target = 'y') # Showing ratio print("Percentage of no clients: ", len(under_mkt_df[under_mkt_df[target] == 0])/len(under_mkt_df)) print("Percentage of yes clients: ", len(under_mkt_df[under_mkt_df[target] == 1])/len(under_mkt_df)) print("To...
Percentage of no clients: 0.5 Percentage of yes clients: 0.5 Total number of clients in resampled data: 9278
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
R U N with the under resampled data set
## Split train and test undersampled dataset X_under_train, X_under_test, y_under_train, y_under_test = train_test_split(under_mkt_df.drop(target,axis=1),under_mkt_df[target], test_size=test_size, random_state = 101) print("") print("Number tra...
Number transactions train dataset: 7422 Number transactions test dataset: 1856 Total number of transactions: 9278 [12:01:25] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.4.0/src/learner.cc:1095: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' w...
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
C O M P A R E when training on the whole dataset and the under- resampled dataset
evaluations = pd.DataFrame() evaluations = evalutation_df.append(under_evalutation_df, ignore_index = True) evaluations
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
ROC curve in case of undersampled dataset Vì ta cần tỉ lệ bỏ sót khách hàng thành công của mô hình phải thấp nên mặc dù accuracy score chạy trên toàn tập data cao hơn, ta sẽ chọn cách train trên tập under sampled data vì trường hợp này cho độ Precision, Recall, F1 score trên nhãn successful tốt hơn và accuracy scor...
visualize_ROC_curves(y_under_test,y_under_test_pred_proba_df)
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
K F O L D validation to avoid improve the model's effectiveness on undersampled by models( LogisticClf, DecisionTree, Random Forest Classifier, XGBoost)
# # scaler on the whole dataset # scaler = pickle.load(open("model/pkl_scaler.pkl", 'rb')) ## init kfold target = 'y' num_fold = 5 kfold = KFold(n_splits=num_fold, shuffle=True) # fold_scaler = StandardScaler() X = scaler.transform(under_mkt_df.drop('y',axis=1)) y = under_mkt_df['y'] fold_idx = 1 fold_evalutation_df =...
[12:02:56] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.4.0/src/learner.cc:1095: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior. [12:03:16]...
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
E V A L U A T E to choose the optimal model with the best avarage metrics
# fold_evalutation_df.to_csv('fold_evalutation_df.csv') # fold_evalutation_df t = fold_evalutation_df.groupby(['Model']).mean().iloc[:,:-1].sort_values(['Recall_test','Accuracy_test'], ascending=False) t # Evaluation metrics for 4 models
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
O P T I M A L Model
## EVALUATION METRICS of the optimal model = mean(EVALUATION METRICS) of k times folding the under_resampled dataset # The optimal model:XGBoost Classifier optimal_evaluation_df = t.head(1) optimal_name =t.head(1).index.values[0] optimal_model = models[names.index(optimal_name)] print('The optimal model is '+str(optim...
The optimal model is XGBoost Classifier
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
O P T I M A L FIT : train on the whole under sampled dataset to get the last one
## Train the optimal model on the whole under resampled dataset target = 'y' X_train = scaler.transform(under_mkt_df.drop(target, axis = 1)) y_train = under_mkt_df[target] optimal_model.fit(X_train,y_train) # ## ghi vào file pickle # with open("model/pkl_model.pkl","wb") as f: # pickle.dump(scaler,f)
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
O P T I M A L Feature Importances
## Hệ số mô hình tối ưu features = [i for i in under_mkt_df.columns.values.tolist() if i!= target] opt_model_importances = pd.Series(data = optimal_model.feature_importances_, index = features, name = optimal_name) plt.figure(figsize = (14,8)) sns.barplot(x = opt_model_importances.sort_values(ascending = False).values...
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
O P T I M A L ROI on the whole dataset
### Real R O I on the whole dataset ## ROI = roi_per_success * # of sales - cost_per_call * # of calls cost_per_call = 10 roi_per_success = 20 target = 'y' # X_opt_test = process_mkt_df.drop(targer,axis = 1) X_opt_test = scaler.transform(process_mkt_df.drop(target,axis = 1)) y_opt_test = process_mkt_df[target] y_pred ...
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
R E S E A R C H Decision tree
## init the research model tree_model = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=0) tree_name = 'Decision Tree Classifier' X_tree_train, X_tree_test, y_tree_train, y_tree_test = train_test_split(under_mkt_df.drop(target,axis=1),under_mkt_df[target], ...
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
V I S U A L I Z E Decision Tree
# from sklearn import tree plt.figure(figsize=(20,15)) tree.plot_tree(tree_model,feature_names = features,rounded=True, filled = True); plt.title("Decision Tree on Banking Tele-marketing dataset");
_____no_output_____
MIT
assignment_7/.ipynb_checkpoints/Nguyen_Bank_Marketing_kFold-checkpoint.ipynb
ngttnguyen/atom-assignments
Neural network hybrid recommendation system on Google Analytics data preprocessingThis notebook demonstrates how to implement a hybrid recommendation system using a neural network to combine content-based and collaborative filtering recommendation models using Google Analytics data. We are going to use the learned use...
# Import helpful libraries and setup our project, bucket, and region import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["...
Updated property [core/project]. Updated property [compute/region].
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Create ML dataset using Dataflow Let's use Cloud Dataflow to read in the BigQuery data, do some preprocessing, and write it out as CSV files.First, let's create our hybrid dataset query that we will use in our Cloud Dataflow pipeline. This will combine some content-based features and the user and item embeddings learn...
query_hybrid_dataset = """ WITH CTE_site_history AS ( SELECT fullVisitorId as visitor_id, (SELECT MAX(IF(index = 10, value, NULL)) FROM UNNEST(hits.customDimensions)) AS content_id, (SELECT MAX(IF(index = 7, value, NULL)) FROM UNNEST(hits.customDimensions)) AS category, (SELECT MAX(...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Let's pull a sample of our data into a dataframe to see what it looks like.
from google.cloud import bigquery bq = bigquery.Client(project = PROJECT) df_hybrid_dataset = bq.query(query_hybrid_dataset + "LIMIT 100").to_dataframe() df_hybrid_dataset.head() df_hybrid_dataset.describe() import apache_beam as beam import datetime, os def to_csv(rowdict): # Pull columns from BQ and create a lin...
Launching Dataflow job preprocess-hybrid-recommendation-features-190412-184419 ... hang on
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Let's check our files to make sure everything went as expected
%%bash rm -rf features mkdir features !gsutil -m cp -r gs://{BUCKET}/hybrid_recommendation/preproc/features/*.csv* features/ !head -3 features/*
==> features/eval.csv-00000-of-00001 <== 710535,951784927766849126,710535,News,"Haus aus Marmor und Grabsteinen",None,503,-0.00170100899413,0.00496714003384,0.0040482301265,0.000690933316946,3.52509268851e-05,-0.00172890012618,0.00153049221262,0.00100265210494,0.00228979066014,-0.00201142113656,-5.59943889043e-19,7.426...
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Create vocabularies using Dataflow Let's use Cloud Dataflow to read in the BigQuery data, do some preprocessing, and write it out as CSV files.Now we'll create our vocabulary files for our categorical features.
query_vocabularies = """ SELECT CAST((SELECT MAX(IF(index = index_value, value, NULL)) FROM UNNEST(hits.customDimensions)) AS STRING) AS grouped_by FROM `cloud-training-demos.GA360_test.ga_sessions_sample`, UNNEST(hits) AS hits WHERE # only include hits on pages hits.type = "PAGE" AND (SELECT MAX(IF...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Also get vocab counts from the length of the vocabularies
import apache_beam as beam import datetime, os def count_to_txt(rowdict): # Pull columns from BQ and create a line # Write out count return "{}".format(rowdict["count_number"]) def mean_to_txt(rowdict): # Pull columns from BQ and create a line # Write out mean return "{}".format(rowdict["m...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Let's check our files to make sure everything went as expected
%%bash rm -rf vocabs mkdir vocabs !gsutil -m cp -r gs://{BUCKET}/hybrid_recommendation/preproc/vocabs/*.txt* vocabs/ !head -3 vocabs/* %%bash rm -rf vocab_counts mkdir vocab_counts !gsutil -m cp -r gs://{BUCKET}/hybrid_recommendation/preproc/vocab_counts/*.txt* vocab_counts/ !head -3 vocab_counts/*
==> vocab_counts/author_vocab_count.txt-00000-of-00001 <== 1103 ==> vocab_counts/category_vocab_count.txt-00000-of-00001 <== 3 ==> vocab_counts/content_id_vocab_count.txt-00000-of-00001 <== 15634
Apache-2.0
courses/machine_learning/deepdive/10_recommend/labs/hybrid_recommendations/hybrid_recommendations_preproc.ipynb
Glairly/introduction_to_tensorflow
Random VariableIn probability and statistics, a random variable, random quantity, aleatory variable, or stochastic variable is described informally as a variable whose values depend on outcomes of a random phenomenon. In random variable we are considering a function whose domain is the set of possible outocmes and wh...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats import seaborn as sns from matplotlib.pyplot import figure
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Discrete Uniform Distribution or Discrete rectangular distributionThe Uniform Distribution can be easily derived from the Bernoulli Distribution. In this case, a possibly unlimited number of outcomes are allowed and all the events hold the same probability to take place. As an example, imagine the roll of a fair dice....
# size = number of experiments # loc = starting point # scale = end point uniform = stats.uniform.rvs(size=10000,loc =0, scale=6) # Means random variable from 0 to 6 ax = sns.distplot(uniform, kde=True) ax.set(xlabel='Uniform Distribution', ylabel='Frequency') import numpy as np x = [0,1,2,3,4,5] coun...
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Mean:- E(X) = (a + b) /2 Variance:- Var = (((b -a +1)^2) - 1) /12 Median:- M = (a + b) /2 Mode:- Not Defined Skewness:- S = 0 Kurtosis:- K = -6(n^2 + 1) / 5(n^2 -1) Entropy:- Entropy = ln(n) Application:- 1. Success in an examination 2. Failure of an engine in an aircraft 3. Spinning of ...
# size = number of experiments # p = probability of success bern = stats.bernoulli.rvs(size=10000,p=0.5) ax= sns.distplot(bern, kde=False) ax.set(xlabel='Bernoulli Distribution', ylabel='Frequency') biased_bern = stats.bernoulli.rvs(size=1000,p=0.7) ax= sns.distplot(biased_bern, kde=Fa...
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Binomial DistributionThe repetition of multiple independent Bernoulli trials is called a Bernoulli process.The outcomes of a Bernoulli process will follow a Binomial distribution. As such, the Bernoulli distribution would be a Binomial distribution with a single trial.Some common examples of Bernoulli processes includ...
# example of simulating a binomial process and counting success from numpy.random import binomial # define the parameters of the distribution p = 0.3 k = 100 # run a single simulation success = binomial(k, p) print('Total Success: %d' % success) # calculate moments of a binomial distribution from scipy.stats import bin...
P of 10 success: 0.000% P of 20 success: 1.646% P of 30 success: 54.912% P of 40 success: 98.750% P of 50 success: 99.999% P of 60 success: 100.000% P of 70 success: 100.000% P of 80 success: 100.000% P of 90 success: 100.000% P of 100 success: 100.000%
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Poisson Distribution It is discovered by french mathematician and physicst simeon denis poisson (1781 - 1840) in 1837.It is a limiting case of binomial distribution because:- 1. n, the number of trial is indefinately large i.e n --> inf2. p, the constant probability of success for each trial is indefinately small i.e ...
from scipy.stats import poisson mu = 0.6 mean, var, skew, kurt = poisson.stats(mu, moments='mvsk') x = np.arange(poisson.ppf(0.01, mu), poisson.ppf(0.99, mu)) #ppf = Percent point function. print(x) pmf = poisson.pmf(x, mu) print('Mean=%.3f, Variance=%.3f, Skew=%.3f, Kurtosis=%.3f' % (mean, var,skew,kurt)...
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Negative Binomial DistributionIn poisson distribution mean and variance are equal and in binomial distribution mean is greater than variance.In negative binomial distribution variance is greater than mean. For ex.- Becterial clustering like death of insects, no of insect bite lead to negative binomial distribution and...
from scipy.stats import nbinom import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) n, p = 0.4, 0.4 mean, var, skew, kurt = nbinom.stats(n, p, moments='mvsk') print('Mean=%.3f, Variance=%.3f, Skew=%.3f, Kurtosis=%.3f' % (mean, var,skew,kurt)) x = np.arange(nbinom.ppf(0.01, n, p), #0.01 is the probability ...
Mean=0.600, Variance=1.500, Skew=3.266, Kurtosis=15.667
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Geometric DistributionGeometric distribution is the distribution of the number of trial needed to get the first success in repeated bernoulli trial. For ex.- In a large population of adults, 30% have recieved CPR training. If adults from this population are randomly selected what is the probability that the 6th perso...
from scipy.stats import geom import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) p = 0.5 mean, var, skew, kurt = geom.stats(p, moments='mvsk') x = np.arange(geom.ppf(0.01, p), # 0.01 is the probability geom.ppf(0.99, p)) ax.plot(x, geom.pmf(x, p), 'bo', ms=8, label='geom pmf') ax.vlines(x, 0, geo...
/home/himanshugoyal/.local/lib/python3.8/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for hi...
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Hypergeometric distributionThe hypergeometric distribution is used to calculate probabilities when sampling without replacement.![hypergeometric.png](attachment:hypergeometric.png)Note that it is different from Binomial distribution as a binomial experiment requires that the probability of success be constant on every...
from scipy.stats import hypergeom import matplotlib.pyplot as plt [M, n, N] = [20, 7, 12] rv = hypergeom(M, n, N) x = np.arange(0, n+1) pmf_dogs = rv.pmf(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, pmf_dogs, 'bo') ax.vlines(x, 0, pmf_dogs, lw=2) ax.set_xlabel('# of dogs in our group of chosen animals') a...
/home/himanshugoyal/.local/lib/python3.8/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for hi...
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Multinomial DistributionMultinomial is the generalization of binomial distribution.A multinomial distribution is the probability distribution of the outcomes from a multinomial experiment.A multinomial experiment is a statistical experiment that has the following properties:1. The experiment consists of n repeated tri...
from scipy.stats import multinomial rv = multinomial(8, [0.3, 0.2, 0.5]) # n:- (int)Number of trials, p:- (array_like)Probability of a trial falling into each category; should sum to 1 rv.pmf([1, 3, 4]) multinomial.pmf([[3, 4], [3, 5]], n=[7, 8], p=[.3, .7])
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Uses:- A common example of the multinomial distribution is the occurrence counts of words in a text document, from the field of natural language processing. A multinomial distribution is summarized by a discrete random variable with K outcomes, a probability for each outcome from p1 to pK, and k successive trials. Co...
# sample a normal distribution from numpy.random import normal # define the distribution mu = 50 sigma = 5 n = 10 # generate the sample sample = normal(mu, sigma, n) print(sample) # pdf and cdf for a normal distribution from scipy.stats import norm from matplotlib import pyplot # define distribution parameters mu = 50 ...
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Exponential Distribution Finally, the Exponential Distribution is used to model the time taken between the occurrence of different events. As an example, let's imagine we work at a restaurant and we want to predict what is going to be the time interval between different customers coming in the restaurant. Using an Exp...
expon = stats.expon.rvs(scale=1,loc=0,size=1000) ax = sns.distplot(expon, kde=True, bins=100, color='skyblue', hist_kws={"linewidth": 15,'alpha':1}) ax.set(xlabel='Exponential Distribution', ylabel='Frequency') figure(num=None, figsize=(8, 6), dpi=...
_____no_output_____
Apache-2.0
Statistics/Random Variable and distribution function..ipynb
himanshu-1205/Statistics
Data types in Python ToC
S1 = 'abc' S2 = 'DEF' display(md('## Strings')) display(md(f'S1 = {S1}; \nS2 = {S2}')) display(md(f"Join strings: ''.join([S1, S2]) = {''.join([S1, S2])}")) display(md(f'Change cases: \n* S2.lower(); S2 = {S2.lower()} \n* S1.upper(); S2 = {S1.upper()}')) display(md("Right justify text with str.rjust(int)) display(m...
_____no_output_____
MIT
DataTypes.ipynb
maufia/MyPyCourse
ปฏิบัติการครั้งที่ 4 กระบวนวิชา 229351 Statistical Learning for Data Scienceคำชี้แจง1. ให้เริ่มทำปฏิบัติการจาก colab notebook ที่กำหนดให้ จากนั้นบันทึกเป็นไฟล์ *.ipynb (File -> Download .ipynb) Task 1 Empirical risk for virus testingในปัญหานี้เราจะทำการศึกษาการสร้างวิธีในการจำแนกคนที่เป็นโรคไวรัสจากการทดสอบชนิดหนึ่ง ก...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from scipy.stats import norm # Note: don't make any changes to this function def generate_ground_truth(N, prevalence): """ สร้างข้อมูลจำลอง""" rs = np.random.RandomState(1) reality = rs.binomial(1, prevalence, N) ...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
ฟังก์ชัน `alpha_threshold_decisions` ใช้ในการตัดสินใจว่าแต่ละคนเป็นหรือไม่เป็นพาหะ (`decisions`)
# Note: don't make any changes to this function, this is exatly the naive thresholding you completed in Lab 1 def alpha_threshold_decisions(p, alpha): """ Returns decisions on p using naive thresholding. Inputs: p: array p[i] คือความน่าจะเป็นที่ตัวอย่างที่ i มีเชื้อไวรัส alpha: threshol...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
ฟังก์ชัน `report_results` ใช้ในการคำนวณว่าการตัดสินใจถูกหรือผิดอย่างไรบ้าง* TP (true positive): `ri`=1,`di`=1 * TN (true negative): `ri`=0,`di`=0 * FP (false positive): `ri`=0,`di`=1 * FN (false negative): `ri`=1,`di`=0
# Note: don't make any changes to this function, this is the report_results function you completed in Lab 1 def report_results(decisions, reality): """ สร้าง dictionary ที่ประกอบไปด้วยจำนวนตัวอย่างในกลุ่ม true positives, true negatives, false negatives, และ false positives จากการตัดสินใจด้วย `alpha_th...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
`results_dictionary["FP_count"]` Exercise 1a: เติมฟังก์ชันเพื่อคำนวณ empirical risk จากค่าจำนวนความถูกต้องและจำนวนความผิดพลาด (TP, FP, TN, FN) ที่บันทึกใน `results_dictionary` โดยที่ `factor_k` คือค่า $k$ ที่ระบุในนิยามของ loss function ข้างบน Loss function คือ$$\begin{cases} \mathcal{l}(di=1,ri=0) = 1\\\mathcal{l}(d...
# TODO: fill in def compute_empirical_risk(results_dictionary, factor_k): """ คำนวณ empirical risk ด้วยค่า TP, FP, TN และ FN ใน results_dictionary โดยที่ค่าของ false positive คือ 1 และค่าของ false negative คือ k Inputs: results_dictionary : dictionary ที่มีค่า TP, FP, TN...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
Exercise 1b: เติมฟังก์ชันเพื่อคำนวณ empirical risk โดยที่มี argument ดังนี้ * `reality` การเป็นพาหะจริง * `p` ความน่าจะเป็นที่ได้จากการทดสอบ * `alpha` ค่า threshold ในการตัดสินใจว่าแต่ละคนเป็นพาหะหรือไม่* `factor_k` คือค่า $k$ ที่ระบุในนิยามของ loss function ข้างบน
# TODO: complete the function def compute_alpha_empirical_risk(p, reality, alpha, factor_k): """ คำนวณค่า empirical risk ที่ค่า threshold alpha Inputs: p: array of floats, p[i] คือความน่าจะเป็นที่ตัวอย่างที่ i มีเชื้อไวรัส reality: array ที่มีค่า 0/1, reality[i] =1 ถ้าคนที่ i มีเชื้อไว...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
Exercise 1c: factor_k กับค่า $\alpha$ ที่ดีทีสุด (Optimal $\alpha$) มีความสัมพันธ์กันอย่างไร คำตอบ: Task 2 Sample points
np.random.seed(42) N = 8 x = 10 ** np.linspace(-2, 0, N) y = np.random.normal(loc = 10 - 1. / (x + 0.1), scale= 0.5) plt.figure() plt.scatter(x, y, c='k') plt.xlabel('x') plt.ylabel('y') plt.title('Sample points');
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
Polynomial regression
p = np.polyfit(x, y, 2) xfit = np.linspace(-0.2, 1.2, 1000) yfit = np.polyval(p, xfit) p plt.figure() plt.scatter(x, y, marker='x', c='k', s=50) plt.plot(xfit, yfit, '-b') plt.xlabel('x') plt.ylabel('y') plt.title('d = 2') xfit = np.linspace(-0.2, 1.2, 1000) titles = ['d = 1 (under-fit)', 'd = 2', 'd = 6 (over-fit)...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
ในกรณีนี้ เราใช้ squared-loss ดังนั้น empirical risk เท่ากับ MSE (mean-squared error)
def empirical_risk(y, yfit): return np.mean((y - yfit) ** 2)
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
Exercise 2: 1. ทำการสร้าง polynomial regression ที่มีค่า degree ตั้งแต่ 1-10 โดยใช้ training set ข้างบน 2. หลังจากสร้างโมเดลแต่ละตัวเสร็จแล้ว ให้คำนวณค่า empirical risk ของการทำนายบน test set เก็บค่าที่ได้ไว้ใน list ที่ชื่อว่า `empirical_risks` (เพราะฉะนั้น list นี้จะมีสมาชิก 10 ตัว)3. สร้าง plot โดยให้แกนนอนคือค่า de...
max_degree = 10 empirical_risks = [0]*max_degree for d in range(1,max_degree+1): #TODO: fill code here p = np.polyfit(xtrain, ytrain, d) ypred = np.polyval(p, xtest) r = empirical_risk(ytest, ypred) p = np.polyfit(xtrain, ytrain, 6) plt.figure() plt.scatter(xtest, ytest) xfit2 = np.linspace(0, 1.1,...
_____no_output_____
MIT
Labs/229351-LAB04.ipynb
donlapark/ds351.github.io
Detecting Payment Card FraudIn this section, we'll look at a credit card fraud detection dataset, and build a binary classification model that can identify transactions as either fraudulent or valid, based on provided, *historical* data. In a [2016 study](https://nilsonreport.com/upload/content_promo/The_Nilson_Report...
import io import os import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import train_test_split %matplotlib inline import boto3 import sagemaker from sagemaker import get_execution_role
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
I'm storing my **SageMaker variables** in the next cell:* sagemaker_session: The SageMaker session we'll use for training models.* bucket: The name of the default S3 bucket that we'll use for data storage.* role: The IAM role that defines our data and model permissions.
# sagemaker session, role sagemaker_session = sagemaker.Session() role = sagemaker.get_execution_role() # S3 bucket name bucket = sagemaker_session.default_bucket()
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Loading and Exploring the DataNext, I am loading the data and unzipping the data in the file `creditcardfraud.zip`. This directory will hold one csv file of all the transaction data, `creditcard.csv`.As in previous notebooks, it's important to look at the distribution of data since this will inform how we develop a fr...
# only have to run once !wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c534768_creditcardfraud/creditcardfraud.zip !unzip creditcardfraud # read in the csv file local_data = 'creditcard.csv' # print out some data transaction_df = pd.read_csv(local_data) print('Data shape (rows, cols): ', tr...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Calculate the percentage of fraudulent dataTake a look at the distribution of this transaction data over the classes, valid and fraudulent. Complete the function `fraudulent_percentage`, below. Count up the number of data points in each class and calculate the *percentage* of the data points that are fraudul...
# Calculate the fraction of data points that are fraudulent def fraudulent_percentage(transaction_df): '''Calculate the fraction of all data points that have a 'Class' label of 1; fraudulent. :param transaction_df: Dataframe of all transaction data points; has a column 'Class' :return: A fractional pe...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Test out your code by calling your function and printing the result.
# call the function to calculate the fraud percentage fraud_percentage = fraudulent_percentage(transaction_df) print('Fraudulent percentage = ', fraud_percentage) print('Total # of fraudulent pts: ', fraud_percentage*transaction_df.shape[0]) print('Out of (total) pts: ', transaction_df.shape[0])
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Split into train/test datasetsIn this example, we'll want to evaluate the performance of a fraud classifier; training it on some training data and testing it on *test data* that it did not see during the training process. So, we'll need to split the data into separate training and test sets.Complete the `tra...
# split into train/test def split_data(transaction_df, test_size= 0.3, random_state=1): ''' Shuffle the data and randomly split into train and test sets; separate the class labels (the column in transaction_df) from the features. :param df: Dataframe of all credit card transaction data :param train_frac:...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Test CellIn the cells below, I'm creating the train/test data and checking to see that result makes sense. The tests below test that the above function splits the data into the expected number of points and that the labels are indeed, class labels (0, 1).
# get train/test data train_features, test_features, train_labels, test_labels = split_data(transaction_df, test_size=0.3, random_state=1) # manual test # for a split of 0.7:0.3 there should be ~2.33x as many training as test pts print('Training data pts: ', len(train_features)) print('Test data pts: ', len(test_feat...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
--- ModelingNow that you've uploaded your training data, it's time to define and train a model!In this notebook, you'll define and train the SageMaker, built-in algorithm, [LinearLearner](https://sagemaker.readthedocs.io/en/stable/linear_learner.html). A LinearLearner has two main applications:1. For regression tasks i...
# import LinearLearner from sagemaker import LinearLearner # specify an output path prefix = 'creditcard' output_path = 's3://{}/{}'.format(bucket, prefix) # instantiate LinearLearner linear = LinearLearner(role=role, train_instance_count=1, train_instance_type='ml.c4.xl...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Convert data into a RecordSet formatNext, prepare the data for a built-in model by converting the train features and labels into numpy array's of float values. Then you can use the [record_set function](https://sagemaker.readthedocs.io/en/stable/linear_learner.htmlsagemaker.LinearLearner.record_set) to forma...
# convert features/labels to numpy train_x_np = train_features.astype('float32') train_y_np = train_labels.astype('float32') # create RecordSet formatted_train_data = linear.record_set(train_x_np, labels=train_y_np)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Train the EstimatorAfter instantiating your estimator, train it with a call to `.fit()`, passing in the formatted training data.
%%time # train the estimator on formatted training data linear.fit(formatted_train_data)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Deploy the trained modelDeploy your model to create a predictor. We'll use this to make predictions on our test data and evaluate the model.
%%time # deploy and create a predictor linear_predictor = linear.deploy(initial_instance_count=1, instance_type='ml.t2.medium')
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
--- Evaluating Your ModelOnce your model is deployed, you can see how it performs when applied to the test data.According to the deployed [predictor documentation](https://sagemaker.readthedocs.io/en/stable/linear_learner.htmlsagemaker.LinearLearnerPredictor), this predictor expects an `ndarray` of input features and r...
# test one prediction test_x_np = test_features.astype('float32') result = linear_predictor.predict(test_x_np[0]) print(result)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Helper function for evaluationThe provided function below, takes in a deployed predictor, some test features and labels, and returns a dictionary of metrics; calculating false negatives and positives as well as recall, precision, and accuracy.
# code to evaluate the endpoint on test data # returns a variety of model metrics def evaluate(predictor, test_features, test_labels, verbose=True): """ Evaluate a model on a test set given the prediction endpoint. Return binary classification metrics. :param predictor: A prediction endpoint :para...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Test ResultsThe cell below runs the `evaluate` function. The code assumes that you have a defined `predictor` and `test_features` and `test_labels` from previously-run cells.
print('Metrics for simple, LinearLearner.\n') # get metrics for linear predictor metrics = evaluate(linear_predictor, test_features.astype('float32'), test_labels, verbose=True) # verbose means we'll print out the metrics
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity