code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import matplotlib.pyplot as plt import re import cv2 import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from wordcloud import WordCloud import stylecloud from IPython.display import Image df = pd.read_csv("Greys Apriyani-1000-tweets.csv") df.head(10) df["Text"][2] pattern_mention = "(@[a-z]+).*?" pattern_rt = ".*?(RT ).*?" mention, rt = [], [] for text in df["Text"]: temp = re.findall(pattern_mention, text, re.IGNORECASE) mention.append(temp) if re.match(pattern_rt, text): rt.append(1) else: rt.append(0) df["Mention"] = mention df["RT"] = rt df.head(10) # remove punctuation clean = [] for text in df["Text"]: tokens = word_tokenize(text) words = [word for word in tokens if word.isalpha()] final = re.sub(".*?(RT ).*?", '', " ".join(words), flags=re.IGNORECASE) final = re.sub(" grey | greys | greysia | polii ", ' greyspolii ', final, flags=re.IGNORECASE) final = re.sub(" apriyani rahayu | apri | rahayu ", ' apriyani ', final, flags=re.IGNORECASE) final = re.sub(" greyspoliiapriyani ", ' greyspolii apriyani ', final, flags=re.IGNORECASE) final = re.sub("badmintontalk", '', final, flags=re.IGNORECASE) clean.append(final) df["Text_clean"] = clean df.head(10) # + # generate wordcloud wordcloud = WordCloud(width = 800, height = 800, background_color ='white', min_font_size = 10).generate(" ".join(clean)) # plot the WordCloud image plt.figure(figsize = (8, 8), facecolor = None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad = 0) plt.show() # - name = "GreyAp-union-rose.png" stylecloud.gen_stylecloud(text=" ".join(clean).lower(), output_name=name,icon_name= "fab fa-twitter", palette="cartocolors.diverging.TealRose_7", background_color="black") Image(filename=name) name = "GreyAp-ID.png" stylecloud.gen_stylecloud(text=" ".join(clean).lower(), output_name=name,icon_name= "fab fa-twitter", colors=["red", "white"], background_color="black") Image(filename=name) name = "GreyAp-union-IDflag.png" stylecloud.gen_stylecloud(text=" ".join(clean).lower(), output_name=name,icon_name= "fas fa-flag", colors=["red", "white"], background_color="black") Image(filename=name) name = "GreyAp-ID-rocket.png" stylecloud.gen_stylecloud(text=" ".join(clean).lower(), output_name=name,icon_name= "fas fa-rocket", colors=["red", "white"], background_color="black") Image(filename=name)
analysis-GreyAp.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import k3d import k3d.platonic as platonic import math import numpy as np def test(plot): colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff] for j in range(5): meshes = [ platonic.Dodecahedron().mesh, platonic.Cube().mesh, platonic.Icosahedron().mesh, platonic.Octahedron().mesh, platonic.Tetrahedron().mesh ] for i, obj in enumerate(meshes): rad = math.radians(i / len(meshes) * 360) radius = 3.5 obj.transform.translation = [math.sin(rad) * radius, math.cos(rad) * radius, 2*j] obj.color = colors[i] plot += obj plot.render() # - plot = k3d.plot() plot.display() plot.auto_rendering = True test(plot) # + while plot.objects: plot -= plot.objects[-1] plot.render() # - test(plot) plot.auto_rendering = False while len(plot.objects) > 2: plot -= plot.objects[-1] plot.render() import numpy as np for i in range(10): plot += k3d.points(np.random.randn(1,3).astype(np.float32)) plot.camera = [-0.9639876204909027, -23.61169267956684, i, 0, 0.334220290184021, 4, 0.007512009764659415, 0.3054834418666324, 0.9521677564665881] plot.render()
examples/auto_rendering.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This notebook compares various Factorization Machines implementations. # # I - Factorization Machines # The dataset used here is [MovieLens 100K](https://grouplens.org/datasets/movielens/). # %load_ext watermark # %watermark --python --machine --packages creme,numpy,pandas,sklearn,xlearn --datename # ## LibFM # Download and uncompress [`libfm`](http://www.libfm.org/) into the working directory. # + import os import shutil import tarfile import urllib archive = 'libfm.tar.gz' with urllib.request.urlopen('http://www.libfm.org/libfm-1.42.src.tar.gz') as r, open(archive, 'wb') as f: shutil.copyfileobj(r, f) tar = tarfile.open(archive, 'r:gz') tar.extractall('.') tar.close() os.remove(archive) libfm_dir = 'libfm-1.42.src' # - # Compile the tools. # + magic_args="-s \"$libfm_dir\"" language="bash" # cd $1 # make all # - # Let's prepare our dataset to [`libfm`](http://www.libfm.org/) format. # + import pandas as pd from creme import datasets def merge_X_y(x, y): x['y'] = y return x ml_100k = [merge_X_y(x, y) for x, y in datasets.MovieLens100K()] ml_100k = pd.DataFrame(ml_100k) ml_100k = ml_100k[['user', 'item', 'gender', 'occupation', 'y']] ml_100k.head() # - # Perform a 80/20 train test split and one hot encode categorical features. # + from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder X_train, X_test, y_train, y_test = train_test_split(ml_100k.drop(columns='y'), ml_100k[['y']], test_size=0.2, random_state=17) ohe = OneHotEncoder(handle_unknown='ignore') X_train = ohe.fit_transform(X_train) X_test = ohe.transform(X_test) # - # Save the data to text files ready to use with [`libfm`](http://www.libfm.org/). # + import numpy as np from sklearn.datasets import dump_svmlight_file train_file, test_file = 'libfm_train.txt', 'libfm_test.txt' with open(train_file, 'wb') as f: dump_svmlight_file(X_train, y_train.values.squeeze(), f=f) with open(test_file, 'wb') as f: dump_svmlight_file(X_test, np.zeros(len(y_test)), f=f) pred_file = 'libfm_pred.txt' # - # Use [`libfm`](http://www.libfm.org/) to train a model and predict the test set. # + magic_args="-s \"$libfm_dir\" \"$train_file\" \"$test_file\" \"$pred_file\"" language="bash" # cd $1 # ./bin/libFM -task r -dim '1,1,10' -method sgd -iter 1 -learn_rate 0.01 -init_stdev 0.1 -regular '0,0,0' -train ../$2 -test ../$3 -out ../$4 # - # Load [`libfm`](http://www.libfm.org/) predictions into memory and compute MAE and RMSE scores. # + from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error libfm_pred = pd.read_csv(pred_file, names='y') print(f'LibFM MAE: {mean_absolute_error(y_test, libfm_pred):.4f}') print(f'LibFM RMSE: {mean_squared_error(y_test, libfm_pred) ** 0.5:.4f}') # - # Clean up the working directory. # + to_remove = [train_file, test_file, pred_file] for path in to_remove: os.remove(path) shutil.rmtree(libfm_dir) # - # ## Creme # Let's do the same thing with [`creme`](https://MaxHalford.github.io/index.html) now! # + from creme import facto from creme import meta from creme import optim from creme import stream X_train, X_test, y_train, y_test = train_test_split(ml_100k.drop(columns='y'), ml_100k[['y']], test_size=0.2, random_state=17) fm_params = { 'n_factors': 10, 'weight_optimizer': optim.SGD(0.01), 'latent_optimizer': optim.SGD(0.01), 'l1_weight': 0., 'l2_weight': 0., 'l1_latent': 0., 'l2_latent': 0., 'intercept': 0., 'intercept_lr': 0.01, 'weight_initializer': optim.initializers.Zeros(), 'latent_initializer': optim.initializers.Normal(mu=0., sigma=0.1, random_state=85), } model = meta.PredClipper( regressor=facto.FMRegressor(**fm_params), y_min=1, y_max=5 ) for x, y in stream.iter_pandas(X_train, y_train.values.squeeze()): model.fit_one(x, y) creme_pred = [model.predict_one(x) for x, _ in stream.iter_pandas(X_test)] print(f'Creme MAE: {mean_absolute_error(y_test, creme_pred):.4f}') print(f'Creme RMSE: {mean_squared_error(y_test, creme_pred) ** 0.5:.4f}') # - # ## Results # | FM - MovieLens100K | MAE | RMSE | # |:-------------------|:--------:|:--------:| # | LibFM | 0.7604 | 0.9689 | # | Creme | 0.7598 | 0.9727 | # # II - Field-aware Factorization Machines # The dataset used here is a 1% subsampling from [Criteo's challenge](https://www.kaggle.com/c/criteo-display-ad-challenge) built by [`libffm`](https://github.com/ycjuan/libffm). Clic [here](https://drive.google.com/uc?export=download&confirm=v1vT&id=1HZX7zSQJy26hY4_PxSlOWz4x7O-tbQjt) to download it from their Google drive, then move it into the working directory. Let's uncompress it now. # + import zipfile archive = 'libffm_toy.zip' with zipfile.ZipFile(archive, 'r') as zf: zf.extractall('.') os.remove(archive) # - # ## LibFFM # Download and uncompress [`libffm`](https://github.com/ycjuan/libffm) into the working directory. # + archive = 'libffm.zip' with urllib.request.urlopen('https://github.com/ycjuan/libffm/archive/master.zip') as r, open(archive, 'wb') as f: shutil.copyfileobj(r, f) with zipfile.ZipFile(archive, 'r') as zf: zf.extractall('.') os.remove(archive) libffm_dir = 'libffm-master' # - # Compile the tools. # + magic_args="-s \"$libffm_dir\"" language="bash" # cd $1 # make # - # Use [`libffm`](https://github.com/ycjuan/libffm) to train a model and predict the test set. train_file = 'libffm_toy/criteo.tr.r100.gbdt0.ffm' test_file = 'libffm_toy/criteo.va.r100.gbdt0.ffm' model_file = 'libffm_model' pred_file = 'libffm_pred' # + magic_args="-s \"$train_file\" \"$test_file\" \"$model_file\" \"$pred_file\"" language="bash" # cd libffm-master # ./ffm-train -l 0.0 -k 10 -t 1 -r 0.01 -s 4 ../$1 ../$3 # ./ffm-predict ../$2 ../$3 ../$4 # - # Load [`libffm`](https://github.com/ycjuan/libffm) predictions into memory and compute Accuracy, Log loss and ROC AUC scores. # + from sklearn.metrics import accuracy_score from sklearn.metrics import log_loss from sklearn.metrics import roc_auc_score y_test = pd.read_csv(test_file, sep=' ', names=['y_true'] + [i for i in range(39)], usecols=['y_true']) libffm_pred = pd.read_csv(pred_file, names=['y_hat']) print(f'LibFFM Accuracy: {accuracy_score(y_test, libffm_pred > .5):.4f}') print(f'LibFFM Log loss: {log_loss(y_test, libffm_pred):.4f}') print(f'LibFFM ROC AUC: {roc_auc_score(y_test, libffm_pred):.4f}') # - # Clean up the working directory. # + os.remove(model_file) os.remove(pred_file) shutil.rmtree(libffm_dir) # - # ## xLearn # Use [`xlearn`](https://xlearn-doc.readthedocs.io/en/latest/index.html) to train a model and predict the test set. # + import xlearn as xl xlearn_model = xl.create_ffm() xlearn_model.setSigmoid() xlearn_model.setTrain(train_file) xlearn_model.disableNorm() # Disable instance-wise normalization xlearn_params = { 'task': 'binary', 'k': 10, 'epoch': 1, 'opt': 'sgd', 'lr': 0.01, 'lambda': 0.0, 'nthread': 4 } model_file = 'xlearn_model' pred_file = 'xlearn_pred' xlearn_model.fit(xlearn_params, model_file) xlearn_model.setTest(test_file) xlearn_model.predict('xlearn_model', pred_file) # - # Load [`xlearn`](https://xlearn-doc.readthedocs.io/en/latest/index.html) predictions into memory and compute Accuracy, Log loss and ROC AUC scores. # + xlearn_pred = pd.read_csv(pred_file, names=['y_hat']) print(f'xLearn Accuracy: {accuracy_score(y_test, xlearn_pred > .5):.4f}') print(f'xLearn Log loss: {log_loss(y_test, xlearn_pred):.4f}') print(f'xLearn ROC AUC: {roc_auc_score(y_test, xlearn_pred):.4f}') # - # Clean up the working directory. os.remove(model_file) os.remove(pred_file) # ## Creme # Format data in order to be compatible with [`creme`](https://MaxHalford.github.io/index.html). # + def load_criteo_data(filepath): X = pd.read_csv(filepath, sep=' ', names=['y'] + [str(i) for i in range(39)]) y = X[['y']].copy() X = X.drop(columns='y').applymap(lambda x: x.split(':')[1]) return X, y X_train, y_train = load_criteo_data(train_file) X_test, y_test = load_criteo_data(test_file) # - # Use [`creme`](https://MaxHalford.github.io/index.html) to train a model and predict the test set. # + ffm_params = { 'n_factors': 10, 'weight_optimizer': optim.SGD(0.01), 'latent_optimizer': optim.SGD(0.01), 'l1_weight': 0., 'l2_weight': 0., 'l1_latent': 0., 'l2_latent': 0., 'intercept': 0., 'intercept_lr': 0.01, 'weight_initializer': optim.initializers.Zeros(), 'latent_initializer': optim.initializers.Normal(mu=0., sigma=0.1, random_state=85), } model = facto.FFMClassifier(**ffm_params) for x, y in stream.iter_pandas(X_train, y_train.values.squeeze()): model.fit_one(x, y) creme_pred = [model.predict_proba_one(x)[True] for x, _ in stream.iter_pandas(X_test)] creme_pred = pd.Series(creme_pred) print(f'Creme Accuracy: {accuracy_score(y_test, creme_pred > .5):.4f}') print(f'Creme Log loss: {log_loss(y_test, creme_pred):.4f}') print(f'Creme ROC AUC: {roc_auc_score(y_test, creme_pred):.4f}') # - # Clean up the working directory. shutil.rmtree('libffm_toy') # ## Results # | FFM - Criteo subsampled | Accuracy | Log loss | ROC AUC | # |:------------------------|:--------:|:--------:|:-------:| # | LibFFM | 0.7480 | 0.5288 | 0.6914 | # | xLearn | 0.7656 | 0.5409 | 0.7397 | # | Creme | 0.7551 | 0.5134 | 0.7422 |
benchmarks/Factorization machines.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import matplotlib.pyplot as plt from models import LinearRegression # %matplotlib inline # - plt.style.use("grayscale") plt.style.use("seaborn-whitegrid") gray = (150/255,150/255,150/255) # 以下のシステムからデータをランダムに生成する # $$ # \beta_1 \sim \mathcal{N}(0, 1) \\ # \beta_2 \sim \mathcal{N}(0, 1) \\ # \boldsymbol{x}_n \sim \mathcal{N}(\bf{0}, \bf{\Sigma}), # \quad \bf{\Sigma} = # \begin{bmatrix} # 1 & \rm{cov} \\ # \rm{cov} & 1 \\ # \end{bmatrix}\\ # y_n \sim \mathcal{N}(\boldsymbol{\beta}^T \boldsymbol{x}_n, 0.1)\\ # $$ # + N = 1000 cov = 0.1 beta = np.random.randn(2) X = np.random.multivariate_normal(mean=[0,0], cov=[[1,cov],[cov,1]], size=N) y = X@beta + np.random.normal(scale=np.sqrt(0.1), size=N) # - # # 完全なデータによる回帰での推定バイアス(OLS) def plot_hist(ax, data, title, bins=None, label=None, alpha=None, color=None): ax.grid(color=gray) ax.hist(data, bins=bins, label=label, alpha=alpha, color=color) ax.set_title(title) # + n_iter = 10000 rate_sample = 0.5 sample_size = int(N*rate_sample) print("サンプルサイズ:{}".format(sample_size)) beta_comp = np.empty((n_iter, 2)) for n in range(n_iter): sample = np.random.choice(range(N), size=sample_size) model = LinearRegression(y=y[sample], Phi=X[sample]) model.fit_OLS() beta_comp[n] = model.beta_OLS.flatten() fig = plt.figure(figsize=(10, 5)) ax1 = fig.add_subplot(121) plot_hist(ax1, beta_comp[:,0]-beta[0], "estimation errores of beta 1", alpha=0.8) ax2 = fig.add_subplot(122) plot_hist(ax2, beta_comp[:,1]-beta[1], "estimation errores of beta 2", alpha=0.8) plt.savefig("../draft/img/EstimationBias(unbiased_estimation).png", dpi=300) plt.show() # - # # 不完全なデータによる回帰での推定バイアス(OLS) # + n_iter = 1000 rate_sample = 0.5 sample_size = int(N*rate_sample) print("サンプルサイズ:{}".format(sample_size)) beta_incomp = np.empty((n_iter, 2)) for n in range(n_iter): sample = np.random.choice(range(N), size=sample_size) model = LinearRegression(y=y[sample], Phi=X[sample,0].reshape((-1,1))) model.fit_OLS() beta_incomp[n,0] = model.beta_OLS.flatten() model = LinearRegression(y=y[sample], Phi=X[sample,1].reshape((-1,1))) model.fit_OLS() beta_incomp[n,1] = model.beta_OLS.flatten() fig = plt.figure(figsize=(10, 5)) ax1 = fig.add_subplot(121) plot_hist(ax1, beta_comp[:,0]-beta[0], "estimation errores of beta 1", label="complete", alpha=0.8) plot_hist(ax1, beta_incomp[:,0]-beta[0], "estimation errores of beta 1", label="incomplete", alpha=0.8) ax1.legend() ax2 = fig.add_subplot(122) plot_hist(ax2, beta_comp[:,1]-beta[1], "estimation errores of beta 2", label="complete", alpha=0.8) plot_hist(ax2, beta_incomp[:,1]-beta[1], "estimation errores of beta 2", label="incomplete", alpha=0.8) ax2.legend() plt.savefig("../draft/img/OmittedVariableBias.png", dpi=300) plt.show() # -
programs/OmitttedVariableBias.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: coe-dmpnn-tl-selfies # language: python # name: coe-dmpnn-tl-selfies # --- # + # #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on sep 1 2020 SHAP analysis for a fully trained RF model. @author: <NAME> """ import numpy as np import math import matplotlib import matplotlib.pyplot as plt import pandas as pd import seaborn as sn from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor import sklearn.ensemble import operator import warnings from sklearn.exceptions import DataConversionWarning import pickle import sys import shap from set_figure_defaults import FigureDefaults def fetch_pickle(filename): """ Fetches any variable saved into a picklefile with the given filename. Parameters: filename (str): filename of the pickle file Returns: variable (any pickle compatible type): variable that was saved into the picklefile. """ with open(filename, 'rb') as picklefile: variable = pickle.load(picklefile) return variable def fetch_csv(filename, index_col=0): """ Fetches any variable saved into a picklefile with the given filename. Parameters: filename (str): filename of the pickle file Returns: variable (any pickle compatible type): variable that was saved into the picklefile. """ variable = pd.read_csv(filename+'.csv', index_col=index_col) return variable # - print(sys.path) shap.initjs() # + # This is the RF regressor trained with the full train dataset. RF_Regressor = fetch_pickle('./Results/RF_regressor_opt_seed3') # Opt. descriptors. descriptors = ['MSD', 'MaxDD', 'TI2_L', 'MATS4v', 'MATS4i', 'P_VSA_MR_5', 'P_VSA_MR_6', 'TDB06s', 'RDF040m', 'Mor20m', 'Mor25m', 'Mor31m', 'Mor10v', 'Mor20v', 'Mor25v', 'Mor26s', 'R7u', 'H-046', 'H-047', 'SHED_AL', 'ALOGP'] # Molecules. dataset = fetch_csv('./Data/dataset_outliers_dropped') X_train = fetch_csv('./Data/Downselection_data_files/x_opt_train_seed3', index_col=None) y_train = fetch_csv('./Data/Downselection_data_files/y_opt_train_seed3').iloc[:,[-1]] # Dropping smiles X_test = fetch_csv('./Data/Downselection_data_files/x_opt_test_seed3', index_col=None) y_test = fetch_csv('./Data/Downselection_data_files/y_opt_test_seed3').iloc[:,[-1]] # Dropping smiles print(X_test.shape) print(y_test.shape) print(X_train.shape) print(y_train.shape) print('These should be the same:') print(X_test.columns) print(X_train.columns) # + # just plotting the RF_Feature importance ranking here again # easy to compare against SHAP plots importances = RF_Regressor.feature_importances_ print(len(importances)) indices = np.argsort(importances) features = X_train.columns #indices = indices[0:30] plt.figure(figsize=(6,8.9)) #plt.title('COE Feature importances') plt.barh(range(len(indices)), importances[indices], color='k', align='center') plt.yticks(range(len(indices)), [features[i] for i in indices], fontsize=12) plt.xticks([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08], fontsize=12) plt.xlabel('Relative importance values', fontsize=12) plt.ylabel('Molecular descriptor in Opt. fingerprint', fontsize=12) plt.tight_layout() plt.savefig('./Results/Final RF feature importances.pdf') plt.savefig('./Results/Final RF feature importances.svg') plt.savefig('./Results/Final RF feature importances.png') plt.show() # - explainer = shap.TreeExplainer(RF_Regressor) # + # this first plot is basic shap plot with bars showing average shap value in each feature # similar to feature importance ranking above shap_values = explainer.shap_values(X_train) ax =shap.summary_plot(shap_values, X_train, plot_type="bar", title='Train', max_display=30, show=False, color='k') plt.savefig('./Results/Final SHAP feature importances - bars.pdf') plt.savefig('./Results/Final SHAP feature importances - bars.svg') plt.savefig('./Results/Final SHAP feature importances - bars.png') ax = plt.gca() labels = [l.get_text() for l in ax.get_yticklabels()] values = [rect.get_width() for rect in ax.patches] df = pd.DataFrame({'Labels': labels, 'Values': values}) print(df) # + ######################################################################################################## # + # second plot is shap plot with scattering of each data point's shap value # Feature importance: Variables are ranked in descending order. # Impact: The horizontal single data point location shows whether the effect # of that value is associated with a higher or lower prediction. # Original value: Color shows whether that variable is high (in red) or low (in blue) for that observation. # Correlation: if lots of red in X+ axis and lots of blue in X- axis, then feature is positively correlated. vise versa. #shap_values = explainer.shap_values(X_test) #shap.summary_plot(shap_values, X_test, max_display = 50) shap_values = explainer.shap_values(X_train) shap.summary_plot(shap_values, X_train, max_display = 50, show=False, cmap='copper', plot_size=(6,6), sort=False) plt.tight_layout() plt.savefig('./Results/Final SHAP feature importances - points.pdf') plt.savefig('./Results/Final SHAP feature importances - points.svg') plt.savefig('./Results/Final SHAP feature importances - points.png', dpi=300) plt.show() # Pick descriptor index and limit from the plot and insert it here. chosen_descriptor = 'ALOGP' upper_lim = -0.1 print('SHAP(' + chosen_descriptor + ')<' + str(upper_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) pd.options.display.max_colwidth = 200 print(dataset.loc[y_train[shap_values[:,chosen_index]<upper_lim].index,['no', 'name', 'log2mic']]) # + ######################################################################################################## # Pick descriptor index and limit from the plot and insert it here. chosen_descriptor = 'Mor20m' lower_lim = 0.18 print('SHAP(' + chosen_descriptor + ')>' + str(lower_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]>lower_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) upper_lim = -0.15 print('SHAP(' + chosen_descriptor + ')<' + str(upper_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]<upper_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) # Pick descriptor index and limit from the plot and insert it here. chosen_descriptor = 'Mor10v' lower_lim = 0 print('SHAP(' + chosen_descriptor + ')>' + str(lower_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]>lower_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) upper_lim = 0 print('SHAP(' + chosen_descriptor + ')<' + str(upper_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]<upper_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) # Pick descriptor index and limit from the plot and insert it here. chosen_descriptor = 'Mor31m' lower_lim = 0.0 print('SHAP(' + chosen_descriptor + ')>' + str(lower_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]>lower_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) upper_lim = -0.0 print('SHAP(' + chosen_descriptor + ')<' + str(upper_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]<upper_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) # Pick descriptor index and limit from the plot and insert it here. chosen_descriptor = 'Mor26m' lower_lim = 0.1 print('SHAP(' + chosen_descriptor + ')>' + str(lower_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]>lower_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) upper_lim = -0.1 print('SHAP(' + chosen_descriptor + ')<' + str(upper_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]<upper_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) # Pick descriptor index and limit from the plot and insert it here. chosen_descriptor = 'ALOGP' lower_lim = 0.0 print('SHAP(' + chosen_descriptor + ')>' + str(lower_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]>lower_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) upper_lim = -0.0 print('SHAP(' + chosen_descriptor + ')<' + str(upper_lim) + ' molecules:') chosen_index = X_train.columns.get_loc(chosen_descriptor) #print(shap_values[:,chosen_index]>lower_lim) print(dataset.loc[y_train[shap_values[:,chosen_index]<upper_lim].index,['no', 'name', 'log2mic', chosen_descriptor]]) # + # this is a collective force plot that I recommend for this study # It collectively shows how much each feature can contribute to increasing/decreasing objective values # its uniqueness is in the "force" nature, almost putting data in a flowing tube, where two powers of +/- correlation # are clashing with different features backing them up # X-axis is how many data points, which you can sample reorder by similarity # for each X, a force plot (column of shap values from different features, distinguished by red/blue color) is plotted # stack these up horizontally to get the collective force plot # Y-axis is predicted output objective value usually, and can be highlighted # features that push predictions higher are in red, push to lower are in blue # to understand more # https://www.nature.com/articles/s41551-018-0304-0.epdf?author_access_token=<KEY> <PASSWORD>xyss1N4y<PASSWORD>5_<PASSWORD>%3D%3D #shap_values = explainer.shap_values(X_test) #shap.force_plot(explainer.expected_value, shap_values, X_test) shap_values = explainer.shap_values(X_train) shap.force_plot(explainer.expected_value, shap_values, X_train) #print(X_train.iloc[67,:]) # - shap_values = explainer.shap_values(X_test) shap.force_plot(explainer.expected_value, shap_values, X_test) # + # SHAP analysis for molecules with low and high MIC. X_train_lowmic = X_train[y_train.values<3] shap_values = explainer.shap_values(X_train_lowmic) shap.summary_plot(shap_values, X_train_lowmic, max_display = 50) shap.force_plot(explainer.expected_value, shap_values, X_train_lowmic) X_train_highmic = X_train[y_train.values>6] shap_values = explainer.shap_values(X_train_highmic) shap.summary_plot(shap_values, X_train_highmic, max_display = 50) shap.force_plot(explainer.expected_value, shap_values, X_train_highmic) # - shap_interaction_values = explainer.shap_interaction_values(X_train) shap.summary_plot(shap_interaction_values, X_train) # + mystyle = FigureDefaults('nature_comp_mat_sc') mystyle.size_fraction_x = 0.4 fig,ax = plt.subplots() shap.dependence_plot( ("ALOGP", "ALOGP"), shap_interaction_values, X_train, display_features=X_train, cmap='copper', show=False, ax=ax ) plt.show() xdata=np.array(ax.collections[0].get_offsets()) ydata=np.ravel(xdata[:,1]) xdata=np.ravel(xdata[:,0]) xlabel=ax.collections[0].get_label() #fig = plt.gcf() #fig.set_size_inches(plt.rcParams['figure.figsize'][0],plt.rcParams['figure.figsize'][1]) #ax = plt.gca() #print(ax) #line = ax.lines #print(line) #color = np.array(sns.color_palette())[0,:] # sns.set_style('ticks') # sns.relplot(x=x_variable, y="RMSE", kind="line", ci="sd", data=ranking_scores, # height=plt.rcParams['figure.figsize'][0], # aspect=plt.rcParams['figure.figsize'][1]/plt.rcParams['figure.figsize'][0], # color=color, style='ticks') sn.set_style('ticks') sn.set_palette('copper') ax=sn.scatterplot(x=xdata, y=ydata, #height=plt.rcParams['figure.figsize'][0], #aspect=plt.rcParams['figure.figsize'][1]/plt.rcParams['figure.figsize'][0])#, color='k')#np.array(sn.color_palette())[4,:]) #palette='copper') #{'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': 'white', 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': 'white'} ax.set_xlabel('ALOGP') ax.set_ylabel('SHAP main effect value for ALOGP') #handles, labels = ax.get_legend_handles_labels() #plt.legend(handles[:1], labels[:1], loc='upper right', frameon=True, markerscale=0.5, borderpad=0.2, # labelspacing=0.2, borderaxespad=0.3, handlelength=1) plt.tight_layout() plt.savefig('./Results/Train Opt fingerprint seed 3 - AlogP.pdf') plt.savefig('./Results/Train Opt fingerprint seed 3 - AlogP.svg') plt.savefig('./Results/Train Opt fingerprint seed 3 - AlogP.png', dpi=300) plt.show() shap.dependence_plot( ("Mor31m", "Mor31m"), shap_interaction_values, X_train, display_features=X_train ) shap.dependence_plot( ("MSD", "MSD"), shap_interaction_values, X_train, display_features=X_train ) shap.dependence_plot( ("Mor20v", "Mor20v"), shap_interaction_values, X_train, display_features=X_train ) shap.dependence_plot( ("H-047", "H-047"), shap_interaction_values, X_train, display_features=X_train ) # - # High - low - high combination leads to low MIC according to the model? Morse values require more investigation. print(np.max(X_train.loc[:, ['Mor31m', 'Mor20m', 'Mor20v']]))#'Mor11m']])) print(np.min(X_train.loc[:, ['Mor31m', 'Mor20m', 'Mor20v']])) X_train.loc[:, ['Mor31m', 'Mor20m', 'Mor20v']]
SHAP for RF analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Using Matplotlib in Jupyter Notebook # !pip install matplotlib # %matplotlib inline import matplotlib.pyplot as plt # # Plot basics # # https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py # # https://matplotlib.org/tutorials/introductory/sample_plots.html#sphx-glr-tutorials-introductory-sample-plots-py import numpy as np # ### 1. Line plot # + # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) plt.plot(t, s) plt.show() # + # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, np.cos(t), 'bs', t, np.sin(t), 'g') plt.show() # - # ### 2. Scatter plot # + # Fixing random state for reproducibility np.random.seed(19680801) N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = (30 * np.random.rand(N))**2 # 0 to 15 point radii plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show() # - # ### 3. Histogram # + np.random.seed(19680801) # example data mu = 100 # mean of distribution sigma = 15 # standard deviation of distribution x = mu + sigma * np.random.randn(437) num_bins = 50 plt.hist(x, num_bins, density=1) plt.show() # - # ### 4. Pie chat # + # Pie chart, where the slices will be ordered and plotted counter-clockwise: labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) plt.show() # - # # Heatmap # + harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]]) plt.imshow(harvest) plt.show() # + vegetables = ["cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley"] farmers = ["<NAME>", "Upland Bros.", "<NAME>", "Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."] harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]]) fig, ax = plt.subplots() im = ax.imshow(harvest) # We want to show all ticks... ax.set_xticks(np.arange(len(farmers))) ax.set_yticks(np.arange(len(vegetables))) # ... and label them with the respective list entries ax.set_xticklabels(farmers) ax.set_yticklabels(vegetables) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. for i in range(len(vegetables)): for j in range(len(farmers)): text = ax.text(j, i, harvest[i, j], ha="center", va="center", color="w") ax.set_title("Harvest of local farmers (in tons/year)") fig.tight_layout() plt.show() # -
viz1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # TimeAtlas import timeatlas as ta import pandas as pd import numpy as np # ## Load the data s = pd.read_csv("../data/bbdata-weather/4652.csv") s = pd.DataFrame(data=s["value"].values, index=pd.to_datetime(s["timestamp"]).values) s.index = s.index.round("S") ts = ta.TimeSeries(s) type(ts[:5].series.index[1]) # ## Plot the data ts.plot() ta.plots.status(ts); # ## Select the data ts = ts["01-2018"] ts.plot() # ### Check the data quality ta.plots.line(ts.resolution()); # ## Get some statistics ts.boundaries() ts.duration() ts.frequency() == None # Because it doesn't comply with Pandas offset aliases: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases # So, let's resample: ts = ts.resample("15min", method="pad") ts.frequency() ts.min() ts.max() ts.mean() ts.kurtosis() ts.skewness() # ## Transform the data # ### Delete the values ts.empty()[:5] # ### Apply functions on a single time series # with one argument ts.apply(lambda x: x**2).plot() # ### Apply functions between time series # with two argument (to mix values between two timeseries for instance) ts.apply(lambda x,y: 0 - x**2 + y, ts).plot() # ## Generate some data ts2 = ta.TimeSeries.create("01-2020", "02-2020", "H") ts2[:5] ts2 = ts2.fill(np.random.randint(0,100,len(ts2))) ts2[:5] ts2.plot() # ## Trim empty values ts2.series[:67] = None ts2.series[-123:] = None ts2.plot() ts2.trim().plot() # ## Add Metadata # + pycharm={"name": "#%%\n"} from timeatlas import Metadata, types # You can use some typed metadata object my_unit = types.Unit("degree", "°C", "float") my_sensor = types.Sensor(4652, "HB/outside/weather/temperature") # Or use Python dictionaries my_location = { "building" : "Blue Factory", "floor" : "12", "room" : "22C" } my_coordinates = { "lat" : 46.796611, "lon" : 7.147563 } my_dict = { "unit": my_unit, "sensor": my_sensor, "location": my_location, "coordinates": my_coordinates } # Create the Metadata object my_meta = Metadata(my_dict) # + pycharm={"name": "#%% Create a TimeSeries\n"} ts.metadata = my_meta ts.plot() # + [markdown] pycharm={"name": "#%% md\n"} # ## Model the data # - # ### with Facebook Prophet m1 = ta.models.Prophet() m1.fit(ts) pts1 = m1.predict("7 day") pts1.plot() ta.plots.prediction(pts1, ts["2018-01":]); # ### Or just make a linear regression... m2 = ta.models.LinearRegression() m2.fit(ts) pts2 = m2.predict(ts) ta.plots.prediction(pts2, ts["2018-01":]);
notebooks/presentation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.7.11 64-bit (''bgflow_env'': conda)' # name: python3 # --- from simtk import openmm, unit from simtk.openmm import app import mdtraj as md import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import LogNorm import pickle def compute_phi_psi_ala2(trajectory): phi_atoms = [4, 6, 8, 14] phi = md.compute_dihedrals(trajectory, indices=[phi_atoms])[:, 0] psi_atoms = [6, 8, 14, 16] psi = md.compute_dihedrals(trajectory, indices=[psi_atoms])[:, 0] return phi, psi def compute_phi_psi_pro(trajectory): phi_atoms = [4,6,7,9] phi = md.compute_dihedrals(trajectory, indices=[phi_atoms])[:, 0] psi_atoms = [6,7,9,24] psi = md.compute_dihedrals(trajectory, indices=[psi_atoms])[:, 0] return phi, psi def plot_phi_psi(ax, fname, label, molecule='ala2',stride=1, cut=1): if molecule == 'pro': fpath_stub = 'proline' top_file = f'{fpath_stub}/cis_pro.pdb' system_file = f'{fpath_stub}/noconstraints_xmlsystem.txt' n_atoms = 26 elif molecule == 'ala2': fpath_stub = 'Alanine_dipeptide' top_file = 'Alanine_dipeptide/ala2_fromURL.pdb' system_file = 'Alanine_dipeptide/ala2_noconstraints_system.txt' n_atoms = 22 if 'coupled' in fname: traj = md.load(f'Coupled_scheme/Trajectories/{fname}.dcd', top=f'{top_file}', stride=stride) else: traj = md.load(f'{fpath_stub}/Trajectories/{fname}.dcd', top=f'{top_file}', stride=stride) # with open('parameterfile.txt') as f: # parameters = f.read() try: pickleFile = open(f'{fpath_stub}/parameters/parameters{fname}.pkl','rb') parametersdict = pickle.load(pickleFile) temperature = parametersdict['Temperature'] collision_rate = parametersdict['Collision rate'] timestep = parametersdict['Timestep'] try: reportInterval = parametersdict['Report Interval'] except: reportInterval = 'N/A' except: if '1000' in fname: temperature = 1000.0 * unit.kelvin collision_rate = 1.0 / unit.picosecond timestep = 1.0 * unit.femtosecond reportInterval = 2500 elif 'samples' in fname: temperature = 300.0 * unit.kelvin collision_rate = 'N/A' timestep = 'N/A' reportInterval = 'N/A' else: temperature = 300.0 * unit.kelvin collision_rate = 1.0 / unit.picosecond timestep = 'N/A' reportInterval = 'N/A' parameters = f'{temperature}\nCollision rate:{collision_rate}\nTimestep: {timestep}\nReport every {reportInterval} steps' try: time = traj.n_frames*reportInterval*timestep except: time = 'N/A' if molecule == 'ala2': phi, psi = compute_phi_psi_ala2(traj[:round(traj.n_frames*cut)]) elif molecule == 'pro': phi, psi = compute_phi_psi_pro(traj[:round(traj.n_frames*cut)]) bins=np.linspace(-np.pi, np.pi, 50) print('length', label, traj.n_frames) ax.hist2d(phi, psi, bins=bins, norm=LogNorm()) ax.set_xlim(-np.pi, np.pi) ax.set_ylim(-np.pi, np.pi) ax.set_title(label) # try: # ax.set_xlabel(f"$\phi$ \n {parameters}\n Time: {time.value_in_unit(unit.seconds):.3E} s") # except: # ax.set_xlabel(f"$\phi$ \n {parameters} \nTime: {time} s") #ax.set_xlabel(f"$\phi$") ax.set_xlabel("$\phi$") _ = ax.set_ylabel("$\psi$") # + #example - figure 18C-F in thesis fig, axes = plt.subplots(1,5,figsize=(20,4)) plot_phi_psi(axes[0], 'joined_pro_300K_noconstr', 'Constrained MD - 50:50 $\it{cis}$, $\it{trans}$', molecule='pro') plot_phi_psi(axes[1], 'joined_pro_300K_noconstr', 'Constrained MD - 50:50 $\it{cis}$, $\it{trans}$\nframes matched to coupled scheme', molecule='pro', stride=20) plot_phi_psi(axes[2], 'trans80_cis20_300K_noconstr', 'Unconstrained MD\n20:80 $\it{cis}$, $\it{trans}$', molecule='pro', stride=10) plot_phi_psi(axes[3], 'coupled_pro_300K_100psMD', 'Coupled scheme 1000 cycles\n100 ps MD stage', molecule='pro') plot_phi_psi(axes[4], 'unconstrainedMD_300K_2_samplestraj', 'BG samples', molecule='pro') plt.tight_layout() #plt.text() #plt.savefig(f'vary_temp/{fname}.png', bbox_inches="tight") #plt.close() # + import pickle pickleFile = open('Alanine_dipeptide/parameters300K.pkl','rb') pickle.load(pickleFile) # + tsftraj = md.load('Alanine_dipeptide/Trajectories/TSFtraj_full.dcd',top='Alanine_dipeptide/ala2_fromURL.pdb', stride=10) tsftraj.save('Alanine_dipeptide/Trajectories/TSFtraj_stride10.dcd') # - temperature = 300.0 * unit.kelvin collision_rate = 1.0 / unit.picosecond timestep = 1.0 * unit.femtosecond reportInterval = 5000 steps = 5E+6 fname = '300K_1fs_noconstr_long_stride2' #time = (steps*timestep).value_in_unit(unit.nanosecond) parametersdict = {'Collision rate':collision_rate,'Temperature':temperature,'Timestep':timestep,'Report Interval':reportInterval} import pickle f_p = open(f'Alanine_dipeptide/parameters/parameters{fname}.pkl','wb') pickle.dump(parametersdict,f_p) f_p.close
BGflow_examples/Ramachandranplot.ipynb
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] colab_type="text" id="hVHY_ZYxWDph" # # Reformer Efficient Attention: Ungraded Lab # The videos describe two 'reforms' made to the Transformer to make it more memory and compute efficient. The *Reversible Layers* reduce memory and *Locality Sensitive Hashing(LSH)* reduces the cost of the Dot Product attention for large input sizes. This ungraded lab will look more closely at LSH and how it is used in the Reformer model. # # Specifically, the notebook has 3 goals # * review dot-product self attention for reference # * examine LSH based self attention # * extend our understanding and familiarity with Trax infrastructure # # ## Outline # - [Part 1: Trax Efficient Attention classes](#1) # - [Part 2: Full Dot Product Self Attention](#2) # - [2.1 Description](#2.1) # - [2.1.1 our_softmax](#2.1.1) # - [2.2 our simple attend](#2.2) # - [2.3 Class OurSelfAttention](#2.3) # - [Part 3: Trax LSHSelfAttention](#3) # - [3.1 Description](#3.1) # - [3.2 our_hash_vectors](#3.2) # - [3.3 Sorting Buckets](#3.3) # - [3.4 Chunked dot product attention](#3.4) # - [3.5 OurLSHSelfAttention](#3.5) # # %% [markdown] colab_type="text" id="1nhevIw88Vm2" # <a name="1"></a> # ## Part 1.0 Trax Efficient Attention classes # Trax is similar to other popular NN development platforms such as Keras (now integrated into Tensorflow) and Pytorch in that it uses 'layers' as a useful level of abstraction. Layers are often represented as *classes*. We're going to improve our understanding of Trax by locally extending the classes used in the attention layers. We will extend only the 'forward' functions and utilize the existing attention layers as parent classes. The original code can be found at [github:trax/layers/Research/Efficient_attention](https://github.com/google/trax/blob/v1.3.4/trax/layers/research/efficient_attention.py). This link references release 1.3.4 but note that this is under the 'research' directory as this is an area of active research. When accessing the code on Github for review on this assignment, be sure you select the 1.3.4 release tag, the master copy may have new changes.: # <img src = "C4W4_LN2_image11.PNG" height="250" width="250"> # <center><b>Figure 1: Reference Tag 1.3.4 on github</b></center> # # # # While Trax uses classes liberally, we have not built many classes in the course so far. Let's spend a few moments reviewing the classes we will be using. # <img src = "C4W4_LN2_image1.PNG" height="788" width="1561"> # # <center><b>Figure 2: Classes from Trax/layers/Research/Efficient_Attention.py that we will be utilizing.</b></center> # # # # %% [markdown] # Starting on the right in the diagram below you see EfficientAttentionBase. The parent to this class is the base.layer which has the routines used by all layers. EfficientAttentionBase leaves many routines to be overridden by child classes - but it has an important feature in the *Forward* routine. It supports a `use_reference_code` capability that selects implementations that limit some of the complexities to provide a more easily understood version of the algorithms. In particular, it implements a nested loop that treats each *'example, head'* independently. This simplifies our work as we need only worry about matrix operations on one *'example, head'* at a time. This loop calls *forward_unbatched*, which is the child process that we will be overriding. # # On the top left are the outlines of the two child classes we will be using. The SelfAttention layer is a 'traditional' implementation of the dot product attention. We will be implementing the *forward_unbatched* version of this to highlight the differences between this and the LSH implementation. # # Below that is the LSHSelfAttention. This is the routine used in the Reformer architecture. We will override the *forward_unbatched* section of this and some of the utility functions it uses to explore its implementation in more detail. # # The code we will be working with is from the Trax source, and as such has implementation details that will make it a bit harder to follow. However, it will allow use of the results along with the rest of the Trax infrastructure. I will try to briefly describe these as they arise. The [Trax documentation](https://trax-ml.readthedocs.io/en/latest/) can also be referenced. # %% [markdown] # <a name="1.2"></a> # ## Part 1.2 Trax Details # The goal in this notebook is to override a few routines in the Trax classes with our own versions. To maintain their functionality in a full Trax environment, many of the details we might ignore in example version of routines will be maintained in this code. Here are some of the considerations that may impact our code: # * Trax operates with multiple back-end libraries, we will see special cases that will utilize unique features. # * 'Fancy' numpy indexing is not supported in all backend environments and must be emulated in other ways. # * Some operations don't have gradients for backprop and must be ignored or include forced re-evaluation. # # Here are some of the functions we may see: # * Abstracted as `fastmath`, Trax supports multiple backend's such as [Jax](https://github.com/google/jax) and [Tensorflow2](https://github.com/tensorflow/tensorflow) # * [tie_in](https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.tie_in.html): Some non-numeric operations must be invoked during backpropagation. Normally, the gradient compute graph would determine invocation but these functions are not included. To force re-evaluation, they are 'tied' to other numeric operations using tie_in. # * [stop_gradient](https://trax-ml.readthedocs.io/en/latest/trax.fastmath.html): Some operations are intentionally excluded from backprop gradient calculations by setting their gradients to zero. # * Below we will execute `from trax.fastmath import numpy as np `, this uses accelerated forms of numpy functions. This is, however a *subset* of numpy # %% colab={} colab_type="code" id="BGLyG_n_4WhH" tags=[] import os import trax from trax import layers as tl # core building block import jax from trax import fastmath # uses jax, offers numpy on steroids # fastmath.use_backend('tensorflow-numpy') import functools from trax.fastmath import numpy as np # note, using fastmath subset of numpy! from trax.layers import ( tie_in, length_normalized, apply_broadcasted_dropout, look_adjacent, permute_via_gather, permute_via_sort, ) # %% [markdown] # <a name="2"></a> # ## Part 2 Full Dot-Product Self Attention # <a name="1.2"></a> # ### Part 2.1 Description # <img src = "C4W4_LN2_image2.PNG" height="200" width="600"> # # <center><b>Figure 3: Project datapath and primary data structures and where they are implemented</b></center> # # The diagram above shows many of the familiar data structures and operations related to attention and describes the routines in which they are implemented. We will start by working on *our_simple_attend* or our simpler version of the original *attend* function. We will review the steps in performing dot-product attention with more focus on the details of the operations and their significance. This is useful when comparing to LSH attention. Note we will be discussing a single example/head unless otherwise specified. # # <img src = "C4W4_LN2_image3.PNG" height="250" width="700"> # # <center><b>Figure 4: dot-product of Query and Key</b></center> # # The *attend* function receives *Query* and *Key*. As a reminder, they are produced by a matrix multiply of all the inputs with a single set of weights. We will describe the inputs as *embeddings* assuming an NLP application, however, this is not required. This matrix multiply very much like a convolutional network where a set of weights (a filter) slide across the input vectors leaving behind a map of the similarity of the input to the filter. In this case, the filters are the weight matrices $W^Q$ and $W^K$. The resulting maps are Q and K. Q and K have the dimensions of (n_seq, n_q) where n_seq is the number input embeddings and n_q or n_k is the selected size of the Q or K vectors. Note the shading of Q and K, this reflects the fact that each entry is associated with a particular input embedding. You will note later in the code that K is optional. Apparently, similar results can be achieved using Query alone saving the compute and storage associated with K. In that case, the dot-product in *attend* is matmul(q,q). Note the resulting dot-product (*Dot*) entries describe a complete (n_seq,n_seq) map of the similarity of all entries of q vs all entries of k. This is reflected in the notation in the dot-product boxes of $w_n$,$w_m$ representing word_n, word_m. Note that each row of *Dot* describes the relationship of an input embedding, say $w_0$, with every other input. # # %% [markdown] # In some applications some values are masked. This can be used, for example to exclude results that occur later in time (causal) or to mask padding or other inputs. # <img src = "C4W4_LN2_image4.PNG" height="300" width="900"> # # <center><b>Figure 5: Masking</b></center> # # # The routine below *mask_self_attention* implements a flexible masking capability. The masking is controlled by the information in q_info and kv_info. # %% colab={} colab_type="code" id="kDAWq_xMX6C1" def mask_self_attention( dots, q_info, kv_info, causal=True, exclude_self=True, masked=False ): """Performs masking for self-attention.""" if causal: mask = fastmath.lt(q_info, kv_info).astype(np.float32) dots = dots - 1e9 * mask if exclude_self: mask = np.equal(q_info, kv_info).astype(np.float32) dots = dots - 1e5 * mask if masked: zeros_like_kv_info = tie_in(kv_info, np.zeros_like(kv_info)) mask = fastmath.lt(kv_info, zeros_like_kv_info).astype(np.float32) dots = dots - 1e9 * mask return dots # %% [markdown] # A SoftMax is applied per row of the *Dot* matrix to scale the values in the row between 0 and 1. # <img src = "C4W4_LN2_image5.PNG" height="300" width="900"> # # <center><b>Figure 6: SoftMax per row of Dot</b></center> # # %% [markdown] # <a name="2.1.1"></a> # ### Part 2.1.1 our_softmax # %% [markdown] # This code uses a separable form of the softmax calculation. Recall the softmax: # $$ softmax(x_i)=\frac{\exp(x_i)}{\sum_j \exp(x_j)}\tag{1}$$ # This can be alternately implemented as: # $$ logsumexp(x)=\log{({\sum_j \exp(x_j)})}\tag{2}$$ # $$ softmax(x_i)=\exp({x_i - logsumexp(x)})\tag{3}$$ # The work below will maintain a copy of the logsumexp allowing the softmax to be completed in sections. You will see how this is useful later in the LSHSelfAttention class. # We'll create a routine to implement that here with the addition of a passthrough. The matrix operations we will be working on below are easier to follow if we can maintain integer values. So, for tests, we will skip the softmax in some cases. # %% def our_softmax(x, passthrough=False): """ softmax with passthrough""" logsumexp = fastmath.logsumexp(x, axis=-1, keepdims=True) o = np.exp(x - logsumexp) if passthrough: return (x, np.zeros_like(logsumexp)) else: return (o, logsumexp) # %% [markdown] # Let's check our implementation. # %% tags=[] ## compare softmax(a) using both methods a = np.array([1.0, 2.0, 3.0, 4.0]) sma = np.exp(a) / sum(np.exp(a)) print(sma) sma2, a_logsumexp = our_softmax(a) print(sma2) print(a_logsumexp) # %% [markdown] # The purpose of the dot-product is to 'focus attention' on some of the inputs. Dot now has entries appropriately scaled to enhance some values and reduce others. These are now applied to the $V$ entries. # <img src = "C4W4_LN2_image6.PNG" height="300" width="900"> # # <center><b>Figure 7: Applying Attention to $V$</b></center> # # $V$ is of size (n_seq,n_v). Note the shading in the diagram. This is to draw attention to the operation of the matrix multiplication. This is detailed below. # # <img src = "C4W4_LN2_image7.PNG" height="300" width="600"/> # # <center><b>Figure 7: The Matrix Multiply applies attention to the values of V</b></center> # # $V$ is formed by a matrix multiply of the input embedding with the weight matrix $W^v$ whose values were set by backpropagation. The row entries of $V$ are then related to the corresponding input embedding. The matrix multiply weights first column of V, representing a section of each of the input embeddings, with the first row of Dot, representing the similarity of $W_0$ and each word of the input embedding and deposits the value in $Z$ # %% [markdown] # <a name="2.2"></a> # ### Part 2.2 our_simple_attend # In this section we'll work on an implementation of *attend* whose operations you can see in figure 3. It is a slightly simplified version of the routine in [efficient_attention.py](https://github.com/google/trax/blob/v1.3.4/trax/layers/research/efficient_attention.py). We will fill in a few lines of code. The main goal is to become familiar with the routine. You have implemented similar functionality in a previous assignment. # # **Instructions** # **Step 1:** matrix multiply (np.matmul) q and the k 'transpose' kr. # **Step 2:** use our_softmax() to perform a softmax on masked output of the dot product, dots. # **Step 3:** matrix multiply (np.matmul) dots and v. # %% colab={} colab_type="code" id="UGvWTWQ4ExAx" def our_simple_attend( q, k=None, v=None, mask_fn=None, q_info=None, kv_info=None, dropout=0.0, rng=None, verbose=False, passthrough=False, ): """Dot-product attention, with masking, without optional chunking and/or. Args: q: Query vectors, shape [q_len, d_qk] k: Key vectors, shape [kv_len, d_qk]; or None v: Value vectors, shape [kv_len, d_v] mask_fn: a function reference that implements masking (e.g. mask_self_attention) q_info: Query-associated metadata for masking kv_info: Key-associated metadata for masking dropout: Dropout rate rng: RNG for dropout Returns: A tuple (output, dots_logsumexp). The output has shape [q_len, d_v], and dots_logsumexp has shape [q_len]. The logsumexp of the attention probabilities is useful for combining multiple rounds of attention (as in LSH attention). """ assert v is not None share_qk = k is None if share_qk: k = q if kv_info is None: kv_info = q_info if share_qk: k = length_normalized(k) k = k / np.sqrt(k.shape[-1]) # Dot-product attention. kr = np.swapaxes(k, -1, -2) # note the fancy transpose for later.. ## Step 1 ## dots = np.matmul(q, kr ) if verbose: print("Our attend dots", dots.shape) # Masking if mask_fn is not None: dots = mask_fn(dots, q_info[..., :, None], kv_info[..., None, :]) # Softmax. # dots_logsumexp = fastmath.logsumexp(dots, axis=-1, keepdims=True) #original # dots = np.exp(dots - dots_logsumexp) #original ## Step 2 ## # replace with our_softmax() dots, dots_logsumexp = our_softmax(dots, passthrough=passthrough) if verbose: print("Our attend dots post softmax", dots.shape, dots_logsumexp.shape) if dropout > 0.0: assert rng is not None # Dropout is broadcast across the bin dimension dropout_shape = (dots.shape[-2], dots.shape[-1]) keep_prob = tie_in(dots, 1.0 - dropout) keep = fastmath.random.bernoulli(rng, keep_prob, dropout_shape) multiplier = keep.astype(dots.dtype) / tie_in(keep, keep_prob) dots = dots * multiplier ## Step 3 ## # The softmax normalizer (dots_logsumexp) is used by multi-round LSH attn. out = np.matmul(dots, v) if verbose: print("Our attend out1", out.shape) out = np.reshape(out, (-1, out.shape[-1])) if verbose: print("Our attend out2", out.shape) dots_logsumexp = np.reshape(dots_logsumexp, (-1,)) return out, dots_logsumexp # %% colab={"base_uri": "https://localhost:8080/", "height": 202} colab_type="code" id="g1861d--trPg" outputId="58a8974e-e3c8-4ec7-92a0-530df96d6d71" seq_len = 8 emb_len = 5 d_qk = 3 d_v = 4 with fastmath.use_backend("jax"): # specify the backend for consistency rng_attend = fastmath.random.get_prng(1) q = k = jax.random.uniform(rng_attend, (seq_len, d_qk), dtype=np.float32) v = jax.random.uniform(rng_attend, (seq_len, d_v), dtype=np.float32) o, logits = our_simple_attend( q, k, v, mask_fn=None, q_info=None, kv_info=None, dropout=0.0, rng=rng_attend, verbose=True, ) print(o, "\n", logits) # %% [markdown] colab_type="text" id="a61Hs5AgH_fu" # <details> # <summary> # <font size="3"><b> Expected Output </b></font> # </summary> # # **Expected Output** # ``` # Our attend dots (8, 8) # Our attend dots post softmax (8, 8) (8, 1) # Our attend out1 (8, 4) # Our attend out2 (8, 4) # [[0.5606324 0.7290605 0.5251243 0.47101074] # [0.5713517 0.71991956 0.5033342 0.46975708] # [0.5622886 0.7288458 0.52172124 0.46318397] # [0.5568317 0.72234154 0.542236 0.4699722 ] # [0.56504494 0.72274375 0.5204978 0.47231334] # [0.56175965 0.7216782 0.53293145 0.48003793] # [0.56753993 0.72232544 0.5141734 0.46625748] # [0.57100445 0.70785505 0.5325362 0.4590797 ]] # [2.6512175 2.1914332 2.6630518 2.7792363 2.4583826 2.5421977 2.4145055 # 2.5111294]``` # %% [markdown] # <details> # <summary> # <font size="3"><b> completed code for reference </b></font> # </summary> # This notebook is ungraded, so for reference, the completed code follows: # # ``` # def our_simple_attend( # q, k=None, v=None, # mask_fn=None, q_info=None, kv_info=None, # dropout=0.0, rng=None, verbose=False, passthrough=False # ): # """Dot-product attention, with masking, without optional chunking and/or. # # Args: # q: Query vectors, shape [q_len, d_qk] # k: Key vectors, shape [kv_len, d_qk]; or None # v: Value vectors, shape [kv_len, d_v] # mask_fn: a function reference that implements masking (e.g. mask_self_attention) # q_info: Query-associated metadata for masking # kv_info: Key-associated metadata for masking # dropout: Dropout rate # rng: RNG for dropout # # Returns: # A tuple (output, dots_logsumexp). The output has shape [q_len, d_v], and # dots_logsumexp has shape [q_len]. The logsumexp of the attention # probabilities is useful for combining multiple rounds of attention (as in # LSH attention). # """ # assert v is not None # share_qk = (k is None) # if share_qk: # k = q # if kv_info is None: # kv_info = q_info # # if share_qk: # k = length_normalized(k) # k = k / np.sqrt(k.shape[-1]) # # # Dot-product attention. # kr = np.swapaxes(k, -1, -2) #note the fancy transpose for later.. # # ## Step 1 ## # dots = np.matmul(q, kr ) # if verbose: print("Our attend dots", dots.shape) # # # Masking # if mask_fn is not None: # dots = mask_fn(dots, q_info[..., :, None], kv_info[..., None, :]) # # # Softmax. # #dots_logsumexp = fastmath.logsumexp(dots, axis=-1, keepdims=True) #original # #dots = np.exp(dots - dots_logsumexp) #original # ## Step 2 ## # #replace with our_softmax() # dots, dots_logsumexp = our_softmax(dots, passthrough=passthrough) # if verbose: print("Our attend dots post softmax", dots.shape, dots_logsumexp.shape) # # if dropout > 0.0: # assert rng is not None # # Dropout is broadcast across the bin dimension # dropout_shape = (dots.shape[-2], dots.shape[-1]) # keep_prob = tie_in(dots, 1.0 - dropout) # keep = fastmath.random.bernoulli(rng, keep_prob, dropout_shape) # multiplier = keep.astype(dots.dtype) / tie_in(keep, keep_prob) # dots = dots * multiplier # # ## Step 3 ## # # The softmax normalizer (dots_logsumexp) is used by multi-round LSH attn. # out = np.matmul(dots, v) # if verbose: print("Our attend out1", out.shape) # out = np.reshape(out, (-1, out.shape[-1])) # if verbose: print("Our attend out2", out.shape) # dots_logsumexp = np.reshape(dots_logsumexp, (-1,)) # return out, dots_logsumexp # ``` # %% [markdown] # <a name="2.3"></a> # ## Part 2.3 Class OurSelfAttention # Here we create our own self attention layer by creating a class `OurSelfAttention`. The parent class will be the tl.SelfAttention layer in Trax. We will only override the `forward_unbatched` routine. # We're not asking you to modify anything in this routine. There are some comments to draw your attention to a few lines. # %% colab={} colab_type="code" id="Wix7oM-i5NV3" class OurSelfAttention(tl.SelfAttention): """Our self-attention. Just the Forward Function.""" def forward_unbatched( self, x, mask=None, *, weights, state, rng, update_state, verbose=False ): print("ourSelfAttention:forward_unbatched") del update_state attend_rng, output_rng = fastmath.random.split(rng) if self.bias: if self.share_qk: w_q, w_v, w_o, b_q, b_v = weights else: w_q, w_k, w_v, w_o, b_q, b_k, b_v = weights else: if self.share_qk: w_q, w_v, w_o = weights else: w_q, w_k, w_v, w_o = weights print("x.shape,w_q.shape", x.shape, w_q.shape) q = np.matmul(x, w_q) k = None if not self.share_qk: k = np.matmul(x, w_k) v = np.matmul(x, w_v) if self.bias: q = q + b_q if not self.share_qk: k = k + b_k v = v + b_v mask_fn = functools.partial( mask_self_attention, causal=self.causal, exclude_self=self.share_qk, masked=self.masked, ) q_info = kv_info = tie_in(x, np.arange(q.shape[-2], dtype=np.int32)) assert (mask is not None) == self.masked if self.masked: # mask is a boolean array (True means "is valid token") ones_like_mask = tie_in(x, np.ones_like(mask, dtype=np.int32)) kv_info = kv_info * np.where(mask, ones_like_mask, -ones_like_mask) # Notice, we are callout our vesion of attend o, _ = our_simple_attend( q, k, v, mask_fn=mask_fn, q_info=q_info, kv_info=kv_info, dropout=self.attention_dropout, rng=attend_rng, verbose=True, ) # Notice, wo weight matrix applied to output of attend in forward_unbatched out = np.matmul(o, w_o) out = apply_broadcasted_dropout(out, self.output_dropout, output_rng) return out, state # %% colab={} colab_type="code" id="e1Krh9er8qTj" causal = False masked = False mask = None attention_dropout = 0.0 n_heads = 3 d_qk = 3 d_v = 4 seq_len = 8 emb_len = 5 batch_size = 1 osa = OurSelfAttention( n_heads=n_heads, d_qk=d_qk, d_v=d_v, causal=causal, use_reference_code=True, attention_dropout=attention_dropout, mode="train", ) rng_osa = fastmath.random.get_prng(1) x = jax.random.uniform( jax.random.PRNGKey(0), (batch_size, seq_len, emb_len), dtype=np.float32 ) _, _ = osa.init(tl.shapes.signature(x), rng=rng_osa) # %% colab={"base_uri": "https://localhost:8080/", "height": 790} colab_type="code" id="BTfRVNkL85i6" outputId="8a321eb9-09b8-4431-ecad-2290ea2310a3" osa(x) # %% [markdown] colab_type="text" id="Km8I7HMZ62Cs" # <details> # <summary> # <font size="3"><b> Expected Output </b></font> # </summary> # # **Expected Output** # Notice a few things: # * the w_q (and w_k) matrices are applied to each row or each embedding on the input. This is similar to the filter operation in convolution # * forward_unbatched is called 3 times. This is because we have 3 heads in this example. # # ``` # ourSelfAttention:forward_unbatched # x.shape,w_q.shape (8, 5) (5, 3) # Our attend dots (8, 8) # Our attend dots post softmax (8, 8) (8, 1) # Our attend out1 (8, 4) # Our attend out2 (8, 4) # ourSelfAttention:forward_unbatched # x.shape,w_q.shape (8, 5) (5, 3) # Our attend dots (8, 8) # Our attend dots post softmax (8, 8) (8, 1) # Our attend out1 (8, 4) # Our attend out2 (8, 4) # ourSelfAttention:forward_unbatched # x.shape,w_q.shape (8, 5) (5, 3) # Our attend dots (8, 8) # Our attend dots post softmax (8, 8) (8, 1) # Our attend out1 (8, 4) # Our attend out2 (8, 4) # DeviceArray([[[ 6.70414209e-01, -1.04319841e-01, -5.33822298e-01, # 1.92711830e-01, -4.54187393e-05], # [ 6.64090097e-01, -1.01875424e-01, -5.35733163e-01, # 1.88311756e-01, -6.30629063e-03], # [ 6.73380017e-01, -1.06952369e-01, -5.31989932e-01, # 1.90056816e-01, 1.30271912e-03], # [ 6.84564888e-01, -1.13240272e-01, -5.50182462e-01, # 1.95673436e-01, 5.47635555e-03], # [ 6.81435883e-01, -1.11068964e-01, -5.32343209e-01, # 1.91912338e-01, 5.69400191e-03], # [ 6.80724978e-01, -1.08496904e-01, -5.34994125e-01, # 1.96332246e-01, 5.89773059e-03], # [ 6.80933356e-01, -1.14087075e-01, -5.18659890e-01, # 1.90674081e-01, 1.14096403e-02], # [ 6.80265009e-01, -1.09031796e-01, -5.38248718e-01, # 1.94203183e-01, 4.23943996e-03]]], dtype=float32) # ``` # # # %% [markdown] # <a name="3"></a> # ## Part 3.0 Trax LSHSelfAttention # <a name="3.1"></a> # ## Part 3.1 Description # The larger the matrix multiply in the previous section is, the more context can be taken into account when making the next decision. However, the self attention dot product grows as the size of the input squared. For example, if one wished to have an input size of 1024, that would result in $1024^2$ or over a million dot products for each head! As a result, there has been significant research related to reducing the compute requirements. One such approach is Locality Sensitive Hashing(LSH) Self Attention. # # You may recall, earlier in the course you utilized LSH to find similar tweets without resorting to calculating cosine similarity for each pair of embeddings. We will use a similar approach here. It may be best described with an example. # <img src = "C4W4_LN2_image8.PNG" height="400" width="750"> # # <center><b>Figure 9: Example of LSH Self Attention</b></center> # # # %% [markdown] # LSH Self attention uses Queries only, no Keys. Attention then generates a metric of the similarity of each value of Q relative to all the other values in Q. An earlier assignment demonstrated that values which hash to the same bucket are likely to be similar. Further, multiple random hashes can improve the chances of finding entries which are similar. This is the approach taken here, though the hash is implemented a bit differently. The values of Q are hashed into buckets using a randomly generated set of hash vectors. Multiple sets of hash vectors are used, generating multiple hash tables. In the figure above, we have 3 hash tables with 4 buckets in each table. Notionally, following the hash, the values of Q have been replicated 3 times and distributed to their appropriate bucket in each of the 3 tables. To find similarity then, one generates dot-products only between members of the buckets. The result of this operation provides information on which entries are similar. As the operation has been distributed over multiple hash tables, these results need to be combined to form a complete picture and this can be used to generate a reduced dot-product attention array. Its clear that because we do not do a compare of every value vs every other value, the size of *Dots* will be reduced. # # The challenge in this approach is getting it to operate efficiently. You may recall from the earlier assignments the buckets were lists of entries and had varying length. This will operate poorly on a vector processing machine such as a GPU or TPU. Ideally, operations are done in large blocks with uniform sizes. While it is straightforward to implement the hash algorithm this way, it is challenging to managed buckets and variable sized dot-products. This will be discussed further below. For now, we will examine and implement the hash function. # %% [markdown] # <a name="3.2"></a> # ## Part 3.2 our_hash_vectors # %% [markdown] # *our_hash_vectors*, is a reimplementation of Trax *hashvector*. It takes in an array of vectors, hashes the entries and returns and array assigning each input vector to n_hash buckets. Hashing is described as creating *random rotations*, see [Practical and Optimal LSH for Angular Distance](https://arxiv.org/pdf/1509.02897.pdf). # # <img src = "C4W4_LN2_image9.PNG" height="400" width="750"> # <img src = "C4W4_LN2_image10.PNG" height="400" width="750"> # <center><b>Figure 10: Processing steps in our_hash_vectors </b></center> # # Note, in the diagram, sizes relate to our expected input $Q$ while our_hash_vectors is written assuming a generic input vector # # %% [markdown] # **Instructions** # **Step 1** # create an array of random normal vectors which will be our hash vectors. Each vector will be hashed into a hash table and into `rot_size//2` buckets. We use `rot_size//2` to reduce computation. Later in the routine we will form the negative rotations with a simple negation and concatenate to get a full `rot_size` number of rotations. # * use fastmath.random.normal and create an array of random vectors of shape (vec.shape[-1],n_hashes, rot_size//2) # # **Step 2** In this step we simply do the matrix multiply. `jax` has an accelerated version of [einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html). Here we will utilize more conventional routines. # # **Step 2x** # * 2a: np.reshape random_rotations into a 2 dimensional array ([-1, n_hashes * (rot_size // 2)]) # * 2b: np.dot vecs and random_rotations forming our rotated_vecs # * 2c: back to 3 dimension with np.reshape [-1, n_hashes, rot_size//2] # * 2d: prepare for concatenating by swapping dimensions np.transpose (1, 0, 2) # **Step 3** Here we concatenate our rotation vectors getting a fullrot_size number of buckets (note, n_buckets = rotsize) # * use np.concatenate, [rotated_vecs, -rotated_vecs], axis=-1 # **Step 4** **This is the exciting step!** You have no doubt been wondering how we will turn these vectors into bucket indexes. By performing np.argmax over the rotations for a given entry, you get the index to the best match! We will use this as a bucket index. # * np.argmax(...).astype(np.int32); be sure to use the correct axis! # **Step 5** In this style of hashing, items which land in bucket 0 of hash table 0 are not necessarily similar to those landing in bucket 0 of hash table 1, so we keep them separate. We do this by offsetting the bucket numbers by 'n_buckets'. # * add buckets and offsets and reshape into a one dimensional array # This will return a 1D array of size n_hashes * vec.shape[0]. # %% colab={} colab_type="code" id="Vzf4dDSHnFQQ" def our_hash_vectors(vecs, rng, n_buckets, n_hashes, mask=None, verbose=False): """ Args: vecs: tensor of at least 2 dimension, rng: random number generator n_buckets: number of buckets in each hash table n_hashes: the number of hash tables mask: None indicating no mask or a 1D boolean array of length vecs.shape[0], containing the location of padding value verbose: controls prints for debug Returns: A vector of size n_hashes * vecs.shape[0] containing the buckets associated with each input vector per hash table. """ # check for even, integer bucket sizes assert isinstance(n_buckets, int) and n_buckets % 2 == 0 rng = fastmath.stop_gradient(tie_in(vecs, rng)) rot_size = n_buckets ### Start Code Here ### Step 1 ### rotations_shape = (vecs.shape[-1], n_hashes, rot_size // 2) random_rotations = fastmath.random.normal(rng, rotations_shape).astype(np.float32) if verbose: print("random.rotations.shape", random_rotations.shape) ### Step 2 ### if fastmath.backend_name() == "jax": rotated_vecs = np.einsum("tf,fhb->htb", vecs, random_rotations) print("using jax") else: # Step 2a random_rotations = np.reshape(random_rotations, [-1, n_hashes * (rot_size // 2)]) if verbose: print("random_rotations reshaped", random_rotations.shape) # Step 2b rotated_vecs = np.dot(vecs, random_rotations) if verbose: print("rotated_vecs1", rotated_vecs.shape) # Step 2c rotated_vecs = np.reshape(rotated_vecs, [-1, n_hashes, rot_size//2]) if verbose: print("rotated_vecs2", rotated_vecs.shape) # Step 2d rotated_vecs = np.transpose(rotated_vecs, (1, 0, 2)) if verbose: print("rotated_vecs3", rotated_vecs.shape) ### Step 3 ### rotated_vecs = np.concatenate([rotated_vecs, -rotated_vecs], axis=-1) if verbose: print("rotated_vecs.shape", rotated_vecs.shape) ### Step 4 ### buckets = np.argmax(rotated_vecs, axis=-1).astype(np.int32) if verbose: print("buckets.shape", buckets.shape) if verbose: print("buckets", buckets) if mask is not None: n_buckets += 1 # Create an extra bucket for padding tokens only buckets = np.where(mask[None, :], buckets, n_buckets - 1) # buckets is now (n_hashes, seqlen). Next we add offsets so that # bucket numbers from different hashing rounds don't overlap. offsets = tie_in(buckets, np.arange(n_hashes, dtype=np.int32)) offsets = np.reshape(offsets * n_buckets, (-1, 1)) ### Step 5 ### buckets = np.reshape(buckets + offsets, (-1,)) if verbose: print("buckets with offsets", buckets.shape, "\n", buckets) ### End Code Here return buckets # %% colab={"base_uri": "https://localhost:8080/", "height": 403} colab_type="code" id="cPGNaVpAi8wM" outputId="a5a6a956-30b7-4de7-a5c2-65011a9d3816" # example code. Note for reference, the sizes in this example match the values in the diagram above. ohv_q = np.ones((8, 5)) # (seq_len=8, n_q=5) ohv_n_buckets = 4 # even number ohv_n_hashes = 3 with fastmath.use_backend("tf"): ohv_rng = fastmath.random.get_prng(1) ohv = our_hash_vectors( ohv_q, ohv_rng, ohv_n_buckets, ohv_n_hashes, mask=None, verbose=True ) print("ohv shape", ohv.shape, "\nohv", ohv) # (ohv_n_hashes * ohv_n_buckets) # note the random number generators do not produce the same results with different backends with fastmath.use_backend("jax"): ohv_rng = fastmath.random.get_prng(1) ohv = our_hash_vectors(ohv_q, ohv_rng, ohv_n_buckets, ohv_n_hashes, mask=None) print("ohv shape", ohv.shape, "\nohv", ohv) # (ohv_n_hashes * ohv_n_buckets) # %% [markdown] colab_type="text" id="XAQqr1_XkCf6" # <details> # <summary> # <font size="3"><b> Expected Output </b></font> # </summary> # # **Expected Values** # ``` # random.rotations.shape (5, 3, 2) # random_rotations reshaped (5, 6) # rotated_vecs1 (8, 6) # rotated_vecs2 (8, 3, 2) # rotated_vecs3 (3, 8, 2) # rotated_vecs.shape (3, 8, 4) # buckets.shape (3, 8) # buckets ndarray<tf.Tensor( # [[3 3 3 3 3 3 3 3] # [3 3 3 3 3 3 3 3] # [3 3 3 3 3 3 3 3]], shape=(3, 8), dtype=int32)> # buckets with offsets (24,) # ndarray<tf.Tensor([ 3 3 3 3 3 3 3 3 7 7 7 7 7 7 7 7 11 11 11 11 11 11 11 11], shape=(24,), dtype=int32)> # ohv shape (24,) # ohv ndarray<tf.Tensor([ 3 3 3 3 3 3 3 3 7 7 7 7 7 7 7 7 11 11 11 11 11 11 11 11], shape=(24,), dtype=int32)> # using jax # ohv shape (24,) # ohv [ 3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 11 11 11 11 11 11 11 11]``` # %% [markdown] # <details> # <summary> # <font size="3" ><b>Completed code for reference </b></font> # </summary> # # ``` # # since this notebook is ungraded the completed code is provided here for reference # # def our_hash_vectors(vecs, rng, n_buckets, n_hashes, mask=None, verbose=False): # """ # Args: # vecs: tensor of at least 2 dimension, # rng: random number generator # n_buckets: number of buckets in each hash table # n_hashes: the number of hash tables # mask: None indicating no mask or a 1D boolean array of length vecs.shape[0], containing the location of padding value # verbose: controls prints for debug # Returns: # A vector of size n_hashes * vecs.shape[0] containing the buckets associated with each input vector per hash table. # # """ # # # check for even, integer bucket sizes # assert isinstance(n_buckets, int) and n_buckets % 2 == 0 # # rng = fastmath.stop_gradient(tie_in(vecs, rng)) # rot_size = n_buckets # ### Start Code Here # # ### Step 1 ### # rotations_shape = (vecs.shape[-1], n_hashes, rot_size // 2) # random_rotations = fastmath.random.normal(rng, rotations_shape).astype( # np.float32) # if verbose: print("random.rotations.shape", random_rotations.shape) # # ### Step 2 ### # if fastmath.backend_name() == 'jax': # rotated_vecs = np.einsum('tf,fhb->htb', vecs, random_rotations) # if verbose: print("using jax") # else: # #Step 2a # random_rotations = np.reshape(random_rotations, # [-1, n_hashes * (rot_size // 2)]) # if verbose: print("random_rotations reshaped", random_rotations.shape) # #Step 2b # rotated_vecs = np.dot(vecs, random_rotations) # if verbose: print("rotated_vecs1", rotated_vecs.shape) # #Step 2c # rotated_vecs = np.reshape(rotated_vecs, [-1, n_hashes, rot_size//2]) # if verbose: print("rotated_vecs2", rotated_vecs.shape) # #Step 2d # rotated_vecs = np.transpose(rotated_vecs, (1, 0, 2)) # if verbose: print("rotated_vecs3", rotated_vecs.shape) # # ### Step 3 ### # rotated_vecs = np.concatenate([rotated_vecs, -rotated_vecs], axis=-1) # if verbose: print("rotated_vecs.shape", rotated_vecs.shape) # ### Step 4 ### # buckets = np.argmax(rotated_vecs, axis=-1).astype(np.int32) # if verbose: print("buckets.shape", buckets.shape) # if verbose: print("buckets", buckets) # # if mask is not None: # n_buckets += 1 # Create an extra bucket for padding tokens only # buckets = np.where(mask[None, :], buckets, n_buckets - 1) # # # buckets is now (n_hashes, seqlen). Next we add offsets so that # # bucket numbers from different hashing rounds don't overlap. # offsets = tie_in(buckets, np.arange(n_hashes, dtype=np.int32)) # offsets = np.reshape(offsets * n_buckets, (-1, 1)) # ### Step 5 ### # buckets = np.reshape(buckets + offsets, (-1,)) # if verbose: print("buckets with offsets", buckets.shape, "\n", buckets) # return buckets``` # %% [markdown] # <a name="3.3"></a> # ## Part 3.3 Sorting Buckets # %% [markdown] # Great! Now that we have a hash function, we can work on sorting our buckets and performing our matrix operations. # We'll walk through this algorithm in small steps: # * sort_buckets - we'll perform the sort # * softmax # * dotandv - do the matrix math to form the dotproduct and output # These routines will demonstrate a simplified version of the algorithm. We won't address masking and variable bucket sizes but will consider how they would be handled. # # **sort_buckets** # # At this point, we have called the hash function and were returned the associated buckets. For example, if we started with # `q[n_seq,n_q]`, with `n_hash = 2; n_buckets = 4; n_seq = 8` # we might be returned: # `bucket = [0,1,2,3,0,1,2,3, 4,5,6,7,4,5,6,7] ` # Note that it is n_hash\*n_seq long and that the bucket values for each hash have been offset by n_hash so the numbers do not overlap. Going forward, we going to sort this array of buckets to group together members of the same (hash,bucket) pair. # # **Instructions** # **Step 1** Our goal is to sort $q$ rather than the bucket list, so we will need to track the association of the buckets to their elements in $q$. # * using np.arange, create `ticker`, just a sequence of numbers (0..n_hashed * seqlen) associating members of q with their bucket. # # **Step 2** This step is provided to you as it is a bit difficult to describe. We want to disambiguate elements that map to the same bucket. When a sorting routine encounters a situation where multiple entries have the same value, it can correctly choose any entry to go first. This makes testing ambiguous. This prevents that. We multiply all the buckets by `seqlen` and then add `ticker % seqlen` # # **Step 3** Here we are! Ready to sort. This is the exciting part. # * Utilize [fastmath.sort_key_val](https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.sort_key_val.html#jax.lax.sort_key_val) and sort `buckets_and_t` and `ticker`. # # **Step 4** We need to be able to undo the sort at the end to get things back into their correct locations # * sort `sticker` and `ticker` to for the reverse map # # **Step 5** create our sorted q and sorted v # * use [np.take](https://numpy.org/doc/stable/reference/generated/numpy.take.html) and `st` to grab correct values in `q` for the sorted values, `sq`. Use axis=0. # # Use the example code below the routine to check and help debug your results. # %% def sort_buckets(buckets, q, v, n_buckets, n_hashes, seqlen, verbose=True): """ Args: buckets: tensor of at least 2 dimension, n_buckets: number of buckets in each hash table n_hashes: the number of hash tables """ if verbose: print("---sort_buckets--") ## Step 1 ticker = np.arange(n_hashes * seqlen) if verbose: print("ticker", ticker.shape, ticker) ## Step 2 buckets_and_t = seqlen * buckets + (ticker % seqlen) # provided if verbose: print("buckets_and_t", buckets_and_t.shape, buckets_and_t) # Hash-based sort ("s" at the start of variable names means "sorted") # Step 3 sbuckets_and_t, sticker = fastmath.sort_key_val(buckets_and_t, ticker, dimension=-1) if verbose: print("sbuckets_and_t", sbuckets_and_t.shape, sbuckets_and_t) if verbose: print("sticker", sticker.shape, sticker) # Step 4 _, undo_sort = fastmath.sort_key_val(sticker, ticker, dimension=-1) if verbose: print("undo_sort", undo_sort.shape, undo_sort) # Step 5 st = sticker % seqlen # provided sq = np.take(q, st, axis=0) sv = np.take(v, st, axis=0) return sq, sv, sticker, undo_sort # %% t_n_hashes = 2 t_n_buckets = 4 t_n_seq = t_seqlen = 8 t_n_q = 3 n_v = 5 t_q = (np.array([(j % t_n_buckets) for j in range(t_n_seq)]) * np.ones((t_n_q, 1))).T t_v = np.ones((t_n_seq, n_v)) t_buckets = np.array( [ (j % t_n_buckets) + t_n_buckets * i for i in range(t_n_hashes) for j in range(t_n_seq) ] ) print("q\n", t_q) print("t_buckets: ", t_buckets) t_sq, t_sv, t_sticker, t_undo_sort = sort_buckets( t_buckets, t_q, t_v, t_n_buckets, t_n_hashes, t_seqlen, verbose=True ) print("sq.shape", t_sq.shape, "sv.shape", t_sv.shape) print("sq\n", t_sq) # %% [markdown] # <details> # <summary> # <font size="3"><b> Expected Output </b></font> # </summary> # # **Expected Values** # ``` # q # [[0. 0. 0.] # [1. 1. 1.] # [2. 2. 2.] # [3. 3. 3.] # [0. 0. 0.] # [1. 1. 1.] # [2. 2. 2.] # [3. 3. 3.]] # t_buckets: [0 1 2 3 0 1 2 3 4 5 6 7 4 5 6 7] # ---sort_buckets-- # ticker (16,) [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] # buckets_and_t (16,) [ 0 9 18 27 4 13 22 31 32 41 50 59 36 45 54 63] # sbuckets_and_t (16,) [ 0 4 9 13 18 22 27 31 32 36 41 45 50 54 59 63] # sticker (16,) [ 0 4 1 5 2 6 3 7 8 12 9 13 10 14 11 15] # undo_sort (16,) [ 0 2 4 6 1 3 5 7 8 10 12 14 9 11 13 15] # sq.shape (16, 3) sv.shape (16, 5) # sq # [[0. 0. 0.] # [0. 0. 0.] # [1. 1. 1.] # [1. 1. 1.] # [2. 2. 2.] # [2. 2. 2.] # [3. 3. 3.] # [3. 3. 3.] # [0. 0. 0.] # [0. 0. 0.] # [1. 1. 1.] # [1. 1. 1.] # [2. 2. 2.] # [2. 2. 2.] # [3. 3. 3.] # [3. 3. 3.]] # # ``` # %% [markdown] # <details> # <summary> # <font size="3" ><b>Completed code for reference </b></font> # </summary> # # ``` # # since this notebook is ungraded the completed code is provided here for reference # def sort_buckets(buckets, q, v, n_buckets, n_hashes, seqlen, verbose=True): # """ # Args: # buckets: tensor of at least 2 dimension, # n_buckets: number of buckets in each hash table # n_hashes: the number of hash tables # """ # if verbose: print("---sort_buckets--") # ## Step 1 # ticker = np.arange(n_hashes * seqlen) # if verbose: print("ticker",ticker.shape, ticker) # ## Step 2 # buckets_and_t = seqlen * buckets + (ticker % seqlen) # if verbose: print("buckets_and_t",buckets_and_t.shape, buckets_and_t) # # # Hash-based sort ("s" at the start of variable names means "sorted") # #Step 3 # sbuckets_and_t, sticker = fastmath.sort_key_val( # buckets_and_t, ticker, dimension=-1) # if verbose: print("sbuckets_and_t",sbuckets_and_t.shape, sbuckets_and_t) # if verbose: print("sticker",sticker.shape, sticker) # #Step 4 # _, undo_sort = fastmath.sort_key_val(sticker, ticker, dimension=-1) # if verbose: print("undo_sort",undo_sort.shape, undo_sort) # # #Step 4 # st = (sticker % seqlen) # sq = np.take(q, st, axis=0) # sv = np.take(v, st, axis=0) # return sq, sv, sticker, undo_sort # ``` # %% [markdown] # <a name="3.4"></a> # ## Part 3.4 Chunked dot product attention # %% [markdown] # Now let's create the dot product attention. We have sorted $Q$ so that elements that the hash has determined are likely to be similar are adjacent to each other. We now want to perform the dot-product within those limited regions - in 'chunks'. # # <img src = "C4W4_LN2_image12.PNG" height="400" width="750"> # <center><b>Figure 11: Performing dot product in 'chunks' </b></center> # # # The example we have been working on is shown above, with sequences of 8, 2 hashes, 4 buckets and, conveniently, the content of Q was such that when sorted, there were 2 entries in each bucket. If we reshape Q into a (8,2,n_q), we can use numpy matmul to perform the operation. Numpy [matmul](https://numpy.org/doc/stable/reference/generated/numpy.matmul.html) will treat the inputs as a stack of matrices residing in the last two indexes. This will allow us to matrix multiply Q with itself in *chunks* and later can also be used to perform the matrix multiply with v. # # We will perform a softmax on the output of the dot product of Q and Q, but in this case, there is a bit more to the story. Recall the output of the hash had multiple hash tables. We will perform softmax on those separately and then must combine them. This is where the form of softmax we defined at the top of the notebook comes into play. The routines below will utilize the logsumexp values that the `our_softmax` routine calculates. # # There is a good deal of [reshaping](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html) to get things into the right formats. The code has many print statements that match the expected values below. You can use those to check your work as you go along. If you don't do a lot of 3-dimensional matrix multiplications in your daily life, it might be worthwhile to open a spare cell and practice a few simple examples to get the hang of it! Here is one to start with: # # %% a = np.arange(16 * 3).reshape((16, 3)) chunksize = 2 ar = np.reshape( a, (-1, chunksize, a.shape[-1]) ) # the -1 usage is very handy, see numpy reshape print(ar.shape) # %% [markdown] # # **Instructions** # **Step 1** Reshaping Q # * np.reshape `sq` (sorted q) to be 3 dimensions. The middle dimension is the size of the 'chunk' specified by `kv_chunk_len` # * np.swapaxes to perform a 'transpose' on the reshaped `sq`, *but only on the last two dimension* # * np.matmul the two values. # # **Step 2** # * use our_softmax to perform the softmax on the dot product. Don't forget `passthrough` # # **Step 3** # * np.reshape `sv`. Like `sq`, the middle dimension is the size of the 'chunk' specified by `kv_chunk_len` # * np.matmul dotlike and the reshaped `sv` # * np.reshape so to a two dimensional array with the last dimension stays the same (`so.shape[-1]`) # * `logits` also needs reshaping, we'll do that. # # **Step 4** Now we can undo the sort. # * use [np.take](https://numpy.org/doc/stable/reference/generated/numpy.take.html) and `undo_sort` and axis = 0 to unsort so # * do the same with `slogits`. # # **Step 5** This step combines the results of multiple hashes. Recall, the softmax was only over the values in one hash, this extends it to all the hashes. Read through it, the code is provided. Note this is taking place *after* the matrix multiply with v while the softmax output is used before the multiply. How does this achieve the correct result? # %% def dotandv( sq, sv, undo_sort, kv_chunk_len, n_hashes, seqlen, passthrough, verbose=False ): # Step 1 rsq = np.reshape(sq,(-1, kv_chunk_len, sq.shape[-1])) rsqt = np.swapaxes(rsq, -1, -2) if verbose: print("rsq.shape,rsqt.shape: ", rsq.shape, rsqt.shape) dotlike = np.matmul(rsq, rsqt) if verbose: print("dotlike\n", dotlike) # Step 2 dotlike, slogits = our_softmax(dotlike, passthrough) if verbose: print("dotlike post softmax\n", dotlike) # Step 3 vr = np.reshape(sv, (-1, kv_chunk_len, sv.shape[-1])) if verbose: print("dotlike.shape, vr.shape:", dotlike.shape, vr.shape) so = np.matmul(dotlike, vr) if verbose: print("so.shape:", so.shape) so = np.reshape(so, (-1, so.shape[-1])) slogits = np.reshape(slogits, (-1,)) # provided if verbose: print("so.shape,slogits.shape", so.shape, slogits.shape) # Step 4 o = np.take(so, undo_sort, axis=0) logits = np.take(slogits, undo_sort, axis=0) if verbose: print("o.shape,o", o.shape, o) if verbose: print("logits.shape, logits", logits.shape, logits) # Step 5 (Provided) if n_hashes > 1: o = np.reshape(o, (n_hashes, seqlen, o.shape[-1])) logits = np.reshape(logits, (n_hashes, seqlen, 1)) probs = np.exp(logits - fastmath.logsumexp(logits, axis=0, keepdims=True)) o = np.sum(o * probs, axis=0) return o # %% t_kv_chunk_len = 2 out = dotandv( t_sq, t_sv, t_undo_sort, t_kv_chunk_len, t_n_hashes, t_seqlen, passthrough=True, verbose=True, ) print("out\n", out) print("\n-----With softmax enabled----\n") out = dotandv( t_sq, t_sv, t_undo_sort, t_kv_chunk_len, t_n_hashes, t_seqlen, passthrough=False, verbose=True, ) print("out\n", out) # %% [markdown] # <details> # <summary> # <font size="3"><b> Expected Output </b></font> # </summary> # # **Expected Values** # ``` # rsq.shape,rsqt.shape: (8, 2, 3) (8, 3, 2) # dotlike # [[[ 0. 0.] # [ 0. 0.]] # # [[ 3. 3.] # [ 3. 3.]] # # [[12. 12.] # [12. 12.]] # # [[27. 27.] # [27. 27.]] # # [[ 0. 0.] # [ 0. 0.]] # # [[ 3. 3.] # [ 3. 3.]] # # [[12. 12.] # [12. 12.]] # # [[27. 27.] # [27. 27.]]] # dotlike post softmax # [[[ 0. 0.] # [ 0. 0.]] # # [[ 3. 3.] # [ 3. 3.]] # # [[12. 12.] # [12. 12.]] # # [[27. 27.] # [27. 27.]] # # [[ 0. 0.] # [ 0. 0.]] # # [[ 3. 3.] # [ 3. 3.]] # # [[12. 12.] # [12. 12.]] # # [[27. 27.] # [27. 27.]]] # dotlike.shape, vr.shape: (8, 2, 2) (8, 2, 5) # so.shape: (8, 2, 5) # so.shape,slogits.shape (16, 5) (16,) # o.shape,o (16, 5) [[ 0. 0. 0. 0. 0.] # [ 6. 6. 6. 6. 6.] # [24. 24. 24. 24. 24.] # [54. 54. 54. 54. 54.] # [ 0. 0. 0. 0. 0.] # [ 6. 6. 6. 6. 6.] # [24. 24. 24. 24. 24.] # [54. 54. 54. 54. 54.] # [ 0. 0. 0. 0. 0.] # [ 6. 6. 6. 6. 6.] # [24. 24. 24. 24. 24.] # [54. 54. 54. 54. 54.] # [ 0. 0. 0. 0. 0.] # [ 6. 6. 6. 6. 6.] # [24. 24. 24. 24. 24.] # [54. 54. 54. 54. 54.]] # logits.shape, logits (16,) [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] # out # [[ 0. 0. 0. 0. 0.] # [ 6. 6. 6. 6. 6.] # [24. 24. 24. 24. 24.] # [54. 54. 54. 54. 54.] # [ 0. 0. 0. 0. 0.] # [ 6. 6. 6. 6. 6.] # [24. 24. 24. 24. 24.] # [54. 54. 54. 54. 54.]] # # -----With softmax enabled---- # # rsq.shape,rsqt.shape: (8, 2, 3) (8, 3, 2) # dotlike # [[[ 0. 0.] # [ 0. 0.]] # # [[ 3. 3.] # [ 3. 3.]] # # [[12. 12.] # [12. 12.]] # # [[27. 27.] # [27. 27.]] # # [[ 0. 0.] # [ 0. 0.]] # # [[ 3. 3.] # [ 3. 3.]] # # [[12. 12.] # [12. 12.]] # # [[27. 27.] # [27. 27.]]] # dotlike post softmax # [[[0.5 0.5 ] # [0.5 0.5 ]] # # [[0.5 0.5 ] # [0.5 0.5 ]] # # [[0.49999976 0.49999976] # [0.49999976 0.49999976]] # # [[0.49999976 0.49999976] # [0.49999976 0.49999976]] # # [[0.5 0.5 ] # [0.5 0.5 ]] # # [[0.5 0.5 ] # [0.5 0.5 ]] # # [[0.49999976 0.49999976] # [0.49999976 0.49999976]] # # [[0.49999976 0.49999976] # [0.49999976 0.49999976]]] # dotlike.shape, vr.shape: (8, 2, 2) (8, 2, 5) # so.shape: (8, 2, 5) # so.shape,slogits.shape (16, 5) (16,) # o.shape,o (16, 5) [[1. 1. 1. 1. 1. ] # [1. 1. 1. 1. 1. ] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [1. 1. 1. 1. 1. ] # [1. 1. 1. 1. 1. ] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [1. 1. 1. 1. 1. ] # [1. 1. 1. 1. 1. ] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [1. 1. 1. 1. 1. ] # [1. 1. 1. 1. 1. ] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995] # [0.9999995 0.9999995 0.9999995 0.9999995 0.9999995]] # logits.shape, logits (16,) [ 0.6931472 3.6931472 12.693148 27.693148 0.6931472 3.6931472 # 12.693148 27.693148 0.6931472 3.6931472 12.693148 27.693148 # 0.6931472 3.6931472 12.693148 27.693148 ] # out # [[1. 1. 1. 1. 1. ] # [1. 1. 1. 1. 1. ] # [0.99999905 0.99999905 0.99999905 0.99999905 0.99999905] # [0.99999905 0.99999905 0.99999905 0.99999905 0.99999905] # [1. 1. 1. 1. 1. ] # [1. 1. 1. 1. 1. ] # [0.99999905 0.99999905 0.99999905 0.99999905 0.99999905] # [0.99999905 0.99999905 0.99999905 0.99999905 0.99999905]] # ``` # %% [markdown] # <details> # <summary> # <font size="3" ><b>Completed code for reference </b></font> # </summary> # # ``` # # since this notebook is ungraded the completed code is provided here for reference # def dotandv(sq, sv, undo_sort, kv_chunk_len, n_hashes, seqlen, passthrough, verbose=False ): # # Step 1 # rsq = np.reshape(sq,(-1, kv_chunk_len, sq.shape[-1])) # rsqt = np.swapaxes(rsq, -1, -2) # if verbose: print("rsq.shape,rsqt.shape: ", rsq.shape,rsqt.shape) # dotlike = np.matmul(rsq, rsqt) # if verbose: print("dotlike\n", dotlike) # # #Step 2 # dotlike, slogits = our_softmax(dotlike, passthrough) # if verbose: print("dotlike post softmax\n", dotlike) # # #Step 3 # vr = np.reshape(sv, (-1, kv_chunk_len, sv.shape[-1])) # if verbose: print("dotlike.shape, vr.shape:", dotlike.shape, vr.shape) # so = np.matmul(dotlike, vr) # if verbose: print("so.shape:", so.shape) # so = np.reshape(so, (-1, so.shape[-1])) # slogits = np.reshape(slogits, (-1,)) # provided # if verbose: print("so.shape,slogits.shape", so.shape, slogits.shape) # # #Step 4 # o = np.take(so, undo_sort, axis=0) # logits = np.take(slogits, undo_sort, axis=0) # if verbose: print("o.shape,o", o.shape, o) # if verbose: print("logits.shape, logits", logits.shape, logits) # # #Step 5 (Provided) # if n_hashes > 1: # o = np.reshape(o, (n_hashes, seqlen, o.shape[-1])) # logits = np.reshape(logits, (n_hashes, seqlen, 1)) # probs = np.exp(logits - fastmath.logsumexp(logits, axis=0, keepdims=True)) # o = np.sum(o * probs, axis=0) # # return(o) # ``` # %% [markdown] # Great! You have now done examples code for most of the operation that are unique to the LSH version of self-attention. I'm sure at this point you are wondering what happens if the number of entries in a bucket is not evenly distributed the way our example is. It is possible, for example for all of the `seqlen` entries to land in one bucket. Further, since the buckets are not aligned, our 'chunks' may be misaligned with the start of the bucket. The implementation addresses this by attending to adjacent chunks as was described in the lecture: # # <img src = "C4W4_LN2_image13.PNG" height="400" width="750"> # <center><b>Figure 12: Misaligned Access, looking before and after </b></center> # # Hopefully, having implemented parts of this, you will appreciate this diagram more fully. # # # %% [markdown] # <a name="3.5"></a> # ## Part 3.5 OurLSHSelfAttention # # You can examine the full implementations below. Area's we did not 'attend to' in our implementations above include variable bucket sizes and masking. We will instantiate a layer of the full implementation below. We tried to use the same variable names above to make it easier to decipher the full version. Note that some of the functionality we implemented in our routines is split between `attend` and `forward_unbatched`. We've inserted our version of hash below, but use the original version of `attend`. # %% # original version from trax 1.3.4 def attend( q, k=None, v=None, q_chunk_len=None, kv_chunk_len=None, n_chunks_before=0, n_chunks_after=0, mask_fn=None, q_info=None, kv_info=None, dropout=0.0, rng=None, ): """Dot-product attention, with optional chunking and/or masking. Args: q: Query vectors, shape [q_len, d_qk] k: Key vectors, shape [kv_len, d_qk]; or None v: Value vectors, shape [kv_len, d_v] q_chunk_len: Set to non-zero to enable chunking for query vectors kv_chunk_len: Set to non-zero to enable chunking for key/value vectors n_chunks_before: Number of adjacent previous chunks to attend to n_chunks_after: Number of adjacent subsequent chunks to attend to mask_fn: TODO(kitaev) doc q_info: Query-associated metadata for masking kv_info: Key-associated metadata for masking dropout: Dropout rate rng: RNG for dropout Returns: A tuple (output, dots_logsumexp). The output has shape [q_len, d_v], and dots_logsumexp has shape [q_len]. The logsumexp of the attention probabilities is useful for combining multiple rounds of attention (as in LSH attention). """ assert v is not None share_qk = k is None if q_info is None: q_info = np.arange(q.shape[-2], dtype=np.int32) if kv_info is None and not share_qk: kv_info = np.arange(v.shape[-2], dtype=np.int32) # Split q/k/v into chunks along the time axis, if desired. if q_chunk_len is not None: q = np.reshape(q, (-1, q_chunk_len, q.shape[-1])) q_info = np.reshape(q_info, (-1, q_chunk_len)) if share_qk: assert kv_chunk_len is None or kv_chunk_len == q_chunk_len k = q kv_chunk_len = q_chunk_len if kv_info is None: kv_info = q_info elif kv_chunk_len is not None: # kv_info is not None, but reshape as required. kv_info = np.reshape(kv_info, (-1, kv_chunk_len)) elif kv_chunk_len is not None: k = np.reshape(k, (-1, kv_chunk_len, k.shape[-1])) kv_info = np.reshape(kv_info, (-1, kv_chunk_len)) if kv_chunk_len is not None: v = np.reshape(v, (-1, kv_chunk_len, v.shape[-1])) if share_qk: k = length_normalized(k) k = k / np.sqrt(k.shape[-1]) # Optionally include adjacent chunks. if q_chunk_len is not None or kv_chunk_len is not None: assert q_chunk_len is not None and kv_chunk_len is not None else: assert n_chunks_before == 0 and n_chunks_after == 0 k = look_adjacent(k, n_chunks_before, n_chunks_after) v = look_adjacent(v, n_chunks_before, n_chunks_after) kv_info = look_adjacent(kv_info, n_chunks_before, n_chunks_after) # Dot-product attention. dots = np.matmul(q, np.swapaxes(k, -1, -2)) # Masking if mask_fn is not None: dots = mask_fn(dots, q_info[..., :, None], kv_info[..., None, :]) # Softmax. dots_logsumexp = fastmath.logsumexp(dots, axis=-1, keepdims=True) dots = np.exp(dots - dots_logsumexp) if dropout > 0.0: assert rng is not None # Dropout is broadcast across the bin dimension dropout_shape = (dots.shape[-2], dots.shape[-1]) # keep_prob = tie_in(dots, 1.0 - dropout) keep = fastmath.random.bernoulli(rng, keep_prob, dropout_shape) multiplier = keep.astype(dots.dtype) / tie_in(keep, keep_prob) dots = dots * multiplier # The softmax normalizer (dots_logsumexp) is used by multi-round LSH attn. out = np.matmul(dots, v) out = np.reshape(out, (-1, out.shape[-1])) dots_logsumexp = np.reshape(dots_logsumexp, (-1,)) return out, dots_logsumexp # %% colab={} colab_type="code" id="ihFoYYBGKFVu" class OurLSHSelfAttention(tl.LSHSelfAttention): """Our simplified LSH self-attention """ def forward_unbatched(self, x, mask=None, *, weights, state, rng, update_state): attend_rng, output_rng = fastmath.random.split(rng) w_q, w_v, w_o = weights q = np.matmul(x, w_q) v = np.matmul(x, w_v) if update_state: _, old_hash_rng = state hash_rng, hash_subrng = fastmath.random.split(old_hash_rng) # buckets = self.hash_vectors(q, hash_subrng, mask) # original ## use our version of hash buckets = our_hash_vectors( q, hash_subrng, self.n_buckets, self.n_hashes, mask=mask ) s_buckets = buckets if self._max_length_for_buckets: length = self.n_hashes * self._max_length_for_buckets if buckets.shape[0] < length: s_buckets = np.concatenate( [buckets, np.zeros(length - buckets.shape[0], dtype=np.int32)], axis=0, ) state = (s_buckets, hash_rng) else: buckets, _ = state if self._max_length_for_buckets: buckets = buckets[: self.n_hashes * x.shape[0]] seqlen = x.shape[0] assert int(buckets.shape[0]) == self.n_hashes * seqlen ticker = tie_in(x, np.arange(self.n_hashes * seqlen, dtype=np.int32)) buckets_and_t = seqlen * buckets + (ticker % seqlen) buckets_and_t = fastmath.stop_gradient(buckets_and_t) # Hash-based sort ("s" at the start of variable names means "sorted") sbuckets_and_t, sticker = fastmath.sort_key_val( buckets_and_t, ticker, dimension=-1 ) _, undo_sort = fastmath.sort_key_val(sticker, ticker, dimension=-1) sbuckets_and_t = fastmath.stop_gradient(sbuckets_and_t) sticker = fastmath.stop_gradient(sticker) undo_sort = fastmath.stop_gradient(undo_sort) st = sticker % seqlen sq = np.take(q, st, axis=0) sv = np.take(v, st, axis=0) mask_fn = functools.partial( mask_self_attention, causal=self.causal, exclude_self=True, masked=self.masked, ) q_info = st assert (mask is not None) == self.masked kv_info = None if self.masked: # mask is a boolean array (True means "is valid token") smask = np.take(mask, st, axis=0) ones_like_mask = tie_in(x, np.ones_like(smask, dtype=np.int32)) kv_info = q_info * np.where(smask, ones_like_mask, -ones_like_mask) ## use original version of attend (could use ours but lacks masks and masking) so, slogits = attend( sq, k=None, v=sv, q_chunk_len=self.chunk_len, n_chunks_before=self.n_chunks_before, n_chunks_after=self.n_chunks_after, mask_fn=mask_fn, q_info=q_info, kv_info=kv_info, dropout=self.attention_dropout, rng=attend_rng, ) # np.take(so, undo_sort, axis=0); np.take(slogits, undo_sort, axis=0) would # also work, but these helpers include performance optimizations for TPU. o = permute_via_gather(so, undo_sort, sticker, axis=0) logits = permute_via_sort(slogits, sticker, buckets_and_t, axis=-1) if self.n_hashes > 1: o = np.reshape(o, (self.n_hashes, seqlen, o.shape[-1])) logits = np.reshape(logits, (self.n_hashes, seqlen, 1)) probs = np.exp(logits - fastmath.logsumexp(logits, axis=0, keepdims=True)) o = np.sum(o * probs, axis=0) assert o.shape == (seqlen, w_v.shape[-1]) out = np.matmul(o, w_o) out = apply_broadcasted_dropout(out, self.output_dropout, output_rng) return out, state # %% colab={} colab_type="code" id="QG3yCwWV3zJd" # Here we're going to try out our LSHSelfAttention n_heads = 3 causal = False masked = False mask = None chunk_len = 8 n_chunks_before = 0 n_chunks_after = 0 attention_dropout = 0.0 n_hashes = 5 n_buckets = 4 seq_len = 8 emb_len = 5 al = OurLSHSelfAttention( n_heads=n_heads, d_qk=3, d_v=4, causal=causal, chunk_len=8, n_chunks_before=n_chunks_before, n_chunks_after=n_chunks_after, n_hashes=n_hashes, n_buckets=n_buckets, use_reference_code=True, attention_dropout=attention_dropout, mode="train", ) x = jax.random.uniform(jax.random.PRNGKey(0), (1, seq_len, emb_len), dtype=np.float32) al_osa = fastmath.random.get_prng(1) _, _ = al.init(tl.shapes.signature(x), rng=al_osa) # %% colab={} colab_type="code" id="TzHug40iMe3S" al(x) # %% [markdown] colab_type="text" id="c5IBhMGjmg0z" # <details> # <summary> # <font size="3"><b> Expected Output </b></font> # </summary> # # **Expected Values** # ``` # using jax # using jax # using jax # DeviceArray([[[ 6.6842824e-01, -1.1364323e-01, -5.4430610e-01, # 2.1126242e-01, -1.0988623e-02], # [ 7.0949769e-01, -1.5455185e-01, -5.9923315e-01, # 2.2719440e-01, 1.3833776e-02], # [ 7.1442688e-01, -1.2046628e-01, -5.3956544e-01, # 1.7320301e-01, -1.6552269e-02], # [ 6.7178929e-01, -7.6611102e-02, -5.9399861e-01, # 2.1236290e-01, 7.9482794e-04], # [ 7.1518433e-01, -1.1359170e-01, -5.7821894e-01, # 2.1304411e-01, 3.0598268e-02], # [ 6.8235350e-01, -9.3979925e-02, -5.5341840e-01, # 2.1608177e-01, -6.6673756e-04], # [ 6.1286640e-01, -8.1027031e-02, -4.8148823e-01, # 1.9373313e-01, 3.1555295e-02], # [ 7.2203505e-01, -1.0199660e-01, -5.5215168e-01, # 1.7872262e-01, -2.2289157e-02]]], dtype=float32)``` # %% [markdown] # **Congratuations!** you have created a custom layer and have become familiar with LSHSelfAttention.
Natural Language Processing/Course 4 - Natural Language Processing with attention models/Labs/Week 4/Reformer Efficient Attention.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # 导入库 import tarfile # tar压缩包库 import os # 操作系统功能模块 import jieba.posseg as pseg # 带词性标注的分词模块 from gensim import corpora, models # gensim的词频统计和主题建模模块 from bs4 import BeautifulSoup # 用于XML格式化处理 # 中文分词 def jieba_cut(text): ''' 将输入的文本句子根据词性标注做分词 :param text: 文本句子,字符串型 :return: 符合规则的分词结果 ''' rule_words = ['z', 'vn', 'v', 't', 'nz', 'nr', 'ns', 'n', 'l', 'i', 'j', 'an', 'a'] # 只保留状态词、名动词、动词、时间词、其他名词、人名、地名、名词、习用语、简称略语、成语、形容词、名形词 words = pseg.cut(text) # 分词 seg_list = [] # 列表用于存储每个文件的分词结果 for word in words: # 循环得到每个分词 if word.flag in rule_words: seg_list.append(word.word) # 将分词追加到列表 return seg_list # 文本预处理 def text_pro(words_list, tfidf_object=None, training=True): ''' gensim主题建模预处理过程,包含分词类别转字典、生成语料库和TF-IDF转换 :param words_list: 分词列表,列表型 :param tfidf_object: TF-IDF模型对象,该对象在训练阶段生成 :param training: 是否训练阶段,用来针对训练和预测两个阶段做预处理 :return: 如果是训练阶段,返回词典、TF-IDF对象和TF-IDF向量空间数据;如果是预测阶段,返回TF-IDF向量空间数据 ''' # 分词列表转字典 dic = corpora.Dictionary(words_list) # 将分词列表转换为字典形式 print ('{:*^60}'.format('token & word mapping review:')) itemss = dic.items() print(itemss[:,5]) for i, w in itemss: # 循环读出字典前5条的每个key和value,对应的是索引值和分词 print ('token:%s -- word:%s' % (i, w)) # 生成语料库 corpus = [] # 建立一个用于存储语料库的列表 for words in words_list: # 读取每个分词列表 corpus.append(dic.doc2bow(words)) # 将每个分词列表转换为语料库词袋(bag of words)形式的列表 print ('{:*^60}'.format('bag of words review:')) print (corpus[0]) # 打印输出第一条语料库 # TF-IDF转换 if training == True: tfidf = models.TfidfModel(corpus) # 建立TF-IDF模型对象 corpus_tfidf = tfidf[corpus] # 得到TF-IDF向量稀疏矩阵 print ('{:*^60}'.format('TF-IDF model review:')) for doc in corpus_tfidf: # 循环读出每个向量 print(doc) # 打印第一条向量 break # 跳出循环 return dic, corpus_tfidf, tfidf else: return tfidf_object[corpus] # 全角转半角 def str_convert(content): ''' 将内容中的全角字符,包含英文字母、数字键、符号等转换为半角字符 :param content: 要转换的字符串内容 :return: 转换后的半角字符串 ''' new_str = '' for each_char in content: # 循环读取每个字符 code_num = ord(each_char) # 读取字符的ASCII值或Unicode值 if code_num == 12288: # 全角空格直接转换 code_num = 32 elif (code_num >= 65281 and code_num <= 65374): # 全角字符(除空格)根据关系转化 code_num -= 65248 new_str += chr(code_num) return new_str # 解析文件内容 def data_parse(data): ''' 从原始文件中解析出文本内容数据 :param data: 包含代码的原始内容 :return: 文本中的所有内容,列表型 ''' raw_code = BeautifulSoup(data, "lxml") # 建立BeautifulSoup对象 content_code = raw_code.find_all('content') # 从包含文本的代码块中找到content标签 content_list = [] # 建立空列表,用来存储每个content标签的内容 for each_content in content_code: # 循环读出每个content标签 if len(each_content) > 0: # 如果content标签的内容不为空 raw_content = each_content.text # 获取原始内容字符串 convert_content = str_convert(raw_content) # 将全角转换为半角 content_list.append(convert_content) # 将content文本内容加入列表 return content_list # 解压缩文件 if not os.path.exists('./news_data'): # 如果不存在数据目录,则先解压数据文件 print ('extract data from news_data.tar.gz...') tar = tarfile.open('news_data.tar.gz') # 打开tar.gz压缩包对象 names = tar.getnames() # 获得压缩包内的每个文件对象的名称 for name in names: # 循环读出每个文件 tar.extract(name, path='./') # 将文件解压到指定目录 tar.close() # 关闭压缩包对象 # 汇总所有内容 print('walk files and get content...') all_content = [] # 总列表,用于存储所有文件的文本内容 for root, dirs, files in os.walk('./news_data'): # 分别读取遍历目录下的根目录、子目录和文件列表 for file in files: # 读取每个文件 file_name = os.path.join(root, file) # 将目录路径与文件名合并为带有完整路径的文件名 with open(file_name) as f: # 以只读方式打开文件 data = f.read() # 读取文件内容 all_content.extend(data_parse(data)) # 从文件内容中获取文本并将结果追加到总列表 # 获取每条内容的分词结果 print ('get word list...') words_list = [] # 分词列表,用于存储所有文件的分词结果 for each_content in all_content: # 循环读出每个文本内容 words_list.append(list(jieba_cut(each_content))) # 将文件内容的分词结果以列表的形式追加到列表 # 建立主题模型 print ('train topic model...') dic, corpus_tfidf, tfidf = text_pro(words_list, tfidf_object=None, training=True) # 训练集的文本预处理 num_topics = 3 # 设置主题个数 lda = models.LdaModel(corpus_tfidf, id2word=dic, num_topics=num_topics) # 通过LDA进行主题建模 print ('{:*^60}'.format('topic model review:')) for i in range(num_topics): # 输出每一类主题的结果 print (lda.print_topic(i)) # 输出对应主题 # 新数据集的主题模型预测 print ('topic forecast...') with open('article.txt') as f: # 打开新的文本 text_new = f.read() # 读取文本数据 text_content = data_parse(data) # 解析新的文本 words_list_new = jieba_cut(text_new) # 将文本转换为分词列表 corpus_tfidf_new = text_pro([words_list_new], tfidf_object=tfidf, training=False) # 新文本数据集的预处理 corpus_lda_new = lda[corpus_tfidf_new] # 获取新的分词列表(文档)的主题概率分布 print ('{:*^60}'.format('topic forecast:')) print (list(corpus_lda_new))
c8/Content_Topic_Mining_Based_On_LDA.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.6.0 # language: julia # name: julia-1.6 # --- # # Section 5 Exercise - Word Count # # # <img src="./img/william_shakespeare.png" alt="<NAME>" width="250" /> # # Sonnet 18 txt = """Shall I compare thee to a summer's day? Thou art more lovely and more temperate: Rough winds do shake the darling buds of May, And summer's lease hath all too short a date: Sometime too hot the eye of heaven shines, And often is his gold complexion dimmed, And every fair from fair sometime declines, By chance, or nature's changing course untrimmed: But thy eternal summer shall not fade, Nor lose possession of that fair thou ow'st, Nor shall death brag thou wander'st in his shade, When in eternal lines to time thou grow'st, So long as men can breathe, or eyes can see, So long lives this, and this gives life to thee.""" ; function tokenize(txt::String)::Vector{String} # TODO end function word_count(token_array::Vector{String})::Dict{String, Int64} # TODO end function tokenize(txt::String)::Vector{String} txt_mod = strip(txt) txt_mod = lowercase(txt_mod) txt_mod = replace(txt_mod, "\n" => " ") txt_mod = replace(txt_mod, r"[,.:?]" => "") txt_arr = split(txt_mod, " ") txt_arr = map(x -> split(x, "'")[1], txt_arr) txt_arr end; function word_count(token_array::Vector{String})::Dict{String, Int64} count_dict = Dict() for token in token_array if !isempty(token) if (token ∉ keys(count_dict)) count_dict[token] = 1 else count_dict[token] += 1 end end end return count_dict end; token_array = tokenize(txt) word_count_dict = word_count(token_array) @assert word_count_dict["of"] === 3 @assert word_count_dict["summer"] === 3 @assert word_count_dict["wander"] === 1 @assert word_count_dict["day"] === 1 @assert word_count_dict["untrimmed"] === 1 @assert word_count_dict["thee"] === 2
sec5_exercise_word_count.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from keras.applications import MobileNetV2 from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.layers import Activation import numpy as np from keras import models from keras import layers from keras import optimizers from keras.utils import np_utils from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau from livelossplot import PlotLossesKeras from keras.optimizers import Adam from keras.models import Sequential, Model, load_model from keras.layers import Dropout, Flatten, Dense from keras.layers import Dense, GlobalAveragePooling2D # + base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # add a global spatial average pooling layer x = base_model.output x = GlobalAveragePooling2D()(x) x = Dropout(0.25)(x) x = Dense(1024, activation='relu')(x) predictions = Dense(7, activation='softmax')(x) # this is the model we will train model = Model(inputs=base_model.input, outputs=predictions) model.compile(loss='categorical_crossentropy', optimizer = Adam(), metrics=['accuracy']) model.summary() # + def preprocess_input(image): return image/255 train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input, shear_range=0.2, zoom_range=0.2, vertical_flip = True, horizontal_flip=True, validation_split = 0.2) train_generator = train_datagen.flow_from_directory('./data', target_size=(224, 224), batch_size=32, class_mode='categorical', subset='training') validation_generator = train_datagen.flow_from_directory( './data', target_size=(224, 224), batch_size=64, class_mode='categorical', subset='validation') model.fit_generator( train_generator, steps_per_epoch = train_generator.samples // 32, validation_data = validation_generator, validation_steps = validation_generator.samples // 64, epochs = 10) # class_weight= # {0: 99, # 1: 93, # 2: 157, # 3: 13, # 4: 119, # 5: 136, # 6: 101} # - def check_keras_backend(print_gpu_availavility = True): from tensorflow.python.client import device_lib assert 'GPU' in str(device_lib.list_local_devices()) from keras import backend assert len(backend.tensorflow_backend._get_available_gpus()) > 0 if print_gpu_availavility: print('Keras: backend is GPU') check_keras_backend() # + model.compile(loss='categorical_crossentropy', optimizer = Adam(0.001/100), metrics=['accuracy']) model.fit_generator( train_generator, steps_per_epoch = train_generator.samples // 32, validation_data = validation_generator, validation_steps = validation_generator.samples // 64, epochs = 2) # - print('True', (np.argmax(y_test[2]))) print('Predicted', np.argmax(model.predict(preprocess_input(Xtest[2]).reshape(1, 224, 224, 3)))) model.save("model.h5")
DEEP LEARNING/image classification/keras/predict transform 2 tflite/kinder classification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # compare chains # + import sys sys.path.insert(0, '../') from ctapipe.utils import get_dataset_path import reco.calib_dl0_to_dl1 as calib import pandas as pd import numpy as np # - filename = get_dataset_path('gamma_test_large.simtel.gz') # ### new chain with hdf5 writer calib.r0_to_dl1(input_filename=filename) new_df = pd.read_hdf('dl1_gamma_test_large.h5', key='events/LSTCam') # ### previous chain df = calib.get_events(filename) # ### compare everything is ok assert len(df) == len(new_df) [print(col) for col in df if col not in new_df] for col in df: if col in new_df and not (df[col] == new_df[col]).all(): if not (np.isclose(df[col], new_df[col], rtol=1e-3)).all(): print(col)
notebooks/compare_chains.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Es hora de decir adiós # Esta será la última clase del semestre en cuanto a contenidos, trataremos de cerrar con broche de oro con lo que debería depararte el destino después del curso de Aplicaciones de la Matemática en la Ingeniería. # ## Mundo Laboral # # Esta sección está basada casi en su totalidad en la versión del curso dictada el año 2018, en esa ocasión el que dictó la clase de Mundo Laboral fue [<NAME>](https://www.linkedin.com/in/sebastiandres/) (mi actual jefe), quien tiene mucha más experiencia en esto. # ### Entrevista de Trabajo # # Algunos tips y recomendaciones que podrían ser útiles a la hora de enfrentar una entrevista de trabajo. Digámos las cosas como son, los sansanos no nos caracterizamos por ser las personas más elocuentes del país. Si a lo anterior le sumas la carrera de Ingeniería Civil Matemática obtenemos un mal cliché. # #### Antes # # 1. **Transversales** # 1. Participar en actividades extraprogramáticas, representación de la carrera u otros intereses. # - **Objetivo**: aprender a distribuir tiempos. # 1. Obtener aprendizajes fuera de la universidad: cursos en línea, kaggle, etc. # - **Objetivo**: romper la burbuja y tener "calle". # 1. Maximizar el aprendizaje, aún a costo de bajar las notas. # - **Objetivo**: obtener recomendaciones, capacidades y habilidades. # 1. Generar perfil profesional: LinkedIn, correo profesional, etc. # - **Objetivo**: mostrarse profesional y poder hacer networking. # 1. **Preparación** # 1. Sobre la **empresa**: ¿Qué hacen? ¿Porqué lo hacen? ¿Quiénes pagan por el producto/servicio? ¿Quiénes trabajan en la empresa? # 1. Sobre la **posición**: ¿Qué se espera del cargo? ¿Que responsabilidades tendrá? ¿Qué herramientas y conocimientos previos se requieren? # 1. **Referencias**: ¿Conozco alguien que ha trabajado/entrevistado ahí? ¿Qué tipo de entrevistas hacen? # 1. **Lecturas**: Si tienes poca/nula experiencia en entrevistas, googlea e infórmate de las preguntas más comunes y prepara algunas respuestas honestas. # 1. Todos las condiciones de un trabajo son referenciales. Si estás interesado, demuéstralo y negocia. # 1. **Curriculum Vitae** # 1. **Formato**: Evitar templates clásicos, buscar algo que sea memorable. # 1. **Extensión**: 1 página. Máximo 2 páginas. # 1. **Ortografía**: Que una tercera persona, ojalá un maniático del detalle, revise el CV. # 1. **Proactividad**: Orientación a resultados generados y experiencias adquiridas. # 1. **Contenido**: Datos de identificación, estudios relevantes al cargo, trabajos anteriores, referencias. No: estado civil, hijos, fotos, información no relevante. # # #### Durante # 1. **Actitud** # 1. **Relajado pero interesado**: # * No pierdes nada. Estadísticamente, lo más probable es que no consigas el trabajo/práctica pero si ganarás experiencia para la próxima entrevista. # * El mayor riesgo está en el lado del empleador, quien está gastando tiempo y recursos por una apuesta de un trabajador sobre la media. # 1. **Interesado y Proactivo**: # * Se busca gente que solucione problemas, no que se quede pasiva, menos aún que los genere. # * Muestra interés genuino por el trabajo/práctica. # 1. **Respaldo con ejemplos**: # * Ten preparados ejemplos de proyectos y trabajos que hayan destacado y que demuestren pasión y calidad. # 2. **_Beer Test_** # - Si la persona que hace la entrevista es otro ingeniero, relájate... # * Situación es fácil de leer y anticipar con suficiente preparación. # * Lo más probable es que el otro ingeniero estaba en medio de su trabajo y lo están obligando a realizar entrevistas. # * No tiene más preparación para hacer entrevistas que tú como entrevistado. Probablemente sólo googleó "Interview questions" en google y anotó las que le parecían más razonables. # * Sólo hay que pasar el _beer test_: el otro ingeniero sólo busca alguien que sea *suficientemente* capacitado para resolver problemas y que sea alguien con quien no sea desagradable trabajar. # 3. Algunas preguntas # * Sobre tipo de **mentalidad**: ¿Cómo has superado un obstáculo o fracaso? # * Soble trabajo con **stress**: ¿Cómo enfrentas situaciones difíciles, como deadlines o personas complejas? # * Sobre **trabajo en equipo**: ¿Cómo trabajas en equipo? # * Sobre **frustración**: ¿Cómo has tratado o tratarías el caso de un compañero de equipo que no hace su parte? # * Sobre **rigor y detallismo**: Cuéntame de algún proyecto personal que te represente profesionalmente. # # #### Después # # 1. Follow Up # * Reflexiona sobre lo que podrías haber hecho mejor. ¿Mejor preparación? ¿Revisión de conceptos e ideas? ¿Mayor confianza? **Corrige** para hacerlo mejor la próxima vez. # * Envía un **correo** agradeciendo la entrevista sin ser falso: "*consideré interesante la pregunta X, ...*". A cada puesto postulan 10 a 100 personas, y esos pequeños gestos destacan. # * En caso de no ser aceptado, puedes pedir retroalimentación. Poca gente lo hace. A veces las razones son diametralmente opuestas a las que uno imaginaba. # * La práctica hace al maestro: postula a prácticas o trabajos aunque no estes 100% interesado. Permitirá generar confianza para la entrevista del *trabajo soñado*. # ### La oficina # # La vida en la oficina puede parecer una locura en ocasiones, aquí algunas cosas a tener en consideración # # 1. Principio de Incompetencia de Peter # - En una jerarquía, todo empleado tiende a ascender hasta su nivel de incompetencia: la nota sube hasta cortarse. # 1. Principio de Hanlon # - Nunca atribuyas a la maldad lo que puede ser explicado por la estupidez. # 1. <NAME> # - El trabajo se expande hasta llenar el tiempo disponible para su realización. # 1. <NAME> # - Todo lo que puede salir mal, saldrá mal. # ### Relaciones Interpersonales # # (Source: Dr. <NAME>, creador de _The Platinium Rule_.) # # * __Silver Rule__ # - *One should not treat others in ways that one would not like to be treated*: No trates a otros en una forma que no quieras ser tratado. # * __Golden Rule__ # - *One should treat others as one would like others to treat oneself*: Trata a otros en la misma forma que quieras ser tratado. # * __Platinium Rule__ # - *Treat others the way they want to be treated*: Trata a otros en la forma que ellos quieren ser tratados. # - Enfoque reduccionista y simplista, pero sencillo de recordar y aplicar. # Hay cuatro tipos básicos de personalidad: # # 1. Pensador (Thinker) # 1. Director (Director) # 1. Relacionador (Relater) # 1. Sociabilizador (Socializer) # # ![pr](../images/PR1.png) # El _cliché_: # 1. ***Pensador (Thinker)***: científico/contador. # 1. ***Director (Director)***: gerente/sargento. # 1. ***Relacionador (Relater)***: enfermero/sicólogo. # 1. ***Sociabilizador (Socializer)***: vendedor de autos/publicista. # # ![pr2](../images/PR4.png) # #### _Thinker_ # # ![thinker](../images/PR4c.png) # # - ¿Qué hacen bien? # * Organizar y planificar. # * Rápido para pensar, pero lento para hablar y actuar. # * Trabajar individualmente. # - ¿Qué les cuesta? # * Trabajar con gente desorganizada o en ambientes caóticos. # * Hablar de temas personales. # * Trabajar en grupo. # * Instrucciones incompletas o confusas. # #### _Director_ # # ![director](../images/PR4d.png) # # - ¿Qué hacen bien? # * Tomar el control. # * Realizar decisiones bajo riesgo. # * Sobreponerse a obstáculos. # - ¿Qué les cuesta? # * Tareas repetitivas. # * Ser diplomáticos. # * Reglas y regulaciones. # * No son tímidos, pero sí reservados de temas personales. # #### _Relaters_ # # ![relatres](../images/PR4a.png) # # - ¿Qué hacen bien? # * Amigables y sensibles: buenos oyentes. # * Construir redes de amigos. # * Coordinar y cooperar con otros. # - ¿Qué les cuesta? # * Competir. # * Trabajar con gente dictatorial o poco amigable. # * Tomar decisiones grandes, propensos a rechazar los cambios. # * Emitir opiniones contrarias. # #### _Socializers_ # # ![socializer](../images/PR4b.png) # # - ¿Qué hacen bien? # * Inspirar a otros a tomar acción. # * Pensar rápido: intuitivos, optimistas, creativos. # * Llenos de ideas, pero impulsivos. # - ¿Qué les cuesta? # * Restricciones. # * Reportes formales o contabilidad. # * Rutina. # * Repetir acciones. # Para relacionarse con cada tipo de personalidad hay que **entregar lo que a la otra personalidad le parece importante**. # # Como enfrentar cada tipo de personalidad: # # 1. Con Pensadores, sé detallado, bien preparado y paciente. # 1. Con Directores, sé eficiente y competente. # 1. Con Relacionadores, sé sincero y no amenazante. # 1. Con Sociabilizadores, interésate por ellos y sus historias. # # __¡Cuidado!__ # # * La personalidad que uno cree/quiere tener es distinta de la que los demás perciben de uno mismo. # * Una misma persona puede presentar diversas personalidades para distintos ámbitos: familia, trabajo, amigos. # ### Metodologías de Trabajo # # - ***Cascada (Waterfall)***: # * Cliente define requerimientos al inicio y empresa cumple, etapa a etapa, con desarrollo especificado. # * Orientado a proyectos de alta complejidad, con horizontes de tiempo de años. # - ***Desarrollo Ágil (Agile)***: # * Trabajo codo a codo con cliente mediante iteraciones constantes. # * Orientado a proyectos de alta variabilidad, con horizontes de tiempo de semanas/meses. # #### Waterfall # # Enfoque metodológico que ordena rigurosa4ente las etapas del proceso para el desarrollo de software, de tal forma que el inicio de cada etapa debe esperar a la finalización de la etapa anterior. # # ![waterfall](../images/MT1.png) # # - Ventajas # * Promueve análisis sobre improvisación: _Definir antes que diseñar, diseñar antes de codificar_. # * Modelo tradicional: ampliamente conocido y utilizado con frecuencia. # * Fácil de implementar, entender y dirigir. # * Requiere de menos capital y herramientas para hacerlo funcionar de manera óptima. # - Desventajas # * Proyectos en el mundo real no son lineales; el cliente siempre tiene ideas adicionales. Involucrar tardíamente al cliente conlleva disconformidad y fracaso del proyecto. # * Secuencialismo: etapa $i+1$ no se puede llevar a cabo a menos que se haya culminado la etapa $i$. # * Demoras: No es posible paralelizar etapas y el software sólo puede validarse una vez que todas las etapas anteriores han finalizado. # * Propenso a costos adicionales: errores no detectados en etapa $i$ conducen a cambios en todas las etapas posteriores ya realizadas. # * Promueve respeto y obediencia sobre innovación y creatividad. # # ![treeswing](../images/treeswing.jpg) # #### Agile # # Enfoque metodológico que promueve el desarrollo iterativo e incremental, donde los requisitos y soluciones evolucionan mediante la colaboración de grupos auto-organizados y multidisciplinarios. # # ![agile](../images/MT2.png) # # ***Manifesto for Agile Software Development, 2001*** # # We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value: # # * Individuals and interactions over processes and tools # * Working software over comprehensive documentation # * Customer collaboration over contract negotiation # * Responding to change over following a plan # # That is, while there is value in the items on the right, we value the # items on the left more. # __Principios Básicos__ # # * La prioridad es satisfacer al cliente mediante tempranas y continuas entregas de software que le aporte un valor. # * Dar la bienvenida a los cambios. Se capturan los cambios para que el cliente tenga una ventaja competitiva. # * Entregar frecuentemente software que funcione desde un par de semanas a un par de meses, con el menor intervalo de tiempo posible entre entregas. # * La gente del negocio y los desarrolladores deben trabajar juntos a lo largo del proyecto. El cliente es un aliado, no un enemigo. # * Construir el proyecto en torno a individuos motivados. Darles el entorno y el apoyo que necesitan y confiar en ellos para conseguir finalizar el trabajo. # * El diálogo cara a cara es el mejor método para comunicar información dentro de un equipo de desarrollo. # * El software que funciona es la medida principal de progreso. La simplicidad es esencial. # # - Ventajas # * Respuesta rápida a cambios de requisitos, minimizando costos, tiempo y frustración. # * Efecto IKEA: el cliente se involucra y tiene una mejor satisfacción sobre el resultado final. # * Al privilegiar la simplicidad se eliminan trabajos innecesarios/superfluos. # * Permite paralelizar requerimientos y validar implementaciones por separado. # * Puesto que el software es siempre “casi funcional” permite mantener proyecto en costo acordado. Siempre es posible parar el proyecto en la iteración actual. # * Promueve innovación y creatividad sobre respeto y obediencia. # - Desventajas # * Falta de documentación del diseño. # * Problemas derivados de la comunicación oral: ambiguedad y futilidad. # * Alta dependencia a las personas del equipo. # * Restricciones en cuanto al tamaño y la complejidad de los proyectos. # #### Agile vs Waterfall # # * Adaptividad vs Predictibilidad # * Iterativo vs Secuencial # * Código vs Documentación # # La Metodología Agil puede interpretarse como una aplicación del principio de Pareto (ley del 80-20), que dice que, para muchos eventos, aproximadamente 80% de los efectos proviene del 20% de las causas. # # Reuniones tempranas con el cliente permite determinar cuáles son las causas de mayor impacto y establecer una ruta óptima de construcción en función de los requerimientos cambiantes del cliente. # # Algunos ejemplos: # - Aplicacion en Ingeniería # * Tener reuniones pequeñas reuniones semanales es mejor que una gran reunión mensual. # * Mejorar incrementalmente informe e implementación numérica. # * El cliente tiene derecho cambiar de opinión: ¡Está pagando por ello! # - Aplicacion en Vida Universitaria # * Tener lo antes posible un entregable que garantice el 50-70 % de la nota. # * Mejorar incrementalmente el entregable, en función del tiempo disponible y del esfuerzo requerido. # * Si se requiere código numérico, preocuparse del código hasta que funcione, luego documentar. # * El profesor es el cliente: preguntar con tiempo y clarificar expectativas. Lo esencial es cumplir los requerimientos. # ## Ética # # ¿Has tomado algún curso de ética durante tu vida universitaria? ¿En cuántos cursos te han hablado de ética? Muchas veces el foco de aprendizaje son las habilidades técnicas, ya sea en menosprecio de las habilidades blandas o asumiendo que todos las poseen. # # Como cualquier otra habilidad, la ética hay que cultivarla. En conjunto a un pensamiento lógico y crítico es posible llevar los problemas con sus respectivas soluciones a un siguiente nivel. # # En el contexto del curso, hay una rama de la ética llamada _Data Ethics_, la cual cubre una gama increíblemente amplia de temas, muchos de los cuales son urgentes, aparecen en los titulares a diario y causan daño a las personas en este mismo momento. # ### ¿Datos _limpios_ = _Buen_ modelo? # # En _machine learning_ se suele hablar mucho de datos sucios y el gasto de HH que implica procesarlos en función de obtener los datos estructurados con tal de ser el insumo de un algoritmo de aprendizaje. Entonces, el santo grial de estos ingenieros o los famosos _data scientits_ serían datos limpios, no procesar nada, _llegar y llevar_. # # Nuestro análisis no se puede quedar solo en el formato de las columnas o en la cantidad de datos faltantes, tiene que ir mucho más allá. Algunas preguntas que deberías hacer son: # # * ¿Cuál es la fuente de estos datos? # * ¿Cómo se recolectaron? # * ¿Son lo suficientemente robusto para generalizar y que el algoritmo _aprenda_? # * ¿Representan la realidad? # * ¿Tienen algún tipo de sesgo? # * etc. $\times$ 1000 # # En ocasiones, ni siquiera esto es suficiente... # #### Sesgo racial en pacientes enfermos # # En 2019, un estudio demostró que un algoritmo ampliamente utilizado por hospitales y aseguradoras de EE. UU. con la finalidad de asignar asistencia adicional para la gestión de la salud discriminaba sistemáticamente a las personas negras. La herramienta de decisión tenía menos probabilidades de derivar a las personas negras que a las blancas a programas de gestión de la atención para necesidades médicas complejas cuando ambos grupos raciales estaban igualmente enfermos. # # La razón subyacente del sesgo estaba relacionada con el algoritmo de asignación de puntajes de riesgo a los pacientes en función de los costos médicos del año anterior. La suposición era que la identificación de pacientes con costos más altos identificaría a aquellos con las necesidades médicas más altas. Sin embargo, muchos pacientes negros tienen menos acceso, menos capacidad de pago y menos confianza en la atención médica que las personas blancas que están igualmente enfermas. En este caso, sus costos médicos más bajos no predijeron con precisión su estado de salud. # # Fuente y más ejemplos: https://www.investopedia.com/bias-in-medical-decision-making-tools-5083308 # #### _Weapons of Math Destruction_ # # ![wmd](https://images-na.ssl-images-amazon.com/images/I/51eUw-v0X+L._SX329_BO1,204,203,200_.jpg) # # _We live in the age of the algorithm. Increasingly, the decisions that affect our lives—where we go to school, whether we get a car loan, how much we pay for health insurance—are being made not by humans, but by mathematical models. In theory, this should lead to greater fairness: Everyone is judged according to the same rules, and bias is eliminated._ # # _But as <NAME> reveals in this urgent and necessary book, the opposite is true. The models being used today are opaque, unregulated, and uncontestable, even when they’re wrong. Most troubling, they reinforce discrimination: If a poor student can’t get a loan because a lending model deems him too risky (by virtue of his zip code), he’s then cut off from the kind of education that could pull him out of poverty, and a vicious spiral ensues. Models are propping up the lucky and punishing the downtrodden, creating a “toxic cocktail for democracy.” Welcome to the dark side of Big Data._ # # **Video Super-mega-recomendado:** [The era of blind faith in big data must end | <NAME>](https://youtu.be/_2u_eHHzRto) # ## Próximos pasos # De este punto en adelante, cada uno es libre de tomar el camino que más le guste. A continuación algunos temas que puedes seguir estudiando para complementar los contenidos del curso y tu desarrollo profesional. # # 1. _Data Ethics_ # - Sin duda de lo más importante, al trabajar con modelos estamos plasmando opiniones en forma de código. # - Este mini-curso se ve muy muy bueno: [Practical Data Ethics](https://ethics.fast.ai/) # 1. Relaciones interpersonales # - Identificar qué tipo de personalidad posees (hay tests disponibles en internet). # - Entender y aplicar metodologías de trabajo sacando provecho a tu personalidad. # 1. Modelamiento # - Preprocesamiento # * Tratar _features_ categóricas, por ejemplo _One-Hot-Encoding_. # * Tratar con datos desbalanceados, por ejemplo _Over-Sampling_. # * _Dimensionality Reduction_, _Feature Selection_, etc., por ejemplo, _Principal Component Analysis_. # - Modelos de Machine Learning # * _Suppor Vector Machine_ # * _Decision Trees_ # * _Ensemble Methods_ # - Redes Neuronales y Deep Learning # * Toda la teoría, incluído redes convolusionales y modelos secuenciales. # * Frameworkds como Tensorflow, Keras, PyTorch entre otros. # - _Hyperparameter tunning_ # - _Feature Importance_ # * Explicar modelos. # * SHAP (este en particular es el que más me gusta a mi). # 1. Operacionales # - SQL # - Git # - Power BI, Tableau, Google Data Studio, Dash u otra herramienta para realizar dashboards. # - Docker # - Linux # - Cloud Computing (AWS, GCP, Azure) # - Otro lenguaje de programación
lessons/M5L01_real_world.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + import gensim import os import collections import smart_open import random from sklearn.manifold import TSNE import matplotlib.pyplot as plt import itertools import plotly.plotly as py import plotly.graph_objs as go import plotly.offline as offline import time import seaborn as sns import numpy as np import multiprocessing flatten = lambda l: [item for sublist in l for item in sublist] # + """ Load basic ingredients and compounds data """ path = 'data' ingr_info = path + os.sep + 'ingr_info.tsv' comp_info = path + os.sep + 'comp_info.tsv' ingr_comp = path + os.sep + 'ingr_comp.tsv' # {ingredient_id: [ingredient_name, ingredient_category]} def load_ingredients(path): ingredients = {} ingredients_list = [] with open(path, 'r') as f: for line in f: if line[0] == '#': pass else: line_split = line.rstrip().split('\t') ingredients_id = line_split[0] ingredients_list = line_split[1:] ingredients[ingredients_id] = ingredients_list return ingredients # {compound_id: [compound_name, CAS_number]} def load_compounds(path): compounds = {} compounds_list = [] with open(path, 'r') as f: for line in f: if line[0] == '#': pass else: line_split = line.rstrip().split('\t') compounds_id = line_split[0] compounds_list = line_split[1:] compounds[compounds_id] = compounds_list return compounds # {ingredient_id: [compound_id1, compound_id2, ...] } def load_relations(path): relations = {} with open(path, 'r') as f: for line in f: if line[0] == '#': pass else: line_split = line.rstrip().split('\t') ingredient_id = line_split[0] compound_id = line_split[1] if ingredient_id in relations: relations[ingredient_id].append(compound_id) else: relations[ingredient_id] = [compound_id] return relations ingredients = load_ingredients(ingr_info) compounds = load_compounds(comp_info) relations = load_relations(ingr_comp) def ingredient_to_category(tag, ingredients): for ingr_id in ingredients: if ingredients[ingr_id][0] == tag: return ingredients[ingr_id][1] else: continue return print ingredient_to_category('copaiba', ingredients) # + """ Load train data and build train_corpus for Doc2Vec """ path = 'data' train_file = path + os.sep + 'ingredient2vec' def read_corpus(fname, tokens_only=False): with smart_open.smart_open(fname, encoding="iso-8859-1") as f: for i, line in enumerate(f): if tokens_only: yield gensim.utils.simple_preprocess(line) else: # For training data, add tags line_split = line.split(' ') ingredient = line_split[0] compounds = ' '.join(line_split[1:]) yield gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(compounds), [ingredient]) # Corpus tag to index def tag_to_index(tags, corpus): for doc_id in range(len(corpus)): if tags == corpus[doc_id].tags[0]: return doc_id else: continue return # Corpus index to tag def index_to_tag(index, corpus): return corpus[index].tags train_corpus = list(read_corpus(train_file)) print index_to_tag(0, train_corpus) print tag_to_index('ruta_chalepensis_oil', train_corpus) # + # thresh hold train_corpus_th10 = [] for doc_id in range(len(train_corpus)): if len(train_corpus[doc_id].words) > 10: train_corpus_th10.append(train_corpus[doc_id]) # + """ Load functions for plotting a graph """ # Prettify ingredients pretty_food = lambda s: ' '.join(s.split('_')).capitalize().lstrip() # Prettify cuisine names pretty_category = lambda s: ''.join(map(lambda x: x if x.islower() else " "+x, s)).lstrip() def make_plot_simple(name, points, labels, publish): traces = [] traces.append(go.Scattergl( x = points[:, 0], y = points[:, 1], mode = 'markers', marker = dict( color = sns.xkcd_rgb["black"], size = 8, opacity = 0.6, #line = dict(width = 1) ), text = labels, hoverinfo = 'text', ) ) layout = go.Layout( xaxis=dict( autorange=True, showgrid=False, zeroline=False, showline=False, autotick=True, ticks='', showticklabels=False ), yaxis=dict( autorange=True, showgrid=False, zeroline=False, showline=False, autotick=True, ticks='', showticklabels=False ) ) fig = go.Figure(data=traces, layout=layout) if publish: plotter = py.iplot else: plotter = offline.plot plotter(fig, filename=name + '.html') def make_plot(name, points, labels, legend_labels, legend_order, legend_label_to_color, pretty_legend_label, publish): lst = zip(points, labels, legend_labels) full = sorted(lst, key=lambda x: x[2]) traces = [] for legend_label, group in itertools.groupby(full, lambda x: x[2]): group_points = [] group_labels = [] for tup in group: point, label, _ = tup group_points.append(point) group_labels.append(label) group_points = np.stack(group_points) traces.append(go.Scattergl( x = group_points[:, 0], y = group_points[:, 1], mode = 'markers', marker = dict( color = legend_label_to_color[legend_label], size = 8, opacity = 0.6, #line = dict(width = 1) ), text = ['{} ({})'.format(label, pretty_legend_label(legend_label)) for label in group_labels], hoverinfo = 'text', name = legend_label ) ) # order the legend ordered = [[trace for trace in traces if trace.name == lab] for lab in legend_order] traces_ordered = flatten(ordered) def _set_name(trace): trace.name = pretty_legend_label(trace.name) return trace traces_ordered = list(map(_set_name, traces_ordered)) """ annotations = [] for index in range(50): new_dict = dict( x=points[:, 0][index], y=points[:, 1][index], xref='x', yref='y', text=labels[index], showarrow=True, arrowhead=7, ax=0, ay=-10 ) annotations.append(new_dict) """ layout = go.Layout( xaxis=dict( autorange=True, showgrid=False, zeroline=True, showline=True, autotick=True, ticks='', showticklabels=False ), yaxis=dict( autorange=True, showgrid=False, zeroline=True, showline=True, autotick=True, ticks='', showticklabels=False ), #annotations=annotations ) fig = go.Figure(data=traces_ordered, layout=layout) if publish: plotter = py.iplot else: plotter = offline.plot plotter(fig, filename=name + '.html') # + """ Train Doc2Vec Model """ time_start = time.time() cores = multiprocessing.cpu_count() #dm/m,d50,n5,w5,mc5,s0.001,t3 #model = gensim.models.doc2vec.Doc2Vec(size=50, min_count=5, iter=55) # load pre-trained character embeddings of flavor compounds load_name = 'embeddings' + os.sep + 'embeddings_flavor_compounds_50dim.bin' model = gensim.models.doc2vec.Doc2Vec(size=50, min_count=5, iter=55) model.build_vocab(train_corpus_th10) #print model.docvecs.index_to_doctag(2), model.docvecs[2] model.intersect_word2vec_format(load_name, lockf=1.0, binary=True, encoding='utf8', unicode_errors='strict') # %time model.train(train_corpus_th10, total_examples=model.corpus_count, epochs=model.iter) print "Corpus_count:", model.corpus_count print 'Doc2Vec training done! Time elapsed: {} seconds'.format(time.time()-time_start) # + """ Check rank of inferred_vector """ ranks = [] second_ranks = [] for doc_id in range(len(train_corpus)): inferred_vector = model.infer_vector(train_corpus[doc_id].words) sims = model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs)) rank = [docid for docid, sim in sims].index(train_corpus[doc_id].tags[0]) ranks.append(rank) second_ranks.append(sims[1]) # + """ Pick a random document from the test corpus and infer a vector from the model Top 10 Similar Vector """ doc_id = random.randint(0, len(train_corpus)) print('Train Document ({}, {}): [{}]\n'.format(doc_id, train_corpus[doc_id].tags[0], ' '.join(train_corpus[doc_id].words))) inferred_vector = model.infer_vector(train_corpus[doc_id].words) sims = model.docvecs.most_similar([inferred_vector], topn=10) for sim in sims: print sim # + # Pick a random document from the test corpus and infer a vector from the model doc_id = random.randint(0, len(train_corpus)) inferred_vector = model.infer_vector(train_corpus[doc_id].words) sims = model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs)) # Compare and print the most/median/least similar documents from the train corpus print('Train Document ({}, {}): [{}]\n'.format(doc_id, train_corpus[doc_id].tags[0], ' '.join(train_corpus[doc_id].words))) print(u'SIMILAR/DISSIMILAR DOCS PER MODEL %s:\n' % model) for label, index in [('MOST', 0), ('MEDIAN', len(sims)//2), ('LEAST', len(sims) - 1)]: print label, sims[index] #print(u'%s %s: «%s»\n' % (label, sims[index], ' '.join(train_corpus[sims[index][0]].words))) # + # Pick a random document from the test corpus and infer a vector from the model doc_id = random.randint(0, len(train_corpus)) inferred_vector = model.infer_vector(train_corpus[doc_id].words) sims = model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs)) # Compare and print the most/median/least similar documents from the train corpus print('Train Document ({}, {}): [{}]\n'.format(doc_id, train_corpus[doc_id].tags[0], ' '.join(train_corpus[doc_id].words))) print(u'SIMILAR/DISSIMILAR DOCS PER MODEL %s:\n' % model) for label, index in [('MOST', 0), ('MEDIAN', len(sims)//2), ('LEAST', len(sims) - 1)]: print label, sims[index] #print(u'%s %s: «%s»\n' % (label, sims[index], ' '.join(train_corpus[sims[index][0]].words))) # + """ TSNE of Doc2Vec """ time_start = time.time() X = model.docvecs tsne = TSNE(n_components=2) X_tsne = tsne.fit_transform(X) print 't-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start) # - print type(X[0]) print type(X) # + labels = [] categories = [] for doc_id in range(0, len(model.docvecs)): labels.append(model.docvecs.index_to_doctag(doc_id)) for label in labels: categories.append(ingredient_to_category(label,ingredients)) categories_color = list(set(categories)) print categories_color category2color = { 'plant' : sns.xkcd_rgb["purple"], 'flower' : sns.xkcd_rgb["forest green"], 'meat' : sns.xkcd_rgb["light pink"], 'nut/seed/pulse' : sns.xkcd_rgb["mustard yellow"], 'herb' : sns.xkcd_rgb["orange"], 'alcoholic beverage' : sns.xkcd_rgb["magenta"], 'plant derivative' : sns.xkcd_rgb["purple"], 'fruit' : sns.xkcd_rgb["blue"], 'dairy' : sns.xkcd_rgb["deep blue"], 'cereal/crop' : sns.xkcd_rgb["sky blue"], 'vegetable' : sns.xkcd_rgb["olive"], 'animal product' : sns.xkcd_rgb["red"], 'fish/seafood' : sns.xkcd_rgb["yellow"], 'spice' : sns.xkcd_rgb["black"], } category_order = [ 'plant', 'flower', 'meat', 'nut/seed/pulse', 'herb', 'alcoholic beverage', 'plant derivative', 'fruit', 'dairy', 'cereal/crop', 'vegetable', 'animal product', 'fish/seafood', 'spice', ] # - make_plot(name='ingredient2vec_2', points=X_tsne, labels=labels, legend_labels=categories, legend_order=category_order, legend_label_to_color=category2color, pretty_legend_label=pretty_category, publish=False) # + """ compound-level plotting """ X_comp = model[model.wv.vocab] tsne_comp = TSNE(n_components=2) X_tsne_comp = tsne_comp.fit_transform(X_comp) labels_comp =[] for comp in model.wv.vocab: labels_comp.append(comp) make_plot_simple(name='food2vec_food_embeddings_tsne_comp', points=X_tsne_comp, labels=labels_comp, publish=False) # -
src/src_old/ingredient2vec.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="vIOjh3AvYWxH" # ## **Setup** # # - Code to download the data directly from the colab notebook. # - If you find it easier to download the data from the kaggle website (and uploading it to your drive), you can skip this section. # + colab={"base_uri": "https://localhost:8080/"} id="lE-oUHZNYlME" outputId="97b0d229-4937-4bae-89e1-54c063b66da0" # First mount your drive before running these cells. # Create a folder for the this HW and change to that dir # %cd # + id="hwwNGPowVz1I" # !pip install -q kaggle # + id="ArePZv5vV7Ui" from google.colab import files # Create a new API token under "Account" in the kaggle webpage and download the json file # Upload the file by clicking on the browse files.upload() # + colab={"base_uri": "https://localhost:8080/"} id="BRcVxAIPWpWb" outputId="aeffdbb5-b827-4d5c-d9e3-b2bd2a696bce" # !kaggle competitions download -c microsoft-malware-prediction # + [markdown] id="8GtADEq4Zw1g" # ## **Section 1: Library and Data Imports (Q1)** # # - Import your libraries and read the data into a dataframe. Print the head of the dataframe. # + id="uXHCH_wAXyEf" use_cols = ["MachineIdentifier", "SmartScreen", "AVProductsInstalled", "AppVersion", "CountryIdentifier", "Census_OSInstallTypeName", "Wdft_IsGamer", "EngineVersion", "AVProductStatesIdentifier", "Census_OSVersion", "Census_TotalPhysicalRAM", "Census_ActivationChannel", "RtpStateBitfield", "Census_ProcessorModelIdentifier", "Census_PrimaryDiskTotalCapacity", "Census_InternalPrimaryDiagonalDisplaySizeInInches", "Wdft_RegionIdentifier", "LocaleEnglishNameIdentifier", "AvSigVersion", "IeVerIdentifier", "IsProtected", "Census_InternalPrimaryDisplayResolutionVertical", "Census_PrimaryDiskTypeName", "Census_OSWUAutoUpdateOptionsName", "Census_OSEdition", "Census_GenuineStateName", "Census_ProcessorCoreCount", "Census_OEMNameIdentifier", "Census_MDC2FormFactor", "Census_FirmwareManufacturerIdentifier", "OsBuildLab", "Census_OSBuildRevision", "Census_OSBuildNumber", "Census_IsPenCapable", "Census_IsTouchEnabled", "Census_IsAlwaysOnAlwaysConnectedCapable", "Census_IsSecureBootEnabled", "Census_SystemVolumeTotalCapacity", "HasDetections" ] dtypes = { 'MachineIdentifier': 'category', 'ProductName': 'category', 'EngineVersion': 'category', 'AppVersion': 'category', 'AvSigVersion': 'category', 'IsBeta': 'int8', 'RtpStateBitfield': 'float16', 'IsSxsPassiveMode': 'int8', 'DefaultBrowsersIdentifier': 'float16', 'AVProductStatesIdentifier': 'float32', 'AVProductsInstalled': 'float16', 'AVProductsEnabled': 'float16', 'HasTpm': 'int8', 'CountryIdentifier': 'int16', 'CityIdentifier': 'float32', 'OrganizationIdentifier': 'float16', 'GeoNameIdentifier': 'float16', 'LocaleEnglishNameIdentifier': 'int8', 'Platform': 'category', 'Processor': 'category', 'OsVer': 'category', 'OsBuild': 'int16', 'OsSuite': 'int16', 'OsPlatformSubRelease': 'category', 'OsBuildLab': 'category', 'SkuEdition': 'category', 'IsProtected': 'float16', 'AutoSampleOptIn': 'int8', 'PuaMode': 'category', 'SMode': 'float16', 'IeVerIdentifier': 'float16', 'SmartScreen': 'category', 'Firewall': 'float16', 'UacLuaenable': 'float32', 'Census_MDC2FormFactor': 'category', 'Census_DeviceFamily': 'category', 'Census_OEMNameIdentifier': 'float16', 'Census_OEMModelIdentifier': 'float32', 'Census_ProcessorCoreCount': 'float16', 'Census_ProcessorManufacturerIdentifier': 'float16', 'Census_ProcessorModelIdentifier': 'float16', 'Census_ProcessorClass': 'category', 'Census_PrimaryDiskTotalCapacity': 'float32', 'Census_PrimaryDiskTypeName': 'category', 'Census_SystemVolumeTotalCapacity': 'float32', 'Census_HasOpticalDiskDrive': 'int8', 'Census_TotalPhysicalRAM': 'float32', 'Census_ChassisTypeName': 'category', 'Census_InternalPrimaryDiagonalDisplaySizeInInches': 'float16', 'Census_InternalPrimaryDisplayResolutionHorizontal': 'float16', 'Census_InternalPrimaryDisplayResolutionVertical': 'float16', 'Census_PowerPlatformRoleName': 'category', 'Census_InternalBatteryType': 'category', 'Census_InternalBatteryNumberOfCharges': 'float32', 'Census_OSVersion': 'category', 'Census_OSArchitecture': 'category', 'Census_OSBranch': 'category', 'Census_OSBuildNumber': 'int16', 'Census_OSBuildRevision': 'int32', 'Census_OSEdition': 'category', 'Census_OSSkuName': 'category', 'Census_OSInstallTypeName': 'category', 'Census_OSInstallLanguageIdentifier': 'float16', 'Census_OSUILocaleIdentifier': 'int16', 'Census_OSWUAutoUpdateOptionsName': 'category', 'Census_IsPortableOperatingSystem': 'int8', 'Census_GenuineStateName': 'category', 'Census_ActivationChannel': 'category', 'Census_IsFlightingInternal': 'float16', 'Census_IsFlightsDisabled': 'float16', 'Census_FlightRing': 'category', 'Census_ThresholdOptIn': 'float16', 'Census_FirmwareManufacturerIdentifier': 'float16', 'Census_FirmwareVersionIdentifier': 'float32', 'Census_IsSecureBootEnabled': 'int8', 'Census_IsWIMBootEnabled': 'float16', 'Census_IsVirtualDevice': 'float16', 'Census_IsTouchEnabled': 'int8', 'Census_IsPenCapable': 'int8', 'Census_IsAlwaysOnAlwaysConnectedCapable': 'float16', 'Wdft_IsGamer': 'float16', 'Wdft_RegionIdentifier': 'float16' } # - import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.ensemble import RandomForestClassifier train_complete = pd.read_csv('microsoft-malware-prediction/train.csv') train = train_complete[use_cols] train.shape train.head() # + [markdown] id="lwCqDB9DUw7t" # ## **Section 2: Measure of Power (Q2a & 2b)** # - # ### Section 2(a): Definition of Power as a Function of RAM and Processor Core Count # For the first part of task 2, I investigated the features in `use_cols` and considered which features are relevant to computer power. I found that the number of logical cores in the processor and the physical RAM are important factors to measure computer power. Therefore, I defined `ComputerPower` as a linear function of `Census_ProcessorCoreCount` and `Census_TotalPhysicalRAM`. That is, the population model is `ComputerPower` $= \beta_0 + \beta_1 \times$ `Census_ProcessorCoreCount` $+ \beta_2 \times$ `Census_TotalPhysicalRAM`. To figure out the appropriate coefficients of the variables ($\beta_0$, $\beta_1$, and $\beta_2$), I used the OuterVision® Power Supply Calculator to help investigate the relationship between the response and explanatory variables. To simplify the analysis, I assumed the following conditions for all machines: the type of device is Windows desktop; the CPU used for every machine is Intel Core i9-10980XE; the memory standard used to compute the load wattage supplies is double data rate third generation (DDR3); machine utilization time is 16 hours per day. Below are the descriptions for each variable. # # `ComputerPower` - Load wattage power consumption in W # # `Census_ProcessorCoreCount` - Number of logical cores in the processor # # `Census_TotalPhysicalRAM` - Retrieves the physical RAM in MB # # To begin, it is essential to look at the value types and the number of observations for each variable. df1 = train[['Census_ProcessorCoreCount', 'Census_TotalPhysicalRAM']] df1.value_counts() df1.isnull().sum() # Note that there are 41306 and 80533 missing values in the variables `Census_ProcessorCoreCount` and `Census_TotalPhysicalRAM`, respectively. The total numbers of missing values are about 0.5% and 1.0%, respectively, of the total number of observations. Here, I considered univariate imputation methods to impute the missing values because of the small proportions of missing data. To further select the best imputation method for this task, it is useful to examine the boxplots of the two variables. Similar strategies will be used to decide on the imputation method for future tasks. sns.boxplot(df1['Census_ProcessorCoreCount']) sns.boxplot(df1['Census_TotalPhysicalRAM']) # From the boxplots, it is obvious that the data for both variables are right-skewed (positively skewed). Therefore, it may not be appropriate to use mean imputation for the variables `Census_ProcessorCoreCount` and `Census_TotalPhysicalRAM`. Thus, I selected median imputation to fill the missing values. df1['Census_ProcessorCoreCount'].fillna(df1['Census_ProcessorCoreCount'].median(), inplace = True) df1['Census_TotalPhysicalRAM'].fillna(df1['Census_TotalPhysicalRAM'].median(), inplace = True) # It is better to verify again that there are no missing values in `Census_ProcessorCoreCount` and `Census_TotalPhysicalRAM`. df1.isnull().sum() # `Census_ProcessorCoreCount` and `Census_TotalPhysicalRAM` are considered continuous variables (some may argue that they are ordinal variables. However, it does not matter a lot to consider them as continuous or ordinal for this task). After a careful analysis of the $\beta$s with the use of linear regression theory and trial and error, I obtained the parameter estimates: $\beta_0=65$, $\beta_1=156$, and $\beta_2=0.0006959$. Hence, I have the following final model for measuring `ComputerPower`: # # `ComputerPower` $=65+156\times$ `Census_ProcessorCoreCount` $+0.0006959\times$ `Census_TotalPhysicalRAM` # # Now, we can create a new variable `ComputerPower`, and calculate computer power for different machines. df1['ComputerPower'] = 65 + 156 * df1['Census_ProcessorCoreCount'] + 0.0006959 * df1['Census_TotalPhysicalRAM'] df1['ComputerPower'].value_counts() q1 = df1['ComputerPower'].quantile(0.25) q3 = df1['ComputerPower'].quantile(0.75) iqr = q3 - q1 len(df1['ComputerPower'][(df1['ComputerPower'] > (q3 + 1.5 * iqr)) | (df1['ComputerPower'] < (q1 - 1.5 * iqr))]) / len(df1) # I noticed that the dataset contains a portion of outliers (about 11%). I used the traditional definition - Q1$-1.5\times$IQR and Q3$+1.5\times$IQR - as my classification of outliers, where Q1 and Q3 represent the 25\% and 75\% quantiles. IQR is the difference between Q3 and Q1. The outliers may affect the distribution of `ComputerPower`. # To properly visualize the distribution of computer power, I included two pairs of histograms. One pair is histograms without outliers, and the other pair is histograms with outliers. Each pair contains a frequency and a density histogram. # + plt.subplot(1, 2, 1) plt.hist(df1['ComputerPower'], range = [q1 - 1.5 * iqr, q3 + 1.5 * iqr]) plt.xlabel('Computer Power') plt.ylabel('Frequency') plt.title('Freq Histogram') plt.subplot(1, 2, 2) plt.hist(df1['ComputerPower'], range = [q1 - 1.5 * iqr, q3 + 1.5 * iqr], density = True) plt.xlabel('Computer Power') plt.ylabel('Density') plt.title('Density Histogram') plt.tight_layout() # + plt.subplot(1, 2, 1) plt.hist(df1['ComputerPower']) plt.xlabel('Computer Power') plt.ylabel('Frequency') plt.title('Freq Histogram') plt.subplot(1, 2, 2) plt.hist(df1['ComputerPower'], density = True) plt.xlabel('Computer Power') plt.ylabel('Density') plt.title('Density Histogram') plt.tight_layout() # - len(df1['ComputerPower'][(df1['ComputerPower'] < (q1 - 1.5 * iqr))]) len(df1['ComputerPower'][(df1['ComputerPower'] > (q3 + 1.5 * iqr))]) # By Central Limit Theorem, the distribution with a reasonably large number of observations should be approximately normal. In this case, because I selected only two factors to measure computer power, where some of the machines have the same measure input, the mass of the distribution aggregates into a few bars, as shown in the histograms. Also, note that all outliers are above Q3 based on the calculation above. Thus, the distribution is skewed to the right. I describe the distribution as a right-skewed bimodal distribution. # ### Section 2(b): Relationship of Computer Power vs Malware Detection # For the second part of the task, to investigate the relationship between machine power and its malware probability, I studied the variable `HasDetections` by looking into the value types and the number of observations. # # `HasDetections` - the ground truth and indicates that Malware was detected on the machine. df1['HasDetections'] = train['HasDetections'] df1['HasDetections'].value_counts() df1['HasDetections'].isnull().sum() # Note that `HasDetections` is a binary variable with no missing value. We do not need to clean the data for now. To measure the linear relationship between `ComputerPower` and `HasDetections`, I used the Pearson product-moment correlation coefficient. df1['ComputerPower'].corr(df1['HasDetections']) # The correlation coefficient is about 0.054, very close to 0. To interpret this result, we can consider the two components of the correlation coefficient: strength and direction. From the strength perspective, note that 0.054 is close to 0. A coefficient of zero represents no linear relationship. Thus, as computer power increases, there is little tendency that the probability of malware will either increase or decrease. Moreover, the direction is positive does not give new information here since the strength is about 0. To be very rigorous, we can conclude that there is a very weak positive correlation between computer power and the probability of malware. # We can obtain a similar result through a scatter plot of the two variables. There is little tendency that as computer power increases will the probability of malware increases or decreases. plt.scatter(df1['ComputerPower'], df1['HasDetections'], alpha = 0.5) plt.xlabel('Computer Power') plt.ylabel('Malware Detection') plt.title('Scatter Plot') # + [markdown] id="1wEXze7jU6Lx" # ## **Section 3: OS version vs Malware detected (Q3)** # - # We begin this task by overviewing the two related variables `Census_OSBuildNumber` and `Census_OSBuildRevision`. Note that the variable `HasDetections` was examined in [Section 2(b)](#Section-2(b):-Relationship-of-Computer-Power-vs-Malware-Detection). # # `Census_OSBuildNumber` - OS Build number extracted from the OsVersionFull. Example - OsBuildNumber = 10512 or 10240 # # `Census_OSBuildRevision` - OS Build revision extracted from the OsVersionFull. Example - OsBuildRevision = 1000 or 16458 df2 = train[['Census_OSBuildNumber', 'Census_OSBuildRevision']] df2.value_counts() df2.isnull().sum() # It is important to realize that software updates may fix vulnerabilities found in the past. However, it is also very likely that new vulnerabilities may arise after new feature updates are released. To understand whether software updates tend to increase or decrease the chances of malware attack, bar charts of the frequencies and densities of malware detection for every OS Build number and OS Build revision number are created separately for an examination. # + plt.subplot(1, 2, 1) plt.hist([df2[train['HasDetections'] == 1]['Census_OSBuildNumber'], df2[train['HasDetections'] == 0]['Census_OSBuildNumber']], label = ['Detected', 'Undetected']) plt.xlabel('OS Build number') plt.ylabel('Frequency') plt.title('Frequency Bar Plot') plt.legend(loc = 'upper left') plt.subplot(1, 2, 2) plt.hist([df2[train['HasDetections'] == 1]['Census_OSBuildNumber'], df2[train['HasDetections'] == 0]['Census_OSBuildNumber']], label = ['Detected', 'Undetected'], density = True) plt.xlabel('OS Build number') plt.ylabel('Density') plt.title('Density Bar Plot') plt.legend(loc = 'upper left') plt.tight_layout() # + plt.subplot(1, 2, 1) plt.hist([df2[train['HasDetections'] == 1]['Census_OSBuildRevision'], df2[train['HasDetections'] == 0]['Census_OSBuildRevision']], label = ['Detected', 'Undetected']) plt.xlabel('OS Build revision') plt.ylabel('Frequency') plt.title('Frequency Bar Plot') plt.legend(loc = 'upper right') plt.subplot(1, 2, 2) plt.hist([df2[train['HasDetections'] == 1]['Census_OSBuildRevision'], df2[train['HasDetections'] == 0]['Census_OSBuildRevision']], label = ['Detected', 'Undetected'], density = True) plt.xlabel('OS Build revision') plt.ylabel('Density') plt.title('Density Bar Plot') plt.legend(loc = 'upper right') plt.tight_layout() # - # Based on the two pairs of bar charts, I noticed the frequency difference of malware cases for different OS Build revisions to be approximately the same. It means that the revision updates may raise new malware that is vulnerable to about half of the machines and about half not. What is more, the frequency of the detection of malware is higher than the undetected malware for OS Build number greater or equal to 16000. On the other hand, the undetected malware frequency is higher than the detected frequency for OS Build number less than 16000. In my opinion, this suggests that new releases may worsen some of the machines because more proportions of machines were affected by malware compared to OS Build number releases less than 16000. To conclude, because the probability of malware detection did not decrease as new updates were released, I believe that updates created new vulnerabilities for machines. # + [markdown] id="6VcDL3PrH-UH" # ## **Section 4: Effect of Number of AV Products Installed (Q4)** # - # To finish the task, I first investigated the related variable `IsProtected` of antivirus software. I already checked the variable `HasDetections` in [Section 2(b)](#Section-2(b):-Relationship-of-Computer-Power-vs-Malware-Detection). # # `IsProtected` - This is a calculated field derived from the Spynet Report's AV Products field. Returns: a. TRUE if there is at least one active and up-to-date antivirus product running on this machine. b. FALSE if there is no active AV product on this machine, or if the AV is active, but is not receiving the latest updates. c. null if there are no Anti Virus Products in the report. Returns: Whether a machine is protected. df3 = train[['IsProtected', 'HasDetections']] df3['IsProtected'].value_counts() df3['IsProtected'].isnull().sum() # Notice that `IsProtected` variable has three possible values: 1, 0, and NaN, where NaN here does not mean the value is missing, as illustrated in the above description. For this variable, I combined the return cases of b and c because I am interested in whether antivirus software(s) reduces the amount of malware. In other words, the difference between inactive and inexistent AV is not important. Therefore, returning categories b and c should be combined into a single case with a return value of 0. df3['IsProtected'].fillna(0.0, inplace = True) df3['IsProtected'].value_counts() df3['IsProtected'].isnull().sum() # To investigate the relationship between `IsProtected` and `HasDetections`, I used the Pearson product-moment correlation coefficient again to measure their linear relationship. df3['IsProtected'].corr(df3['HasDetections']) # The correlation coefficient is about 0.059, close to the correlation coefficient of computer power and malware detection in [Section 2(b)](#Section-2(b):-Relationship-of-Computer-Power-vs-Malware-Detection). Therefore, the interpretation is about the same: antivirus software(s) does not necessarily reduce the amount of malware. Furthermore, the number of antivirus products used does not matter because `IsProtected` is a binary variable denoting whether at least one or none (combined with the ones not receiving the latest updates), the actual number of antivirus software used, assuming there is at least one, does not change the correlation interpretation just obtained. # + [markdown] id="g8VNweURVXip" # ## **Section 5: Interesting findings (Q5)** # - # As a beginner in computer hardware, I am interested in studying the specifications of desktops and laptops. One particular specification is display resolution. Display resolution is quoted as width (horizontal) $\times$ height (vertical), with the units in pixels. Most of the time, I observed that a large number of horizontal pixels will be paired with another large number of vertical pixels, comparatively speaking. For example, a 1920 $\times$ 1080 resolution versus a 1366 $\times$ 768 resolution. For this task, I will investigate the linear relationship between the two and see if it is strong enough so that I am convinced of the existence of a general rule. # # Similar to the previous tasks, knowing the information about the interested variables is critical in exploring their relationship. # # `Census_InternalPrimaryDisplayResolutionHorizontal` - Retrieves the number of pixels in the horizontal direction of the internal display. # # `Census_InternalPrimaryDisplayResolutionVertical` - Retrieves the number of pixels in the vertical direction of the internal display df4 = train_complete[['Census_InternalPrimaryDisplayResolutionHorizontal', 'Census_InternalPrimaryDisplayResolutionVertical']] df4.value_counts() df4.isnull().sum() # Note that there are 46986 missing values in each of the variables. I verified that the missing values are paired so that either a machine has data for both variables or none. Since only a small portion of the paired resolution data is missing (about 0.5%), I will drop them for further analysis. df4.dropna(how = 'any', inplace = True) df4.isnull().sum() df4['Census_InternalPrimaryDisplayResolutionHorizontal'].corr(df4['Census_InternalPrimaryDisplayResolutionVertical']) # The correlation coefficient is about 0.902, very close to 1. Again, we can consider the two components of the correlation coefficient to interpret its meaning: strength and direction. From the strength perspective, because 0.902 is close to 1, an absolute value of the coefficient close to 1 represents a nearly perfect linear relationship. Moreover, the direction is positive implies that a linear equation with a positive slope can describe the relationship between the number of pixels in the horizontal and vertical direction of the internal display. # I also included a scatter plot of `Census_InternalPrimaryDisplayResolutionHorizontal` and `Census_InternalPrimaryDisplayResolutionVertical` with a straight line of $y = x$ to visualize the relationship intuitively. Except for a limited number of potential outliers or uncommon points, most points match the conclusion made by the correlation interpretation. plt.scatter(df4['Census_InternalPrimaryDisplayResolutionHorizontal'], df4['Census_InternalPrimaryDisplayResolutionVertical'], alpha = 0.5) plt.xlabel('Number of pixels in the horizontal direction of the internal display') plt.ylabel('Number of pixels in the vertical direction of the internal display') plt.title('Scatter Plot') axes = plt.gca() x_vals = np.array(axes.get_xlim()) y_vals = 0 + 1 * x_vals plt.plot(x_vals, y_vals, 'r-') # + [markdown] id="ylT6xzFmVfT-" # ## **Section 6: Baseline modelling (Q6)** # - # To build a simple baseline model, Model 0, I selected the feature `AVProductsInstalled` based on my research in malware statistics to predict the probability of malware. The malware detection is denoted as variable `HasDetections` in [Section 2(b)](#Section-2(b):-Relationship-of-Computer-Power-vs-Malware-Detection). # # `AVProductsInstalled` - Number of antivirus software installed # # Before proceeding to inspect the data for `AVProductsInstalled`, it is important to split the data into a train data and a test data. For this task and the tasks in [Section 7](#Section-7:-Feature-Cleaning-and-Additional-models-(Q7a-&-7b)), I will train models on 80% of the training data and test it on the remaining 20% chosen at random. X, y = train.iloc[:, :-1], train.iloc[:, -1] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 123) # For this particular task, I am only interested in the feature `AVProductsInstalled`. X_train0 = X_train['AVProductsInstalled'] X_test0 = X_test['AVProductsInstalled'] # Now, we can examine the data and see if missing values need to be filled. Remark that it is unnecessary to examine the variable separately in the train set and the test set because the split of the dataset is random. X['AVProductsInstalled'].value_counts() X['AVProductsInstalled'].isnull().sum() # Note that `AVProductsInstalled` contains integer values from 0 to 7. There are about 0.4% of missing data in total for this variable. I used an imputation method here rather than listwise deletion to deal with the missing values. Moreover, because the variable values are mostly 1 or 2, I used mode imputation here to proceed. X_train0.fillna(X['AVProductsInstalled'].mode()[0], inplace = True) X_test0.fillna(X['AVProductsInstalled'].mode()[0], inplace = True) X_train0.isnull().sum() X_test0.isnull().sum() # Note that for this baseline model Model 0, I only included one feature to train the logistic regression. Given the documentation of `sklearn.linear_model.LogisticRegression`: # # > fit(X, y, sample_weight=None) # > # > **Parameters: X: {array-like, sparse matrix} of shape (n_samples, n_features)** # > # > Training vector, where n_samples is the number of samples and n_features is the number of features. # # > predict(X) # > # > **Parameters: X: {array-like, sparse matrix} of shape (n_samples, n_features)** # > # > Samples. # # The input arrays X for the two functions above should be 2 dimensional. Thus, I used `reshape()` function below to change the dimension of `X_train0` in the train and test datasets. model_0 = LogisticRegression() model_0.fit(X_train0.values.reshape(-1, 1), y_train) y_predict0 = model_0.predict(X_test0.values.reshape(-1, 1)) (y_test != y_predict0).mean() # The error rate is about 43.32% for this model. roc_auc_score(y_test, y_predict0) # The AUC score of this model is about 0.567. # + [markdown] id="WmJ8gezsVkz4" # ## **Section 7: Feature Cleaning and Additional models (Q7a & 7b)** # - # ### Section 7(a): Cleaning Features # To build a more sophisticated and useful model, I added more features that I believe will be relevant to the model for training. In particular, I have included variables `RtpStateBitfield`, `AVProductsInstalled` (inspected in [Section 6](#Section-6:-Baseline-modelling-(Q6))), `IsProtected` (inspected in [Section 4](#Section-4:-Effect-of-Number-of-AV-Products-Installed-(Q4))), `Census_PrimaryDiskTotalCapacity`, `Census_PrimaryDiskTypeName`, `Census_IsSecureBootEnabled`, `Census_IsAlwaysOnAlwaysConnectedCapable`, and `Wdft_IsGamer`. Also, note that the target variable `HasDetections` was already checked in [Section 2(b)](#Section-2(b):-Relationship-of-Computer-Power-vs-Malware-Detection). Similar to the procedures done in previous tasks, it is essential to first understand the meaning and the value types of the variables. # # `RtpStateBitfield` - RTP state # # `Census_PrimaryDiskTotalCapacity` - Amount of disk space on primary disk of the machine in MB # # `Census_PrimaryDiskTypeName` - Friendly name of Primary Disk Type - HDD or SSD # # `Census_IsSecureBootEnabled` - Indicates if Secure Boot mode is enabled. # # `Census_IsAlwaysOnAlwaysConnectedCapable` - Retreives information about whether the battery enables the device to be AlwaysOnAlwaysConnected. # # `Wdft_IsGamer` - Indicates whether the device is a gamer device or not based on its hardware combination. X_train1 = X_train[['RtpStateBitfield', 'AVProductsInstalled', 'IsProtected', 'Census_PrimaryDiskTotalCapacity', 'Census_PrimaryDiskTypeName', 'Census_IsSecureBootEnabled', 'Census_IsAlwaysOnAlwaysConnectedCapable', 'Wdft_IsGamer']] X_test1 = X_test[['RtpStateBitfield', 'AVProductsInstalled', 'IsProtected', 'Census_PrimaryDiskTotalCapacity', 'Census_PrimaryDiskTypeName', 'Census_IsSecureBootEnabled', 'Census_IsAlwaysOnAlwaysConnectedCapable', 'Wdft_IsGamer']] # Similar to the data analysis procedure in [Section 6](#Section-6:-Baseline-modelling-(Q6)), we do not have to inspect the variables individually for the train and test set. X['RtpStateBitfield'].value_counts() X['Census_PrimaryDiskTotalCapacity'].value_counts() sns.boxplot(X['Census_PrimaryDiskTotalCapacity']) X['Census_PrimaryDiskTypeName'].value_counts() X['Census_IsSecureBootEnabled'].value_counts() X['Census_IsAlwaysOnAlwaysConnectedCapable'].value_counts() X['Wdft_IsGamer'].value_counts() X[['RtpStateBitfield', 'AVProductsInstalled', 'IsProtected', 'Census_PrimaryDiskTotalCapacity', 'Census_PrimaryDiskTypeName', 'Census_IsSecureBootEnabled', 'Census_IsAlwaysOnAlwaysConnectedCapable', 'Wdft_IsGamer']].isnull().sum() # Given the above variables data types and the number of missing value observations, I used similar analysis procedures as the previous tasks to impute the missing values for each variable. I will impute `RtpStateBitfield`, `Census_PrimaryDiskTotalCapacity`, `Census_PrimaryDiskTypeName`, `Census_IsAlwaysOnAlwaysConnectedCapable`, and `Wdft_IsGamer` using mode, median, random sample (70% HDD, 30% SSD), random sample (94% 0, 6% 1), and random sample (70% 0, 30% 1) imputation, respectively. Note that `AVProductsInstalled` and `IsProtected` can be imputed using their respective techniques discussed in [Section 6](#Section-6:-Baseline-modelling-(Q6)) and [Section 4](#Section-4:-Effect-of-Number-of-AV-Products-Installed-(Q4)). There is no missing value for `Census_IsSecureBootEnabled`. # + X_train1['RtpStateBitfield'].fillna(X['RtpStateBitfield'].mode()[0], inplace = True) X_test1['RtpStateBitfield'].fillna(X['RtpStateBitfield'].mode()[0], inplace = True) X_train1['AVProductsInstalled'].fillna(X['AVProductsInstalled'].mode()[0], inplace = True) X_test1['AVProductsInstalled'].fillna(X['AVProductsInstalled'].mode()[0], inplace = True) X_train1['IsProtected'].fillna(0.0, inplace = True) X_test1['IsProtected'].fillna(0.0, inplace = True) X_train1['Census_PrimaryDiskTotalCapacity'].fillna(X['Census_PrimaryDiskTotalCapacity'].median(), inplace = True) X_test1['Census_PrimaryDiskTotalCapacity'].fillna(X['Census_PrimaryDiskTotalCapacity'].median(), inplace = True) np.random.seed(123) X_train1['Census_PrimaryDiskTypeName'].fillna(np.random.choice(('HDD', 'SSD'), 1, p = [0.7, 0.3])[0], inplace = True) np.random.seed(124) X_test1['Census_PrimaryDiskTypeName'].fillna(np.random.choice(('HDD', 'SSD'), 1, p = [0.7, 0.3])[0], inplace = True) np.random.seed(125) X_train1['Census_PrimaryDiskTypeName'].replace(['UNKNOWN', 'Unspecified'], np.random.choice(('HDD', 'SSD'), 1, p = [0.7, 0.3])[0], inplace = True) np.random.seed(126) X_test1['Census_PrimaryDiskTypeName'].replace(['UNKNOWN', 'Unspecified'], np.random.choice(('HDD', 'SSD'), 1, p = [0.7, 0.3])[0], inplace = True) X_train1['Census_PrimaryDiskTypeName'].replace(['HDD', 'SSD'], [0, 1], inplace = True) X_test1['Census_PrimaryDiskTypeName'].replace(['HDD', 'SSD'], [0, 1], inplace = True) np.random.seed(127) X_train1['Census_IsAlwaysOnAlwaysConnectedCapable'].fillna(np.random.choice((0, 1), 1, p = [0.94, 0.06])[0], inplace = True) np.random.seed(128) X_test1['Census_IsAlwaysOnAlwaysConnectedCapable'].fillna(np.random.choice((0, 1), 1, p = [0.94, 0.06])[0], inplace = True) np.random.seed(129) X_train1['Wdft_IsGamer'].fillna(np.random.choice((0, 1), 1, p = [0.7, 0.3])[0], inplace = True) np.random.seed(130) X_test1['Wdft_IsGamer'].fillna(np.random.choice((0, 1), 1, p = [0.7, 0.3])[0], inplace = True) # - # After the data cleaning process is done, I verified the data types are correctly transformed, and no missing values are present. Here, I only listed the value counts for `Census_PrimaryDiskTypeName` because I did some encoding to this variable, whereas only imputations were done for the rest of the variables. X_train1['Census_PrimaryDiskTypeName'].value_counts() X_test1['Census_PrimaryDiskTypeName'].value_counts() X_train1.isnull().sum() X_test1.isnull().sum() # Usually, it is critical to normalize the variables so that the ranges and distributions of the variables are comparable. However, after a careful inspection of the value types and ranges of the features, I did not perform the normalization process due to the following reasons. First, of the eight features, only three variables are considered continuous, and the rest are binary variables with only 0 and 1 values. It is unnecessary to perform normalization on the dummy variables. Among the three continuous variables, `RtpStateBitfield` and `AVProductsInstalled` contain data values mostly small integers from 0 to 8. Performing such normalization may not benefit much. Finally, normalizing variable `Census_PrimaryDiskTotalCapacity` can potentially raise computing overflow errors because the normalized values are extremely small (e.g. 1.0e-07), which provides a worse matrix for the model training procedure. Therefore, the model training performs better without normalizing the variables. # ### Section 7(b): Final Model Creation # #### Section 7(b)(i): Logistic Regression # Before training the final model, feature selection is preferred to reduce the number of input variables. The predictive model can have a lower error rate if some redundant features are not included in the training process. Here, I used a univariate feature selection method called `SelectKBest` to remove all features except the $k$ highest scoring features. In particular, the scoring function used is the sample's ANOVA F-value. test = SelectKBest(score_func = f_classif, k = 3) fit = test.fit(X_train1, y_train) print(fit.scores_) # For this particular task, I chose to have the highest three scoring features ($k=3$) as the final features for training. The three highest features are `AVProductsInstalled`, `IsProtected`, and `Census_IsAlwaysOnAlwaysConnectedCapable`. Hence, we can proceed to do the logistic regression training. Name the model Model 1. X_train1 = X_train1[['AVProductsInstalled', 'IsProtected', 'Census_IsAlwaysOnAlwaysConnectedCapable']] X_test1 = X_test1[['AVProductsInstalled', 'IsProtected', 'Census_IsAlwaysOnAlwaysConnectedCapable']] model_1 = LogisticRegression() model_1.fit(X_train1, y_train) y_predict1 = model_1.predict(X_test1) (y_test != y_predict1).mean() # The error rate is about 41.72% for the logistic regression model. # #### Section 7(b)(ii): Random Forest # For random forest training, I used the same three features for training, with the number of trees in the forest set to be 100 by default. The training process is similar to the logistic regression training. Name the model Model 2. model_2 = RandomForestClassifier() model_2.fit(X_train1, y_train) y_predict2 = model_2.predict(X_test1) (y_test != y_predict2).mean() # The error rate is about 41.72% for the random forest model. # ### Summary # Here is a table summarizing the error rates for the three models built in [Section 6](#Section-6:-Baseline-modelling-(Q6)) and [Section 7(b)](#Section-7(b):-Final-Model-Creation). # # | Model | Error Rate | # |----------|----------- | # | Model 0 | 43.32% | # | Model 1 | 41.72% | # | Model 2 | 41.72% | # # To compare the performance of the models, I will start with the difference in terms of the error rate. Model 0 only uses `AVProductsInstalled` as the feature for training. Model 1 and 2 use three features for training: `AVProductsInstalled`, `IsProtected`, and `Census_IsAlwaysOnAlwaysConnectedCapable`. Therefore, adding more relevant features to the model decreases the error rate of prediction. This is intuitive because there are more useful resources for training so that it is very possible to have a better prediction. # # Furthermore, observing that no difference in error rate between Model 1 and Model 2, I conclude that there is no difference in prediction error rate using logistic regression algorithm and random forest algorithm. I conjecture the reason is that logistic regression predicts similar to the random forest for large datasets. # + [markdown] id="5RzjvrYtVs-V" # ## **Section 8: Screenshots (Q8)** # - # Last but not least, to predict the data in test.csv using the three models, we first import the test.csv dataset. test = pd.read_csv('microsoft-malware-prediction/test.csv') # Model 0 prediction: X_test_0 = test['AVProductsInstalled'] X_test_0.fillna(test['AVProductsInstalled'].mode()[0], inplace = True) y_predict_test_0 = model_0.predict(X_test_0.values.reshape(-1, 1)) result = test['MachineIdentifier'] result_0 = pd.concat([result, pd.DataFrame(y_predict_test_0, columns = ['HasDetections'])], axis = 1) result_0.to_csv('model_0.csv', index = False) # Model 1 prediction: X_test_1 = test[['AVProductsInstalled', 'IsProtected', 'Census_IsAlwaysOnAlwaysConnectedCapable']] X_test_1['AVProductsInstalled'].fillna(test['AVProductsInstalled'].mode()[0], inplace = True) X_test_1['IsProtected'].fillna(0.0, inplace = True) X_test_1['Census_IsAlwaysOnAlwaysConnectedCapable'].fillna(np.random.choice((0, 1), 1, p = [0.94, 0.06])[0], inplace = True) y_predict_test_1 = model_1.predict(X_test_1) result_1 = pd.concat([result, pd.DataFrame(y_predict_test_1, columns = ['HasDetections'])], axis = 1) result_1.to_csv('model_1.csv', index = False) # Model 2 prediction: y_predict_test_2 = model_2.predict(X_test_1) result_2 = pd.concat([result, pd.DataFrame(y_predict_test_2, columns = ['HasDetections'])], axis = 1) result_2.to_csv('model_2.csv', index = False) # + [markdown] id="wVkK-WfdV73b" # Public Score: 0.57462 # # Private Score: 0.52528 # # Kaggle profile link: https://www.kaggle.com/garylikai # # Screenshot(s): ![Screenshot](Kaggle_Challenge.png)
cse519_hw2_Li_Kai_113358694.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/VishalDalwadi/027_VishalDalwadi/blob/main/0_logistic_regression_.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" id="hfV503AtcBDp" #Importing libraries import numpy as np import pandas as pd import io import matplotlib.pyplot as plt # + colab={"base_uri": "https://localhost:8080/"} id="74P68822m1vR" outputId="7c18c761-51e2-412e-f20e-3ca5e0b75ec5" from google.colab import drive drive.mount('/content/drive') # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" colab={"base_uri": "https://localhost:8080/"} id="Y4rK9ffYcBEP" outputId="3db75a5a-d88f-44fb-fe97-e0fa6e0f988b" # reading the csv file, del 2 columns from the file, checking first few rows of the file data = pd.read_csv('/content/drive/MyDrive/ML_Labs/Lab6/BuyComputer.csv') data.drop(columns=['User ID',],axis=1,inplace=True) data.head() print(data) # + _uuid="4cb45e28344e7e245ab398e9f4f5272ef21d2129" id="jwuPgU6_cBE8" #Declare label as last column in the source file y = data.iloc[:,-1].values # + _uuid="2e7a145fa49435ad9578ec2827f76a70cc99f2e1" id="2lhBrOp8cBFX" #Declaring X as all columns excluding last X = data.iloc[:,:-1].values # + _uuid="dffb1f3e19e19964995ac827bf55108b5815ff67" id="t8nwbTn6cBFp" # Splitting data from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 27) # + _uuid="7d4ed14782e114ae3282f20d3754121398e6d232" id="U4bUiVVFcBGD" # Sacaling data from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # + _uuid="2ff7415e3e0e0673d59051cfe6154c63d3312a32" colab={"base_uri": "https://localhost:8080/"} id="W5yGgzqbcBGc" outputId="ad2d5b1c-c155-431e-d319-c54323ccbfa9" #Variabes to calculate sigmoid function y_pred = [] len_x = len(X_train[0]) w = [] b = 0.2 print(len_x) # + _uuid="a228174207f4631be4f26a0cc05e379f3f58aa56" colab={"base_uri": "https://localhost:8080/"} id="ZbqwTM0bcBGr" outputId="fe0a2a1c-e513-4da5-dc8b-2f725f24200c" entries = len(X_train[:,0]) entries # + _uuid="5d4d6e47ee65c9c7404e60fcf8f05c11708546b3" colab={"base_uri": "https://localhost:8080/"} id="vEV7Nn73cBG7" outputId="4796711d-ee4a-4ba6-f212-4a16e9c8f9b1" for weights in range(len_x): w.append(0) w # + _uuid="18dbd2196d72527a82d30ab88ed2aa8d10bd01ce" id="_fAtpylNcBHM" # Sigmoid function def sigmoid(z): return (1/(1+np.exp(-z))) # + _uuid="daa0f87fdbf98591cb9f51b8dc7157dc399ca827" id="kfchkScTcBHd" def predict(inputs): z = np.dot(w,inputs)+b a = sigmoid(z) return a # + _uuid="4126f842d072ccd40019cc283b767a014e2ee074" id="K2ryTgglcBHt" #Loss function def loss_func(y,a): J = -(y*np.log(a) + (1-y)*np.log(1-a)) return J # + _uuid="fc0ceb65c69f4ee0c3f28e050744229dc90c621b" id="1KW3eDpmcBIA" dw = [] db = 0 J = 0 alpha = 0.1 for x in range(len_x): dw.append(0) # + _uuid="e4be38e9b500ae0c5a7134296a3055675c4fb2d8" id="ipqdFLP3cBIO" #Repeating the process 3000 times for iterations in range(3000): for i in range(entries): localx = X_train[i] a = predict(localx) dz = a - y_train[i] J += loss_func(y_train[i],a) for j in range(len_x): dw[j] = dw[j]+(localx[j]*dz) db += dz J = J/entries db = db/entries for x in range(len_x): dw[x]=dw[x]/entries for x in range(len_x): w[x] = w[x]-(alpha*dw[x]) b = b-(alpha*db) J=0 # + _uuid="5479ccb6073ed1ea310ef7de01b2935fc3ec400e" colab={"base_uri": "https://localhost:8080/"} id="7Q585AdrcBIs" outputId="8aa21bcc-faf0-47b2-de83-1f9167358f1a" #Print weight print(w) # + _uuid="a939c247b8a092f74c9843975612daa85c423621" colab={"base_uri": "https://localhost:8080/"} id="rEiF-bNHcBJB" outputId="8174511c-ea29-4525-8c14-a7fffbf73e96" #print bias print(b) # + _uuid="b7ae24169a21c7ac8ea0787f4a38a0de3e07a6b5" id="MPt5nUcpcBJR" #predicting the label for x in range(len(y_test)): y_pred.append(predict(X_test[x])) # + _uuid="967ad1b72305ad792a5d50e4d8b8a07632f7b241" colab={"base_uri": "https://localhost:8080/"} id="79HPPz7jcBJg" outputId="f5749631-c981-4b0f-f43b-6001c9848c50" #print actual and predicted values in a table for x in range(len(y_pred)): print('Actual ',y_test[x],' Predicted ',y_pred[x]) if y_pred[x]>=0.5: y_pred[x]=1 else: y_pred[x]=0 # + _uuid="a59807150900082ab876ef0200c6c7f8f93e098c" colab={"base_uri": "https://localhost:8080/"} id="sdZDj_iVcBJt" outputId="8fe5d307-9927-40af-ddad-8cb82f38dd15" # Calculating accuracy of prediction count = 0 for x in range(len(y_pred)): if(y_pred[x]==y_test[x]): count=count+1 print('Accuracy:',(count/(len(y_pred)))*100) # + [markdown] id="x6nmajpzhAEn" # #Using sklearn LogisticRegression model # + _kg_hide-output=true _uuid="9aaade066015e04f20dd7eb1d37339be75ca3836" colab={"base_uri": "https://localhost:8080/"} id="iG-BK4i9cBKH" outputId="ac161587-0165-4978-e0be-e325d069966c" # Fitting Logistic Regression to the Training set from sklearn.linear_model import LogisticRegression LR = LogisticRegression(random_state = 27) #Fit LR.fit(X_train, y_train) #predicting the test label with LR. Predict always takes X as input y_predLR=LR.predict(X_test) for x in range(len(y_pred)): print('Actual ',y_test[x],' Predicted ',y_predLR[x]) if y_predLR[x]>=0.5: y_predLR[x]=1 else: y_predLR[x]=0 count = 0 for x in range(len(y_pred)): if(y_pred[x]==y_test[x]): count=count+1 print('Accuracy:',(count/(len(y_pred)))*100) # + colab={"base_uri": "https://localhost:8080/"} id="vGRcb_ECmrt1" outputId="e7f6d838-344a-4c0d-afd6-6dbc0ab995cd" #Exercise Problem # Fitting Logistic Regression to the Training set from sklearn.linear_model import LogisticRegression LR = LogisticRegression(random_state = 27) #Fit LR.fit(X_train, y_train) #predicting the test label with LR. Predict always takes X as input y_predLR=LR.predict(X_test) for x in range(len(y_pred)): print('Actual ',y_test[x],' Predicted ',y_predLR[x]) if y_predLR[x]>=0.5: y_predLR[x]=1 else: y_predLR[x]=0 count = 0 for x in range(len(y_pred)): if(y_pred[x]==y_test[x]): count=count+1 print('Accuracy:',(count/(len(y_pred)))*100) # + [markdown] id="Y8sYVBu-iSW-" # **Exercise:** # # Try logistic regression on BuyComputer dataset and set Random state=Your_RollNumber (last 3 digit of ID, incase if you don't have ID)
Lab6/0_logistic_regression_.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #Calculate a life import datetime date_a = datetime.date(2018,1,1) date_b = datetime.date(2019,1,1) # - days_2019 = date_b - date_a print(days_2019) print(date_a) print(type(date_a)) print(type(days_2019)) #daysはtimedelta型が持っている関数 #あるデータ型に属している専用関数のことをデータ属性、または属性(アトリビュート)と呼ぶ days_2019.days today = datetime.date.today() print(today) mybirthday = datetime.date(2000,1,1) print(mybirthday) lifetime = today - mybirthday print(lifetime.days)
chapter3/program3-7.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pickle import re import ujson as json import numpy as np import matplotlib.pyplot as plt import pandas as pd from collections import Counter from pprint import pprint from tqdm import tqdm font = {"family" : "Times New Roman", "size" : 14, "weight": "bold"} plt.rc("font", **font) colors = [(0.6509803921568628, 0.807843137254902, 0.8901960784313725), (0.12156862745098039, 0.47058823529411764, 0.7058823529411765), (0.6980392156862745, 0.8745098039215686, 0.5411764705882353), (0.2, 0.6274509803921569, 0.17254901960784313), (0.984313725490196, 0.6039215686274509, 0.6), (0.8901960784313725, 0.10196078431372549, 0.10980392156862745), (0.9921568627450981, 0.7490196078431373, 0.43529411764705883), (1.0, 0.4980392156862745, 0.0), (0.792156862745098, 0.6980392156862745, 0.8392156862745098), (0.41568627450980394, 0.23921568627450981, 0.6039215686274509), (1.0, 1.0, 0.6), (0.6941176470588235, 0.34901960784313724, 0.1568627450980392)] # - # ### Clean Text with open("../data/arg_impact/argument_impact.pkl", "rb") as f: data = pickle.load(f) data["test_X"][1071] # ### Load Stance stance_labels = [ "<none>", "<pro>", "<con>" ] with open("../data/arg_spec_stance/argument_specificity_stance.pkl", "rb") as f: stance = pickle.load(f) argument_id = dict() for _id, arg in stance["id_argument"].items(): argument_id[arg] = _id stc = dict() for v in stance["child_parent_stance"].values(): stc.update(v) stance = stc # ### Load Discourse INF = 1e30 _INF = -1e30 # + with open("../data/arg_impact/train_discourse.jsonl", "r") as f: train_disco = [] for x in f: x = json.loads(x) train_disco.append(x) with open("../data/arg_impact/valid_discourse.jsonl", "r") as f: valid_disco = [] for x in f: x = json.loads(x) valid_disco.append(x) with open("../data/arg_impact/test_discourse.jsonl", "r") as f: test_disco = [] for x in f: x = json.loads(x) test_disco.append(x) # - discourse_labels = [ "<Null>", "<Concession>", "<Contrast>", "<Reason>", "<Result>", "<Condition>", "<Alternative>", "<ChosenAlternative>", "<Conjunction>", "<Exception>", "<Instantiation>", "<Restatement>", "<Precedence>", "<Succession>", "<Synchrony>" ] np.array(train_disco[0]["discourse"]).argmax(axis=1) # ### Generate Paths impact_labels = ["IMPACTFUL", "MEDIUM IMPACT", "NOT IMPACTFUL"] # + train = [] for i, (x, y) in tqdm(enumerate(zip(data["train_X"], data["train_y"]))): _id = "train_%d" % (i) text = [x["claim_text"]] context = x["path"][::-1] stc = ["<null>"] for z in context[1:] + text: if z in argument_id: stc.append("<%s>" % (stance[argument_id[z]][1])) else: stc.append("<unk>") disco = [[0.0] * len(discourse_labels)] disco[0][0] = INF for d in train_disco[i]["discourse"]: disco.append([_INF] + d) train.append({ "id": _id, "text": text, "context": context, "label": y, "stance_label": stc, "discourse_label": [discourse_labels[z] for z in np.array(disco).argmax(axis=1)], "discourse_logit": disco }) valid = [] for i, (x, y) in tqdm(enumerate(zip(data["val_X"], data["val_y"]))): _id = "valid_%d" % (i) text = [x["claim_text"]] context = x["path"][::-1] stc = ["<null>"] for z in context[1:] + text: if z in argument_id: stc.append("<%s>" % (stance[argument_id[z]][1])) else: stc.append("<unk>") disco = [[0.0] * len(discourse_labels)] disco[0][0] = INF for d in valid_disco[i]["discourse"]: disco.append([_INF] + d) valid.append({ "id": _id, "text": text, "context": context, "label": y, "stance_label": stc, "discourse_label": [discourse_labels[z] for z in np.array(disco).argmax(axis=1)], "discourse_logit": disco }) test = [] for i, (x, y) in tqdm(enumerate(zip(data["test_X"], data["test_y"]))): _id = "test_%d" % (i) text = [x["claim_text"]] context = x["path"][::-1] stc = ["<null>"] for z in context[1:] + text: if z in argument_id: stc.append("<%s>" % (stance[argument_id[z]][1])) else: stc.append("<unk>") disco = [[0.0] * len(discourse_labels)] disco[0][0] = INF for d in test_disco[i]["discourse"]: disco.append([_INF] + d) test.append({ "id": _id, "text": text, "context": context, "label": y, "stance_label": stc, "discourse_label": [discourse_labels[z] for z in np.array(disco).argmax(axis=1)], "discourse_logit": disco }) # - len(valid[0]["context"]) valid_disco[0] # + for x in train: if "<unk>" in x["stance_label"]: print(x["id"]) for i in range(len(x["stance_label"])): if x["stance_label"][i] == "<unk>": if i < len(x["context"]): print(i, x["context"][i-1], x["context"][i], sep="|||||") else: print(i, x["context"][-1], x["text"][0], sep="-----") print() # the missing topics are at # https://www.kialo.com/are-identity-politics-detrimental-to-society-7018?path=7018.0~7018.1&active=~7018.1&action=comments, # https://www.kialo.com/should-transgender-personae-only-be-performed-by-transgender-people-16846?path=16846.0~16846.1&active=~16846.1&action=comments # + train[59]["stance_label"][1] = "<con>" train[59]["stance_label"][2] = "<con>" train[362]["stance_label"][1] = "<pro>" train[362]["stance_label"][2] = "<pro>" train[592]["stance_label"][1] = "<pro>" train[592]["stance_label"][2] = "<con>" train[1162]["stance_label"][1] = "<pro>" train[1353]["stance_label"][1] = "<pro>" train[1868]["stance_label"][1] = "<con>" train[2289]["stance_label"][1] = "<pro>" train[2289]["stance_label"][2] = "<con>" train[2350]["stance_label"][1] = "<con>" train[2689]["stance_label"][1] = "<con>" train[2689]["stance_label"][2] = "<pro>" train[3392]["stance_label"][1] = "<pro>" train[3392]["stance_label"][2] = "<pro>" train[4061]["stance_label"][1] = "<pro>" train[5169]["stance_label"][1] = "<con>" train[5169]["stance_label"][2] = "<con>" train[1875]["stance_label"][1] = "<con>" train[3321]["stance_label"][1] = "<con>" train[4892]["stance_label"][1] = "<con>" # + for x in valid: if "<unk>" in x["stance_label"]: print(x["id"]) for i in range(len(x["stance_label"])): if x["stance_label"][i] == "<unk>": if i < len(x["context"]): print(i, x["context"][i-1], x["context"][i], sep="|||||") else: print(i, x["context"][-1], x["text"][0], sep="-----") # the missing topic is at https://www.kialo.com/are-identity-politics-detrimental-to-society-7018?path=7018.0~7018.1&active=~7018.1&action=comments # - valid[336]["stance_label"][1] = "<pro>" valid[336]["stance_label"][2] = "<con>" valid[336]["stance_label"][3] = "<con>" # + for x in test: if "<unk>" in x["stance_label"]: print(x["id"]) for i in range(len(x["stance_label"])): if x["stance_label"][i] == "<unk>": if i < len(x["context"]): print(i, x["context"][i-1], x["context"][i], sep="|||||") else: print(i, x["context"][-1], x["text"][0], sep="-----") # the missing topics are at # https://www.kialo.com/are-identity-politics-detrimental-to-society-7018?path=7018.0~7018.1&active=~7018.1&action=comments, # https://www.kialo.com/should-transgender-personae-only-be-performed-by-transgender-people-16846?path=16846.0~16846.1&active=~16846.1&action=comments # - # + test[272]["stance_label"][1] = "<pro>" test[272]["stance_label"][2] = "<con>" test[956]["stance_label"][1] = "<pro>" test[277]["stance_label"][1] = "<con>" # - # + import torch as th logits = th.stack([th.tensor(x["discourse_logit"]).sum(dim=0) for x in train + valid + test], dim=0) # - list(zip(discourse_labels, logits.sum(dim=0))) th.stack([logits[i].mean(dim=0) for i in range(len(logits))]).mean(dim=0) # + with open("data/arg_impact/train.jsonl", "w") as f: for x in tqdm(train): f.write(json.dumps(x)) f.write("\n") with open("data/arg_impact/valid.jsonl", "w") as f: for x in tqdm(valid): f.write(json.dumps(x)) f.write("\n") with open("data/arg_impact/test.jsonl", "w") as f: for x in tqdm(test): f.write(json.dumps(x)) f.write("\n") # - print(Counter([x["label"] for x in train])) print(Counter([x["label"] for x in valid])) print(Counter([x["label"] for x in test])) stance_counter = Counter() for x in test: stance_counter.update(x["stance_label"]) print(stance_counter.most_common()) disco_counter = Counter() for x in train + valid + test: disco_counter.update(x["discourse_label"]) print(disco_counter.most_common()) plt.figure(figsize=(10, 8)) labels = ["Conjunction", "Contrast", "Chosen\nAlternative", "Result", "Instantiation", "Reason", "Restatement"] bar = plt.bar(np.arange(len(labels)), [disco_counter["<%s>" % (x.replace("\n", ""))] for x in labels], width=0.6, color=colors[8]) plt.xticks(list(range(len(labels))), labels, rotation=45, fontsize=24) plt.yticks([10, 100, 1000, 10000], fontsize=24) plt.yscale("log") for rect in bar: plt.text(rect.get_x() + rect.get_width()/2.0, rect.get_height(), "%d" % (int(rect.get_height())), ha="center", va="bottom", fontsize=18) plt.savefig("disco_dist.png", bbox_inches="tight") plt.show() # + pattern_len = 1 disco_co_occur = Counter() for x in train + valid + test: for i in range(len(x["discourse_label"])-1, max(-1, len(x["discourse_label"])-1-pattern_len), -1): d = "-".join(x["discourse_label"][i:]).replace("<", "").replace(">", "") l = x["label"].replace("<", "").replace(">", "") disco_co_occur["%s=%s" % (d, l)] += 1 pprint(disco_co_occur.most_common(300)) plt.figure(figsize=(6, 8)) sorted_disco_co_occur = [x for x in disco_co_occur.most_common() if x[1] >= 5] # sorted_disco_co_occur = disco_co_occur.most_common() plt.plot(np.arange(len(sorted_disco_co_occur)), [x[1] for x in sorted_disco_co_occur]) # plt.xticks([x[0] for x in sorted_disco_co_occur]) plt.show() discos = list(set([x[0].split("=", 1)[0] for x in sorted_disco_co_occur])) df = pd.DataFrame(np.zeros((len(impact_labels), len(discos))), columns=discos) df.index = impact_labels for k, v in sorted_disco_co_occur: i, j = k.split("=", 1) df[i][j] = float(v) # - print(df.shape) df df.sum(axis=1) # disco_corr = df.div(df.sum(axis=1), axis=0) # disco_corr = disco_corr.div(disco_corr.sum(axis=0), axis=1) disco_corr = df.div(df.sum(axis=0), axis=1) disco_corr plt.figure(figsize=(20, 8)) plt.matshow(disco_corr, fignum=0) columns = [x.replace("ChosenAlternative", "Chosen\nAlternative") for x in df.columns] plt.xticks(range(len(df.columns)), columns, rotation=-45, fontsize=36) plt.yticks(range(len(df.index)), ["Impactful", "Medium Impact", "Not Impactful"], fontsize=36) plt.clim(0.0, 0.8) cbar = plt.colorbar() for l in cbar.ax.get_yticklabels(): l.set_fontsize(36) plt.savefig("disco_corr.png", bbox_inches="tight") plt.show() # + pattern_len = 1 stance_co_occur = Counter() for x in train + valid + test: for i in range(len(x["stance_label"])-1, max(-1, len(x["stance_label"])-1-pattern_len), -1): s = "-".join(x["stance_label"][i:]).replace("<", "").replace(">", "") l = x["label"].replace("<", "").replace(">", "") stance_co_occur["%s=%s" % (s, l)] += 1 pprint(stance_co_occur.most_common(300)) plt.figure(figsize=(6, 8)) sorted_stance_co_occur = [x for x in stance_co_occur.most_common() if x[1] >= 5] # sorted_stance_co_occur = stance_co_occur.most_common() plt.plot(np.arange(len(sorted_stance_co_occur)), [x[1] for x in sorted_stance_co_occur]) # plt.xticks([x[0] for x in sorted_stance_co_occur]) plt.show() stances = list(set([x[0].split("=", 1)[0] for x in sorted_stance_co_occur])) df = pd.DataFrame(np.zeros((len(impact_labels), len(stances))), columns=stances) df.index = impact_labels for k, v in sorted_stance_co_occur: i, j = k.rsplit("=", 1) df[i][j] = float(v) # - print(df.shape) df df.sum(axis=1) # stance_corr = df.div(df.sum(axis=1), axis=0) # stance_corr = stance_corr.div(stance_corr.sum(axis=0), axis=1) stance_corr = df.div(df.sum(axis=0), axis=1) stance_corr plt.figure(figsize=(20, 8)) plt.matshow(stance_corr, fignum=0) plt.xticks(range(len(df.columns)), ["Pro", "Con"], rotation=-45, fontsize=36) plt.yticks(range(len(df.index)), ["Impactful", "Medium Impact", "Not Impactful"], fontsize=36) plt.clim(0.0, 0.8) cbar = plt.colorbar() for l in cbar.ax.get_yticklabels(): l.set_fontsize(36) plt.savefig("stance_corr.png", bbox_inches="tight") plt.show() # + pattern_len = 1 disco_stance_co_occur = Counter() for x in train + valid + test: for i in range(len(x["discourse_label"])-1, max(-1, len(x["discourse_label"])-1-pattern_len), -1): d = "-".join(x["discourse_label"][i:]).replace("<", "").replace(">", "") s = "-".join(x["stance_label"][i:]).replace("<", "").replace(">", "") disco_stance_co_occur["%s=%s" % (d, s)] += 1 pprint(disco_stance_co_occur.most_common(300)) plt.figure(figsize=(6, 8)) sorted_disco_stance_co_occur = [x for x in disco_stance_co_occur.most_common() if x[1] >= 5] # sorted_disco_stance_co_occur = disco_stance_co_occur.most_common() plt.plot(np.arange(len(sorted_disco_stance_co_occur)), [x[1] for x in sorted_disco_stance_co_occur]) # plt.xticks([x[0] for x in sorted_disco_stance_co_occur]) plt.show() discos = list(set([x[0].rsplit("=", 1)[0] for x in sorted_disco_stance_co_occur])) stances = list(set([x[0].rsplit("=", 1)[1] for x in sorted_disco_stance_co_occur])) df = pd.DataFrame(np.zeros((len(stances), len(discos))), columns=discos) df.index = list(stances) for k, v in sorted_disco_stance_co_occur: i, j = k.rsplit("=", 1) df[i][j] = float(v) # - print(df.shape) df # stance_corr = df.div(df.sum(axis=1), axis=0) # stance_corr = stance_corr.div(stance_corr.sum(axis=0), axis=1) disco_stance_corr = df.div(df.sum(axis=0), axis=1) disco_stance_corr # + plt.figure(figsize=(20, 8)) plt.matshow(disco_stance_corr, fignum=0) plt.xticks(range(len(df.columns)), columns, rotation=-45, fontsize=36) plt.yticks(range(len(df.index)), ["Pro", "Con"], fontsize=36) plt.clim(0.0, 0.8) cbar = plt.colorbar() for l in cbar.ax.get_yticklabels(): l.set_fontsize(36) # plt.savefig("disco_stance_corr.png", bbox_inches="tight") plt.show() # - # + df = pd.DataFrame(np.zeros((3, 1)), columns=["Impact Label\nDistribution"]) df.index = impact_labels for x in train + valid + test: df["Impact Label\nDistribution"][x["label"]] += 1 # - df # + plt.figure(figsize=(20, 8)) plt.matshow(df.div(df.sum(axis=0), axis=1), fignum=0) plt.xticks(range(len(df.columns)), df.columns, rotation=-45, fontsize=36) plt.yticks(range(len(df.index)), ["Impactful", "Medium\n Impact ", "Not \nImpactful"], fontsize=36) plt.clim(0.0, 0.8) cbar = plt.colorbar() for l in cbar.ax.get_yticklabels(): l.set_fontsize(36) plt.savefig("label_dist.png", bbox_inches="tight") plt.show() # - sents = set() # + train_sents = set() for x in train: train_sents.update(x["text"]) train_sents.update(x["context"]) valid_sents = set() for x in valid: valid_sents.update(x["text"]) valid_sents.update(x["context"]) test_sents = set() for x in test: test_sents.update(x["text"]) test_sents.update(x["context"]) # - print(len(train_sents), len(valid_sents), len(test_sents), sum([len(train_sents), len(valid_sents), len(test_sents)]), len(train_sents | valid_sents | test_sents)) sum([len(x["context"]) + 1 for x in train]) sum([len(x["context"]) + 1 for x in valid]) sum([len(x["context"]) + 1 for x in test]) from itertools import chain from collections import Counter Counter(chain.from_iterable([x["stance_label"] for x in train + valid + test])) # + train_thesises = set() for x in train: train_thesises.add(x["context"][0]) valid_thesises = set() for x in valid: valid_thesises.add(x["context"][0]) test_thesises = set() for x in test: test_thesises.add(x["context"][0]) # - from itertools import chain from collections import Counter print("train", Counter(chain.from_iterable([x["stance_label"] for x in train]))) print("valid", Counter(chain.from_iterable([x["stance_label"] for x in valid]))) print("test", Counter(chain.from_iterable([x["stance_label"] for x in test]))) # + from itertools import chain arr = np.array(list(chain.from_iterable([[len(t) for t in x["text"]] + [len(ct) for ct in x["context"]] for x in train + valid + test]))) # - arr.mean() arr.max() # + Counter([(len(x["context"]) if len(x["context"]) <=5 else 6) for x in train + valid + test]).most_common() # - (605) / 7386 # + pattern = ["<Restatement>", "<Reason>"] pattern_idx = 0 for x in pattern: pattern_idx = pattern_idx * 14 + (discourse_labels.index(x) - 1) print(pattern, pattern_idx) scores = [] ids = [] for x in train+valid+test: if len(pattern) <= len(x["discourse_label"]) - 1: array = th.tensor(x["discourse_logit"][-len(pattern):])[:, 1:].softmax(-1) if array.shape[0] == 1: scores.append(array[pattern_idx].item()) ids.append(x["id"]) else: o = th.ger(array[0], array[1]).view(-1) for i in range(2, array.shape[0]): o = th.ger(o, array[i]).view(-1) scores.append(o[pattern_idx].item()) ids.append(x["id"]) # - print(len(train), len(valid), len(test)) scores = th.tensor(scores) sorted_idx = (-scores).argsort() print(sorted_idx[:10]) print([ids[idx] for idx in sorted_idx[:10]]) Counter([train[int(ids[idx].split("_")[1])]["label"] for idx in sorted_idx[:6]]) print([train[int(ids[idx].split("_")[1])]["context"][0] for idx in sorted_idx[:6]], sep="\n") print([train[int(ids[idx].split("_")[1])]["context"][0] for idx in sorted_idx[8:10]]) print(test[44]["context"][0]) print(valid[102]["context"][0], valid[102]["label"]) print(ids[3499], scores[3499]) train[int(ids[3499].split("_")[1])] Counter(chain.from_iterable([x["discourse_label"][1:] for x in train+valid+test if x["context"][0] == 'The European Union should become a United States of Europe'])) Counter([x["discourse_label"][-1] for x in train+valid+test if x["context"][0] == 'The European Union should become a United States of Europe']) Counter([tuple(x["discourse_label"][-2:]) for x in train+valid+test if x["context"][0] == 'The European Union should become a United States of Europe']) Counter([x["label"] for x in train+valid+test if x["context"][0] == 'The European Union should become a United States of Europe']) Counter([x["label"] for x in train+valid+test if x["context"][0] == 'The European Union should become a United States of Europe' and x["discourse_label"][-2:] == ['<Restatement>', '<Reason>']]) print(ids[3548], scores[3548]) train[4459]
src/preprocess_argimpact.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # reload packages # %load_ext autoreload # %autoreload 2 # ### Choose GPU (this may not be needed on your computer) # %env CUDA_DEVICE_ORDER=PCI_BUS_ID # %env CUDA_VISIBLE_DEVICES=1 # ### load packages from tfumap.umap import tfUMAP import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tqdm.autonotebook import tqdm import umap import pandas as pd # ### Load dataset from tensorflow.keras.datasets import fashion_mnist # + # load dataset (train_images, Y_train), (test_images, Y_test) = fashion_mnist.load_data() X_train = (train_images/255.).astype('float32') X_test = (test_images/255.).astype('float32') X_train = X_train.reshape((len(X_train), np.product(np.shape(X_train)[1:]))) X_test = X_test.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) # subset a validation set n_valid = 10000 X_valid = X_train[-n_valid:] Y_valid = Y_train[-n_valid:] X_train = X_train[:-n_valid] Y_train = Y_train[:-n_valid] # flatten X X_train_flat = X_train.reshape((len(X_train), np.product(np.shape(X_train)[1:]))) X_test_flat = X_test.reshape((len(X_test), np.product(np.shape(X_test)[1:]))) X_valid_flat= X_valid.reshape((len(X_valid), np.product(np.shape(X_valid)[1:]))) print(len(X_train), len(X_valid), len(X_test)) # - # ### define networks dims = (28,28,1) n_components = 2 encoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=dims), tf.keras.layers.Conv2D( filters=64, kernel_size=3, strides=(2, 2), activation="relu" ), tf.keras.layers.Conv2D( filters=128, kernel_size=3, strides=(2, 2), activation="relu" ), tf.keras.layers.Flatten(), tf.keras.layers.Dense(units=512, activation="relu"), tf.keras.layers.Dense(units=512, activation="relu"), tf.keras.layers.Dense(units=n_components), ]) decoder = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(n_components)), tf.keras.layers.Dense(units=512, activation="relu"), tf.keras.layers.Dense(units=512, activation="relu"), tf.keras.layers.Dense(units=7 * 7 * 256, activation="relu"), tf.keras.layers.Reshape(target_shape=(7, 7, 256)), tf.keras.layers.Conv2DTranspose( filters=128, kernel_size=3, strides=(2, 2), padding="SAME", activation="relu" ), tf.keras.layers.Conv2DTranspose( filters=64, kernel_size=3, strides=(2, 2), padding="SAME", activation="relu" ), tf.keras.layers.Conv2DTranspose( filters=1, kernel_size=3, strides=(1, 1), padding="SAME", activation="sigmoid" ) ]) # ### Create model and train embedder = tfUMAP( direct_embedding=False, verbose=True, negative_sample_rate=5, training_epochs=5, encoder=encoder, decoding_method="network", decoder=decoder, valid_X = X_valid, valid_Y = Y_valid, dims = dims ) z = embedder.fit_transform(X_train_flat) # ### Plot model output fig, ax = plt.subplots( figsize=(8, 8)) sc = ax.scatter( z[:, 0], z[:, 1], c=Y_train.astype(int)[:len(z)], cmap="tab10", s=0.1, alpha=0.5, rasterized=True, ) ax.axis('equal') ax.set_title("UMAP in Tensorflow embedding", fontsize=20) plt.colorbar(sc, ax=ax); # ### View loss from tfumap.umap import retrieve_tensors import seaborn as sns loss_df = retrieve_tensors(embedder.tensorboard_logdir) loss_df[:3] loss_df.group.unique() # + fig, axs = plt.subplots(ncols=2, figsize=(20,5)) ax = axs[0] sns.lineplot(x="step", y="val", hue="group", data=loss_df[loss_df.variable=='umap_loss'], ax = ax) ax.set_xscale('log') ax.set_title('UMAP loss') ax = axs[1] sns.lineplot(x="step", y="val", hue="group", data=loss_df[loss_df.variable=='recon_loss'], ax = ax) ax.set_xscale('log') ax.set_title('Reconstruction loss') # - # ### Save output from tfumap.paths import ensure_dir, MODEL_DIR output_dir = MODEL_DIR/'projections'/ 'fmnist' / 'recon-network' ensure_dir(output_dir) embedder.save(output_dir) loss_df.to_pickle(output_dir / 'loss_df.pickle') np.save(output_dir / 'z.npy', z) # ### Compare to direct embedding with base UMAP from umap import UMAP z_umap = UMAP(verbose=True).fit_transform(X_train_flat) ### realign using procrustes from scipy.spatial import procrustes z_align, z_umap_align, disparity = procrustes(z, z_umap) print(disparity) # + fig, axs = plt.subplots(ncols=2, figsize=(20, 8)) ax = axs[0] sc = ax.scatter( z_align[:, 0], z_align[:, 1], c=Y_train.astype(int)[:len(z)], cmap="tab10", s=0.1, alpha=0.5, rasterized=True, ) ax.axis('equal') ax.set_title("UMAP in Tensorflow", fontsize=20) #plt.colorbar(sc, ax=ax); ax = axs[1] sc = ax.scatter( z_umap_align[:, 0], z_umap_align[:, 1], c=Y_train.astype(int)[:len(z)], cmap="tab10", s=0.1, alpha=0.5, rasterized=True, ) ax.axis('equal') ax.set_title("UMAP with UMAP-learn", fontsize=20) #plt.colorbar(sc, ax=ax); # - # ### View reconstructions on test data z_test = embedder.transform(X_test) X_test_recon = embedder.inverse_transform(z_test) nex = 10 fig, axs = plt.subplots(ncols=nex, nrows=2, figsize=(nex,2)) for i in range(nex): axs[0,i].matshow(X_test[i].reshape(28,28), cmap='Greys') axs[1,i].matshow(X_test_recon[i].reshape(28,28), cmap="Greys") for ax in axs.flatten(): ax.axis('off')
notebooks/dataset-projections/fmnist/delete-fmnist-recon-network-embedding-Copy1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # 4.2.2 データの読み込み・書き込み import pandas as pd df = pd.read_csv("data/201704health.csv", encoding="utf-8") df df = pd.read_excel("data/201704health.xlsx") df url = "https://ja.wikipedia.org/wiki/%E3%83%88%E3%83%83%E3%83%97%E3%83%AC%E3%83%99%E3%83%AB%E3%83%89%E3%83%A1%E3%82%A4%E3%83%B3%E4%B8%80%E8%A6%A7" tables = pd.read_html(url) len(tables) df = tables[4] df df.to_csv("data/write_data.csv") df.to_excel("data/write_data.xlsx") df.to_pickle("data/write_df.pickle") df = pd.read_pickle("data/write_df.pickle")
ds-newtextbook-python/notebooks/4-2-2-pandas-dataio.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/cybertraining-dsc/fa20-523-312/blob/master/toxicologyASV.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="lw4eY8-thzwQ" # # **A basic programming and data-analysis framework (*under updation*)** # # The tasks below is carried out for the USGS data related to: *"USGS 03275500 EAST FORK WHITEWATER RIVER AT RICHMOND, IN"*. # # Data was collected continuously from October 9, 2020 till October 16, 2020. # + id="cnnnUXgOh6Tm" outputId="82672f7c-9d6f-4dab-f87b-e12b4182bd5e" colab={"base_uri": "https://localhost:8080/", "height": 1000} # Name: <NAME> # Date: 11/01/2020 # ENGR-E 534: Aquatic Toxicity Analysis with the aid of Autonomous Surface Vehicle (ASV) # Description: Implementation of a basic pythonic framework for analyzing the USGS and EPA databases # IMPORTANT INSTRUCTION: The following code assumes all applicable packages/libraries are pre-installed. import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from pandas import Series, DataFrame def geturl(wlink, year, season): # this section will possibly be addressed in a later part # it will be showed how the various factors express dependency on each other pass def download(url, filename): #NOTE: This section is not being currently used as data is only being read from an external website. It is not downloaded at all! #if filename already there: # skip #else: # download from url and store into filename pass def test_fit(x, a, b): return a * np.sin(b * x) def main(): # loading the USGS database as a panda data-frame df = pd.read_csv("https://waterdata.usgs.gov/nwis/uv?cb_00010=on&cb_00095=on&cb_00300=on&cb_00400=on&format=rdb&site_no=03275500&period=&begin_date=2020-10-09&end_date=2020-10-16", skiprows = 31, sep = "\t", header = None) #2019 full data from Richmond, IN: https://nwis.waterdata.usgs.gov/usa/nwis/uv/?cb_00010=on&cb_00095=on&cb_00300=on&cb_00400=on&format=rdb&site_no=03275500&period=&begin_date=2019-01-01&end_date=2019-12-31 param_df = df[[4,6,8,10]] columns = ['Temperature', 'Sp. Conductance', 'pH', 'Dissolved O2'] param_df.columns = columns print(param_df) print() # imputing missing values of a particular column 'x' with the mean of non-NaN values of the same column ## mean_x = param_df["x"].mean() ## filled_df = param_df.fillna(mean_x) # running basic statistical operations temp_med = param_df["Temperature"].median() print("Median Temperature value is:", temp_med) cond_med = param_df["Sp. Conductance"].median() print("Median Specific Conductance value is:", cond_med) pH_med = param_df["pH"].median() print("Median pH value is:", pH_med) dissox_med = param_df["Dissolved O2"].median() print("Median Dissolved-Oxygen value is:", dissox_med) # plot separate histograms for each of the nine attributes #for j in columns: # fig = plt.figure() # sp = fig.add_subplot(1, 1, 1) # sp.set_title("Histogram of attribute: " + str(j), fontsize = 12) # sp.set_xlabel("Value of the attribute") # sp.set_ylabel("Number of data points") # sp.hist(param_df[j], bins = 10, color = "red", edgecolor='black', linewidth=1.2, alpha = 0.5) x_data = list(range(0,768,1)); y1_data = param_df["Temperature"]; y2_data = param_df["Sp. Conductance"]; y3_data = param_df["pH"]; y4_data = param_df["Dissolved O2"]; #def test_fit(x, a, b): # return a * np.sin(b * x) #params, params_covariance = curve_fit(test_fit, x_data, y_data, p0=[2, 2]) #print(params) params1, params_covariance = curve_fit(test_fit, x_data, y1_data)#, p1=[2, 2]) params2, params_covariance = curve_fit(test_fit, x_data, y2_data)#, p2=[2, 2]) params3, params_covariance = curve_fit(test_fit, x_data, y3_data)#, p3=[2, 2]) params4, params_covariance = curve_fit(test_fit, x_data, y4_data)#, p4=[2, 2]) # ans1 = (params1[0]*(np.sin(params1[1]*x_data))) # ans2 = (params2[0]*(np.sin(params2[1]*x_data))) # ans3 = (params3[0]*(np.sin(params3[1]*x_data))) # ans4 = (params4[0]*(np.sin(params4[1]*x_data))) # plt.plot(x_data, y1_data, 'o', color ='red', label ="data") # plt.plot(x_data, ans1, '--', color ='blue', label ="optimized data") # plt.legend() # plt.show() # # plt.plot(x_data, y2_data, 'o', color ='red', label ="data") # plt.plot(x_data, ans2, '--', color ='blue', label ="optimized data") # plt.legend() # plt.show() # # plt.plot(x_data, y3_data, 'o', color ='red', label ="data") # plt.plot(x_data, ans3, '--', color ='blue', label ="optimized data") # plt.legend() # plt.show() # # plt.plot(x_data, y4_data, 'o', color ='red', label ="data") # plt.plot(x_data, ans4, '--', color ='blue', label ="optimized data") # plt.legend() # plt.show() # plt.scatter(x_data, y1_data, color = "red") # plt.scatter(x_data, y2_data, color = "blue") # plt.scatter(x_data, y3_data, color = "green") # plt.scatter(x_data, y4_data, color = "yellow") for j in columns: x_data = list(range(0,768,1)); fig = plt.figure() sp = fig.add_subplot(1, 1, 1) sp.set_title("Line plot of attribute: " + str(j), fontsize = 12) sp.set_ylabel("Value of the attribute") sp.set_xlabel("Number of data points") sp.plot(x_data, param_df[j], color = "green", label='Data') #sp.scatter(x_data, param_df[j], color = "blue", label='Data') #sp.hist(param_df[j], bins = 10, color = "red", edgecolor='black', linewidth=1.2, alpha = 0.5) for j in columns: x_data = list(range(0,768,1)); fig = plt.figure() sp = fig.add_subplot(1, 1, 1) sp.set_title("Scatter plot of attribute: " + str(j), fontsize = 12) sp.set_ylabel("Value of the attribute") sp.set_xlabel("Number of data points") #sp.plot(x_data, param_df[j], color = "green", label='Data') sp.scatter(x_data, param_df[j], color = "blue", label='Data') #sp.hist(param_df[j], bins = 10, color = "red", edgecolor='black', linewidth=1.2, alpha = 0.5) for j in columns: x_data = list(range(0,768,1)); fig = plt.figure() sp = fig.add_subplot(1, 1, 1) sp.set_title("Histogram of attribute: " + str(j), fontsize = 12) sp.set_xlabel("Value of the attribute") sp.set_ylabel("Number of data points") #sp.plot(x_data, param_df[j], color = "green", label='Data') #sp.scatter(x_data, param_df[j], color = "blue", label='Data') sp.hist(param_df[j], bins = 10, color = "red", edgecolor='black', linewidth=1.2, alpha = 0.5) if __name__ == "__main__": main()
docs/report/fa20-523-312/toxicologyASV.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: text_data # language: python # name: python3 # --- # + #HI <NAME> # - # # TAD_FINAL_PROJECT_Broker_Carl # - [1. Research Question](#1.) # - [2. Import Datasets](#2.) # - [2.1 Setup](#2.1) # - [2.2 Import Game Reviews via API](#2.2) # - [2.3 Clean Game Reviews](#2.3) # - [2.4 Save Game Reviews](#2.4) # - [2.5 Import 'Users Per Day'](#2.5) # - [3. Analysis](#3.) # - [3.1 Sentiment Analysis](#3.1) # - [3.1.1 Setup](#3.1.1) # - [3.1.2 Load Training Datasets and Pre-Process](#3.1.2) # - [3.1.3 Pre-Process Cont. (Tokenize Data)](#3.1.3) # - [3.1.4 Neural Network Sentiment Classification with BERT and Hugging Face](#3.1.4) # - [3.1.5 Training (of Model)](#3.1.5) # - [3.1.6 Sentiment Analysis of Game Reviews](#3.1.6) # - [3.2 Sentiment Over Time](#3.2) # - [3.2.1 Setup](#3.2.1) # - [3.2.2 Figures](#3.2.2) # - [3.3 Sentiment Distribution vs. Twitch Views](#3.3) # - [4. Closing Thoughts](#4.) # <a id='#1.'></a> # ## 1. Research Question # I am currently seeking employment in the field of Machine Learning, and gearing my coursework around such. # # For several years, since I played Halflife as a boy, I've dreamed of working at Valve. So, as I progress through my career I submit a job applicaiton to them yearly. In 2018 a team member there responsed to my application and said I wasn't ready. So, I've maintained contact with them showcasing my progress in Graduate School. This summer, studying Natural Language Processing(NLP) gave me the enviornament I needed to scratch the surface of game reviews and what analyzing such entails. Below you will find the suggestions the Valve member gave me to explore during my summer course. I attempted, keyword 'attempted' here, to answer as many of them as I could. Please see my 4. Closing Thoughts section for description of my successes and failures. # Hi Carl, # # There would seem to be a wide range of analyses to pursue: # # --Can you predict review scores from review text? # # --If yes, why? If not, why not? # # --Do review texts predict game sales, user counts, retention over time, etc.? # # --Can you quantify user sentiment about a game? # # --Can you watch that sentiment shift over time? # # --How many different sentiments can you identify? # # --How many reviews contain multiple sentiments? # # I’m sure there are many more, but those are a few that seemed useful off the top of my head. # # Best of luck with the project! # # Mike # Steam # (Over the Summer I attempted to answer as many of these questions as I could.) # <a id='#2.'></a> # ## 2. Import Datasets: # <a id='#2.1'></a> # ### 2.1 Setup # + # import packages import os import sys import time import json import numpy as np import pandas as pd import urllib.parse import urllib.request from tqdm import tqdm import plotly.express as px from datetime import datetime from pandas import json_normalize from tqdm import tqdm # list package ver. etc. print("Python version") print (sys.version) print("Version info.") print (sys.version_info) print('---------------') # - # <a id='#2.2'></a> # ## 2.2 Import Game Reviews via API # ##### (API Documentation: https://partner.steamgames.com/doc/store/getreviews) # + # generate game review df #steam 'chunks' their json files (the game reviews) in sets of 100 #ending with a signature, a 'cursor'. This cursor is then pasted #onto the the same url, to 'grab' the next chunk and so on. #This sequence block with an 'end cursor' of 'AoJ4tey90tECcbOXSw==' #set variables url_base = 'https://store.steampowered.com/appreviews/393380?json=1&filter=updated&language=all&review_type=all&purchase_type=all&num_per_page=100&cursor=' #first pass url = urllib.request.urlopen("https://store.steampowered.com/appreviews/393380?json=1&filter=updated&language=all&review_type=all&purchase_type=all&num_per_page=100&cursor=*") data = json.loads(url.read().decode()) next_cursor = data['cursor'] next_cursor = next_cursor.replace('+', '%2B') df1 = json_normalize(data['reviews']) print(next_cursor) #add results till stopcursor met, then send all results to csv while True: time.sleep(0.5) # Sleep for half-second url_temp = url_base + next_cursor url = urllib.request.urlopen(url_temp) data = json.loads(url.read().decode()) next_cursor = data['cursor'] next_cursor = next_cursor.replace('+', '%2B') df2 = json_normalize(data['reviews']) df1 = pd.concat([df1, df2]) print(next_cursor) if next_cursor == 'AoJwnPKp0tECeIWXSw==' or next_cursor == '*': df_steam_reviews = df1 df1 = None break #the hash below is each 'cursor' I loop through until the 'end cursor'. #this is just my way of monitoring the download. # - # inspect columns print(df_steam_reviews.info(verbose=True)) # inspect shape print(df_steam_reviews.shape) # --- # ### Data Dictionary: # # - Response: # - success - 1 if the query was successful # - query_summary - Returned in the first request # - recommendationid - The unique id of the recommendation # - author # - steamid - the user’s SteamID # - um_games_owned - number of games owned by the user # - num_reviews - number of reviews written by the user # - playtime_forever - lifetime playtime tracked in this app # - playtime_last_two_weeks - playtime tracked in the past two weeks for this app # - playtime_at_review - playtime when the review was written # - last_played - time for when the user last played # - language - language the user indicated when authoring the review # - review - text of written review # - timestamp_created - date the review was created (unix timestamp) # - timestamp_updated - date the review was last updated (unix timestamp) # - voted_up - true means it was a positive recommendation # - votes_up - the number of users that found this review helpful # - votes_funny - the number of users that found this review funny # - weighted_vote_score - helpfulness score # - comment_count - number of comments posted on this review # - steam_purchase - true if the user purchased the game on Steam # - received_for_free - true if the user checked a box saying they got the app for free # - written_during_early_access - true if the user posted this review while the game was in Early Access # - developer_response - text of the developer response, if any # - timestamp_dev_responded - Unix timestamp of when the developer responded, if applicable # # --- # Source: https://partner.steamgames.com/doc/store/getreviews # inspect df df_steam_reviews # <a id='#2.3'></a> # ## 2.3 Clean Game Reviews # + #drop empty cols 'timestamp_dev_responded' and 'developer_response' df_steam_reviews = df_steam_reviews.drop(['timestamp_dev_responded', 'developer_response'], axis=1) # convert unix timestamp columns to datetime format def time_to_clean(x): return datetime.fromtimestamp(x) df_steam_reviews['timestamp_created'] = df_steam_reviews['timestamp_created'].apply(time_to_clean) df_steam_reviews['timestamp_updated'] = df_steam_reviews['timestamp_updated'].apply(time_to_clean) df_steam_reviews['author.last_played'] = df_steam_reviews['author.last_played'].apply(time_to_clean) # inspect df_steam_reviews # - # <a id='#2.4'></a> # ## 2.4 Save Game Reviews # save that sheet df_steam_reviews.to_csv(r'../data/processed/game_reviews_processed.csv', index=False) #load that sheet, if restarted instance # save that sheet df_steam_reviews = pd.read_csv(r'../data/processed/game_reviews_processed.csv') # <a id='#2.5'></a> # ## 2.5 Import 'Users Per Day' #load 'steam charts for every day' downloaded by hand from https://steamdb.info/ on August 14th df_upd = pd.read_csv(r'../data/processed/users_per_day.csv') #convert 'DateTime' col to datetime Dtype. df_upd['DateTime'] = pd.to_datetime(df_upd['DateTime']) #inspect cols print(df_upd.info(verbose=True)) #inspect shape df_upd.shape #inspect df df_upd # <a id='#3.'></a> # # 3. Analysis: # <a id='#3.1'></a> # ## 3.1 Sentiment Analysis # --Can you quantify user sentiment about a game? # <a id='#3.1.1'></a> # ## 3.1.1 Setup # + import transformers from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup import os as os import sys as sys import numpy as np import pandas as pd import seaborn as sns from matplotlib import rc from pylab import rcParams from torch import nn, optim import matplotlib.pyplot as plt from collections import defaultdict from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, classification_report import torch from torch import nn, optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader import json import pandas as pd import urllib.parse import urllib.request from time import sleep from pandas import json_normalize #set graph config # %matplotlib inline # %config InlineBackend.figure_format='retina' sns.set(style='whitegrid', palette='muted', font_scale=1.2) HAPPY_COLORS_PALETTE = ["#01BEFE", "#FFDD00", "#FF7D00", "#FF006D", "#ADFF02", "#8F00FF"] sns.set_palette(sns.color_palette(HAPPY_COLORS_PALETTE)) rcParams['figure.figsize'] = 12, 8 #set seed RANDOM_SEED = 42 np.random.seed(RANDOM_SEED) torch.manual_seed(RANDOM_SEED) #check gpu device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device # - # <a id='#3.1.2'></a> # ## 3.1.2 Load Training Datasets and Pre-Process #load training dataset (google app reviews, 16K rows) df_google = pd.read_csv(r'../data/processed/reviews.csv') #inspect google reviews df_google.head(0) #inspect #2 df_google.shape # + #The imbalce is ok, because we're dividing between negative(1,2) neutral(3) and positive (4,5). def to_sentiment(rating): rating = int(rating) if rating <= 2: return 0 elif rating == 3: return 1 else: return 2 #apply above function to dataset df_google['sentiment'] = df_google.score.apply(to_sentiment) # - #review changes class_names = ['negative', 'neutral', 'positive'] ax = sns.countplot(df_google.sentiment) plt.xlabel('review sentiment') sns.countplot(df_google.sentiment) ax.set_xticklabels(class_names); # + #subset google for relavent info df_google_subset = df_google[['content', 'sentiment']] #rename for gpu loading frames = [df_google_subset] #I omitted df_imdb, due to limited gpu memory df = pd.concat(frames) df # - # <a id='#3.1.3'></a> # ## 3.1.3 Pre-Process Cont. (Tokenize Data) # # 1) Add special tokens to separate sentences and do classification # # 2) Pass sequences of constant length (introduce padding) # # 3) Create array of 0s (pad token) and 1s (real token) called 'attention mask' # + #there are two model types to choose from, case and uncased. #We're using 'cased', as "BAD" might convey more sentiment than "bad". #identify model PRE_TRAINED_MODEL_NAME = 'bert-base-cased' # + #load pre-trained BertTokenizer #https://huggingface.co/transformers/model_doc/bert.html#berttokenizer tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME) #if you get an error, execute 'conda install -c conda-forge ipywidgets' in your env: #https://ipywidgets.readthedocs.io/en/stable/user_install.html # + #BERT works with fixed-length sequences. Let's inspect the length of each review from our training dataset and tokenize it token_lens = [] for txt in tqdm(df.content): tokens = tokenizer.encode(txt, max_length=512) #max len of this model is 512, sadly token_lens.append(len(tokens)) #let's plot the distribution to get a sense of what we're working with sns.distplot(token_lens) plt.xlim([0, 600]); plt.xlabel('Token count'); # - #as a result of trial and error, due to gpu memeory limitations, we need to set a max len of our tensors to 150. MAX_LEN = 512 #let's format our dataset to PyTorch dataset. class GPReviewDataset(Dataset): def __init__(self, reviews, targets, tokenizer, max_len): self.reviews = reviews self.targets = targets self.tokenizer = tokenizer self.max_len = max_len def __len__(self): return len(self.reviews) def __getitem__(self, item): review = str(self.reviews[item]) target = self.targets[item] encoding = self.tokenizer.encode_plus( review, add_special_tokens=True, max_length=self.max_len, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', ) return { 'review_text': review, 'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'targets': torch.tensor(target, dtype=torch.long) } #test-train-split training data df_train, df_test = train_test_split(df, test_size=0.1, random_state=RANDOM_SEED) df_val, df_test = train_test_split(df_test, test_size=0.5, random_state=RANDOM_SEED) #inspect shape df_train.shape, df_val.shape, df_test.shape #data loader, that's required in the tutorial. I see that it's converting things to numpy arrays, #but aside from that, that's all I understand (sadly) def create_data_loader(df, tokenizer, max_len, batch_size): ds = GPReviewDataset( reviews=df.content.to_numpy(), targets=df.sentiment.to_numpy(), tokenizer=tokenizer, max_len=max_len ) return DataLoader( ds, batch_size=batch_size, num_workers=0 #when running pytorch in windows, not linux, you need to set this to zero or it crashes. ) #https://github.com/pytorch/pytorch/issues/2341 # + #set batch size and loader values BATCH_SIZE = 8 train_data_loader = create_data_loader(df_train, tokenizer, MAX_LEN, BATCH_SIZE) val_data_loader = create_data_loader(df_val, tokenizer, MAX_LEN, BATCH_SIZE) test_data_loader = create_data_loader(df_test, tokenizer, MAX_LEN, BATCH_SIZE) # - #let's look at an example batch from out trining data loader: data = next(iter(train_data_loader)) data.keys() #inspect shape print(data['input_ids'].shape) print(data['attention_mask'].shape) print(data['targets'].shape) # <a id='#3.1.4'></a> # ## 3.1.4 Neural Netowrk Sentiment Classification with BERT and Hugging Face # load model: bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) #we use this knowledge to make a classifier that uses the BERT mdoel: class SentimentClassifier(nn.Module): def __init__(self, n_classes): super(SentimentClassifier, self).__init__() self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME, return_dict=False) self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.bert.config.hidden_size, n_classes) def forward(self, input_ids, attention_mask): _, pooled_output = self.bert( input_ids=input_ids, attention_mask=attention_mask ) output = self.drop(pooled_output) return self.out(output) #let's make an instace if the the above class and move it to our GPU model = SentimentClassifier(len(class_names)) model = model.to(device) # <a id='#3.1.5'></a> # ## 3.1.5 Training (of Model) # + EPOCHS = 20 optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False) total_steps = len(train_data_loader) * EPOCHS scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=0, num_training_steps=total_steps ) loss_fn = nn.CrossEntropyLoss().to(device) # - #set training function def train_epoch( model, data_loader, loss_fn, optimizer, device, scheduler, n_examples ): model = model.train() losses = [] correct_predictions = 0 for d in tqdm(data_loader): input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() scheduler.step() optimizer.zero_grad() return correct_predictions.double() / n_examples, np.mean(losses) # set eval funciton def eval_model(model, data_loader, loss_fn, device, n_examples): model = model.eval() losses = [] correct_predictions = 0 with torch.no_grad(): for d in tqdm(data_loader): input_ids = d["input_ids"].to(device) attention_mask = d["attention_mask"].to(device) targets = d["targets"].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) return correct_predictions.double() / n_examples, np.mean(losses) #clear gpu cache before training torch.cuda.empty_cache() # + # execute training history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): print(f'Epoch {epoch + 1}/{EPOCHS}') print('-' * 10) train_acc, train_loss = train_epoch( model, train_data_loader, loss_fn, optimizer, device, scheduler, len(df_train) ) print(f'Train loss {train_loss} accuracy {train_acc}') val_acc, val_loss = eval_model( model, val_data_loader, loss_fn, device, len(df_val) ) print(f'Val loss {val_loss} accuracy {val_acc}') print() history['train_acc'].append(train_acc) history['train_loss'].append(train_loss) history['val_acc'].append(val_acc) history['val_loss'].append(val_loss) if val_acc > best_accuracy: torch.save(model.state_dict(), 'best_model_state.bin') best_accuracy = val_acc # - #gather training results df_history = pd.DataFrame.from_dict(history, orient='index') df_history_t = df_history.transpose() df_history_t.head() # + #make figure data train_acc_lst = df_history_t['train_acc'].tolist() val_acc_lst = df_history_t['val_acc'].tolist() #annoying stuff temp_train = [] for item in range(0,20): acc = train_acc_lst[item].item() temp_train.append(acc) train_acc = temp_train temp_train = None temp_val = [] for item in range(0,20): acc = val_acc_lst[item].item() temp_val.append(acc) val_acc = temp_val temp_val = None # + #display figuer plt.plot(train_acc, label='train accuracy') plt.plot(val_acc, label='validation accuracy') plt.title('20 Epochs') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend() plt.ylim([0, 1]) # - # <a id='#3.1.6'></a> # ## 3.1.6 Sentiment Analysis of Game Reviews # load raw text df_game_reviews = pd.read_csv(r'../data/processed/game_reviews_processed.csv', low_memory=False) # subset df to just english reviews df_english = df_game_reviews[df_game_reviews["language"] == 'english'] # set reviews to list title_lst = df_english['review'].tolist() # + title_lst_final = [] for item in title_lst: temp = str(item) title_lst_final.append(temp) # + # pass each review through sentiment model review_text_lst = [] prediction_lst = [] for item in tqdm(title_lst_final): encoded_review = tokenizer.encode_plus(item, max_length=MAX_LEN, add_special_tokens=True, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt',) input_ids = encoded_review['input_ids'].to(device) attention_mask = encoded_review['attention_mask'].to(device) output = model(input_ids, attention_mask) _, prediction = torch.max(output, dim=1) review_text_lst.append(item) prediction_lst.append(class_names[prediction]) # + #count up your glorious sentiment results pos_count = 0 neg_count = 0 neu_count = 0 for item in prediction_lst: if item == 'positive': pos_count += 1 elif item == 'neutral': neu_count += 1 else: neg_count += 1 # - print('Positive reviews: ', pos_count) print('Negative reviews: ', neg_count) print('Neutral reviews: ', neu_count) # <a id='#3.2'></a> # <a id='#3.1.7'></a> # ## 3.2 Sentiment Over Time # --Can you watch that sentiment shift over time? # <a id='#3.2.1'></a> # ## 3.2.1 Setup # + # join reviews, predictions, timestamps, views-per-day into one df df_analysis = pd.DataFrame(df_english) # add predictions to df_analysis df_analysis['predictions'] = prediction_lst # - #add blank sentiment counts to views per day dataframe df_upd['pos_sent_count'] = np.nan df_upd['neg_sent_count'] = np.nan df_upd['neu_sent_count'] = np.nan #save dfs to csvs df_upd.to_csv(r'../data/processed/df_upd.csv', index=False) df_analysis.to_csv(r'../data/processed/df_analysis.csv', index=False) # + #edit df_upd in Excel, yep. excel. deal with it. #reload df df_upd = pd.read_csv(r'../data/processed/df_upd_edited.csv', low_memory=False) #reformat datetime column to python DateTime df_upd['DateTime'] = pd.to_datetime(df_upd['DateTime']) #regormat pos_dist to int64 #df_upd["pos_dist"] = pd.to_numeric(df_upd["pos_dist"]) df_upd.head() # - #make list of dates, pos_dist, pos_count, neg_count and neu_count scatter_dates = df_upd['DateTime'].tolist() scatter_postdist = df_upd['pos_dist'].tolist() scatter_pos_count = df_upd['pos_sent_count'].tolist() scatter_neg_count = df_upd['neg_sent_count'].tolist() scatter_neu_count = df_upd['neu_sent_count'].tolist() # <a id='#3.2.2'></a> # ## 3.2.2 Figures #inspect pos counts plt.scatter(scatter_dates, scatter_pos_count) plt.title('Positive Sentiment Count, per day') plt.ylabel('pos_sent') plt.xlabel('Date') # inspect sentiment over time plt.scatter(scatter_dates, scatter_neg_count, c='r') plt.title('Negative Sentiment Count, per day') plt.ylabel('neg_sent') plt.xlabel('Date'); # inspect neutral sentiment over time plt.scatter(scatter_dates, scatter_neu_count, c='black') plt.title('Neutral Sentiment Count, per day') plt.ylabel('neu_sent') plt.xlabel('Date'); # + #In review of the sentiment counts and distributions, it would be interesting to see if some #of the 'spikes' were the result of the game going on sale. Steam does have regular sales, #such as 'summer sales' as well as sales around the holidays. I assume the spikes #were the direct result of these. It's also possible that these spikes were due to big #Twitch streamers playing the game, and their viewers buying it. Also, the increase observed #at the end of 2019 remained a mystery. # - # <a id='#3.3'></a> # ## 3.3 Sentiment Distribution vs. Twitch Views # + # make list of twitch views #scatter_ttv_views = df_upd['Twitch_Viewers'].tolist() # + # inspect sentiment over time #plt.scatter(scatter_ttv_views, scatter_postdist) #plt.title('Positive Sentiment Distribution vs. Twitch Views (same day reviews)') #plt.ylabel('pos_dist') #plt.xlabel('Twitch Views') #plt.xlim(0,6000); # - # <a id='#4.'></a> # ## 4. Closing Thoughts # There were several major hurdles that I had to overcome in my journey that I wanted to quickly address. Sadly, I was not able to answer all the posted questions. The game developers did not share sales figures with me. As as result I was not able to predict sales trends as a function of previous game reviews. I could have used Twitch views as a soft marker of 'sales' but that would have been a stretch. Also, I couldn't explore multiple sentiments via a 3rd-party model: # [crystalfeel](http://www.crystalfeel.socialanalyticsplus.net/) # # They did not return my inquiries. Nevertheless, I hand-coded a portion of the game reviews by hand, with a ~51% accuracy of expending the lables to the rest of the game reviews. A notebook of that may be found here: # [multiple sentiments via crystalfeel](https://github.com/cbroker1/text-as-data/blob/master/notebooks/TAD_Week_7_Broker_Carl.ipynb) # # GPU Training. Up till this point I did not have that much experience using my GPU for training. Learning how to use pytorch to set up tensors and pass them to my GPU was a challenge. Once I got it up and running however, I had a lot of fun exploring different training datasets and the power GPU training offered in developing larger models (we're talking days of training). My model's accuracy ended up being worse @100k training samples vs 10k, which was a valuable lesson learned: # [training exploration](https://github.com/cbroker1/text-as-data/blob/master/notebooks/TAD_Week_5_Broker_Carl.ipynb) # # I did explore increasing my Epoch count to 100 (8 hours of training on my 10K training dataset) and did not find a significant increace in model performace. Hence why in my final draft I left it at 10 Epochs. # # In the future, I'm interested in exploring longer lenghts of tokens (in turn, sentence length) when using BERT models. A significant portion of the game reviews are longer than what BERT allows. Also, using a rented cloud service for training as that took a significant portion of my time. # # Thank you for your time.
notebooks/TAD_FINAL_PROJECT_Broker_Carl.ipynb
# --- # jupyter: # jupytext: # cell_metadata_filter: -all # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.14.4 # --- # %% import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.models import Sequential from tensorflow.keras.callbacks import EarlyStopping import tensorflow as tf from Funcoes import * import pickle # %% # %matplotlib inline # %% plt.rcParams['font.size'] = 18 plt.rcParams['figure.figsize'] = [16, 8] plt.rcParams['lines.linewidth'] = 2 # %% resultados = dict() for amostras in [2**x for x in range(5,11)]: print(f'{"#"*20} {amostras} Amostras {"#"*20}') M = 16 # ordem da modulação Fb = 40e9 # taxa de símbolos SpS = 4 # amostras por símbolo Fs = SpS*Fb # taxa de amostragem SNR = 40 # relação sinal ruído (dB) rolloff = 0.01 # Rolloff do filtro formatador de pulso sfm, A = sinal_qam_fase_min(M,Fb,SpS,SNR) #amostras = 128 dataset , X , y = dataset_02(sfm,amostras) X_train = X[:50000] X_test = X[50000:] y_train = y[:50000] y_test = y[50000:] scaler = MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) stop = EarlyStopping(monitor='val_loss', patience=5) model = Sequential() model.add(Dense(128, activation='relu', input_shape=(amostras,))) model.add(Dense(128, activation='relu')) Dropout(0.5) model.add(Dense(1)) model.compile(optimizer='adam', loss='mse') model.fit(X_train, y_train, epochs=300, callbacks=[stop], validation_data=(X_test, y_test), batch_size=64,verbose=2) predicoes = model.predict(X_test) sinal_predito = (dataset['amplitudes'][50000:]*np.exp(1j*predicoes.reshape(-1,))).reshape(1,-1) sinal_predito_revertido = reverter_sinal_fase_min(sinal_predito ,A).reshape(1,-1) sinal_predito_filtrado = normcenter(lowpassFilter(sinal_predito_revertido, Fs, 1/Fb, 0.001, taps=4001)) sinal_base_revertido = reverter_sinal_fase_min(sfm[:,50000:60001],A) teste = str(amostras) + ' Amostras' resultados[teste] = {'Sinais fase minima':(sfm[:,50000:60001], sinal_predito), 'Sinais revertidos':(sinal_base_revertido,sinal_predito_revertido), 'Sinal predito filtrado':(sinal_predito_filtrado)} print('\n\n') print(' FIM ') # %% # nome_arquivo = 'Result_dif_num_amostras.pkl' # arquivo = open(nome_arquivo,'wb') # pickle.dump(resultados,arquivo) # arquivo.close()
.ipynb_checkpoints/Analise_num_amostras-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Python ClassMethod # 파이썬에서는 클래스를 작성하여 객체를 만들 수 있습니다. # 그리고 그 객체 안에 메서드를 작성할 수도 있습니다. # 간단한 예제를 통해서 살펴보겠습니다. class Person: def __init__(self, name, age): self.name = name self.age = age def info(self): print('name: {0}\n age: {1}'.format(self.name, self.age)) mike = Person('mike', 20) mike.info() Person.info() # 위에서는 Person이라는 클래스를 만들고, 객체를 생성하여 info() 함수를 호출하였습니다. # 그 결과로 이름과 나이를 출력하는 것을 볼 수 있습니다. # 객체를 만들지 않고 바로 클래스를 통해서 info를 호출하게 되면 에러가 발생합니다. # 이렇게 객체를 만들어야만 호출할 수 있는 함수를 인스턴스 메서드라고 합니다. # # 이제 객체를 만들지 않고도 호출할 수 있는 static method와 class method에 대해서 알아보겠습니다. # Person 클래스에 각각 statichello와 classhello 함수를 작성한 뒤, 각각 데코레이터를 달아줍니다. class Person: classname = 'Person' def __init__(self, name, age): self.name = name self.age = age @staticmethod def statichello(msg): print('Hello {0}'.format(msg)) @classmethod def classhello(cls, msg): print('Hello {0}'.format(msg)) Person.classhello('World') Person.statichello('World') # 두 함수 모두 동일하게 결과를 출력하는 것을 볼 수 있습니다. # 하지만 두 함수는 상속과 관련해서 미세한 차이를 보이는데요, 이 차이를 알아보겠습니다. # 먼저 Person 클래스를 약간 수정하고, 이를 상속받는 Student라는 객체를 만들어보겠습니다. # + class Person: classname = 'Person' def __init__(self, name, age): self.name = name self.age = age @staticmethod def static_person(name, age): return Person(name, age) @classmethod def class_person(cls, name, age): return cls(name, age) def info(self): print('class: {0}\n name: {1}\n age: {2}'.format(self.classname, self.name, self.age)) class Student(Person): classname = 'Student' # - mike = Student.static_person('mike', 20) jane = Student.class_person('jane', 22) mike.info() jane.info() # 둘은 같은 Student 클래스의 메서드를 호출하였습니다만, 둘은 각기 다른 클래스 명을 리턴합니다. # 이를 통해서 스태틱 메서드는 클래스 변수를 부모 클래스에서 가져온다는 것을 알 수 있고, # 클래스 메서드는 현재의 클래스에서 가져온다는 것을 알 수 있습니다. # ## 마치며 # 지금까지 클래스와 스태틱 메서드, 클래스 메서드의 사용, 그리고 그 둘의 차이까지 알아보았습니다. # 사실 이런 기능들은 실제 개발을 할때는 많이 활용하지 않습니다. # 하지만 직접 라이브러리 소스코드를 볼 때에는 많이 마주치는 문법들이므로 # 잘 익혀두었다가 당황하지 말고 개발할 수 있으면 좋겠습니다. # 감사합니다.
week6_class.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/VikriAulia/Tensorflow-Deep-Learning-Speech-Recognition/blob/master/Google-Command-Classification-CNN-RNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="8Wr1OULRyzmZ" colab_type="code" outputId="d5416910-237d-4a6f-a0b5-d3ace4062a12" colab={"base_uri": "https://localhost:8080/", "height": 35} import numpy as np import wave import matplotlib.pyplot as plt # %matplotlib inline # %tensorflow_version 1.x from glob import glob import random import struct from keras.models import * from keras.layers import * from keras.callbacks import * from kapre.time_frequency import Melspectrogram, Spectrogram from kapre.utils import Normalization2D # %load_ext tensorboard DATA_DIR = './speech_commands' RUN = 1 # + id="_RDAbJD7zbry" colab_type="code" outputId="bda1529c-928f-447a-9ebb-15a084b582cc" colab={"base_uri": "https://localhost:8080/", "height": 410} # !wget http://download.tensorflow.org/data/speech_commands_v0.01.tar.gz -O speech_commands_v0.01.tar.gz # !wget http://download.tensorflow.org/data/speech_commands_v0.02.tar.gz -O speech_commands_v0.02.tar.gz # + id="_ADpnZ002oWZ" colab_type="code" outputId="ef5fcf1a-45db-4559-b298-2faebe0f8b4e" colab={"base_uri": "https://localhost:8080/", "height": 35} # !mkdir speech_commands # !ls -l speech_commands # + id="Kd1vOvYY0W1L" colab_type="code" colab={} # !tar -xzf speech_commands_v0.01.tar.gz --directory speech_commands # !tar -xzf speech_commands_v0.02.tar.gz --directory speech_commands # + [markdown] id="jdkFEFQC8_ml" colab_type="text" # ### contoh pemprosesan dengan spektogram. satu channel data wave # + id="M0wd-kPhyzmv" colab_type="code" outputId="808d7e25-3af8-4fb6-bde3-53477edaca2e" colab={"base_uri": "https://localhost:8080/", "height": 351} test_file = "{}/house/ad89eb1e_nohash_0.wav".format(DATA_DIR) with wave.open(test_file, 'rb') as f: params = f.getparams() nchannels, sampwidth, framerate, nframes = params[:4] # print(nchannels, sampwidth, framerate, nframes) # 1 2 16000 16000 strData = f.readframes(nframes)#读取音频,字符串格式 # print(type(strData)) # <class 'bytes'> # print(strData[:20]) # b'\xff\xff\xea\xff\xe3\xff\xef\xff\xf6 waveData = np.fromstring(strData, dtype=np.int16)#将字符串转化为int # print(type(waveData)) # <class 'numpy.ndarray'> # print(waveData[:20]) # [ -1 -22 -29 -17 -10 -14 -19 -18 -18 -21 -11 8] waveData_norm = waveData * 1.0 / (max(abs(waveData)))#wave幅值归一化 # print(type(waveData_norm)) #<class 'numpy.ndarray'> # print(waveData_norm[:20]) #[-0.00010379 -0.00228334 -0.00300986 -0.0017644] # print(waveData_norm.shape) # (16000,) time = np.arange(0, nframes)*(1.0 / framerate) plt.plot(time, waveData_norm) plt.xlabel("Time(s)") plt.ylabel("Amplitude") plt.title("Single channel wavedata") plt.grid('on') plt.show() # + id="zgYGfi_0kDbG" colab_type="code" outputId="572203de-9e5b-48d6-9756-682522562fe2" colab={"base_uri": "https://localhost:8080/", "height": 53} print(waveData_norm) type(waveData_norm) # + id="AV1mV5XNyzm-" colab_type="code" colab={} def get_wave_norm(file): with wave.open(file, 'rb') as f: params = f.getparams() nchannels, sampwidth, framerate, nframes = params[:4] data = f.readframes(nframes) data = np.fromstring(data, dtype=np.int16) data = data * 1.0 / max(abs(data)) return data def save_wave(data, file='./save.wav'): with wave.open(file, 'wb') as outwave: nchannels = 1 sampwidth = 2 framerate = 16000 nframes = data.shape[0] comptype = "NONE" compname = "not compressed" outwave.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname)) for v in data: outwave.writeframes(struct.pack('h', int(v * 64000 / 2)))#outData:16位,-32767~32767,注意不要溢出 # + id="Qxo8p2PayznK" colab_type="code" outputId="02c75d89-0f0a-4884-e2e5-b25bd44a79d6" colab={"base_uri": "https://localhost:8080/", "height": 73} MAX_FRAME = 16000 LABELS = ['five', 'happy', 'one', 'house', 'tree', 'bed', 'marvin', 'dog', 'left', 'stop', 'sheila', 'four', 'zero', 'cat', 'three', 'two', 'bird', 'yes', 'wow', 'seven', 'on', 'down', 'nine', 'right', 'up', 'no', 'eight', 'six', 'off', 'go','follow','visual','backward','forward','learn'] N_CLASS = len(LABELS) file_glob, noise_glob = [], [] for f in glob('{}/*/*.wav'.format(DATA_DIR)): # bug, this wav has no sound if f.find('bird/3e7124ba_nohash_0.wav') != -1: #Buang file bug pada bird/3e7124ba_nohash_0.wav ( tidak ada suara ) continue if f.find('/_background_noise_/') == -1: file_glob.append(f) else: noise_glob.append(f) noize_data = [get_wave_norm(f) for f in noise_glob] noize_data = np.concatenate(noize_data, axis=0) # + id="hTtwEQM5yznV" colab_type="code" colab={} def add_noise(w): idx = random.randint(0, noize_data.shape[0] - w.shape[0]) w = w + noize_data[idx:idx+w.shape[0]] / 5.0 w = w * 1.0 / (max(abs(w))) return w def get_wave(file): data = get_wave_norm(file) #if random.random() >= 0.5: #random noise # data = add_noise(data) #tambahkan noise ke data wave_data = np.zeros((MAX_FRAME, )) wave_len = min(MAX_FRAME, data.shape[0]) wave_data[:wave_len] = data[:wave_len] return np.expand_dims(wave_data, axis=1) # test # x = get_wave('{}/bed/0a7c2a8d_nohash_0.wav'.format(DATA_DIR)) # save_wave(x[:,0], 'mix.wav') def gen(batch_size=32, verbose=False): while True: X = np.zeros((batch_size, MAX_FRAME, 1), dtype=np.float32) #y = np.zeros((batch_size, N_CLASS), dtype=np.uint8) #edit y = np.empty((batch_size), dtype=int) files = np.random.choice(file_glob, batch_size) if verbose: print(files) for i in range(batch_size): f = files[i] X[i] = get_wave(f) label = f[len(DATA_DIR) + 1:] label = label[:label.index('/')] label_idx = LABELS.index(label) # y[i, label_idx] = 1 #edit "#" untuk rnn saja y[i] = label_idx yield X, y # + id="DXuYCMYBc8Tl" colab_type="code" outputId="8ea8006c-2961-4fe2-b4d3-4110b2fb2091" colab={"base_uri": "https://localhost:8080/", "height": 216} files = np.random.choice(file_glob, 1) Z = get_wave(files[0]) print(Z) type(Z) # + id="hHLt4Qyryzng" colab_type="code" colab={} # class AudioEvaluator(Callback): # def on_epoch_end(self, epoch, logs=None): # print('*******') # X_test, y_test = next(gen(1, verbose=True)) # (1, 128, 128, 1) # y_pred = self.model.predict(X_test) # (1, 128, 128, AB_PAIRS) # print("predict:{}\n*******".format(LABELS[np.argmax(y_pred[0])])) # evaluator = AudioEvaluator() import math def step_decay(epoch): initial_lrate = 0.001 drop = 0.4 epochs_drop = 10.0 lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop)) if (lrate < 4e-5): lrate = 4e-5 print('Changing learning rate to {}'.format(lrate)) return lrate def do_train(m): global RUN RUN += 1 print("RUN {}".format(RUN)) LOG_DIR = '/output/training_logs/run-{}'.format(RUN) LOG_FILE_PATH = LOG_DIR + '/checkpoint-{epoch:02d}-{val_loss:.4f}.hdf5' # tensorboard = TensorBoard(log_dir=LOG_DIR, histogram_freq=1, write_grads=False, write_graph=False) tensorboard = TensorBoard(log_dir=LOG_DIR, write_graph=True) checkpoint = ModelCheckpoint(filepath=LOG_FILE_PATH, monitor='val_sparse_categorical_accuracy', verbose=1, save_best_only=True) early_stopping = EarlyStopping(monitor='val_sparse_categorical_accuracy', patience=100, verbose=1) lrate = LearningRateScheduler(step_decay) history = m.fit_generator(generator=gen(32), steps_per_epoch=256, validation_data=gen(32), validation_steps=16, epochs=1000, verbose=1, use_multiprocessing=True, callbacks=[tensorboard, checkpoint, early_stopping, lrate]) # + [markdown] id="EinDgoPpyzno" colab_type="text" # # CNN # + id="3K_1r66iyznr" colab_type="code" colab={} def get_conv_model(): m = Sequential() m.add(Conv1D(filters=64, kernel_size=2, strides=2, padding='valid', activation='relu', input_shape=(MAX_FRAME,1))) m.add(BatchNormalization()) m.add(Conv1D(filters=64, kernel_size=2, strides=2, padding='valid', activation='relu')) m.add(BatchNormalization()) # m.add(Conv1D(filters=64, kernel_size=2, strides=2, padding='valid', activation='relu')) # m.add(BatchNormalization()) m.add(Flatten()) # m.add(GlobalAveragePooling1D()) m.add(Dropout(0.3)) m.add(Dense(N_CLASS, activation='softmax')) m.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) return m # + colab_type="code" id="30gr4h9LhNhK" colab={} def ConvSpeechModel(samplingrate = 16000, inputLength = 16000): """ Base fully convolutional model for speech recognition """ inputs = Input(shape=(inputLength,1)) x = Reshape((1, -1)) (inputs) x = Melspectrogram(n_dft=1024, n_hop=128, input_shape=(1, inputLength), padding='same', sr=samplingrate, n_mels=80, fmin=40.0, fmax=samplingrate/2, power_melgram=1.0, return_decibel_melgram=True, trainable_fb=False, trainable_kernel=False, name='mel_stft') (x) x = Normalization2D(int_axis=0)(x) #note that Melspectrogram puts the sequence in shape (batch_size, melDim, timeSteps, 1) #we would rather have it the other way around for LSTMs x = Permute((2,1,3)) (x) #x = Reshape((94,80)) (x) #this is strange - but now we have (batch_size, sequence, vec_dim) c1 = Conv2D(20, (5,1) , activation='relu', padding='same') (x) c1 = BatchNormalization() (c1) p1 = MaxPooling2D((2, 1)) (c1) p1 = Dropout(0.03) (p1) c2 = Conv2D(40, (3,3) , activation='relu', padding='same') (p1) c2 = BatchNormalization() (c2) p2 = MaxPooling2D((2, 2)) (c2) p2 = Dropout(0.01) (p2) c3 = Conv2D(80, (3,3) , activation='relu', padding='same') (p2) c3 = BatchNormalization() (c3) p3 = MaxPooling2D((2, 2)) (c3) p3 = Flatten()(p3) p3 = Dense(64, activation = 'relu')(p3) p3 = Dense(32, activation = 'relu')(p3) output = Dense(N_CLASS, activation = 'softmax')(p3) model = Model(inputs=[inputs], outputs=[output], name='ConvSpeechModel') model.compile(optimizer='adam', loss=['sparse_categorical_crossentropy'], metrics=['sparse_categorical_accuracy']) return model # + id="LYA2Fj9Iyzn0" colab_type="code" outputId="31c3da4e-ed4f-4287-f9d3-a43d21042ddf" colab={"base_uri": "https://localhost:8080/", "height": 1000} m = ConvSpeechModel() m.summary() do_train(m) # + [markdown] id="kpZ-Ki8-yzn-" colab_type="text" # # CNN & RNN # + id="Yyx6AxbRyzoC" colab_type="code" colab={} def get_cnn_rnn_model(): ipt = Input(shape=(MAX_FRAME, 1)) x = ipt x = Conv1D(filters=128, kernel_size=50, strides=2, padding='valid', activation='relu')(x) x = Conv1D(filters=128, kernel_size=50, strides=2, padding='valid', activation='relu')(x) x = BatchNormalization()(x) # LSTM x = LSTM(64)(x) # double # x = LSTM(128, return_sequences=True)(x) # x = LSTM(64)(x) # 正反 # r = LSTM(32, return_sequences=True, go_backwards=False)(x) # r_b = LSTM(32, return_sequences=True, go_backwards=True)(x) # x = concatenate([r, r_b]) # x = Flatten()(x) x = Dense(64)(x) x = Dropout(0.3)(x) x = Dense(N_CLASS, activation='softmax')(x) m = Model(inputs=[ipt], outputs=[x]) m.compile(loss='categorical_crossentropy', optimizer='Adadelta', metrics=['accuracy']) return m # get_cnn_rnn_model().summary() # + id="H<KEY>" colab_type="code" colab={} def RNNSpeechModel(samplingrate = 16000, inputLength = 16000): #simple LSTM sr = samplingrate iLen = inputLength inputs = Input(shape=(iLen,1)) x = Reshape((1, -1)) (inputs) x = Melspectrogram(n_dft=1024, n_hop=128, input_shape=(1, iLen), padding='same', sr=sr, n_mels=80, fmin=40.0, fmax=sr/2, power_melgram=1.0, return_decibel_melgram=True, trainable_fb=False, trainable_kernel=False, name='mel_stft') (x) x = Normalization2D(int_axis=0)(x) #note that Melspectrogram puts the sequence in shape (batch_size, melDim, timeSteps, 1) #we would rather have it the other way around for LSTMs x = Permute((2,1,3)) (x) x = Conv2D(10, (5,1) , activation='relu', padding='same') (x) x = BatchNormalization() (x) x = Conv2D(1, (5,1) , activation='relu', padding='same') (x) x = BatchNormalization() (x) #x = Reshape((125, 80)) (x) x = Lambda(lambda q: K.squeeze(q, -1), name='squeeze_last_dim') (x) #keras.backend.squeeze(x, axis) x = Bidirectional(CuDNNLSTM(64, return_sequences = True)) (x) # [b_s, seq_len, vec_dim] x = Bidirectional(CuDNNLSTM(64)) (x) x = Dense(64, activation = 'relu')(x) x = Dense(32, activation = 'relu')(x) x = Dense(N_CLASS, activation='softmax')(x) model = Model(inputs=[inputs], outputs=[x]) model.compile(optimizer='adam', loss=['sparse_categorical_crossentropy'], metrics=['sparse_categorical_accuracy']) return model # + id="K5PZLRaTyzof" colab_type="code" outputId="23ab9380-86bf-46c7-fbf2-1914655d1e84" colab={"base_uri": "https://localhost:8080/", "height": 458} # LSTM without data augumentation[Best Model]Acc:68% m = get_cnn_rnn_model() m.summary() #do_train(m) # + colab_type="code" id="RGIelhVC_bLK" outputId="63a898cd-9110-4d15-b516-c567a1e6a3ce" colab={"base_uri": "https://localhost:8080/", "height": 1000} # LSTM paper 2018 m = RNNSpeechModel() m.summary() do_train(m) # + id="xIy79b5ayzpG" colab_type="code" colab={} # %load_ext tensorboard #LOG_DIR = '/output/training_logs/run-{}'.format(RUN) # %tensorboard --logdir LOG_DIR # + id="13ORkS53Vupa" colab_type="code" outputId="a961d0ac-ef09-45e8-be59-310e67b0c99d" colab={"base_uri": "https://localhost:8080/", "height": 35} tf.__version__
Google-Command-Classification-CNN-RNN.ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .java // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: Java // language: java // name: java // --- // # PaddleOCR DJL example // // In this tutorial, we will be using pretrained PaddlePaddle model from [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR) to do Optical character recognition (OCR) from the given image. There are three models involved in this tutorial: // // - Word detection model: used to detect the word block from the image // - Word direction model: used to find if the text needs to rotate // - Word recognition model: Used to recognize test from the word block // // ## Import dependencies and classes // // PaddlePaddle is one of the Deep Engines that requires DJL hybrid mode to run inference. Itself does not contains NDArray operations and needs a supplemental DL framework to help with that. So we import Pytorch DL engine as well in here to do the processing works. // + // // %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/ // %maven ai.djl:api:0.15.0 // %maven ai.djl.paddlepaddle:paddlepaddle-model-zoo:0.15.0 // %maven org.slf4j:slf4j-simple:1.7.32 // second engine to do preprocessing and postprocessing // %maven ai.djl.pytorch:pytorch-engine:0.15.0 // - import ai.djl.*; import ai.djl.inference.Predictor; import ai.djl.modality.Classifications; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.modality.cv.output.*; import ai.djl.modality.cv.util.NDImageUtils; import ai.djl.ndarray.*; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.repository.zoo.*; import ai.djl.paddlepaddle.zoo.cv.objectdetection.PpWordDetectionTranslator; import ai.djl.paddlepaddle.zoo.cv.imageclassification.PpWordRotateTranslator; import ai.djl.paddlepaddle.zoo.cv.wordrecognition.PpWordRecognitionTranslator; import ai.djl.translate.*; import java.util.concurrent.ConcurrentHashMap; // ## the Image // Firstly, let's take a look at our sample image, a flight ticket: String url = "https://resources.djl.ai/images/flight_ticket.jpg"; Image img = ImageFactory.getInstance().fromUrl(url); img.getWrappedImage(); // ## Word detection model // // In our word detection model, we load the model exported from [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.0/doc/doc_en/inference_en.md#convert-detection-model-to-inference-model). After that, we can spawn a DJL Predictor from it called detector. var criteria1 = Criteria.builder() .optEngine("PaddlePaddle") .setTypes(Image.class, DetectedObjects.class) .optModelUrls("https://resources.djl.ai/test-models/paddleOCR/mobile/det_db.zip") .optTranslator(new PpWordDetectionTranslator(new ConcurrentHashMap<String, String>())) .build(); var detectionModel = criteria1.loadModel(); var detector = detectionModel.newPredictor(); // Then, we can detect the word block from it. The original output from the model is a bitmap that marked all word regions. The `PpWordDetectionTranslator` convert the output bitmap into a rectangle bounded box for us to crop the image. var detectedObj = detector.predict(img); Image newImage = img.duplicate(); newImage.drawBoundingBoxes(detectedObj); newImage.getWrappedImage(); // As you can see above, the word block are very narrow and does not include the whole body of all words. Let's try to extend it a bit for a better result. `extendRect` extend the box height and width to a certain scale. `getSubImage` will crop the image and extract the word block. // + Image getSubImage(Image img, BoundingBox box) { Rectangle rect = box.getBounds(); double[] extended = extendRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); int width = img.getWidth(); int height = img.getHeight(); int[] recovered = { (int) (extended[0] * width), (int) (extended[1] * height), (int) (extended[2] * width), (int) (extended[3] * height) }; return img.getSubImage(recovered[0], recovered[1], recovered[2], recovered[3]); } double[] extendRect(double xmin, double ymin, double width, double height) { double centerx = xmin + width / 2; double centery = ymin + height / 2; if (width > height) { width += height * 2.0; height *= 3.0; } else { height += width * 2.0; width *= 3.0; } double newX = centerx - width / 2 < 0 ? 0 : centerx - width / 2; double newY = centery - height / 2 < 0 ? 0 : centery - height / 2; double newWidth = newX + width > 1 ? 1 - newX : width; double newHeight = newY + height > 1 ? 1 - newY : height; return new double[] {newX, newY, newWidth, newHeight}; } // - // Let's try to extract one block out: List<DetectedObjects.DetectedObject> boxes = detectedObj.items(); var sample = getSubImage(img, boxes.get(5).getBoundingBox()); sample.getWrappedImage(); // ## Word Direction model // // This model is exported from [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.0/doc/doc_en/inference_en.md#convert-angle-classification-model-to-inference-model) that can help to identify if the image is required to rotate. The following code will load this model and create a rotateClassifier. var criteria2 = Criteria.builder() .optEngine("PaddlePaddle") .setTypes(Image.class, Classifications.class) .optModelUrls("https://resources.djl.ai/test-models/paddleOCR/mobile/cls.zip") .optTranslator(new PpWordRotateTranslator()) .build(); var rotateModel = criteria2.loadModel(); var rotateClassifier = rotateModel.newPredictor(); // ## Word Recgonition model // // The word recognition model is exported from [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.0/doc/doc_en/inference_en.md#convert-recognition-model-to-inference-model) that can recognize the text on the image. Let's load this model as well. // var criteria3 = Criteria.builder() .optEngine("PaddlePaddle") .setTypes(Image.class, String.class) .optModelUrls("https://resources.djl.ai/test-models/paddleOCR/mobile/rec_crnn.zip") .optTranslator(new PpWordRecognitionTranslator()) .build(); var recognitionModel = criteria3.loadModel(); var recognizer = recognitionModel.newPredictor(); // Then we can try to play with these two models on the previous cropped image: System.out.println(rotateClassifier.predict(sample)); recognizer.predict(sample); // Finally, let's run these models on the whole image and see the outcome. DJL offers a rich image toolkit that allows you to draw the text on image and display them. // + Image rotateImg(Image image) { try (NDManager manager = NDManager.newBaseManager()) { NDArray rotated = NDImageUtils.rotate90(image.toNDArray(manager), 1); return ImageFactory.getInstance().fromNDArray(rotated); } } List<String> names = new ArrayList<>(); List<Double> prob = new ArrayList<>(); List<BoundingBox> rect = new ArrayList<>(); for (int i = 0; i < boxes.size(); i++) { Image subImg = getSubImage(img, boxes.get(i).getBoundingBox()); if (subImg.getHeight() * 1.0 / subImg.getWidth() > 1.5) { subImg = rotateImg(subImg); } Classifications.Classification result = rotateClassifier.predict(subImg).best(); if ("Rotate".equals(result.getClassName()) && result.getProbability() > 0.8) { subImg = rotateImg(subImg); } String name = recognizer.predict(subImg); names.add(name); prob.add(-1.0); rect.add(boxes.get(i).getBoundingBox()); } newImage.drawBoundingBoxes(new DetectedObjects(names, prob, rect)); newImage.getWrappedImage();
jupyter/paddlepaddle/paddle_ocr_java.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Exploratory Data Analysis # Exploratory data analysis helps one understand the data, to form and change new theories, and decide which techniques are appropriate for analysis. After a model is finished, exploratory data analysis can look for patterns in these data that may have been missed by the original hypothesis tests. Successful exploratory analyses help the researcher modify theories and refine the analysis. # # We are using Yelp dataset. The documentation about the dataset can be found in this link: https://www.yelp.com/dataset/documentation/json # #### Step 1: # Reading the business.json and checking the type of data that we have there. import pandas as pd import matplotlib.pyplot as plt business_df = pd.read_json('business.json',orient='records', lines=True) business_df.info() business_df.head() # !python -m pip install missingno import missingno as msno msno.bar(business_df) plt.show() # There was no missing data to handle but the file was large, so we had to do a lot of data processing to find out the relevant data to do recommendation on restaurants. # #### Step 2: # Checking the attribute of the restaurant if its open or not and eliminating the restaurant which is closed. business_grouped_by_status = business_df[['is_open','stars']].groupby(by='is_open').sum().reset_index() business_grouped_by_status.columns = ['open_status', 'count'] business_grouped_by_status.plot(kind='bar', x='open_status', y='count') plt.show() # eliminate restaurants that are closed business_df = business_df[business_df['is_open'] == 1] business_df.shape # #### Step 3: # Selecting the top states with most restaurants most_business_info = business_df[['state', 'stars']].groupby(by='state').count().reset_index().sort_values(by='stars', ascending=False).head(5) most_business_info.plot(kind='bar', x='state', y='stars') plt.show() # #### Step 4: # We find out that the states Arizona, Nevada, Ontario, North Carolina and Ohio has the most number of restaurants in the data set so we eliminated the other states as they were significantly low in number top_states = most_business_info['state'] top_states_df = business_df[business_df['state'].isin(top_states)] top_states_df.shape # #### Step 5: # Looking at the categories that the business were segregated into, we cherry picked the categories that were related to restaurants and food # + state_cat_dict = dict() def check_record(record) : state = record['state'] categories = record.categories if state in state_cat_dict : state_obj = state_cat_dict[state] for cat in categories : if cat in state_obj : #cat exist state_obj[cat] = state_obj[cat] + 1 else : # cat does not exist in dict state_obj[cat] = 1 state_cat_dict[state] = state_obj else : # new state state_obj = dict() for cat in categories : state_obj[cat] = 1 state_cat_dict[state] = state_obj temp = top_states_df.apply(lambda x : check_record(x), axis=1) # + category_dict = dict() def check_record(record) : categories = record.categories for cat in categories : if cat in category_dict : #cat exist category_dict[cat] = category_dict[cat] + 1 else : # cat does not exist in dict category_dict[cat] = 1 temp = top_states_df.apply(lambda x : check_record(x), axis=1) # - # Following are the categories we are selecting to cherry pick. required_category = ['Restaurants','Food','Nightlife','Bars','Fast Food','Sandwiches', 'American (Traditional)','Pizza','Coffee & Tea','Burgers','Mexican','Breakfast & Brunch','Specialty Food', 'Chinese','Italian','American (New)','Bakeries','Desserts','Chicken Wings','Salad','Beer','Wine & Spirits', 'Pubs','Sushi Bars','Delis','Juice Bars & Smoothies','Steakhouses' ] len(required_category) # Following are the states we have filtered the restaurants for. state_cat_dict.keys() def check_if_restaurant(categories): for cat in categories : if cat in required_category : return True return False top_states_df['restaurant'] = top_states_df.apply(lambda x : check_if_restaurant(x['categories']), axis = 1) top_states_df = top_states_df[top_states_df['restaurant'] == True] top_states_df.drop('restaurant', axis=1, inplace=True) top_states_df.to_json('business_restaurant.json', orient='records', lines=True) business_restaurant_df = pd.read_json('business_restaurant.json',orient='records', lines=True) business_restaurant_df.shape business_restaurant_df.head() # #### Step 6: # With the help of the filtered business dataset, we selected the reviews based on those businesses and merged the files for computing the results. # + OH_rest_df = business_restaurant_df[business_restaurant_df['state']=="OH"] OH_rest_df.to_json('OH_restaurant_business.json', orient='records', lines=True) NC_rest_df = business_restaurant_df[business_restaurant_df['state']=="NC"] NC_rest_df.to_json('NC_restaurant_business.json', orient='records', lines=True) ON_rest_df = business_restaurant_df[business_restaurant_df['state']=="ON"] ON_rest_df.to_json('ON_restaurant_business.json', orient='records', lines=True) NV_rest_df = business_restaurant_df[business_restaurant_df['state']=="NV"] NV_rest_df.to_json('NV_restaurant_business.json', orient='records', lines=True) AZ_rest_df = business_restaurant_df[business_restaurant_df['state']=="AZ"] AZ_rest_df.to_json('AZ_restaurant_business.json', orient='records', lines=True) # - # After cleaning and segregating the data and merging appropriate files, we get the data frame which has only the relevant features needed for a recommendation model # # Sentiment Analysis using LDA # # Businesses often want to know how customers think about the quality of their services to improve and make more profits. Restaurant goers may want to learn from others' experience using a variety of criteria such as food quality, service, ambience, discounts and worthiness. Yelp users may post their reviews and ratings on businesses and services or simply express their thoughts on other reviews. Bad (negative) reviews from one's perspective may influence potential customers in making decisions, e.g., a potential customer may cancel a service and persuade other do the same. # #### Topic Modelling # # As the name suggests, it is a process to automatically identify topics present in a text object and to derive hidden patterns exhibited by a text corpus. Thus, assisting better decision making. # # Topic Modelling is different from rule-based text mining approaches that use regular expressions or dictionary based keyword searching techniques. It is an unsupervised approach used for finding and observing the bunch of words (called “topics”) in large clusters of texts. # # Topics can be defined as “a repeating pattern of co-occurring terms in a corpus” # # Topic Models are very useful for the purpose for document clustering, organizing large blocks of textual data, information retrieval from unstructured text and feature selection. import pandas as pd import numpy as np import gensim from textblob import TextBlob import re import nltk from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer as ps from nltk.stem.wordnet import WordNetLemmatizer import string from gensim.parsing.preprocessing import STOPWORDS # #### Reading the json file path = 'Filtered_review_10K.json' df = pd.read_json(path, orient='records', lines=True) # #### Preparing Documents # Cleaning is an important step before any text mining task, in this step, we will remove the punctuations, stopwords and normalize the corpus. # + import re rest_review_dict = dict() for temp in df.iterrows() : row = temp[1] business_id = row.business_id exclude = set(string.punctuation) review_text = row['text'] stop_free = ' '.join([word for word in review_text.lower().split() if word not in STOPWORDS]) stop_punc = ''.join(ch for ch in stop_free if ch not in exclude) text = ''.join([i for i in stop_punc if not i.isdigit()]) review_stars = row['stars'] if business_id in rest_review_dict : reviews_array = rest_review_dict[business_id] reviews_array.append({'review_text' : review_text, 'review_stars' : review_stars, 'polarity' : TextBlob(text).sentiment.polarity, 'stemmed_text' : text}) else : reviews_array = list() reviews_array.append({'review_text' : review_text, 'review_stars' : review_stars, 'polarity' : TextBlob(text).sentiment.polarity, 'stemmed_text' : text}) rest_review_dict[business_id] = reviews_array # - # #### Latent Dirichlet Allocation (LDA) for Topic Modeling # # Latent Dirichlet Allocation is the most popular topic modeling technique. LDA assumes documents are produced from a mixture of topics. Those topics then generate words based on their probability distribution. Given a dataset of documents, LDA backtracks and tries to figure out what topics would create those documents in the first place. # # LDA is a matrix factorization technique. In vector space, any corpus (collection of documents) can be represented as a document-term matrix. # #### Preparing Document-Term Matrix # All the text documents combined is known as the corpus. To run any mathematical model on text corpus, it is a good practice to convert it into a matrix representation. LDA model looks for repeating term patterns in the entire DT matrix. Python provides many great libraries for text mining practices, “gensim” is one such clean and beautiful library to handle text data. It is scalable, robust and efficient. Following code shows how to convert a corpus into a document-term matrix. # # #### Running LDA Model # Next step is to create an object for LDA model and train it on Document-Term matrix. The training also requires few parameters as input. The gensim module allows both LDA model estimation from a training corpus and inference of topic distribution on new, unseen documents. # + import gensim from gensim import corpora, models, similarities business_corpus = dict() for business_id, review_array in rest_review_dict.items(): consolidated_text = [review['stemmed_text'] for review in review_array] texts = [] for t in consolidated_text : for word in t.split(" ") : texts.append(word) texts = [texts] dictionary = corpora.Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts] ## Creating the object for LDA model using gensim library lda = models.LdaModel(corpus=corpus, id2word=dictionary, num_topics=2) topics = dict() for topic in lda.top_topics(corpus) : b = topic[0][0:15] for tup in b : if tup[1] not in topics : topics[tup[1]] = tup[0] else : if topics[tup[1]] < tup[0] : topics[tup[1]] = tup[0] business_corpus[business_id] = topics # - # #### Result # We can check the top topics and the top numbers from our lda model print(lda.print_topics(num_topics=10, num_words=3)) print(business_corpus['hW0Ne_HTHEAgGF1rAdmR-g']) # + all_reviews = rest_review_dict['hW0Ne_HTHEAgGF1rAdmR-g'] business_reviews = [] for review in all_reviews : if review['polarity'] < 0 : print ('Negative review: ' + review['stemmed_text']) else : print ('Positive review: ' + review['stemmed_text']) # + # Sentiment Analysis using RNN with LSTM from collections import Counter from datetime import datetime import json from keras.layers import Embedding, LSTM, Dense, Conv1D, MaxPooling1D, Dropout, Activation from keras.models import Sequential from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import numpy as np To load the reviews from disk, run the following in the next cell: import json input="Filtered_review_1L.json" with open(input, "r") as f: reviews = f.read().strip().split("\n") reviews = [json.loads(review) for review in reviews] Each review in the Yelp dataset contains the text of the review and the associated star rating, left by the reviewer. Our task is to teach a classifier to differentiate between positive and negative reviews, looking only at the review text itself. It is very important to have a balanced dataset for supervised learning. This means that we want the same amount of positive and negative reviews when we train our neural network to tell the difference between them. If we have more positive reviews than negative reviews, the network will learn that most reviews are positive, and adjust its predictions accordingly. We’ll, therefore, take a sample of the Yelp reviews which contains the same amount of positive (four or five-star reviews) and negative (one, two, or three-star reviews). text_list = [review['text'] for review in reviews] # Convert our 5 classes into 2 (negative or positive) binstars = [0 if review['stars'] <= 3 else 1 for review in reviews] trained_texts = [] trained_labels = [] limit = 100000 # Change this to grow/shrink the dataset neg_pos_counts = [0, 0] for i in range(len(text_list)): polarity = binstars[i] if neg_pos_counts[polarity] < limit: trained_texts.append(text_list[i]) trained_labels.append(binstars[i]) neg_pos_counts[polarity] += 1 This gets 100000 positive and 100000 negative reviews. If we use less data, we’ll get significantly worse accuracy, as neural networks usually need a lot of data to train well. More data will result in longer training times for our neural network. ### Tokenizing the texts Keras represents each word as a number, with the most common word in a given dataset being represented as 1, the second most common as a 2, and so on. This is useful because we often want to ignore rare words, as usually, the neural network cannot learn much from these, and they only add to the processing time. If we have our data tokenized with the more common words having lower numbers, we can easily train on only the N most common words in our dataset, and adjust N as necessary (for larger datasets, we would want a larger N, as even comparatively rare words will appear often enough to be useful). Tokenization in Keras is a two step process. First, we need to calculate the word frequencies for our dataset (to find the most common words and assign these low numbers). Then we can transform our text into numerical tokens. The calculation of the word frequencies is referred to as ‘fitting’ the tokenizer, and Keras calls the numerical representations of our texts ‘sequences’. from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences tokenizer = Tokenizer(num_words=20000) tokenizer.fit_on_texts(trained_texts) sequences = tokenizer.texts_to_sequences(trained_texts) data = pad_sequences(sequences, maxlen=300) import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt # %matplotlib inline from subprocess import check_output from wordcloud import WordCloud, STOPWORDS mpl.rcParams['figure.figsize']=(12.0,10.0) #(6.0,4.0) mpl.rcParams['font.size']=12 #10 mpl.rcParams['savefig.dpi']=100 #72 mpl.rcParams['figure.subplot.bottom']=.1 text = tokenizer.word_index stopwords = set(STOPWORDS) data = text wordcloud = WordCloud( background_color='white', stopwords=stopwords, max_words=200, max_font_size=40, random_state=42 ).generate(str(data)) print(wordcloud) fig = plt.figure(1) plt.imshow(wordcloud) plt.axis('off') plt.show() fig.savefig("word1.png", dpi=900) ### Creating Neural network model One of the more complicated architectures, which is known to perform very well on text data, is the Recurrent Neural Network (RNN) with Long Short-Term Memory (LSTM). RNNs are designed to learn from sequences of data, where there is some kind of time dependency. For example, they are used for time-series analysis, where each data point has some relation to those immediately before and after. By extension, they work very well for language data, where each word is related to those before and after it in a sentence. When we use more layers the accuracy gets slightly worse, but the execution gets there much faster. model = Sequential() model.add(Embedding(20000, 128, input_length=300)) model.add(Dropout(0.2)) model.add(Conv1D(64, 5, activation='relu')) model.add(MaxPooling1D(pool_size=4)) model.add(LSTM(128)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(data, np.array(trained_labels), validation_split=0.5, epochs=3) print(model.summary()) ### Change in plateau We are displaying the accuracy vs expected accuracy and loss with expected loss import matplotlib.pyplot as plt # summarize history for accuracy plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() #### Result Predicting with the model with some new phrases. We will analyze it with different scenarios. newtexts = ["Awesome", "Rotten", "OMG", "Not good", "Murdered here. Would not recommend"] sequences = tokenizer.texts_to_sequences(newtexts) data = pad_sequences(sequences, maxlen=300) predictions = model.predict(data) print(predictions*100) Here we are passing some new data to check if our trained model is working fine. This can be easily done by creating a dictionary with new works and passing that to our model to predict. Our result will be negative to positive when we go from 0 to 100. We analyzed for different scenarios: 1. Positive 2. Negative 3. Sarcasm We see that the prediction is fair enough and justifies our model. # - # ### License: # # The text in the document by <NAME>, <NAME> and <NAME> is licensed under CC BY 3.0 https://creativecommons.org/licenses/by/3.0/us/ # # The code in the document by <NAME>, <NAME> and <NAME>har is licensed under the MIT License https://opensource.org/licenses/MIT
src/scripts/BusinessEDA.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.9.6 64-bit (''venv'': venv)' # name: python3 # --- # # Corona Daily Case Prograssion (INDIA) # @author - <NAME>, # date - 20-08-2021 # ## This project was made to analyze daily case progression of coronavirus cases in INDIA. import pandas as pd import plotly.graph_objects as go # + # Uncomment the below and run to get the visualization with latest data. # df = pd.read_csv('https://api.covid19india.org/csv/latest/case_time_series.csv') df = pd.read_csv('case_time_series.csv') df # + fig = go.Figure() fig.add_traces(go.Scatter(x=df['Date'], y=df['Daily Confirmed'], mode='lines', name='Daily Confirmed', marker=dict(color='blue'), text=df['Daily Confirmed'])) fig.add_traces(go.Scatter(x=df['Date'], y=df['Daily Recovered'], mode='lines', name='Daily Recovered', marker=dict(color='green'), text=df['Daily Recovered'])) fig.add_traces(go.Scatter(x=df['Date'], y=df['Daily Deceased'], mode='lines', name='Daily Deceased', marker=dict(color='red'), text=df['Daily Deceased'])) fig.show('png') # use this to get a interactive graph # fig.show() # -
corona_daily_case_progression/daily_case_progression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import k3d import math import numpy as np import nibabel as nib from k3d.helpers import download import ipywidgets as widgets import vtk from vtk.util import numpy_support basic_color_maps = [(attr, getattr(k3d.basic_color_maps, attr)) for attr in dir(k3d.basic_color_maps) if not attr.startswith('__')] paraview_color_maps = [(attr, getattr(k3d.paraview_color_maps, attr)) for attr in dir(k3d.paraview_color_maps) if not attr.startswith('__')] matplotlib_color_maps = [(attr, getattr(k3d.matplotlib_color_maps, attr)) for attr in dir(k3d.matplotlib_color_maps) if not attr.startswith('__')] colormaps = basic_color_maps + paraview_color_maps + matplotlib_color_maps # + filename = download('https://vedo.embl.es/examples/data/embryo.slc') reader = vtk.vtkSLCReader() reader.SetFileName(filename) reader.Update() vti = reader.GetOutput() bounds = vti.GetBounds() x, y, z = vti.GetDimensions() img = numpy_support.vtk_to_numpy(vti.GetPointData().GetArray(0)).reshape(-1, y, x) # + tf_editor = k3d.transfer_function_editor() volume = k3d.volume(img.astype(np.float16)) @widgets.interact(x=widgets.Dropdown(options=colormaps, description='ColorMap:')) def g(x): tf_editor.color_map = np.array(x, dtype=np.float32) # - plot = k3d.plot() plot += volume tf_editor.display() plot.display() a = widgets.jslink((tf_editor, 'color_map'), (volume, 'color_map')) a = widgets.jslink((tf_editor, 'opacity_function'), (volume, 'opacity_function'))
examples/transfer_function.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Simple Linear Regression # # Checkout the [Source](https://github.com/Avik-Jain/100-Days-Of-ML-Code/blob/master/Code/Day2_Simple_Linear_Regression.md) # ## Step-1: Data preprocessing (Day 1) # + import pandas as pd import numpy as np import matplotlib.pyplot as plt data = pd.read_csv('../Datasets/studentscores.csv') X = data.iloc[:, :1].values Y = data.iloc[:, 1].values from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 1/4, random_state = 0) # - # ## Step-2: Simple Linear Regrassion model to train set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor = regressor.fit(X_train, Y_train) # ## Step-3: Predecting results Y_pred = regressor.predict(X_test) # ## Step-4: Visualization # Training set plt.scatter(X_train, Y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') # Test results plt.scatter(X_test, Y_test, color = 'blue') plt.plot(X_test, regressor.predict(X_test), color = 'yellow')
Codes/Simple Linear Regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <a href="https://colab.research.google.com/github/PytorchLightning/pytorch-lightning/blob/master/notebooks/05-trainer-flags-overview.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="goRmGIRI5cfC" # # Introduction to Lightning Flags ⚡🚩 # # In this notebook, we'll go over the flags available in the `Trainer` object. Note that not everything will work in the Colab environment (multi-gpu, etc). This notebook accompanies the Trainer videos we'll be putting out. # # --- # - Give us a ⭐ [on Github](https://www.github.com/PytorchLightning/pytorch-lightning/) # - Check out [the documentation](https://pytorch-lightning.readthedocs.io/en/latest/) # - Join us [on Slack](https://join.slack.com/t/pytorch-lightning/shared_invite/zt-f6bl2l0l-JYMK3tbAgAmGRrlNr00f1A) # + [markdown] id="jKj5lgdr5j48" # --- # ### Setup # First thing first, we need to install Lightning. Simply ```pip install pytorch-lightning``` # + id="UGjilEHk4vb7" # ! pip install pytorch-lightning # + id="zaVUShmQ5n8Y" import os from argparse import ArgumentParser import torch from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.data import random_split from torchvision.datasets import MNIST from torchvision import transforms import pytorch_lightning as pl from pytorch_lightning.metrics.functional import accuracy from torchvision.datasets.mnist import MNIST from torchvision import transforms # + id="6tgkS8IYZwY_" # ------------ # data # ------------ pl.seed_everything(1234) batch_size = 32 # Init DataLoader from MNIST Dataset dataset = MNIST(os.getcwd(), train=True, download=True, transform=transforms.ToTensor()) mnist_test = MNIST(os.getcwd(), train=False, download=True, transform=transforms.ToTensor()) mnist_train, mnist_val = random_split(dataset, [55000, 5000]) train_loader = DataLoader(mnist_train, batch_size=batch_size) val_loader = DataLoader(mnist_val, batch_size=batch_size) test_loader = DataLoader(mnist_test, batch_size=batch_size) # + [markdown] id="gEulmrbxwaYL" # ### Simple AutoEncoder Model # # Were gonna define a simple Lightning model so we can play with all the settings of the Lightning Trainer. # # LightningModule is simply pure Pytorch reorganized into hooks, that represents all the steps in the training process. # # You can use LightningModule hooks to control every part of your model, but for the purpose of this video we will use a very simple MNIST classifier, a model that takes 28*28 grayscale images of hand written images, and can predict the digit between 0-9. # # The LightningModule can encompass a single model, like an image classifier, or a deep learning system composed of multiple models, like this auto encoder that contains an encoder and a decoder. # # # # + id="x-34xKCI40yW" class LitAutoEncoder(pl.LightningModule): def __init__(self, batch_size=32, lr=1e-3): super().__init__() self.encoder = nn.Sequential( nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 3) ) self.decoder = nn.Sequential( nn.Linear(3, 64), nn.ReLU(), nn.Linear(64, 28 * 28) ) self.batch_size=batch_size self.learning_rate=lr def forward(self, x): # in lightning, forward defines the prediction/inference actions embedding = self.encoder(x) return embedding def training_step(self, batch, batch_idx): x, y = batch x = x.view(x.size(0), -1) z = self.encoder(x) x_hat = self.decoder(z) loss = F.mse_loss(x_hat, x) self.log('train_loss', loss) return loss def validation_step(self, batch, batch_idx): x, y = batch x = x.view(x.size(0), -1) z = self.encoder(x) x_hat = self.decoder(z) loss = F.mse_loss(x_hat, x) self.log('val_loss', loss) def test_step(self, batch, batch_idx): x, y = batch x = x.view(x.size(0), -1) z = self.encoder(x) x_hat = self.decoder(z) loss = F.mse_loss(x_hat, x) self.log('test_loss', loss) def configure_optimizers(self): optimizer = torch.optim.Adam(self.parameters(), lr=1e-3) return optimizer # + [markdown] id="VbxcRCrxiYly" # You'll notice the LightningModule doesn't have epoch and batch loops, we're not calling model.train() and model.eval(), and no mentions of CUDA or hardware. That's because it is all automated by the Lightning Trainer. All the engineering boilerplate is automated by the trainer: # # * Training loops # * Evaluation and test loops # * Calling model.train(), model.eval(), no_grad at the right time # * CUDA or to_device calls # # It also allows you to train your models on different hardware like GPUs and TPUs without changing your code! # # # ### To use the lightning trainer simply: # # 1. init your LightningModule and datasets # # 2. init lightning trainer # # 3. call trainer.fit # # + id="HOk9c4_35FKg" ##################### # 1. Init Model ##################### model = LitAutoEncoder() ##################### # 2. Init Trainer ##################### # these 2 flags are explained in the later sections...but for short explanation: # - progress_bar_refresh_rate: limits refresh rate of tqdm progress bar so Colab doesn't freak out # - max_epochs: only run 2 epochs instead of default of 1000 trainer = pl.Trainer(progress_bar_refresh_rate=20, max_epochs=2) ##################### # 3. Train ##################### trainer.fit(model, train_loader, val_loader) # + [markdown] id="3meDako-Qa_6" # Our model is training just like that, using the Lightning defaults. The beauty of Lightning is that everything is easily configurable. # In our next videos were going to show you all the ways you can control your Trainer to do things like controlling your training, validation and test loops, running on GPUs and TPUs, checkpointing, early stopping, and a lot more. # # + [markdown] id="z_Wry2MckQkI" # # Training loop and eval loop Flags # + [markdown] id="0MkI1xB2vsLj" # # To really scale up your networks, you can use accelerators like GPUs. GPUs or Graphical Processing Units, parallelize matrix multiplications which enable speed ups of at least 100x over training on CPUs. # # Let's say you have a machine with 8 GPUs on it. You can set this flag to 1, 4, or 8 GPUs and lightning will automatically distribute your training for you. # # ``` # trainer = pl.Trainer(gpus=1) # ``` # # --------- # # Lightning makes your code hardware agnostic... This means, you can switch between CPUs, GPUs without code changes. # # However, it requires forming good PyTorch habits: # # 1. First, remove the .cuda() or .to() calls in your code. # 2. Second, when you initialize a new tensor, set the device=self.device in the call since every lightningModule knows what gpu index or TPU core it is on. # # You can also use type_as and or you can register the tensor as a buffer in your module’s __init__ method with register_buffer(). # # ``` # # before lightning # def forward(self, x): # z = torch.Tensor(2, 3) # z = z.cuda(0) # # # with lightning # def forward(self, x): # z = torch.Tensor(2, 3) # z = z.type_as(x, device=self.device) # ``` # # # ``` # class LitModel(LightningModule): # # def __init__(self): # ... # self.register_buffer("sigma", torch.eye(3)) # # you can now access self.sigma anywhere in your module # ``` # + [markdown] id="hw6jJhhjvlSL" # Lightning Trainer automates all the engineering boilerplate like iterating over epochs and batches, training eval and test loops, CUDA and to(device) calls, calling model.train and model.eval. # # You still have full control over the loops, by using the following trainer flags: # + [markdown] id="pT5-ETH9eUg6" # ## Calling validation steps # Sometimes, training an epoch may be pretty fast, like minutes per epoch. In this case, you might not need to validate on every epoch. Instead, you can actually validate after a few epochs. # # Use `check_val_every_n_epoch` flag to control the frequency of validation step: # + id="Z-EMVvKheu3D" # run val loop every 10 training epochs trainer = pl.Trainer(check_val_every_n_epoch=10) trainer.fit(model, train_loader, val_loader) # + [markdown] id="UOzZr9S2UcSO" # ## val_check_interval # # In some cases where your epoch is very long, you might want to check validation within an epoch. # # You can also run validation step within your training epochs, by setting `val_check_interval` flag. # # Set `val_check_interval` to a float between [0.0 to 1.0] to check your validation set within a training epoch. For example, setting it to 0.25 will check your validation set 4 times during a training epoch. # # Default is set to 1.0 # + id="9kbUbvrUVLrT" # check validation set 4 times during a training epoch trainer = pl.Trainer(val_check_interval=0.25) trainer.fit(model, train_loader, val_loader) # + [markdown] id="Onm1gBsKVaw4" # When you have iterable data sets, or when streaming data for production use cases, it is useful to check the validation set every number of steps. # Set val_check_interval to an int: # + id="psn6DVb5Vi85" # check validation set every 1000 training batches # use this when using iterableDataset and your dataset has no length # (ie: production cases with streaming data) trainer = pl.Trainer(val_check_interval=1000) trainer.fit(model, train_loader, val_loader) # + [markdown] id="QkoYonrWkb7-" # ## num_sanity_val_steps # # You may have run into an issue, where you have a bug in your validation loop, but won't catch it until your training loop ends. # # and if your training loop takes hours or days, you will waste valuable compute. # # Instead, lightning automatically runs through 2 steps of validation in the beginning to catch these kinds of bugs up front. # # # The `num_sanity_val_steps` flag can help you run n batches of validation before starting the training routine. # # You can set it to 0 to turn it off # + id="zOcT-ugSkiKW" # turn it off trainer = pl.Trainer(num_sanity_val_steps=0) trainer.fit(model, train_loader, val_loader) # + [markdown] id="zS0ob1ZmTw56" # Set it to -1 to check all validation data before training # + id="rzqvjA4UT263" # check all validation data trainer = pl.Trainer(num_sanity_val_steps=-1) trainer.fit(model, train_loader, val_loader) # + [markdown] id="uMB41wq4T3Z2" # Or use any arbitrary number of validation steps # + id="lGP78aQzT7VS" trainer = pl.Trainer(num_sanity_val_steps=10) trainer.fit(model, train_loader, val_loader) # + [markdown] id="H-xaYRtd1rb-" # ## Limit train, validation, and test batches # # You can set limits on how much of training, validation and test dataset you want your model to check. This is useful if you have really large validation or tests sets, for debugging or testing something that happens at the end of an epoch. # # Set the flag to int to specify the number of batches to run # # # + id="XiK5cFKL1rcA" # run for only 10 batches trainer = pl.Trainer(limit_test_batches=10) trainer.fit(model, train_loader, val_loader) # + [markdown] id="Y4LK0g65RrBm" # For example, some metrics need to be computed on the entire validation results, such as AUC ROC. # + id="8MmeRs2DR3dD" trainer = pl.Trainer(limit_val_batches=10) trainer.fit(model, train_loader, val_loader) # + [markdown] id="xmigcNa1A2Vy" # You can use a float to limit the batches be percentage of the set on every epoch # + id="W7uGJt8nA4tv" # run through only 25% of the test set each epoch trainer = pl.Trainer(limit_test_batches=0.25) trainer.fit(model, train_loader, val_loader) # + [markdown] id="YRI8THtUN7_e" # # Training on GPUs # # # + [markdown] id="R8FFkX_FwlfE" # To run on 1 GPU set the flag to 1 # + id="Nnzkf3KaOE27" trainer = pl.Trainer(gpus=1) trainer.fit(model, train_loader, val_loader) # + [markdown] id="cxBg47s5PB1P" # to run on 2 or 4 GPUs, set the flag to 2 or 4. # + id="cSEM4ihLrohT" trainer = pl.Trainer(gpus=2) trainer.fit(model, train_loader, val_loader) # + [markdown] id="ZE6ZgwtNudro" # You can also select which GPU devices to run on, using a list of indices like [1, 4] # # or a string containing a comma separated list of GPU ids like '1,2' # # + id="gQkJtq0urrjq" # list: train on GPUs 1, 4 (by bus ordering) # trainer = Trainer(gpus='1, 4') # equivalent trainer = pl.Trainer(gpus=[1, 4]) trainer.fit(model, train_loader, val_loader) # + id="XghDPad4us74" trainer = pl.Trainer(gpus=list(range(4))) trainer.fit(model, train_loader, val_loader) # + [markdown] id="6FVkKHpSPMTW" # You can use all the GPUs you have available by setting `gpus=-1` # + id="r6cKQijYrtPe" # trainer = Trainer(gpus='-1') - equivalent trainer = pl.Trainer(gpus=-1) trainer.fit(model, train_loader, val_loader) # + [markdown] id="2C-fNLm3UGCV" # Lightning uses the PCI bus_id as the index for ordering GPUs. # + [markdown] id="_V75s7EhOFhE" # ### `auto_select_gpus` # # You can save on GPUs by running in “exclusive mode”, meaning only one process at a time can access them. If your not sure which GPUs you should use when running exclusive mode, Lightning can automatically find unoccupied GPUs for you. # # Simply specify the number of gpus as an integer `gpus=k`, and set the trainer flag `auto_select_gpus=True`. Lightning will automatically help you find k gpus that are not occupied by other processes. # + id="_Sd3XFsAOIwd" # enable auto selection (will find two available gpus on system) trainer = pl.Trainer(gpus=2, auto_select_gpus=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="a5JGSBMQhJNp" # ## analyzing GPU usage # # ### log_gpu_memory # # This is useful to analyze the memory usage of your GPUs. # # To get the GPU memory usage for every GPU on the master node, set the flag to log_gpu_memory=all. # # Under the hood, lightning uses the nvidia-smi command which may slow your training down. # # Your logs can become overwhelmed if you log the usage from many GPUs at once. In this case, you can also set the flag to min_max which will log only the min and max usage across all the GPUs of the master node. # # Note that lightning is not logging the usage across all nodes for performance reasons. # + id="idus3ZGahOki" # log all the GPUs (on master node only) trainer = Trainer(log_gpu_memory='all') trainer.fit(model, train_loader, val_loader) # + [markdown] id="-mevgiy_hkip" # To avoid the performance decrease you can also set `log_gpu_memory=min_max` to only log the min and max memory on the master node. # # + id="SlvLJnWyhs7J" # log only the min and max memory on the master node trainer = Trainer(log_gpu_memory='min_max') trainer.fit(model, train_loader, val_loader) # + [markdown] id="K82FLLIJVQG3" # # But what if you want to train on multiple machines and not just one? # + [markdown] id="YViQ6PXesAue" # # Training on multiple GPUs # + [markdown] id="WacbBQUivxQq" # Lightning makes your models hardware agnostic, and you can run on GPUs with a flip of a flag. Lightning also supports training on multiple GPUs across many machines. # # You can do this by setting the num_nodes flag. # # The world size, or the total number of GPUs you are using, will be gpus*num_nodes. # # If i set gpus=8 and num_nodes=32 then I will be training on 256 GPUs. # + id="5iKckmDvr8zZ" trainer = pl.Trainer(gpus=8, num_nodes=32) trainer.fit(model, train_loader, val_loader) # + [markdown] id="GgcSbDjjlSTh" # ## Accelerators # # Under the hood, Lightning uses distributed data parallel (or DDP) by default to distribute training across GPUs. # # This Lightning implementation of DDP calls your script under the hood multiple times with the correct environment variables. # # Under the hood it's as if you had called your script like this: # # 1. Each GPU across each node gets its own process. # 2. Each GPU gets visibility into a subset of the overall dataset. It will only ever see that subset. # 3. Each process inits the model. (Make sure to set the random seed so that each model initializes with the same weights.) # 4. Each process performs a full forward and backward pass in parallel. # 5. The gradients are synced and averaged across all processes. # 6. Each process updates its optimizer. # If you request multiple GPUs or nodes without setting a mode, DDP will be automatically used. # # + id="n_Brr7F5wdtj" # ddp = DistributedDataParallel # trainer = pl.Trainer(gpus=2, num_nodes=2) equivalent trainer = pl.Trainer(gpus=2, num_nodes=2, accelerator='ddp') trainer.fit(model, train_loader, val_loader) # + [markdown] id="edxHyttC5J3e" # DDP is the fastest and recommended way to distribute your training, but you can pass in other backends to `accelerator` trainer flag, when DDP is not supported. # # DDP isn't available in # * Jupyter Notebook, Google COLAB, Kaggle, etc. # * If You have a nested script without a root package # * or if Your script needs to invoke .fit or .test multiple times # + [markdown] id="ZDh96mavxHxf" # ### DDP_SPAWN # # In these cases, you can use `ddp_spawn` instead. `ddp_spawn` is exactly like DDP except that it uses `.spawn()` to start the training processes. # + id="JM5TKtgLxo37" trainer = pl.Trainer(gpus=2, num_nodes=2, accelerator='ddp_spawn') trainer.fit(model, train_loader, val_loader) # + [markdown] id="sebhVE3qrhKK" # We STRONGLY discourage this use because it has limitations (due to Python and PyTorch): # # * Since .spawn() trains the model in subprocesses, the model on the main process does not get updated. # # * Dataloader(num_workers=N), where N is large, bottlenecks training with DDP… ie: it will be VERY slow or won’t work at all. This is a PyTorch limitation. # # * Forces everything to be picklable. # # DDP is MUCH faster than DDP_spawn. To be able to use DDP we recommend you: # # 1. Install a top-level module for your project using setup.py # # ``` # # setup.py # # # #!/usr/bin/env python # # from setuptools import setup, find_packages # # setup(name='src', # version='0.0.1', # description='Describe Your Cool Project', # author='', # author_email='', # url='https://github.com/YourSeed', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK # install_requires=[ # 'pytorch-lightning' # ], # packages=find_packages() # ) # # ``` # # 2. Setup your project like so: # # ``` # /project # /src # some_file.py # /or_a_folder # setup.py # ``` # 3. Install as a root-level package # ``` # # # cd /project # pip install -e . # ``` # 4. You can then call your scripts anywhere # ``` # # # cd /project/src # # python some_file.py --accelerator 'ddp' --gpus 8 # ``` # + [markdown] id="cmB3I_oyw7a8" # ### DP # # If you're using windows, DDP is not supported. You can use `dp` for DataParallel instead: DataParallel uses multithreading, instead of multiprocessing. It splits a batch across k GPUs. That is, if you have a batch of 32 and use DP with 2 gpus, each GPU will process 16 samples, after which the root node will aggregate the results. # # DP use is discouraged by PyTorch and Lightning. Use DDP which is more stable and at least 3x faster. # # + id="OO-J0ISvlVCg" # dp = DataParallel trainer = pl.Trainer(gpus=2, accelerator='dp') trainer.fit(model, train_loader, val_loader) # + [markdown] id="Y7E2eHZKwUn9" # ### DDP2 # # In certain cases, it’s advantageous to use ***all*** batches on the same machine, instead of a subset. For instance, in self-supervised learning, a common performance boost comes from increasing the number of negative samples. # # In this case, we can use DDP2 which behaves like DP in a machine and DDP across nodes. DDP2 does the following: # # * Copies a subset of the data to each node. # * Inits a model on each node. # * Runs a forward and backward pass using DP. # * Syncs gradients across nodes. # * Applies the optimizer updates. # # # # + id="Y4xweqL3xHER" # ddp2 = DistributedDataParallel + dp trainer = pl.Trainer(gpus=2, num_nodes=2, accelerator='ddp2') trainer.fit(model, train_loader, val_loader) # + [markdown] id="lhKNCnveeeq5" # - The second mode is ddp_spawn. This works like ddp, but instead of calling your script multiple times, lightning will use multiprocessing spawn to start a subprocess per GPU. # # However, you should be careful of mixing this mode with num_workers > 0 in your dataloaders because it will bottleneck your training. This is a current known limitation of PyTorch which is why we recommend using our ddp implementation instead. # # + [markdown] id="HUf9ANyQkFFO" # # ### mocking ddp # # Testing or debugging DDP can be hard, so we have a distributed backend that simulates ddp on cpus to make it easier. Set `num_processes` to a number greater than 1 when using accelerator="ddp_cpu" to mimic distributed training on a machine without GPUs. Note that while this is useful for debugging, it will not provide any speedup, since single-process Torch already makes efficient use of multiple CPUs. # + id="ZSal5Da9kHOf" # Simulate DDP for debugging on your GPU-less laptop trainer = Trainer(accelerator="ddp_cpu", num_processes=2) trainer.fit(model, train_loader, val_loader) # + [markdown] id="Br_btCy5lgES" # # Training on TPUS # # + [markdown] id="DXkBNITdv44d" # Another option for accelerating your training is using TPUs. # A TPU is a Tensor processing unit, designed specifically for deep learning. Each TPU has 8 cores where each core is optimized for 128x128 matrix multiplies. Google estimates that 8 TPU cores are about as fast as 4 V100 GPUs! # # A TPU pod hosts many TPUs on it. Currently, TPU pod v2 has 2048 cores! You can request a full pod from Google cloud or a “slice” which gives you some subset of those 2048 cores. # # At this moment, TPUs are available on Google Cloud (GCP), Google Colab and Kaggle Environments. # # Lightning supports training on TPUs without any code adjustments to your model. Just like when using GPUs, Lightning automatically inserts the correct samplers - no need to do this yourself! # # Under the hood, lightning uses the XLA framework developed jointly by the facebook and google XLA teams. And we want to recognize their efforts in advancing TPU adoption of PyTorch. # # ## tpu_cores # To train on TPUs, set the tpu_cores flag. # # When using colab or kaggle, the allowed values are 1 or 8 cores. When using google cloud, any value above 8 is allowed. # # Your effective batch size is the batch size passed into a dataloader times the total number of tpu cores. # + id="itP9y70gmD9M" # int: train on a single core trainer = pl.Trainer(tpu_cores=1) trainer.fit(model, train_loader, val_loader) # + id="NJKnzPb3mKEg" # int: train on all cores few cores trainer = pl.Trainer(tpu_cores=8) trainer.fit(model, train_loader, val_loader) # + [markdown] id="8a4exfWUmOHq" # You can also choose which TPU core to train on, by passing a list [1-8]. This is not an officially supported use case but we are working with the XLA team to improve this user experience. # # + id="S6OrjE_bmT-_" # list: train on a single selected core trainer = pl.Trainer(tpu_cores=[2]) trainer.fit(model, train_loader, val_loader) # + [markdown] id="Afqx3sFUmfWD" # To train on more than 8 cores (ie: a POD), submit this script using the xla_dist script. # # # # ``` # python -m torch_xla.distributed.xla_dist # --tpu=$TPU_POD_NAME # --conda-env=torch-xla-nightly # --env=XLA_USE_BF16=1 # -- python your_trainer_file.py # ``` # # # + [markdown] id="ncPvbUVQqKOh" # # Advanced distributed training # # + [markdown] id="4MP7bEgnv7qK" # # Lightning supports distributed training across multiple GPUs and TPUs out of the box by setting trainer flags, but it also allows you to control the way sampling is done if you need to. # + [markdown] id="wdHiTfAMepKH" # ## replace_sampler_ddp # In PyTorch, you must use torch.nn.DistributedSampler for multi-node or GPU training. The sampler makes sure each GPU sees the appropriate part of your data. # # ``` # # without lightning # def train_dataloader(self): # dataset = MNIST(...) # sampler = None # # if self.on_tpu: # sampler = DistributedSampler(dataset) # # return DataLoader(dataset, sampler=sampler) # ``` # Lightning adds the correct samplers when needed, so no need to explicitly add samplers. By default it will add `shuffle=True` for train sampler and `shuffle=False` for val/test sampler. # # If you want to customize this behaviour, you can set `replace_sampler_ddp=False` and add your own distributed sampler. # # (note: For iterable datasets, we don’t do this automatically.) # # + id="ZfmcB_e_7HbE" sampler = torch.utils.data.distributed.DistributedSampler(dataset, shuffle=False) dataloader = DataLoader(dataset, batch_size=32, sampler=sampler) trainer = pl.Trainer(gpus=2, num_nodes=2, replace_sampler_ddp=False) # + [markdown] id="-IOhk1n0lL3_" # ## prepare_data_per_node # # When doing multi NODE training, if your nodes share the same file system, then you don't want to download data more than once to avoid possible collisions. # # Lightning automatically calls the prepare_data hook on the root GPU of the master node (ie: only a single GPU). # # In some cases where your nodes don't share the same file system, you need to download the data on each node. In this case you can set this flag to true and lightning will download the data on the root GPU of each node. # # This flag is defaulted to True. # + id="WFBMUR48lM04" trainer = pl.Trainer(gpus=2, num_nodes=2, prepare_data_per_node=False) trainer.fit(model, train_loader, val_loader) # + [markdown] id="FKBwXqo4q-Vp" # ## sync_batchnorm # # Batch norm is computed per GPU/TPU. This flag enables synchronization between batchnorm layers across all GPUs. # It is recommended if you have small batch sizes. # # + id="GhaCLTEZrAQi" trainer = Trainer(gpus=4, sync_batchnorm=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="XuFA7VTFMY9-" # # Debugging flags # # Lightning offers a couple of flags to make debugging your models easier: # # + [markdown] id="AKoS3fdml4Jx" # ## Fast Dev Run # # To help you save time debugging, your first run should use the fast_dev_run flag. # # This won't generate logs or save checkpoints but will touch every line of your code to make sure that it is working as intended. # # Think about this flag like a compiler. You make changes to your code, and run Trainer with this flag to verify that your changes are bug free. # # + id="L5vuG7GSmhzK" trainer = pl.Trainer(fast_dev_run=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="HRP1qQR5nT4p" # ## overfit_batches # # Uses this much data of the training set. If nonzero, will use the same training set for validation and testing. If the training dataloaders have shuffle=True, Lightning will automatically disable it. # # Useful for quickly debugging or trying to overfit on purpose. # + id="NTM-dqGMnXms" # use only 1% of the train set (and use the train set for val and test) trainer = pl.Trainer(overfit_batches=0.01) trainer.fit(model, train_loader, val_loader) # + id="c0LV0gC3nl1X" # overfit on 10 of the same batches trainer = pl.Trainer(overfit_batches=10) trainer.fit(model, train_loader, val_loader) # + [markdown] id="lt3UHU6WgtS_" # Or a float to represent percentage of data to run # + id="K3yUqADhgnkf" # run through only 25% of the test set each epoch trainer = pl.Trainer(limit_test_batches=0.25) trainer.fit(model, train_loader, val_loader) # + [markdown] id="ODN66NeVg_2o" # In the case of multiple test dataloaders, the limit applies to each dataloader individually. # # + [markdown] id="8aQx5SLeMz1R" # # accumulate_grad_batches # # # # + [markdown] id="g8GczZXFwKC7" # The batch size controls the accuracy of the estimate of the gradients. Small batch size use less memory, but decrease accuracy. When training large models, such as NLP transformers, it is useful to accumulate gradients before calling backwards(). It allows for bigger batch sizes than what can actually fit on a GPU/TPU in a single step. # # Use accumulate_grad_batches to accumulate gradients every k batches or as set up in the dict. Trainer also calls optimizer.step() for the last indivisible step number. # # For example, set accumulate_grad_batches to 4 to accumulate every 4 batches. In this case the effective batch size is batch_size*4, so if your batch size is 32, effectively it will be 128. # + id="2jB6-Z_yPhhf" # accumulate every 4 batches (effective batch size is batch*4) trainer = pl.Trainer(accumulate_grad_batches=4) trainer.fit(model, train_loader, val_loader) # + [markdown] id="_Yi-bdTOgINC" # You can also pass a dictionary to specify different accumulation per epoch. We can set it to `{5: 3, 10: 20}` to have no accumulation for epochs 1 to 4, accumulate 3 batches for epoch 5 to 10, and 20 batches after that. # + id="X3xsoZ3YPgBv" # no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that trainer = pl.Trainer(accumulate_grad_batches={5: 3, 10: 20}) trainer.fit(model, train_loader, val_loader) # + [markdown] id="myzH8mV4M1_9" # # 16 bit precision # # # + [markdown] id="v9EaFAonwOk6" # Most deep learning frameworks like PyTorch, train with 32-bit floating point arithmetic. # # But many models can still achieve full accuracy using half the precision. # # In 2017, NVIDIA researchers successfully used a combination of 32 and 16 bit precision (also known as mixed precision) and achieved the same accuracy as 32 bit precision training. # # The main two advantages are: # # - a reduction in memory requirements which enables larger batch sizes and models. # - and a speed up in compute. On ampere, turing and volta architectures 16 bit precision models can train at least 3 times faster. # # As of PyTorch 1.6, NVIDIA and Facebook moved mixed precision functionality into PyTorch core as the AMP package, torch.cuda.amp. # # This package supersedes the apex package developed by NVIDIA. # + [markdown] id="TjNypZPHnxvJ" # ## precision # # Use precision flag to switch between full precision (32) to half precision (16). Can be used on CPU, GPU or TPUs. # # When using PyTorch 1.6+ Lightning uses the native amp implementation to support 16-bit. # # If used on TPU will use torch.bfloat16 but tensor printing will still show torch.float32 # + id="kBZKMVx1nw-D" # 16-bit precision trainer = pl.Trainer(gpus=1, precision=16) trainer.fit(model, train_loader, val_loader) # + [markdown] id="VJGj3Jh7oQXU" # In earlier version of Lightning, we use NVIDIA Apex for 16-bit precision. Apex was the first library to attempt 16-bit and the automatic mixed precision library (amp), has since been merged into core PyTorch as of 1.6. # # If you insist in using Apex, you can set the amp_backend flag to 'apex' and install Apex on your own. # + id="BDV1trAUPc9h" trainer = pl.Trainer(gpus=1, precision=16, amp_backend='apex') trainer.fit(model, train_loader, val_loader) # + [markdown] id="HK5c_aVfNV4e" # ## amp_level # Apex includes 4 optimization levels: # O0 (FP32 training) # O1 (Conservative Mixed Precision): only some whitelist ops are done in FP16. # O2 (Fast Mixed Precision): this is the standard mixed precision training. It maintains FP32 master weights and optimizer.step acts directly on the FP32 master weights. # O3 (FP16 training): full FP16. Passing keep_batchnorm_fp32=True can speed things up as cudnn batchnorm is faster anyway. # # + id="FshMFPowNbWt" # default used by the Trainer trainer = pl.Trainer(gpus=1, precision=16, amp_backend='apex', amp_level='O2') trainer.fit(model, train_loader, val_loader) # + [markdown] id="y8KEr1YvNgkC" # # `auto_scale_batch_size` # # # # # + [markdown] id="7F1pKFIuwSFl" # Lightning can help you improve your model by using auto_scale_batch_size flag, which tries to find the largest batch size that fits into memory, before you start your training. # Larger batch size often yields better estimates of gradients, but may also result in longer training time. # # Set it to True to initially run a batch size finder trying to find the largest batch size that fits into memory. The result will be stored in self.batch_size in the LightningModule. # # + id="9_jE-iyyheIv" trainer = pl.Trainer(auto_scale_batch_size=True) trainer.tune(model, train_dataloader=train_loader, val_dataloaders=val_loader) # + [markdown] id="yaHsJvwFhNJt" # You can set the value to `power`. `power` scaling starts from a batch size of 1 and keeps doubling the batch size until an out-of-memory (OOM) error is encountered. # # + id="Qx0FbQrphgw1" trainer = pl.Trainer(auto_scale_batch_size='power') trainer.tune(model, train_dataloader=train_loader, val_dataloaders=val_loader) # + [markdown] id="8bwgVF9zhZ75" # You can also set it to `binsearch`, that continues to finetune the batch size by performing a binary search. # # + id="QObXNs3yNrg9" # run batch size scaling, result overrides hparams.batch_size trainer = pl.Trainer(auto_scale_batch_size='binsearch') trainer.tune(model, train_dataloader=train_loader, val_dataloaders=val_loader) # + [markdown] id="5OWdhSsZjqW7" # This feature expects that a batch_size field in the hparams of your model, i.e., model.hparams.batch_size should exist and will be overridden by the results of this algorithm. # # Additionally, your train_dataloader() method should depend on this field for this feature to work. # # The algorithm in short works by: # 1. Dumping the current state of the model and trainer # # 2. Iteratively until convergence or maximum number of tries max_trials (default 25) has been reached: # * Call fit() method of trainer. This evaluates steps_per_trial (default 3) number of training steps. Each training step can trigger an OOM error if the tensors (training batch, weights, gradients etc.) allocated during the steps have a too large memory footprint. # * If an OOM error is encountered, decrease the batch size # * Else increase it. # * How much the batch size is increased/decreased is determined by the chosen strategy. # # 3. The found batch size is saved to model.hparams.batch_size # # 4. Restore the initial state of model and trainer # # # + [markdown] id="q4CvxfZmOWBd" # # `auto_lr_find` # # # # # + [markdown] id="j85e8usNwdBV" # Selecting a good learning rate for your deep learning training is essential for both better performance and faster convergence. # # Even optimizers such as Adam that are self-adjusting the learning rate can benefit from more optimal choices. # # To reduce the amount of guesswork concerning choosing a good initial learning rate, you can use Lightning auto learning rate finder. # # The learning rate finder does a small run where the learning rate is increased after each processed batch and the corresponding loss is logged. The result of this is a lr vs. loss plot that can be used as guidance for choosing an optimal initial lr. # # # warning: For the moment, this feature only works with models having a single optimizer. LR support for DDP is not implemented yet, it is coming soon. # # # ***auto_lr_find=*** # # In the most basic use case, this feature can be enabled during trainer construction with Trainer(auto_lr_find=True). # When .fit(model) is called, the LR finder will automatically run before any training is done. The lr that is found and used will be written to the console and logged together with all other hyperparameters of the model. # + id="iuhve9RBOfFh" # default used by the Trainer (no learning rate finder) trainer = pl.Trainer(mnist_model, auto_lr_find=False) # + [markdown] id="BL-gjXNCPDXk" # This flag sets your learning rate which can be accessed via self.lr or self.learning_rate. # # + id="wEb-vIMmPJQf" class LitModel(LightningModule): def __init__(self, learning_rate): self.learning_rate = learning_rate def configure_optimizers(self): return Adam(self.parameters(), lr=(self.lr or self.learning_rate)) # finds learning rate automatically # sets hparams.lr or hparams.learning_rate to that learning rate trainer = pl.Trainer(mnist_model, auto_lr_find=True) trainer.tune(model, train_dataloader=train_loader, val_dataloaders=val_loader) # + [markdown] id="RweqvpnVPPSh" # To use an arbitrary value set it as auto_lr_find # # + id="4LKI39IfPLJv" trainer = pl.Trainer(mnist_model, auto_lr_find='my_value') trainer.tune(model, train_dataloader=train_loader, val_dataloaders=val_loader) # + [markdown] id="9VAhPRKbPX-m" # Under the hood, when you call tune it runs the learning rate finder. # # If you want to inspect the results of the learning rate finder before doing any actual training or just play around with the parameters of the algorithm, this can be done by invoking the lr_find method of the trainer. A typical example of this would look like # # # ``` # trainer = pl.Trainer(auto_lr_find=True) # # # Run learning rate finder # lr_finder = trainer.lr_find(model) # # # Results can be found in # lr_finder.results # # # Plot with # fig = lr_finder.plot(suggest=True) # fig.show() # # # Pick point based on plot, or get suggestion # new_lr = lr_finder.suggestion() # # # update hparams of the model # model.hparams.lr = new_lr # # # Fit model # trainer.fit(model) # ``` # # The figure produced by lr_finder.plot() should look something like the figure below. It is recommended to not pick the learning rate that achieves the lowest loss, but instead something in the middle of the sharpest downward slope (red point). This is the point returned py lr_finder.suggestion(). # # ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAgAElEQVR4Ae3dB3hUZb7H8bheey94r+URdMWOuq66a1mVtazX3nVX17p617bqursGUCMo9gIWUFBRBBGwoEAgtEDoLbQgIQklCS0kkJAQkpDyv8//xRlnkkkyM++UM3O+53nykDlz3jPnfM5/8v44NUUYEEAAAQQQQAABBFwlkOKqtWVlEUAAAQQQQAABBIQASBEggAACCCCAAAIuEyAAumyDs7oIIIAAAggggAABkBpAAAEEEEAAAQRcJkAAdNkGZ3URQAABBBBAAAECIDWAAAIIIIAAAgi4TIAA6LINzuoigAACCCCAAAIEQGoAAQQQQAABBBBwmQAB0GUbnNVFAAEEEEAAAQQIgNQAAggggAACCCDgMgECoMs2OKuLAAIIIIAAAggQAKkBBBBAAAEEEEDAZQIEQJdtcFYXAQQQQAABBBAgAFIDCCCAAAIIIICAywQIgC7b4KwuAggggAACCCBAAKQGEEAAAQQQQAABlwkQAF22wVldBBBAAAEEEECAAEgNIIAAAggggAACLhMgALpsg7O6CCCAAAIIIIAAAZAaQAABBBBAAAEEXCZAAHTZBmd1EUAAAQQQQAABAiA1gAACCCCAAAIIuEyAAOiyDc7qIoAAAggggAACBEBqAAEEEEAAAQQQcJkAAdBlG5zVRQABBBBAAAEECIDUAAIIIIAAAggg4DIBAqDLNjiriwACCCCAAAIIEACpAQQQQAABBBBAwGUCBECXbXBWFwEEEEAAAQQQIABSAwgggAACCCCAgMsECIAu2+CsLgIIIIAAAgggQACkBhBAAAEEEEAAAZcJEABdtsFZXQQQQAABBBBAgABIDSCAAAIIIIAAAi4TIAC6bIOzuggggAACCCCAAAGQGkAAAQQQQAABBFwmQAB02QZndRFAAAEEEEAAAQIgNYAAAggggAACCLhMgADosg3O6iKAAAIIIIAAAgRAagABBBBAAAEEEHCZAAHQZRuc1UUAAQQQQAABBAiA1AACCCCAAAIIIOAyAQKgyzY4q4sAAggggAACCBAAqQEEEEAAAQQQQMBlAgRAl21wVhcBBBBAAAEEECAAUgMIIIAAAggggIDLBAiALtvgrC4CCCCAAAIIIEAApAYQQAABBBBAAAGXCRAAXbbBWV0EEEAAAQQQQIAASA0ggAACCCCAAAIuEyAAumyDs7oIIIAAAggggAABkBpAAAEEEEAAAQRcJkAAdNkGZ3URQAABBBBAAAECIDWAAAIIIIAAAgi4TIAA6LINzuoigAACCCCAAAIEQGoAAQQQQAABBBBwmQAB0GKDNzY2SnFxsVRUVMi2bdv4wYAaoAaoAWqAGkiAGtB+W/tv7cfdOhAALba8Fk9KSgo/GFAD1AA1QA1QAwlYA9qPu3UgAFpsef0fhAZALSD2ALIHlBqgBqgBaoAaSIwa8OzA0X7crQMB0GLL6xddA6D+y4AAAggggAACiSFA/y1CALSoVQrIAo+mCCCAAAIIxEmA/psAaFV6FJAVH40RQAABBBCIiwD9NwHQqvAoICs+GiOAAAIIIBAXAfpvAqBV4VFAVnw0RgABBBBAIC4C9N8EQKvCo4Cs+GiMAAIIIIBAXATovwmAVoVHAVnx0RgBBBBAAIG4CNB/EwCtCo8CsuKjMQIIIIAAAnERoP8mAFoVHgVkxUdjBBBAAAEE4iJA/00AtCo8CsiKj8YIIIAAAgjERYD+mwBoVXgUkBUfjRFAAAEEEIiLAP03AdCq8CggKz4aI4AAAgggEBcB+m8CoFXhUUBWfDRGAAEEEEAgLgL03wRAq8KjgKz4aIwAAggggECrAiPmF8k/hmXLuGUbWp0m3DfovwmA4daOaUcBWfHRGAEEEEAAgVYFUr9dIh2fHSN9J+W1Ok24b9B/EwDDrR3TjgKy4qMxAggggAACrQo8PHi+CYCDZ69tdZpw36D/JgCGWzumHQVkxUdjBBBAAAEEWhW4tf9MEwDHLuUQcKtIFm+kWLR1fVMCoOtLAAAEEEAAgSgJ/PGtTBMAZxWURfwT6L/ZA2hVVBSQFR+NEUAAAQQQaFXgrJ4ZJgCu3FTZ6jThvkH/TQAMt3ZMOwrIio/GCCCAAAIIBBRoaGySTqljTAAsraoNOI3NSPpvAqBN/QgFZMVHYwQQQAABBAIKlFXVmvCnVwHXNzQGnMZmJP03AdCmfgiAVno0RgABBBBAILBA3qZKEwDP7JkReALLsQRAAqBVCVFAVnw0RgABBBBAIKDAnFVlJgB2fTMz4Pu2I+m/CYBWNUQBWfHRGAEEEEAAgYAC6Us3mAB4S7+ZAd+3HUn/TQC0qiEKyIqPxggggAACCAQUGDJnrQmAf/tifsD3bUfSfxMArWqIArLiozECCCCAAAIBBd6blGcC4LPfLAn4vu1I+m8CoFUNUUBWfDRGAAEEEEAgoMCLP+aYAPjauBUB37cdSf9NALSqIQrIio/GCCCAAAIIBBT4x7BsEwAHZq0K+L7tSPpvAqBVDVFAVnw0RgABBBBAIKDA3Z/MMQHwmwXFAd+3HUn/TQC0qiEKyIqPxggggAACCAQUuLpvlgmAU3JLAr5vO5L+mwBoVUMUkBUfjRFAAAEEEAgocP4rk0wAXFxUHvB925H03wRAqxqigKz4aIwAAggggEALgaamJjmxR7oJgEVbqlu8H4kR9N8EQKs6ooCs+GiMAAIIIIBAC4HttfUm/OlzgPX3aAz03y4PgOvWrZO77rpLDj30UNl7773l9NNPl/nzg7/pJAUUja8l80QAAQQQcLOA7vXT8Kd7AXVvYDQG+m8XB8CtW7dKx44d5b777pO5c+fK6tWrJSMjQwoKCoKuNQooaComRAABBBBAICgBPe9PA+DvX5kU1PThTET/7eIA+Oyzz8pFF10UTt1421BAXgp+QQABBBBAICICeuWvBkC9EjhaA/23iwPgKaecIk899ZTceuut0qFDBznrrLNkwIABbdZabW2taNF4foqLiyUlJcW8brMhbyKAAAIIIIBAUAJ67z8NgHovwGgNBEAXB8C99tpL9Kdbt26SnZ0tH3/8sTkP8PPPP2+13tLS0kzg09Dn+6OFxIAAAggggAAC9gL69A8NgPo0kGgNBEAXB8A99thDzj//fL/aeuKJJ+T3v/+93zjfF+wB9NXgdwQQQAABBCIvoM//1QCY9kNO5Gf+8xwJgC4OgMcee6w8+OCDfsXVr18/Oeqoo/zGtfWCAmpLh/cQQAABBBAIXeDZb5aYAPjepLzQGwfZgv7bxQHwz3/+c4uLQPScwOZ7BduqJQqoLR3eQwABBBBAIHSBv30x3wTAIXPWht44yBb03y4OgPPmzZP/+q//kt69e0t+fr4MHTpU9t13XxkyZEiQ5SPm4g8uAgmaiwkRQAABBBBoV+CWfjNNAExfuqHdacOdgADo4gCoRTN69Ghz82e9GOTkk09u9yrg5oVGATUX4TUCCCCAAAJ2Al3fzDQBcM6qMrsZtdGa/tvlAbCN2gjqLQooKCYmQgABBBBAIGiBM3tmmACYt6ky6DahTkj/TQAMtWb8pqeA/Dh4gQACCCCAgJVAfUOjCX96FXBZVa3VvNpqTP9NAGyrPtp9jwJql4gJEEAAAQQQCFpgc2WtCYCdUsdIQ2N0ngOsC0P/TQAMuigDTUgBBVJhHAIIIIAAAuEJrNxUaQLgWT0zwptBkK3ovwmAQZZK4MkooMAujEUAAQQQQCAcgVkFZSYAdn0rM5zmQbeh/yYABl0sgSakgAKpMA4BBBBAAIHwBMYu3WAC4K39Z4Y3gyBb0X8TAIMslcCTUUCBXRiLAAIIIIBAOAKDZ681AfChL+aH0zzoNvTfBMCgiyXQhBRQIBXGIYAAAgggEJ5A30l5JgCmfrskvBkE2Yr+mwAYZKkEnowCCuzCWAQQQAABBMIRSPshxwTA18etCKd50G3ovwmAQRdLoAkpoEAqjEMAAQQQQCA8gSe+yjYBcGDWqvBmEGQr+m8CYJClEngyCiiwC2MRQAABBBAIR+CugXNMAPx2YXE4zYNuQ/9NAAy6WAJNSAEFUmEcAggggAAC4Qn8b58sEwAzc0vCm0GQrei/CYBBlkrgySigwC6MRQABBBBAIByB3/WeZALgkuLycJoH3Yb+mwAYdLEEmpACCqTCOAQQQAABBEIXaGpqks490k0ALN5aHfoMQmhB/00ADKFcWk5KAbU0YQwCCCCAAALhCFTV1pvw1/HZMVJdVx/OLIJuQ/9NAAy6WAJNSAEFUmEcAggggAACoQsUllWbAHjSc+mhNw6xBf03ATDEkvGfnALy9+AVAggggAAC4QosKio3AfCCVyeHO4ug29F/EwCDLpZAE1JAgVQYhwACCCCAQOgCk1dsMgHwmveyQm8cYgv6bwJgiCXjPzkF5O/BKwQQQAABBMIVGLmg2ATAv346N9xZBN2O/psAGHSxBJqQAgqkwjgEEEAAAQRCF/h4WoEJgE8Oyw69cYgt6L8JgCGWjP/kFJC/B68QQAABBBAIV+DV9BUmAPb8cXm4swi6Hf03ATDoYgk0IQUUSIVxCCCAAAIIhC7w75GLTQB8f3Je6I1DbEH/TQAMsWT8J6eA/D14hQACCCCAQLgCD34+3wTAoXMKw51F0O3ovwmAQRdLoAkpoEAqjEMAAQQQQCB0gZs+nGEC4LhlG0JvHGIL+m8CYIgl4z85BeTvwSsEEEAAAQTCFbj0zUwTAOeu3hLuLIJuR/9NAAy6WAJNSAEFUmEcAggggAACoQt0SRtvAmB+SWXojUNsQf9NAAyxZPwnp4D8PXiFAAIIIIBAOAI7GxpN+NPnAG/ZXhfOLEJqQ/9NAAypYJpPTAE1F+E1AggggAACoQuUVNaYANgpdYw0NDaFPoMQW9B/EwBDLBn/ySkgfw9eIYAAAgggEI7Aio3bTAD8Ta8J4TQPuQ39NwEw5KLxbUAB+WrwOwIIIIAAAuEJzCwoNQHwj29lhjeDEFvRfxMAQywZ/8kpIH8PXiGAAAIIIBCOwOgl600AvK3/rHCah9yG/psAGHLR+DaggHw1+B0BBBBAAIHwBAbPWmMC4MOD54c3gxBb0X8TAEMsGf/JKSB/D14hgAACCCAQjsC7E1eaAJj67dJwmofchv6bABhy0fg2oIB8NfgdAQQQQACB8AReGLXMBMA3xq8IbwYhtqL/JgCGWDL+k1NA/h68QgABBBBAIByBx4YuNAHwk+mrw2kechv6bwJgyEXj24AC8tXgdwQQQAABBMITuP2jWSYAjlq0LrwZhNiK/psAGGLJ+E9OAfl78AoBBBBAAIFwBC54dbIJgAvWRv85wLp89N8EwHDq1NuGAvJS8AsCCCCAAAJhCdQ3NMrx3caaALhpW01Y8wi1Ef03ATDUmvGbngLy4+AFAggggAACIQsUbak24a9z93RpjMFj4HQB6b8JgCEXqm8DCshXg98RQAABBBAIXWBWQZkJgJe+GZungOgS0n8TAEOvVJ8WFJAPBr8igAACCCAQhsCI+UUmAN79yZwwWofXhP6bABhe5fzcigKy4qMxAggggAAC8s6E2N4EWsnpvwmAVl89CsiKj8YIIIAAAgjIP4cvNnsAP5iSHzMN+m8CoFWxUUBWfDRGAAEEEEBAYn0PQCWn/yYAWn31KCArPhojgAACCCAgv9wDcGvMNOi/CYBWxUYBWfHRGAEEEEDA5QK+9wAsidE9AJWc/psAaPXVo4Cs+GiMAAIIIOByAe89AHvE7h6ASk7/TQC0+upRQFZ8NEYAAQQQcLnAzIJScwFI1xjeA1DJ6b8JgFZfPQrIio/GCCCAAAIuFxgeh3sAKjn9NwHQ6qtHAVnx0RgBBBBAwOUCb8fhHoBKTv9NALT66lFAVnw0RgABBBBwucDTwxfF/B6ASk7/TQC0+upRQFZ8NEYAAQQQcLnAbR/NMgFw1KJ1MZWg/yYAWhUcBWTFR2MEEEAAAZcLeO4BuLAwdvcAVHL6bwKg1VePArLiozECCCCAgIsFdjY0ynGpY8wewJLKmphK0H8TAK0KjgKy4qMxAggggICLBTz3ADyxR7o0NTXFVIL+mwBoVXAUkBUfjRFAAAEEXCzgvQfgW5kxV6D/JgBaFR0FZMVHYwQQQAABFwt47gH410/nxlyB/psAaFV0FJAVH40RQAABBFws4LkHYLfvlsZcgf6bAGhVdBSQFR+NEUAAAQRcLOC5B+CHmfkxV6D/dnkATEtLk5SUFL+fk046KehCpICCpmJCBBBAAAEE/AQ89wD8YfF6v/GxeEH/TQCU0047TTZu3Oj9KS0tDbr2KKCgqZgQAQQQQAABP4F43QNQF4L+mwAoZ555pl9BhvKCAgpFi2kRQAABBBDYJRDPewDqEtB/EwBl3333lSOPPFKOO+44+ctf/iKFhYVBfz8poKCpmBABBBBAAAGvQDzvAagLQf/t8gCYnp4uI0aMkCVLlsj48ePl/PPPl2OPPVYqKyu9Rer7S21trSkaLRz9KS4uNucP6u8MCCCAAAIIIBCcwMz8UvMEkD/G4R6AuoQEQJcHwOZlWl5eLgceeKB88sknzd8yrwNdNKIXkRAAA3IxEgEEEEAAgYACw+cVmQB4TxzuAagLRAAkALYozHPOOUdSU1NbjNcR7AEMyMJIBBBAAAEEQhJ4OyPXBMDucbgHoC4oAZAA6FewVVVVcsghh0jfvn39xrf2ggJqTYbxCCCAAAIItC7w9NeLTADsl1nQ+kRRfIf+2+UB8JlnnpGpU6fKmjVrZObMmXL55ZfL4YcfLps3bw6q7CigoJiYCAEEEEAAAT+B2/rPMgHwxzjcA1AXhP7b5QHwjjvuMFcA77nnnnL00UeLvi4oCP5/IxSQ3/eZFwgggAACCAQlcP4rk0wAzC7cGtT0kZ6I/tvlAdC2oCggW0HaI4AAAgi4TaCuvlGOSx1jAuDmytq4rD79NwHQqvAoICs+GiOAAAIIuFCgsKzahL8Te6RLU1NTXATovwmAVoVHAVnx0RgBBBBAwIUC8b4HoJLTfxMArb56FJAVH40RQAABBFwoEO97ACo5/TcB0OqrRwFZ8dEYAQQQQMCFAvG+B6CS038TAK2+ehSQFR+NEUAAAQRcKOC5B2D/qcHfdSPSTPTfBECrmqKArPhojAACCCDgQgHPPQBHL1kft7Wn/yYAWhUfBWTFR2MEEEAAAZcJVNfVy0nPpZurgH/asC1ua0//TQC0Kj4KyIqPxggggAACLhMYs2SDCX9/eH1K3G4Bo+T03wRAq68eBWTFR2MEEEAAAZcJPDpkoQmAr6T/FNc1p/8mAFoVIAVkxUdjBBBAAAEXCeyoa5CTnxtnAuCS4vK4rjn9NwHQqgApICs+GiOAAAIIuEhg7NJdh38vfG1yXA//Kjn9NwHQ6qtHAVnx0RgBBBBAwEUCjw79+fDv2Pge/lVy+m8CoNVXjwKy4qMxAggggIBLBPTw7ynP7zr8u7govod/lZz+mwBo9dWjgKz4aIwAAggg4BKBccucc/hXyem/CYBWXz0KyIqPxggggAACLhF4/Ktsc/FHbwcc/lVy+m8CoNVXjwKy4qMxAggggIALBGp2/nL4d5EDDv8qOf03AdDqq0cBWfHRGAEEEEDABQLjlm00e/8ueDX+V/96uOm/CYCeWgjrXwooLDYaIYAAAgi4SOCJnw//vjR6uWPWmv6bAGhVjBSQFR+NEUAAAQSSXEAP/57689W/Cwu3OmZt6b8JgFbFSAFZ8dEYAQQQQCDJBcbn7Dr8e/4rk+J+82dfavpvAqBvPYT8OwUUMhkNEEAAAQRcJPCPYbuu/u3loMO/yk//TQC0+hpSQFZ8NEYAAQQQSGKBTdtqvM/+XbDWOYd/lZz+mwBo9dWjgKz4aIwAAgggkMQCT/689+/GD2c46vCvktN/EwCtvnoUkBUfjRFAAAEEklRg3pot5tYvnVLHyNLiCsetJf03AdCqKCkgKz4aI4AAAggkoUBDY5P8b58sEwBTv13iyDWk/yYAWhUmBWTFR2MEEEAAgSQU+HL2WhP+uqSNl7KqWkeuIf03AdCqMCkgKz4aI4AAAggkmcDW7XVyZs8MEwAHzVjt2LWj/yYAWhUnBWTFR2MEEEAAgSQTeO77ZSb8XfnONKlvaHTs2tF/EwCtipMCsuKjMQIIIIBAEgksX79NjksdYwLgrIIyR68Z/TcB0KpAKSArPhojgAACCCSJwPbaernpwxkm/D06dKHj14r+mwBoVaQUkBUfjRFAAAEEkkBgUVG5XPLGFBP+Tn5unKwv3+H4taL/JgBaFSkFZMVHYwQQQACBBBbQ2718MCVfft1trAl/+rxfvf9fIgz03wRAqzqlgKz4aIwAAgggkKAC68p3yG0fzTLBr+OzY0QP+1ZU70yYtaH/JgBaFSsFZMVHYwQQQACBBBGo2dkgMwtK5e0JK+X2j2ZJ5+7pJvyd+vw4Gbmg2HGPemuPlf6bANhejbT5PgXUJg9vIoAAAggkuIDeyPmugXO8gU/39nl+9Bm/a0q3J+Qa0n8TAK0KlwKy4qMxAggggIDDBXSPnyfwndd7ojzxVbYMnVMoBZurEm6vny81/TcB0LceQv6dAgqZjAYIIIAAAgkioBd56IUdGgC/nleY0IGvOTn9NwGweU2E9JoCComLiRFAAAEEEkggM7fEhL8zXswQPQcwmQb6bwKgVT1TQFZ8NEYAAQQQcLDAI0MWmACY9kOOg5cyvEWj/yYAhlc5P7eigKz4aIwAAggg4FABvfjjhO677u+nj3hLtoH+mwBoVdMUkBUfjRFAAAEEHCowMGuV2ft33fvTHbqEdotF/00AtKogCsiKj8YIIIAAAg4UaGpqksvfnmoC4Jez1zpwCe0Xif6bAGhVRRSQFR+NEUAAAQQcKLCwcKsJfyc9ly7bahLn6R6hUNJ/EwBDqZcW01JALUgYgQACCCCQ4AL/GbnEBMCnhy9K8DVpffHpvwmArVdHEO9QQEEgMQkCCCCAQMIIVNXWyynPjzMBcO7qLQmz3KEuKP03ATDUmvGbngLy4+AFAggggECCC+gNn/XGz13fzEyqGz833yz03wTA5jUR0msKKCQuJkYAAQQQcLjATR/OMAGw/9QChy+p3eLRfxMArSqIArLiozECCCCAgIME8jZVmvB3fLexUlJZ46Ali/yi0H8TAK2qigKy4qMxAggggICDBN6duNIEwAc/n++gpYrOotB/EwCtKosCsuKjMQIIIICAgwTu/Hi2CYBD5iTnvf98qem/CYC+9RDy7xRQyGQ0QAABBBBwoEBdfaOc2CPdBMD8kkoHLmFkF4n+mwBoVVEUkBUfjRFAAAEEHCKwYO0WE/5+02tCUl/96+Gm/yYAemohrH8poLDYaIQAAggg4DCBDzPzTQD8v8ELHLZk0Vkc+m8CoFVlUUBWfDRGAAEEEHCIwL2fzTUB8NPpqx2yRNFdDPpvAqBVhVFAVnw0RgABBBBwgEBDY5Oc9sJ4EwCXratwwBJFfxHovwmAVlVGAVnx0RgBBBBAwAECS4srTPg7PW28aBh0w0D/TQC0qnMKyIqPxggggAACDhAYmLXKBMD7B81zwNLEZhHovwmAVpVGAVnx0RgBBBBAwAECD30x3wTAZH/8my81/XeCBsCioiIpLi72bsu5c+fKk08+KR9//LF3XKi/vPrqq5KSkmLmE2xbCihYKaZDAAEEEHCiQGNjk5zVM8MEwIWFW524iFFZJvrvBA2AF110kQwePNgUxcaNG+XAAw+U888/Xw4//HDp2bNnyMUyb9486dSpk5xxxhkEwJD1aIAAAgggkKgCK39+/u/Jz40TvRm0WwYCYIIGwIMPPlhyc3NNnfbt21cuuOAC83tGRoYcd9xxIdVvVVWVdO7cWSZOnCiXXHIJATAkPSZGAAEEEEhkgcGz15q9f38ZODuRVyPkZScAJmgA3G+//WTNmjVmg1933XXy2muvmd8LCwtl7733DqkQ7rnnHnnqqadMGwJgSHRMjAACCCCQ4AKPf5VtAmCfiXkJviahLT4BMEED4HnnnSfPPvusZGVlmcC3ePFis+Vnz54tRx99dNBVMGzYMDn99NOlpqbGtGkvANbW1ooWjedHz0PU8wb1NQMCCCCAAAKJJNDU1CTnvjzRBMBZBWWJtOjWy0oATNAAmJmZKXoY+Fe/+pXcf//93kLo1q2b3HTTTd7Xbf2iF5IcccQRsmTJEu9k7QXAtLQ0E/g09Pn+EAC9hPyCAAIIIJAgAmtKt5vwd0L3sVKzsyFBljoyi0kATNAAqJu/oaFBtm71v2JJDwuXlJQEVR3ff/+9CXG77767eH401O22227mtc6/+cAewOYivEYAAQQQSFSB4fOKTAC8pd/MRF2FsJebAJigAXDHjh1SXV3t3fBr166Vd999V8aPH+8d194vlZWVsmzZMr+fc845R+6++24zrr32+j4FFIwS0yCAAAIIOFHgn8MXmwD4xvgVTly8qC4T/XeCBsArrrhC+vfvb4qjvLxc/vu//1uOOeYYcz5gv379wi6a9g4BN58xBdRchNcIIIAAAokicNHrk00AnLpyc6IscsSWk/47QQPgYYcdJjk5OaYQBg4caO7f19jYKCNGjJCTTz457AIhAIZNR0MEEEAAgQQSWF++w4S/41LHSFVtfQIteWQWlQCYoAFwn332Eb3liw633XabvPjii+Z3vbBD34vVQAHFSprPQQABBBCIpMCoRetMALzu/emRnG3CzIv+O0EDYJcuXURvAK2BT58CMmvWLFN0CxYsMIeDY1WBFFCspPkcBBBAAIFICvT4fqkJgL1GL4/kbBNmXvTfCRoAR44cKXvssYe5Dczll1/uLbhXXnlFrrrqKu/raP9CAUVbmPkjgAACCERD4Nr3ppsAOHrJ+mjM3vHzpP9O0AColaXPAM7OzhY9988zzJ07V1asiN3VTBSQR55/EUAAAQQSRaC2vkH03n8dn204e50AACAASURBVB0jRVt+uaNGoix/JJaT/juBA6CnAPRpHPoTj4ECioc6n4kAAgggYCOwqKjchL+zemaIPg3EjQP9d4IGQN3r17NnT3P+nz4NRH8OOugg6dWrl98ewWgXNQUUbWHmjwACCCAQaYEvZq0xAfCeT+dGetYJMz/67wQNgKmpqdKhQwfRe/7po9z058MPPzTjunfvHrMCpIBiRs0HIYAAAghESOCZEbtuAP1WRm6E5ph4s6H/TtAAeOSRR8oPP/zQouJGjRolRx11VIvx0RpBAUVLlvkigAACCERL4Ip3ppo9gBOWb4rWRzh+vvTfCRoA99prL1m5cmWLAsvNzTVPA2nxRpRGUEBRgmW2CCCAAAJREdheWy9682e9AKRkW01UPiMRZkr/naAB8LzzzpMnnniiRY09/vjjou/FaqCAYiXN5yCAAAIIREJgzqoyE/5+13tSJGaXsPOg/07QADh16lTZb7/95JRTTpEHHnjA/Ojv+++/v2RlZcWsICmgmFHzQQgggAACERAYmLXKBMCHvpgfgbkl7izovxM0AGrJrV+/XvSCj5tvvtn89OjRwzwe7qGHHopZRVJAMaPmgxBAAAEEIiDw+FfZJgC+PzkvAnNL3FnQfydwAAxUdosXLza3hAn0XjTGUUDRUGWeCCCAAALRErj4jSkmAE5buTlaH5EQ86X/JgBaFSoFZMVHYwQQQACBGAqUV9eZ8KcXgOjvbh7ovwmAVvVPAVnx0RgBBBBAIIYCutdPw5/uBXT7QP9NALT6DlBAVnw0RgABBBCIocAHU/JNANTzAN0+0H8nWAC86aabpK2frl27cg6g27/VrD8CCCCAQEABvfJX9wAOmLYq4PtuGkkATLAAeN9990kwP7EqYgooVtJ8DgIIIICArYDe+08DoN4L0O0D/XeCBUCnFSwF5LQtwvIggAACCAQS0Kd+aPjTp4Do00DcPtB/EwCtvgMUkBUfjRFAAAEEYiSgz/3VAKjPAWYQof8mAFp9DyggKz4aI4AAAgjESODtjFwTAJ8ZsThGn+jsj6H/JgBaVSgFZMVHYwQQQACBGAnc8+lcEwC/mLUmRp/o7I+h/yYAWlUoBWTFR2MEEEAAgRgINDU1yVk9M0wAXFRUHoNPdP5H0H8TAK2qlAKy4qMxAggggEAMBIq2VJvwd0L3sVJb3xCDT3T+R9B/EwCtqpQCsuKjMQIIIIBADATGLNlgAuC1702PwaclxkfQfxMArSqVArLiozECCCCAQAwEXhn7kwmA3b9bGoNPS4yPoP8mAFpVKgVkxUdjBBBAAIEYCFzdN8sEwOHzi2LwaYnxEfTfBECrSqWArPhojAACCCAQZYH8kkoT/n7dbaxs2V4X5U9LnNnTfxMAraqVArLiozECCCCAQJQF3hy/6/5/DwyaF+VPSqzZ038TAK0qlgKy4qMxAggggEAUBfT2Lxe+NtnsAfxx8fooflLizZr+mwBoVbUUkBUfjRFAAAEEoigwf80WE/5OfX6c7Kjj9i++1PTfBEDfegj5dwooZDIaIIAAAgjESECv+tXn//5zOI9/a05O/00AbF4TIb2mgELiYmIEEEAAgRgJ1NU3ypk/P/1jel5pjD41cT6G/psAaFWtFJAVH40RQAABBKIkMGH5JrP379yXJ0pDY1OUPiVxZ0v/TQC0ql4KyIqPxggggAACURJ4dMhCEwBfGr08Sp+Q2LOl/yYAWlUwBWTFR2MEEEAAgSgIbKvZKSf2SDcBcNm6iih8QuLPkv6bAGhVxRSQFR+NEUAAAQSiIKBP/NCLPy57e6rorWAYWgrQfxMAW1ZFCGMooBCwmBQBBBBAICYCfx4w2wTAD6bkx+TzEvFD6L8JgFZ1SwFZ8dEYAQQQQCDCAhsraqRT6hgTAIu2VEd47skzO/pvAqBVNVNAVnw0RgABBBCIsMDH0wpM+Lu1/8wIzzm5Zkf/TQC0qmgKyIqPxggggAACERa4/v3pJgAOmbM2wnNOrtnRfxMArSqaArLiozECCCCAQAQFanY2yPHdxpoAuK58RwTnnHyzov8mAFpVNQVkxUdjBBBAAIEICixYu+vZv+e8PJGrf9txpf8mALZTIm2/TQG17cO7CCCAAAKxExiYtcrs/Xvw8/mx+9AE/ST6bwKgVelSQFZ8NEYAAQQQiKDA419lmwDI7V/aR6X/JgC2XyVtTEEBtYHDWwgggAACMRX4w+tTTACcnlca089NxA+j/yYAWtUtBWTFR2MEEEAAgQgJlFXVmvCnTwCp2LEzQnNN3tnQfxMAraqbArLiozECCCCAQIQEpqwoMQHwj29lRmiOyT0b+m8CoFWFU0BWfDRGAAEEEIiQwNsTVpoA+PTwRRGaY3LPhv6bAGhV4RSQFR+NEUAAAQQiJHDPp3NNABw8a02E5pjcs6H/JgBaVTgFZMVHYwQQQACBCAg0NTXJmT0zTABcUlwegTkm/yzovwmAVlVOAVnx0RgBBBBAIAICa0q3m/DXuUe61NU3RmCOyT8L+m8CoFWVU0BWfDRGAAEEEIiAwKhF60wAvPHDGRGYmztmQf9NALSqdArIio/GCCCAAAIREHjxxxwTANN+yInA3NwxC/pvAqBVpVNAVnw0RgABBBCIgIDu+dP7/32fvS4Cc3PHLOi/CYBWlU4BWfHRGAEEEEDAUkDP+dNz/zQA6rmADMEJ0H8TAIOrlFamooBagWE0AggggEBMBJYWV5jwp1cB69XADMEJ0H8TAIOrlFamooBagWE0AggggEBMBPS+f7r3T+8DyBC8AP03ATD4agkwJQUUAIVRCCCAAAIxE/jn8MUmAOqTQBiCF6D/dnkA7Nevn3Tp0kUOOOAA8/P73/9e0tPTg64gCihoKiZEAAEEEIiCgD77V/cATl6xKQpzT95Z0n+7PAD++OOPMnbsWMnLy5OVK1dK9+7dZY899pCcnOAupaeAkvePA2uGAAIIOF1gW81OE/40AJZV1Tp9cR21fPTfLg+AgarxkEMOkU8++STQWy3GUUAtSBiBAAIIIBAjgRn5pSYAXvT65Bh9YvJ8DP03AdBbzQ0NDTJs2DDZc889Zfny5d7xbf1CAbWlw3sIIIAAAtEU+GBKvgmAj3+VHc2PScp5038TAGXp0qWy3377ye677y4HHXSQOSTcWrXX1taKFo3np7i4WFJSUszr1towHgEEEEAAgWgI/O2L+SYADsxaFY3ZJ/U8CYAEQKmrq5P8/HxZsGCBpKamyuGHH97qHsC0tDQT+DT0+f5oITEggAACCCAQK4EddQ3ym14TTACcv2ZLrD42aT6HAEgAbFHMl112mTz88MMtxusI9gAGZGEkAggggECMBd7KyDXh74JXJ4s+DYQhNAECIAGwRcV07dpV7r333hbjA42ggAKpMA4BBBBAIJoCq0u3S+fuux7/Nm7Zxmh+VNLOm/7b5QFQD/lOmzZN1qxZY84F1Ne77babTJgwIaiip4CCYmIiBBBAAIEICejj3u79bK7Z+/fXT+fy+LcwXem/XR4AH3jgAenYsaO58rdDhw6ih3+DDX9acxRQmN88miGAAAIIhCUwPmejCX+6B1D3BDKEJ0D/7fIAGF7Z/NKKAvrFgt8QQAABBKIroBd+6Dl/euPnN8aviO6HJfnc6b8JgFYlTgFZ8dEYAQQQQCAEAd8LP6rr6kNoyaTNBei/CYDNayKk1xRQSFxMjAACCCAQpsAavws/NoQ5F5p5BOi/CYCeWgjrXwooLDYaIYAAAgiEKHAfF36EKNb25PTfBMC2K6SddymgdoB4GwEEEEDAWqCkssac93dc6hhZtbnKen7MgIs4tQZSKITwBQiA4dvREgEEEEAgOIHZq8pMALz4jSnBNWCqdgXovwmA7RZJWxNQQG3p8B4CCCCAQCQEhs0tNAHwnk/nRmJ2zIPbuJkaYA+gxVeBAGiBR1MEEEAAgaAEXkn/yQTAF0YtC2p6JmpfgP6bPYDtV0kbU1BAbeDwFgIIIIBARAQeHjzfBMDPZqyOyPyYCecAag2wB9Dim0AAtMCjKQIIIIBAUAJXvjPNBMApuSVBTc9E7QvQfxMA26+SNqaggNrA4S0EEEAAAWuBxsYmObFHugmAei9AhsgI0H8TAK0qiQKy4qMxAggggEA7AuvLd5jw9+tuY6W+obGdqXk7WAH6bwJgsLUScDoKKCALIxFAAAEEIiQwM7/UBMBL38yM0ByZjQrQfxMArb4JFJAVH40RQAABBNoRGDJnrQmA+iQQhsgJ0H8TAK2qiQKy4qMxAggggEA7Ai+PWW4C4Is/5rQzJW+HIkD/TQAMpV5aTEsBtSBhBAIIIIBABAUe/HzXLWC+mLUmgnNlVvTfBECrbwEFZMVHYwQQQACBdgQue3uq2QM4beXmdqbk7VAE6L8JgKHUS4tpKaAWJIxAAAEEEIiQQENjk3TuvusWMEVbqiM0V2ajAvTfBECrbwIFZMVHYwQQQACBNgSKt1abvX8aAjUMMkROgP6bAGhVTRSQFR+NEUAAAQTaEJiet+sWMH98i1vAtMEU1lv03wTAsArH04gC8kjwLwIIIIBApAUGz951C5gHP58X6Vm7fn703wRAqy+BEwtozqoyue2jWfL3LxfIxooaq/WjMQIIIIBA/AR6jd51C5iXRi+P30Ik6Sc7sf+ONXVKrD8wmT7PSQWk54o8OmShOV+k47NjzL9nvJghPyxe3yp5U1OTbNleJ3py8fL122Temi2iDxufsHyTLFi7VQrLqqW6rr7V9pF8Q593qc+5zFlfIZu21UhdfeiPPNL10XZVtfVmvXQ+68p3xGwdIunBvBBAAIEHBs0zf8u/nL0WjAgLOKn/jvCqBT07AmDQVC0njFYBfbOgWG7uN1P0/k//GblEXk1fIQOmrRIdP2VFiSwuKjehbXttvQk3b2fkeh8WflzqGHn2myVy7XvTvWHw0aELZev2OrMCeiKx7iVM+yFHftd7kncaT2gM9O8pz4+TC1+bLFe8M1Wue3+62cP410/nysOD58s/hy8283orI1c+mlogQ+cUyugl60VvWbCoqFxWba6SzZW1UlJZYwLlyk2VsqS43CzD8HlF8sKoZXJr/5ly2gvjWyzL6WnjRR9/9L99sqTrW5lywauT5Te9Jogujz4X8/huY0XXV386pe4KvYGWX8dpm4vfmGJcdbm7f7dU1O3zmWvM8urjltR2xPwisx69x/5k1u2Jr7LlyWHZ8vTXi+SZEYvl3yMXS7fvlkrPH5fLa+NWSJ+JeWb6fpkFom3+NWKx6OEa3X5X982Suz+ZY9rqex9PK5BvFxbL5BW7AnbB5iopraqVnTzfs+WXizEIIGD+7unfrxn5pWhEWCBa/XeEFzOqsyMAWvBGq4DeGL+iRRhqLdj4Bp87Pp5l9uTpKmmoeHfiShOStO05L080YfK3L01sMe+TnxsnOv6SN6bINe9lyfXvTzeB76Tndt1+oLXPjvT4zj3SzXJosIvEvHU+J3SPzLwisTxtzUMDrYbg3740wQRdvffXXQPnmKCqwXF8zkZZsXGbbKvZKbqnkwEBBJJboL6h0fv3S4/wMERWIFr9d2SXMrpzIwBa+EargHSvWfrSDaLPgHxvUp7oI4D+MSzb7E3SvUrnvzLJu8dPQ4XunRu3bEPAYKB72/QKMt/w0SVtvNm7NXH5JqnZ2dCqgAYNPZyqh2YXFm4V3Uume6/GLt1g9kbqYYn+UwtEA+vzo5bJU18vMnu/9BzEP707zQQZ3Yunn61BVYOm7sHT5e/6Zqbc+fFs0XNbvssultyNlaJ/8HTQw8G6xzK/pMrsKczMLZHZq8rMnk+dTg9N6/mNeoi3RH8qd/3o3rSKHTvNOnlumeBZh9Wl280hbnXVO+q/M2Gl9Ph+qTlX8rb+s4yR2uqeTV0PXa4PM/Pl0+mrZWDWKrP3TvfyfTAl3wRr3fun20X3Bj49fJHx1Db6/ldzC8328OxR1HZ6Lo9uQw11GrIven2y6Hbw3S7B/q57M3XP6O0fzRLdQ6l7I7VOdHvotplVUGb2EBMUWy1t3kDA8QL6d07/Juh/jPVvIkNkBaLVf0d2KaM7NwKghW88C0g7dz0/b335Dm9wam1VNORpMNGQpmEqnPPrWpt3MOP1jxdhJLCUBtWK6p0m0GrQ1r18euh8ZkGpORz95vhcefyrbHPoPdTAqHsT9TQC3fY6Pw3zDAggkBgCU1duNgHw8renJsYCJ9hSxrP/dgoVAdBiS1BAFng0DUtAQ78GRT2PUy/w0b2TujdSz/t86Iv55nxK3eMb6NC37oXVQ8t6PuOgGavNhT476lrfAxzWAtIIAQQiIqDnJ+sewL99MT8i82Mm/gL039wGxr8iQnxFAYUIxuQxE9C9vnoltwZEvQhID7u3dohZD8tf1SdL7vtsrqR+u9QcTtbTAzZU7GDPbcy2GB+EgL+AXqin31m9gIwh8gL03wRAq6qigKz4aBxjAT1XUs/h1IuD9PYSgS4Iah4Sz+41wZx7qnsZta1ehMKAAALRF7j3s7kmAOqdFRgiL0D/TQC0qioKyIqPxnEW0PMy9WKbnzZsM/d/HDa30Fwco4eI9SKeQFdj6y139BZDL49ZLpN+2iR6KyIGBBCIvIDelUH/Q6bn7zJEXoD+mwBoVVUUkBUfjR0uoIeR9Z6TejW63o/S0yH57iU8sUe6OUdJ71GpF7MwIICAvYDexsvzHzA9FYMh8gL03wRAq6qigKz4aJyAAnr7nVGL1knqt0vMrWx8w6Dey1BvfP3J9NXmfpTcuiIBNzCL7AgBvW2Vfrf0Xqx8j6KzSei/CYBWlUUBWfHROMEF9BCyHj7Weype+c4002H5BsIze2aYp8XoFcf5JZVcUJLg25vFj52A3kNUv0t6KgZDdATovwmAVpVFAVnx0TjJBPQG5vo4wHs+nWsevecbBvX3P7w+xTw2MCtvc8zvRZlk1KxOkgt8NmO1CYD/N3hBkq9p/FaP/psAaFV9FJAVH42TWEDPYdKnx+jTVPSwcOfu/o8VPPX5ceYG1/qEF24SnsSFwKqFJaDPSNf/NOlz4BmiI0D/TQC0qiwKyIqPxi4S0KuF9XnGejFJ89vP6JMO9Ka33GLGRQXBqrYpoI+k1AD49TxuAdMmlMWb9N8EQIvyEaGArPho7FIBPak9u3Cruem0Ph/ac6hYn3GsF5csW1fhUhlWG4FdAnq6hH4v9Ik/DNERoP8mAFpVFgVkxUdjBMxeP937p3sBPUFQ/73hgxkyckGx6K1oGBBwk4A+q13vt6nfg5JtNW5a9ZiuK/03AdCq4CggKz4aI+AV0PMAdW/H419l+z3HWK8k1ptOF22p9k7LLwgks0DepkoT/nSPOOfHRm9L038TAK2qiwKy4qMxAgEFNlfWygdT8uWCVyd79wrqHpFHhiwwzzcO2IiRCCSJgF44pXv//jxgdpKskTNXg/6bAGhVmRSQFR+NEWhToKGxyTx/WK8i9j08fOOHM2TMkg2i7zMgkGwCeu8/rXd9NCND9ATovwmAVtVFAVnx0RiBoAVWbNwm/x652O92Mlf1yZJpKzcHPQ8mRMDpAp7Dvyd0Hyvl1XVOX9yEXj76bwKgVQFTQFZ8NEYgZAE9PPx2Rq6cnjbeu1dQ9xDmrOfK4ZAxaeA4gbcyck1dPzBonuOWLdkWiP6bAGhV0xSQFR+NEQhbYOv2Ouk1ern3gpFOqWPk6a8XyfryHWHPk4YIxFNAL/i4+I1dt3/R520zRFeA/psAaFVhFJAVH40RsBYoLKs2Vw57zhHU+wr2nZTH7WOsZZlBrAWWFJebvX8nPZcueuN0hugK0H8TAK0qjAKy4qMxAhETWFxULrf2n+k9LKxXEI9duoHbaERMmBlFW+Cl0ctN/T42dGG0P4r5Cw9y0CJIoRLCFyAAhm9HSwQiLaCH0H5YvF5+/8okbxC84+NZsnz9tkh/FPNDIKIC+nSc3/XeVbcZORsjOm9mFliA/psAGLgyghxLAQUJxWQIxFCguq5e3p6wUk7skW6CoJ4fqFcQb+KpCjHcCnxUKAKzV5WZWu2SNl5q63n6TSh24U5L/00ADLd2TDsKyIqPxghEVUCfHvLo0IXevYF6fuC7E1eKBkQGBJwk0O27paZO9T8qDLERoP8mAFpVGgVkxUdjBGIisGDtVrnpwxneIHhe74kyYn6R6GE3BgTiLbCzoVHO6plh6nN6Xmm8F8c1n0//TQC0KnYKyIqPxgjETEDPD9Snh1z0+i+Pl7v+/ek8Wi5mW4APak1gyooSE/5++9JEnm7TGlIUxtN/EwCtyooCsuKjMQIxF9Dzqz6aWiCnvfDLjaSf+nqRbKyoifmy8IEIqIDWn97GKO2HHEBiKED/TQC0KjcKyIqPxgjETaCkssZcGKIXiGjnq+cHvj+5nfsHNjWJlJaKrFmz6199zYCAhcCOugY59flxpgb1VAWG2AnQfxMAraqNArLiozECcRfQm+/e3O+X+wde+NpkSW9+/8DycpE+fUR+/WuRlJRffvS1jtf3GRAIQ0BrTf8Dovet1NMUGGInQP9NALSqNgrIio/GCDhCQDteffRW8/sH/rRhm8j48SL77Sey2267fnwDoGecvq/TMSAQooDn8O/LY5aH2JLJbQXovwmAVjVEAVnx0RgBRwk0v3/gPbf3lMZf/UqafvWrX/b6+QZAz+/6/u67EwIdtTWdvzB69a/e90/3AM5bs8X5C5xkS0j/TQC0KmkKyIqPxgg4UqB4a7U8M2CqbN9jb2lI2a3t8OcbAnVPIIeDHblNnbhQM/JLTfg7u9cErv6Nwwai/yYAWpUdBWTFR2MEnCvQp4806SFeT8AL5l+dvm9f564TS+YogRdGLTMB8D8jlzhqudyyMPTfLg+Ar7zyipxzzjmy//77S4cOHeSGG26Q3NzcoOufAgqaigkRSBwBPRlfL/AIJwBqO07mT5xtHacl1fNOPeecTl6xKU5L4e6Ppf92eQD805/+JIMGDZKcnBxZvHixXH311XLsscfK9u3bg/pmUEBBMTERAokloLd6CWaPX2vTlJUl1vqytDEXWFpcYfb+nfL8OKnZybN/Y74BRIT+2+UBsHnRbd68WVJSUmTatGnN3wr4mgIKyMJIBBJbQO/z11q4C2a8tmdAoA2BtzJyTQB8ZMiCNqbirWgK0H8TAP3qKz8/3wTAZcuW+Y1v7QUF1JoM4xFIYAH2ACbwxkuMRb/ynWkmAH6fvS4xFjgJl5L+mwDoLevGxka55ppr5MILL/SOa/5LbW2t2W2shaM/xcXFJjDq7wwIIJAkAmGeA6gXjTRxDmCSFEH0VmNN6XYT/n7dbaxUVO+M3gcx5zYFCIAEQG+B/P3vf5eOHTuaUOcd2eyXtLQ0E/j0MLHvDwGwGRQvEUh0AX3CR4gXgTSm7CYDbn1SctZXJPras/xRFBgwbZUJgHcNnBPFT2HW7QkQAAmApkYee+wxOeaYY2T16tVt1gx7ANvk4U0EkkdA7+en9/Vr7ybQP58T2Ljbr6R6j72ly5Nfy3GpY6TX6OWyvbY+eTxYk4gJ3PLzowe/mMW5ohFDDWNGBECXB0C9FF/D31FHHSV5eXkhlxAFFDIZDRBIHAF9vJs+4aO9EPjzk0C2fjdaHh2y0Ozd0ac76G0+vllQzE1+E2eLR31JN1fWSqfUMaZG1pfviPrn8QGtC9B/uzwAPvLII3LQQQfJ1KlTZePGjd6fHTuC+2JSQK1/uXgHgaQQCPZZwBkZ3tWdklsiF70+2RsE9YT/ics3if6Hk8HdAsPmFpq6uO796e6GcMDa03+7PAD6nsfn+7veGzCYgQIKRolpEEhwAT0crE/40As8fG8Do691fEXLc/521DVIv8wC77NedY+gHvrjma8JXguWi3//oHkmAL4/OfQjTpYfTfNmAvTfLg+Azeoh5JcUUMhkNEAgcQV0D57e5Fnv86f/BrFHT6/yfDV9hZzYI927R1Dv/bahIrijDImLxZI3F6iqrZfOP9fByk2Vzd/mdYwF6L8JgFYlRwFZ8dEYAdcIbKyokdRvl5oLRHRvoD4B4qOpBVJX3+gaA7ev6KhF68x/Ai55YwqnAzigGOi/CYBWZUgBWfHRGAHXCSxfv80cCtYQqD+XvT1VZhXw6LhkL4SdDY3S9a1Ms83fzgj+efPJ7hLP9aP/JgBa1R8FZMVHYwRcKdDY2CQjFxTL2b0meA8LP/X1IimrqnWlhxtW+rMZq8221m1eWcPNn52wzem/CYBWdUgBWfHRGAFXC+j5gc+PWua9LciZPTNk+PwiDg8mWVWUV9fJGS9mmAA4dE5hkq1d4q4O/TcB0Kp6KSArPhojgICILC4ql6v6ZHn3Bt7x8SxZtbkKmyQRSPshx2zbP707jXtCOmib0n8TAK3KkQKy4qMxAgj8LFDf0CgfTyuQk57bdbVw5+7p8sb4FVKxg8OFiVwkBZurRJ/5q+d7Ts8rTeRVSbplp/8mAFoVNQVkxUdjBBBoJlC0pVru+XSud29gl7Tx8sGUfB4r18wpUV4+8PN9/x78fF6iLLJrlpP+mwBoVewUkBUfjRFAIICAPjFkfM5G0SeIeK4W/u1LE+ST6aulZmdDgBaMcqJAVt5ms/10DyCH9J23hei/CYBWVUkBWfHRGAEE2hBoaGwSvXec3jfOEwTP6z1R9IpSgmAbcA54Sw/pewL8iz/mOGCJWITmAvTfBMDmNRHSawooJC4mRgCBMAT0HnL6DNnzX5nkDYLnvjyRPYJhWMaqycCsVWZb6ZXdehUwg/ME6L8JgFZVSQFZ8dEYAQRCEKitb5AvZ6+VC16d7A2Cv31pomjY0GcPMzhDYNJPm7xPfBk8e60zFoqlaCFA/00AbFEUoYyggELRYloEEIiEgD4+Tu8n5x8EJ8iAaaukuq4+Eh/BPMIUWFpcISc/N84E9P+MXMI9HcN0jEUz+m8CoFWdUUBWfDRGAAELAQ2CzY3rMAAAFkdJREFUemj4wtd+2SOoT5rQZwwTBC1gw2y6rnyHnPPyRBP+7v5kjuihewbnCtB/EwCtqpMCsuKjMQIIREBAg8bweUXyh9d/uVjkN70mSL/MAm4fEwHfYGaxrWanXPHOVBP+9IbP+prB2QL03wRAqwqlgKz4aIwAAhEU0CA4Yn6RXOxz1fBZPTPMfQSrajk0HEFqv1npnti/DJxtwp9enLO+fIff+7xwpgD9NwHQqjIpICs+GiOAQBQE9BYk3ywolkvfzDShRG8ho1ej9p2UxxWpEfbW0P3Y0IXG+dTnx8mydRUR/gRmFy0B+m8CoFVtUUBWfDRGAIEoCmgQ/D57nXR965cgqBcovDBqmRSWVUfxk90xa70Xoz7hQwP2Cd3HypTcEneseJKsJf03AdCqlCkgKz4aI4BADAQ8N5S+qk+Wd4/gcalj5JEhC2Rh4dYYLEHyfYQeUr/z412HfU/skU74S8BNTP9NALQqWwrIio/GCCAQQwF9xNyM/FK/Zw3r3qvr3p8uw+cX8XSRILeF3tj5hg9mmDB92gvjZfaqsiBbMpmTBOi/CYBW9UgBWfHRGAEE4iSwYuM2eWbEYuncPd27V/CMFzPkpdHLZXXp9jgtlfM/dnNlrehVvp7zKhcXlTt/oVnCgAL03wTAgIUR7EgKKFgppkMAAScKlFXVmtvF+N5UWsPN376YL4sIN36bLLtwq/fm23q/v9yNlX7v8yKxBOi/CYBWFUsBWfHRGAEEHCKg5wlOXrFJ7vtsrnRKHePdK6i3N5mZX+rqJ1roofPPZqw2F3poOL7kjSmyhr2kDqnc8BeD/psAGH71iAgFZMVHYwQQcKBAfkml/HP4Yjm+21hvELz+gxny7sSV8uPi9bJ8/TbXPHtYb+isF8to8NOfv3+5gJs8O7Bmw1kk+m8CYDh1421DAXkp+AUBBJJMoHhrtblljF7l6glAvv/qYePb+s+SR4culBd/zDGHkvX+g3roWG+OnOiDPtdX9/bpOuttXnQvoO4NZEgOAfpvAqBVJVNAVnw0RgCBBBDQCx8GZq2Sf49cLDf3m2luKu0bBAP93rlHuplWLyoZs2SDlFbVJsCa7lpEvbBDz4H0rJcGXT3/jyG5BOi/CYBWFU0BWfHRGAEEElRgy/Y6mb9mi4xesl4+nb5aXk1fIU8PX2QeiaaPn/OEJ8+/ejj5gUHzZNyyDY7cO6h79mYVlMndn8zxLrueC/n4V9mydXtdgm4lFrstAfpvAmBb9dHuexRQu0RMgAACLhPQMKW3kvl2YbH0+H6p97YpnjCoATHthxzRQ6yxOqSqn6OHtPUcxl6jl8sTX2XL/YPmyW0fzZKr+2Z5r+7VZdSwqmFWz4VkSF4B+m8CoFV1U0BWfDRGAAGXCOSXVJm9hOe+PNG7h03Dlh5e1TCoe9/00XWRGvTiDb3p9YeZ+fLQF/NFb9viCaCt/auHrTWwFm3hMXmR2g5Ong/9NwHQqj4pICs+GiOAgMsENOTpM3P1whF9LrFvGDuzZ4Y8OSzbXGyhh5er6+rb1dFHsulNrScu32TOU9T2Xd/85dnHvvP/dbexcv37082FLZ9MXy1fzys0h7Azc0vM4Ww9rM3gHgH6bwKgVbVTQFZ8NEYAARcL7KhrkAnLN5knkgQ6b1CfV3z521PNrVf+b/ACc49CvS/hrf1nmsO2gdr4Br4LX5tsbuEyYNoqE/Bqdja4WJtVby5A/00AbF4TIb2mgELiYmIEEEAgoIDuGdTDwO9MWGkuFjmvd/uHbD1hT/ccXvNelgmKfSbmmT2M+oQTBgTaEqD/JgC2VR/tvkcBtUvEBAgggEBYAiWVNebpJHr/vcGz18rweUXyffY6Gbt0gxn/04ZtUlmzM6x50wgB+m8CoNW3gAKy4qMxAggggAACcRGg/yYAWhUeBWTFR2MEEEAAAQTiIkD/TQC0KjwKyIqPxggggAACCMRFgP6bAGhVeBSQFR+NEUAAAQQQiIsA/TcB0KrwKCArPhojgAACCCAQFwH6bwKgVeFRQFZ8NEYAAQQQQCAuAvTfBECrwqOArPhojAACCCCAQFwE6L8JgFaFRwFZ8dEYAQQQQACBuAjQfxMArQqPArLiozECCCCAAAJxEaD/JgBaFR4FZMVHYwQQQAABBOIiQP9NALQqPArIio/GCCCAAAIIxEWA/psAaFV4FJAVH40RQAABBBCIiwD9NwHQqvAoICs+GiOAAAIIIBAXAfpvAqBV4VFAVnw0RgABBBBAIC4C9N8EQKvCq6iokJSUFCkuLhYtJn4woAaoAWqAGqAGnF8D2m9r/639uFuHFLeueCTW21NAWkT8YEANUAPUADVADSRWDWg/7taBAGix5RsbG83eP/0fhP6P78QTT2yxF7C9cc3f97z2hEv9NxL/m/TMN5h5tTdta+8HGt/euObve16z/rv+d8r2T+z6D/R3wVPjnu+i72vP74lY/4HWNdA4zzqy/rv2kvl6eH5n+0f/75/22+qs/bhbBwJgBLf8Kaec0mJu7Y1r/r7ntf5x1P9J6r+RGDzzDWZe7U3b2vuBxrc3rvn7ntesP9s/Gepfv2+emvZ899p67XkvEes/0LoGGudZx0AenvdY/8T7/gfa1oHGebaxU7e/Z7nc8C8BMIJb+YMPPmgxt/bGNX/f8zrSfwA9822xgAFGtDdta+8HGt/euObve16z/pHtADyuATZ3i1HtTdva+4HGtzeu+fue18my/RXXs04e6LZee95LxPUPtK6BxnnWMZCH5z3WP/G+/4G2daBxnm3s1O3vWS43/EsAdOhWjvQfQIeuZquLxfpHtgNoFdqhb7D92f6R3APs0DJvdbGof3fXf6uFEeE3CIARBo3U7GprayUtLU30XzcOrD/bn/rn+8/fP/7+u7H/i9U6EwBjJc3nIIAAAggggAACDhEgADpkQ7AYCCCAAAIIIIBArAQIgLGS5nMQQAABBBBAAAGHCBAAHbIhWAwEEEAAAQQQQCBWAgTAWEnzOQgggAACCCCAgEMECIAO2RAsBgIIIIAAAgggECsBAmCspKP4Oe+8846ceuqp5okDTzzxhDQ1NUXx05w169zcXDnzzDO9P3vvvbd8//33zlrIKC/N6tWr5dJLLzXb//TTT5ft27dH+ROdNfuOHTtKly5dTA2ogxuH6upqOfbYY+WZZ55x1eqXl5fLb3/7W7PtTzvtNBkwYICr1r+oqEguueQS893X78CIESNctf66sjfeeKMcfPDBcsstt7hu3W1XmABoKxjn9ps3b5bjjz9eampqpKGhQS644AKZNWtWnJcqPh9fVVUlhx12mOsC0MUXXyxZWVkGfcuWLVJfXx+fDRCnT9UAqNvezUP37t3l9ttvd10A1L95Gn510P/4dOrUScrKylxTChs2bJBFixaZ9d24caMcddRRrvv7l5mZKT/++CMBMIyqJwCGgeakJhoA9X/++j9hDYHnnnuuFBQUOGkRY7YsQ4cONZ1gzD7QAR+Uk5Mjl112mQOWJH6L4PYAmJeXJzfffLMMGjTIdQHQt+r0Pz9aC6Wlpb6jXfX7GWecIbpX0G2DhkD2AIa+1QmAoZuF1GLatGly7bXXypFHHin6aKNAhyf12Yj6h2uvvfaS8847T+bOnRvSZ7z33ntywAEHyCGHHCLdunULqW20J47F+nvW4YYbbpBvv/3W89IR/0Z7/bWedL21xn7zm99I7969HbHenoWI9vrr5+hen7PPPlvOOeccGTJkiOejHfFvLNb/+uuvl5UrVzoyAMZi/fU/vxp89tlnnxbPXY53EcRi/T3ruGDBAtHD4E4aYrX+BMDwtjoBMDy3oFulp6dLjx495LvvvgsYAL/++mvZc8895bPPPpPly5fLQw89ZM5nKCkp8X6GnuOmX+zmP+vXr5etW7fKlVdeKfq/3x07dpjzQfRL55Qh2uvvWU99dmaHDh3MXlDPOCf8G+31HzlypBx66KHmf/362Cw9B27ChAlOWHWzDNFef/2QdevWmc/Sw2F6LuySJUtcs/6jRo2Sf/3rX2Z9nbgHMBbb37OxN23aZE6B0X+dMsRq/fXvv9b+zJkznbLqZjlitf4EwPA2OwEwPLewWgXaA6h7/B577DHv/BobG815HK+++qp3XFu/6Em/jz76qHeSN954Q15//XXvayf9Eo3196zf4MGD5a677vK8dOS/0Vh/Pd9T/wPgGXT7648Th2isf/P11DCkQciJQzTWPzU1VY455hhzBEHPfz3wwAOlZ8+eTlz9gP8Btv3713xFH3nkEdH/FDlxiMb21/XU//j94Q9/EP0b6OQhWuuv60wADG/LEwDDcwurVfMvQF1dney+++4tDgvfc889ood1ghlmz54tZ511lvcikKuvvlp0r4ATh2isv2c99RCongjs5CEa668XfOj21z3B+p8HdRg9erQjGaKx/nrif2VlpVlfvRBEDwXPmzfPNevvu6JO3APou3zR2P66t8+z/SsqKsxRkqVLl/p+rGN+j8b66x0f7rzzTklLS3PMera2INFYf89nEQA9EqH9SwAMzctq6uZfAD2Eq+OaX7X773//25wLGOyH6RWAJ598sjkE4OTbwERr/fUP/xFHHCEaqJ08RGv99TCL3v5FTxF4+umnHUsQjfVftWqVOf9LzwHT9e/Tp4+r1t93ZRMtAEbi75+eL62nyOj219ugfPTRR74kjvo9GvU/ffp02W233by3wVKLRAnAkdj+uoH1IrjDDz/cnAN69NFHt+hPHVUEDlsYAmAMN0g0/gDEcPGtP4r1978IKFJ/AK03TIxmwPZn+/teBEf9R2YHQIy+vtYf4/bvvzVgFGZAAIwCamuzbP4FiMQh4NY+y4njWX//AMD2tz8Fwol13toyUf/Uv28A5vvvru9/a38X4jmeABhD/eYdgH60ngT9+OOPe5dCz+PS3djBXgTibZgAv7D+/h0g25/65/vP3z/+/ruj/3NiF00AjPJW0RPT9U7t+qMBSB/bpr8XFhaaT9bbwOj9/z7//HP56aef5OGHHza3gXHSrQxsiFh/tj/1z/efv3/8/Xdj/2fTd8aiLQEwysp6dZIWfvOfe++91/vJ77//vnmah94PUPcIzJkzx/teov/C+rP9m9e+vqb++f57/rbx94+///o0q2Ts/zw17tR/CYBO3TIsFwIIIIAAAgggECUBAmCUYJktAggggAACCCDgVAECoFO3DMuFAAIIIIAAAghESYAAGCVYZosAAggggAACCDhVgADo1C3DciGAAAIIIIAAAlESIABGCZbZIoAAAggggAACThUgADp1y7BcCCCAAAIIIIBAlAQIgFGCZbYIIIAAAggggIBTBQiATt0yLBcCCCCAAAIIIBAlAQJglGCZLQIIJIZAx44d5d13302MhWUpEUAAgQgJEAAjBMlsEECgdQF99NsNN9zQ+gRxfGfz5s1SXV0dxyVo+6OdbNf2kvMuAgg4WYAA6OStw7IhkCQC8QgxO3fudLResMsXDztHw7FwCCAQEQECYEQYmQkCCLQl0F6IWbZsmVx11VWy3377yRFHHCF33323lJaWemc5btw4ufDCC+Wggw6SQw89VK655hopKCjwvr9mzRpJSUmRr7/+Wi6++GLZa6+9ZNCgQeL53DfffFP+53/+x7R99NFHxTd8NT8ErPMZOHCg3HjjjbLPPvvICSecID/88IP3s/QXfa3j9XMuvfRS+fzzz83nl5eX+03n+0Ln269fP7nuuutk3333lbS0NGloaJAHHnhAOnXqJHvvvbeceOKJ0qdPH28znUbb+f5kZmaa94uKiuS2224zJocccohcf/31og4MCCCAQDACBMBglJgGAQSsBDxBLNBMNDR16NBBunXrJitWrJDs7Gy54oorpGvXrt7Jv/nmG/n2228lPz9fFi1aZEJUly5dpLGx0UzjCYAapHS61atXy4YNG0wAPPDAA+Xvf/+7mffo0aNN+BowYIB33oEC4DHHHCNfffWV+bx//OMfsv/++8uWLVtMG533HnvsIf/6178kNzdXhg0bJkcffXRQAVDD7WeffSarVq2SwsJCE0RfeOEFmT9/vlnmIUOGmOUbPny4+ayqqiq5/fbbTTjeuHGj6E9dXZ1pd8opp5jwuHTpUvnpp5/kL3/5i5x00knmfe/K8QsCCCDQigABsBUYRiOAQOQE2gqAL730klx55ZV+H1ZcXGwC1cqVK/3Ge17o3kHdK6Z7DnXwBEDfvWc6Xj9XA57uafMMutfsjjvu8Lw07/teBKLzfe6557zvb9++3XyW7oXU4dlnn5XTTz/d+77+0qNHj6AC4FNPPeXXLtCLxx57TG655RbvW4HsvvzySxP2mpqavNNpMNQ9lhkZGd5x/IIAAgi0JkAAbE2G8QggEDGBQCHGM/Nbb73V7FHTw7++PxrE0tPTzWR5eXly5513ynHHHScHHHCAmU7fHzt2rHnfEwBnzJjhma35Vz/36quv9hune/R89y4G2gM4YsQIvza6F/GLL74w4/TQ8P333+/3vh4S1uVp7xCw7uFrPnzwwQdy9tlny+GHH27WS/cunnvuud7JAtnp3sfdd9/dz0vtdtttN3OY2duYXxBAAIFWBAiArcAwGgEEIicQKMR45q7n/t18883mcKse4vX90b1vOuihTd1LOGnSJHO4MycnxwSu77//3rzvCYB6eNh3CPS5Tz75pFxyySXeyQIFQM98PRPpuYd6TqEONgGw+Xz18LGe+/fhhx+aQ9+67g8//LCceeaZno/2nsfoHSFiDmmfd955flYet4qKCt9J+R0BBBAIKEAADMjCSAQQiKRAoCDmmX/37t1NwKuvr/eM8vu3rKzMhL2srCzv+OnTp8ctAOohYD3/0HfQQ8bB7AFsHgAff/xx+eMf/+g7K7nsssv8AuBDDz0k1157rd80eg6jXvixbds2v/G8QAABBIIVIAAGK8V0CCAQtoAGQL1aVvfQ+f7olazr1683F4HooeB58+aZq3vHjx8v9913nzl3Ty/0OOyww8yVwbqXa/LkyeYQqQYuT6CK5R5Az0Ug//nPf0TPUdQLNvSiEV2etva++S6vB7Jv376ih5d1fXVeGiT1te8ewN69e8uxxx5rLjjRcx/1Cma9b2Hnzp2NqQZjXSa9OviJJ54QPX+SAQEEEGhPgADYnhDvI4CAtYAGQA1AzX8efPBBM289x++mm26Sgw8+2FzIcPLJJ4teMOG5yGHixImiV73qbVfOOOMMmTp1qplXPAKgLnDz28D079/fLE9NTU2rVoECYG1trQm6eohZ1/2RRx6R1NRUvwCoN6rWq6L1SmSdh+c2MHpF8D333GPOHVSX448/XnRvIXsFW90EvIEAAj4CBEAfDH5FAAEEwhF4+eWXzV7AcNrSBgEEEIiHAAEwHup8JgIIJLSAXrShh6v1fn6DBw82N2PWW8EwIIAAAokiQABMlC3FciKAgGME9PD0kUceaQ5J67l4vXr1ktYuYnHMQrMgCCCAgI8AAdAHg18RQAABBBBAAAE3CBAA3bCVWUcEEEAAAQQQQMBHgADog8GvCCCAAAIIIICAGwQIgG7YyqwjAggggAACCCDgI0AA9MHgVwQQQAABBBBAwA0C/w+ELQeExqjNywAAAABJRU5ErkJggg==) # + [markdown] id="tn1RV-jfOjt1" # # `benchmark` # # # + [markdown] id="rsmTl5zfwjM3" # You can try to speed your system by setting `benchmark=True`, which enables cudnn.benchmark. This flag is likely to increase the speed of your system if your input sizes don’t change. This flag makes cudnn auto-tuner look for the optimal set of algorithms for the given hardware configuration. This usually leads to faster runtime. # But if your input sizes changes at each iteration, then cudnn will benchmark every time a new size appears, possibly leading to worse runtime performances. # + id="dWr-OCBgQCeb" trainer = pl.Trainer(gpus=1, benchmark=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="qwAvSKYGa24K" # # `deterministic` # # # + [markdown] id="tl5mfmafwmat" # PyTorch does not guarantee reproducible results, even when using identical seeds. To guarentee reproducible results, you can remove most of the randomness from your process by setting the `deterministic` flag to True. # # Note that it might make your system slower. # + id="Mhv5LZ3HbNCK" trainer = pl.Trainer(gpus=1, deterministic=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="u_5eJSvTf60f" # # Exploding and vanishing gradients # + [markdown] id="B6drjh4pq6Jv" # ## track_grad_norm # # You can debug your grad norm to identify exploding or vanishing gradients using the `track_grad_norm` flag. # # Set value to 2 to track the 2-norm. or p to any p-norm. # + id="2taHUir8rflR" # track the 2-norm trainer = pl.Trainer(track_grad_norm=2) trainer.fit(model, train_loader, val_loader) # + [markdown] id="3vHKxmruk62f" # May be set to ‘inf’ infinity-norm. # + id="g7TbD6SxlAjP" trainer = pl.Trainer(track_grad_norm='inf') trainer.fit(model, train_loader, val_loader) # + [markdown] id="TcMlRe7ywpe6" # ## Gradient clipping # # # Exploding gradients refer to the problem that the gradients get too large and overflow in training, making the model unstable. Gradient clipping will ‘clip’ the gradients or cap them to a Threshold value to prevent the gradients from getting too large. To avoid this, we can set `gradient_clip_val` (default is set to 0.0). # # [when to use it, what are relevant values] # + id="jF9JwmbOgOWF" trainer = pl.Trainer(gradient_clip_val=0.1) trainer.fit(model, train_loader, val_loader) # + [markdown] id="ggb4MkkQrr1h" # # truncated_bptt_steps # # # + [markdown] id="s1Iu6PyAw9_r" # If you have a large recurrent model, you can use truncated_bptt_steps flag to split up the backprop over portions of the sequence. This flag will automatically truncate your batches and the trainer will apply Truncated Backprop to it. # # Make sure your batches have a sequence dimension. # # Lightning takes care of splitting your batch along the time-dimension. # ``` # # we use the second as the time dimension # # (batch, time, ...) # sub_batch = batch[0, 0:t, ...] # Using this feature requires updating your LightningModule’s pytorch_lightning.core.LightningModule.training_step() to include a hiddens arg with the hidden # # # Truncated back-propagation through time # def training_step(self, batch, batch_idx, hiddens): # # hiddens are the hiddens from the previous truncated backprop step # out, hiddens = self.lstm(data, hiddens) # # return { # "loss": ..., # "hiddens": hiddens # remember to detach() this # } # ``` # + id="WiTF1VMtruMU" # backprop every 5 steps in a batch trainer = pl.Trainer(truncated_bptt_steps=5) trainer.fit(model, train_loader, val_loader) # + [markdown] id="8XI_kEWkS-nT" # To modify how the batch is split, override pytorch_lightning.core.LightningModule.tbptt_split_batch(): # # ``` # class LitMNIST(LightningModule): # def tbptt_split_batch(self, batch, split_size): # # do your own splitting on the batch # return splits # ``` # # + [markdown] id="oLbEmbmupwQ8" # # reload_dataloaders_every_epoch # # + [markdown] id="CLdNGVv9xD_L" # Set to True to reload dataloaders every epoch (instead of loading just once in the beginning of training). # # ``` # # if False (default) # train_loader = model.train_dataloader() # for epoch in epochs: # for batch in train_loader: # ... # # # if True # for epoch in epochs: # train_loader = model.train_dataloader() # for batch in train_loader: # # ``` # + id="10AXthXxp311" trainer = pl.Trainer(reload_dataloaders_every_epoch=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="f513EYl0bmmL" # # Callbacks # # + [markdown] id="2pt7iGh4xNs5" # # Lightning Callbacks are self-contained programs that can be reused across projects. # Callbacks should capture NON-ESSENTIAL logic that is NOT required for your LightningModule to run. Lightning includes some a few built-in callbacks that can be used with flags like early stopping and Model Checkpointing, but you can also create your own callbacks to add any functionality to your models. # # The callback API includes hooks that allow you to add logic at every point of your training: # setup, teardown, on_epoch_start, on_epoch_end, on_batch_start, on_batch_end, on_init_start, on_keyboard_interrupt etc. # # # + [markdown] id="1t84gvDNsUuh" # ## callbacks # # Use **callbacks=** to pass a list of user defined callbacks. These callbacks DO NOT replace the built-in callbacks (loggers or EarlyStopping). # # In this example, we create a dummy callback that prints a message when training starts and ends, using on_train_start and on_train_end hooks. # + id="oIXZYabub3f0" from pytorch_lightning.callbacks import Callback class PrintCallback(Callback): def on_train_start(self, trainer, pl_module): print("Training is started!") def on_train_end(self, trainer, pl_module): print("Training is done.") # a list of callbacks callbacks = [PrintCallback()] trainer = pl.Trainer(callbacks=callbacks) trainer.fit(model, train_loader, val_loader) # + [markdown] id="cNF74CLYfJJu" # # Model checkpointing # # # + [markdown] id="2blgquBrxLtS" # Checkpoints capture the exact value of all parameters used by a model. # # Checkpointing your training allows you to resume a training process in case it was interrupted, fine-tune a model or use a pre-trained model for inference without having to retrain the model. # # Lightning automates saving and loading checkpoints so you restore a training session, saving all the required parameters including: # * 16-bit scaling factor (apex) # * Current epoch # * Global step # * Model state_dict # * State of all optimizers # * State of all learningRate schedulers # * State of all callbacks # * The hyperparameters used for that model if passed in as hparams (Argparse.Namespace) # # By default Lightning will save a checkpoint in the working directory, which will be updated every epoch. # # ### Automatic saving # By default Lightning will save a checkpoint in the end of the first epoch in the working directory, which will be updated every epoch. # + id="XGu0JULrg9l7" # default used by the Trainer trainer = pl.Trainer(default_root_dir=os.getcwd()) trainer.fit(model, train_loader, val_loader) # + [markdown] id="3s9OjkGuhq1W" # To change the checkpoint path pass in **default_root_dir=** # + id="DgdxkrIQhvfw" trainer = pl.Trainer(default_root_dir='/your/path/to/save/checkpoints') trainer.fit(model, train_loader, val_loader) # + [markdown] id="Qyvj_bkWrJiE" # # You can also have Lightning update your checkpoint based on a specific metric that you are logging (using self.log), by passing the key to `monitor=`. For example, if we want to save checkpoint based on the validation loss, logged as `val_loss`, you can pass: # # # ``` # checkpoint_callback = ModelCheckpoint( # filepath=os.getcwd(), # save_top_k=1, # verbose=True, # monitor='val_loss', # mode='min', # prefix='' # ) # ``` # # + id="YzYMivw1rO1O" from pytorch_lightning.callbacks import ModelCheckpoint trainer = pl.Trainer(callbacks=[ModelCheckpoint(monitor='val_loss')]) trainer.fit(model, train_loader, val_loader) # + [markdown] id="5hYs_FV8iDMn" # You can modify the behavior of checkpointing by creating your own callback, and passing it to the trainer. # You can control # * filepath- where logs are saved # * save_top_k- save k top models # * verbose # * monitor- the metric to monitor # * mode # * prefix # # # + id="Tb1K2VYDiNTu" from pytorch_lightning.callbacks import ModelCheckpoint # DEFAULTS used by the Trainer checkpoint_callback = ModelCheckpoint( filepath=os.getcwd(), save_top_k=3, verbose=True, monitor='val_loss', mode='min', prefix='', ) trainer = Trainer(callbacks=[checkpoint_callback]) trainer.fit(model, train_loader, val_loader) # + [markdown] id="YKhZ6xRojJcl" # You can disable checkpointing it by passing # # # + id="Yt8zd2ZFjOXX" trainer = Trainer(checkpoint_callback=False) # + [markdown] id="HcLy8asCjrj9" # ### Manual saving # # You can manually save checkpoints and restore your model from the checkpointed state. # # + id="kZSkMJf0jR4x" trainer.fit(model) trainer.save_checkpoint("example.ckpt") new_model = LitAutoEncoder.load_from_checkpoint(checkpoint_path="example.ckpt") # + [markdown] id="X2d9cjVPj7CP" # ### Checkpoint Loading # To load a model along with its weights, biases and module_arguments use following method: # # # + id="BpAFfg5zkFmH" model = LitAutoEncoder.load_from_checkpoint(PATH) print(model.learning_rate) # prints the learning_rate you used in this checkpoint model.eval() y_hat = model(x) # + [markdown] id="jTQ3mxSJkhFN" # But if you don’t want to use the values saved in the checkpoint, pass in your own here # + id="IoMcOh9-kfUP" class LitAutoEncoder(LightningModule): def __init__(self, in_dim, out_dim): super().__init__() self.save_hyperparameters() self.l1 = nn.Linear(self.hparams.in_dim, self.hparams.out_dim) # + [markdown] id="ITPVY8mNknut" # you can restore the model like this # # # + id="H7XeRJzVkuY8" # if you train and save the model like this it will use these values when loading # the weights. But you can overwrite this LitAutoEncoder(in_dim=32, out_dim=10) # uses in_dim=32, out_dim=10 model = LitAutoEncoder.load_from_checkpoint(PATH) # + id="14WwGpnVk0a4" # uses in_dim=128, out_dim=10 model = LitAutoEncoder.load_from_checkpoint(PATH, in_dim=128, out_dim=10) # + [markdown] id="bY5s6wP_k1CU" # # # ## Restoring Training State (resume_from_checkpoint) # If your training was cut short for some reason, you can resume exactly from where you left off using the `resume_from_checkpoint` flag, which will automatically restore model, epoch, step, LR schedulers, apex, etc... # + id="9zfhHtyrk3rO" model = LitAutoEncoder() trainer = pl.Trainer(resume_from_checkpoint='some/path/to/my_checkpoint.ckpt') # automatically restores model, epoch, step, LR schedulers, apex, etc... trainer.fit(model) # + [markdown] id="xkKdvALFsmT2" # ## weights_save_path # You can specify a directory for saving weights file using `weights_save_path`. # # (If you are using a custom checkpoint callback, the checkpoint callback will override this flag). # + id="9OwHHFcCsrgT" # save to your custom path trainer = pl.Trainer(weights_save_path='my/path') trainer.fit(model, train_loader, val_loader) # + id="PbNtlJ9Wsscf" # if checkpoint callback used, then overrides the weights path # **NOTE: this saves weights to some/path NOT my/path checkpoint = ModelCheckpoint(filepath='some/path') trainer = pl.Trainer( callbacks=[checkpoint], weights_save_path='my/path' ) trainer.fit(model, train_loader, val_loader) # + [markdown] id="uDdxCuyHdWQt" # # Early stopping # # + [markdown] id="fqAy3ihRxTfR" # The EarlyStopping callback can be used to monitor a validation metric and stop the training when no improvement is observed, to help you avoid overfitting. # # To enable Early Stopping you can init the EarlyStopping callback, and pass it to `callbacks=` trainer flag. The callback will look for a logged metric to early stop on. # # # + id="lFx976CheH93" from pytorch_lightning.callbacks.early_stopping import EarlyStopping trainer = pl.Trainer(callbacks=[EarlyStopping('val_loss')]) trainer.fit(model, train_loader, val_loader) # + [markdown] id="MwpJfTvjeOwF" # You can customize the callback using the following params: # # + id="V6I9h6HteK2U" from pytorch_lightning.callbacks.early_stopping import EarlyStopping early_stop_callback = EarlyStopping( monitor='val_accuracy', min_delta=0.00, patience=3, verbose=False, mode='max' ) trainer = pl.Trainer(callbacks=[early_stop_callback]) trainer.fit(model, train_loader, val_loader) # + [markdown] id="7TAIerPYe_Q1" # The EarlyStopping callback runs at the end of every validation epoch, which, under the default configuration, happens after every training epoch. However, the frequency of validation can be modified by setting various parameters on the Trainer, for example check_val_every_n_epoch and val_check_interval. It must be noted that the patience parameter counts the number of validation epochs with no improvement, and not the number of training epochs. Therefore, with parameters check_val_every_n_epoch=10 and patience=3, the trainer will perform at least 40 training epochs before being stopped. # + [markdown] id="VoKrX2ENh9Fg" # # Logging # + [markdown] id="-CQTPKd7iKLm" # Lightning has built in integration with various loggers such as TensorBoard, wandb, commet, etc. # # # You can pass any metrics you want to log during training to `self.log`, such as loss or accuracy. Similarly, pass in to self.log any metric you want to log during validation step. # # These values will be passed in to the logger of your choise. simply pass in any supported logger to logger trainer flag. # # # # Use the as`logger=` trainer flag to pass in a Logger, or iterable collection of Loggers, for experiment tracking. # # # # # + id="ty5VPS3AiS8L" from pytorch_lightning.loggers import TensorBoardLogger # default logger used by trainer logger = TensorBoardLogger( save_dir=os.getcwd(), version=1, name='lightning_logs' ) trainer = pl.Trainer(logger=logger) trainer.fit(model, train_loader, val_loader) # + [markdown] id="jc5oWNpoiuuc" # Lightning supports the use of multiple loggers, just pass a list to the Trainer. # # # + id="BlYwMRRyivp_" from pytorch_lightning.loggers import TensorBoardLogger, TestTubeLogger logger1 = TensorBoardLogger('tb_logs', name='my_model') logger2 = TestTubeLogger('tb_logs', name='my_model') trainer = pl.Trainer(logger=[logger1, logger2]) # + [markdown] id="a7EyspQPh7iQ" # ## flush_logs_every_n_steps # # Use this flag to determine when logging to disc should happen. # + id="Em_XvsmyiBbk" trainer = pl.Trainer(flush_logs_every_n_steps=100) trainer.fit(model, train_loader, val_loader) # + [markdown] id="_vDeKE98qsl1" # ## log_every_n_steps # How often to add logging rows (does not write to disk) # # # + id="HkqD7D_0w1Tt" trainer = pl.Trainer(log_every_n_steps=1000) trainer.fit(model, train_loader, val_loader) # + [markdown] id="9uw0gfe422CT" # # info logging # + [markdown] id="dQXpt0aatDGo" # ### default_root_dir # # --- # # # # Default path for logs and weights when no logger or pytorch_lightning.callbacks.ModelCheckpoint callback passed. On certain clusters you might want to separate where logs and checkpoints are stored. If you don’t then use this argument for convenience. Paths can be local paths or remote paths such as s3://bucket/path or ‘hdfs://path/’. Credentials will need to be set up to use remote filepaths. # + [markdown] id="CMmID2Bts5W3" # ## weights_summary # Prints a summary of the weights when training begins. Default is set to `top`- print summary of top level modules. # # Options: ‘full’, ‘top’, None. # + id="KTl6EdwDs6j2" # print full summary of all modules and submodules trainer = pl.Trainer(weights_summary='full') trainer.fit(model, train_loader, val_loader) # + id="R57cSLl9w9ma" # don't print a summary trainer = Trainer(weights_summary=None) trainer.fit(model, train_loader, val_loader) # + [markdown] id="bSc2hU5AotAP" # # progress bar # + [markdown] id="GgvbyDsBxcH6" # ## process_position # # Orders the progress bar. Useful when running multiple trainers on the same node. # # (This argument is ignored if a custom callback is passed to callbacks) # # # + id="6ekz8Es8owDn" # default used by the Trainer trainer = pl.Trainer(process_position=0) trainer.fit(model, train_loader, val_loader) # + [markdown] id="itivQFgEphBU" # ## progress_bar_refresh_rate # # How often to refresh the progress bar (in steps). In notebooks, faster refresh rates (lower number) is known to crash them because of their screen refresh rates, so raise it to 50 or more. # + id="GKe6eVxmplL5" # default used by the Trainer trainer = pl.Trainer(progress_bar_refresh_rate=1) trainer.fit(model, train_loader, val_loader) # + id="8rDHJOJbxNtf" # disable progress bar trainer = Trainer(progress_bar_refresh_rate=0) trainer.fit(model, train_loader, val_loader) # + [markdown] id="NCNvYLwjpWne" # # profiler # + id="pRknrG_zpY6M" # to profile standard training events trainer = pl.Trainer(profiler=True) trainer.fit(model, train_loader, val_loader) # + [markdown] id="Ji6aWpU73kMM" # You can also use Lightning AdvancedProfiler if you want more detailed information about time spent in each function call recorded during a given action. The output is quite verbose and you should only use this if you want very detailed reports. # # # + id="layG55pt316C" from pytorch_lightning.profiler import AdvancedProfiler trainer = Trainer(profiler=AdvancedProfiler()) trainer.fit(model, train_loader, val_loader) # - # <code style="color:#792ee5;"> # <h1> <strong> Congratulations - Time to Join the Community! </strong> </h1> # </code> # # Congratulations on completing this notebook tutorial! If you enjoyed this and would like to join the Lightning movement, you can do so in the following ways! # # ### Star [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) on GitHub # The easiest way to help our community is just by starring the GitHub repos! This helps raise awareness of the cool tools we're building. # # * Please, star [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) # # ### Join our [Slack](https://join.slack.com/t/pytorch-lightning/shared_invite/zt-f6bl2l0l-JYMK3tbAgAmGRrlNr00f1A)! # The best way to keep up to date on the latest advancements is to join our community! Make sure to introduce yourself and share your interests in `#general` channel # # ### Interested by SOTA AI models ! Check out [Bolt](https://github.com/PyTorchLightning/pytorch-lightning-bolts) # Bolts has a collection of state-of-the-art models, all implemented in [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) and can be easily integrated within your own projects. # # * Please, star [Bolt](https://github.com/PyTorchLightning/pytorch-lightning-bolts) # # ### Contributions ! # The best way to contribute to our community is to become a code contributor! At any time you can go to [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) or [Bolt](https://github.com/PyTorchLightning/pytorch-lightning-bolts) GitHub Issues page and filter for "good first issue". # # * [Lightning good first issue](https://github.com/PyTorchLightning/pytorch-lightning/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) # * [Bolt good first issue](https://github.com/PyTorchLightning/pytorch-lightning-bolts/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) # * You can also contribute your own notebooks with useful examples ! # # ### Great thanks from the entire Pytorch Lightning Team for your interest ! # # <img src="https://github.com/PyTorchLightning/pytorch-lightning/blob/master/docs/source/_static/images/logo.png?raw=true" width="800" height="200" />
notebooks/05-trainer-flags-overview.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="A5BABQHx3ep6" # # ## **Data Analytics in Health Care and Connected Care** # --- # --- # *Practical Session I: Introduction to Data Analytics in Healthcare - understanding and working with healthcare data* # # # --- # --- # The aims of this practical session are: (a) to make you understand the importance of the information found in electronic health records (EHR); (b) gain insights in performing data analysis using [Python](https://www.python.org/) programming language; (c) complete the CITI “Data or Specimens Only Research” course related with ethics in healthcare. During all the practical sessions, you should use ['Google Colab'](https://colab.research.google.com/notebooks/intro.ipynb#recent=true) cloud service to run your code (basic instructions how to get started are found [here](https://colab.research.google.com/notebooks/welcome.ipynb)). All practical sessions are graded. You must work in groups of two students and submit (only one submission) the completed notebook of the first practical session in Canvas by March 13th, 23:59:59 (GMT+1). # # --- # --- # # *Lecturer/s: <NAME> (<EMAIL>), <NAME> (<EMAIL>), <NAME> (<EMAIL>)* # # *Teaching assistant/s: <NAME>(<EMAIL>), <NAME> (<EMAIL>), <NAME> (<EMAIL>)* # # + id="KvdwO1uaC6gC" student1_full_name = str(input('Enter your full name: ')) student1_id = int(input('Enter your student ID: ')) student2_full_name = str(input('Enter your full name: ')) student2_id = int(input('Enter your student ID: ')) # + [markdown] id="4_zaHFgpIHT2" # --- # --- # #Electronic Health Records (EHR) # --- # # --- # # # > As already seen during the lecture/s, EHRs contain an enormous amount of information (usually available in an unstructured format/free text). While humans can read the document and easily get the information they need, using their data for analysis or machine learning without structuring or preprocessing them firstly, is challenging. Considering examples found [here](https://www.mtsamples.com/index.asp) and what you saw/learned during lectures, please list what information is usually written/found there and some possible research use-cases using the information we get from them. # # # # --- # --- # + [markdown] id="2IEzC4yfK6bp" # # > Info inside an EHR # # * List item # * List item # * ... # # > Possible research use-cases using EHR information: # # * List item # * List item # * .... # # # + [markdown] id="hQuhz8U-2klT" # --- # --- # #Healthcare data analysis using Python # --- # --- # To complete this part of the lab, you should use the excel files shared in Canvas ('noteevents.xlsx' and 'patients.xlsx'). The 'noteevents.xlsx' file, consists of four columns: subject_id (the patient identifier), chartdate (date when the note was created), category (what is the type of the note, e.g. urology, dentistry, orthopedic) and text (the EHR text portion of the note). The other excel file 'patients.xlsx', contains very basic structured information for patients (columns: subject_id (the patient identifier), gender (male or female), dob (date of birth)). You will be performing some basic analysis (using Python) which will help you to better understand the data available. To work with the excel files, you should use [pandas library](https://pandas.pydata.org/docs/getting_started/overview.html). For plotting, you are allowed to use [matplotlib](https://matplotlib.org/)/[seaborn](https://seaborn.pydata.org/)/[bokeh](https://bokeh.org//). # # --- # + id="WUqsX5NP15YI" #import libraries import numpy as np, pandas as pd, seaborn as sns, matplotlib.pyplot as plt from datetime import datetime, date import xlrd # + [markdown] id="TGQti-iXWrsg" # ##Basic analysis on patients using Python # # Perform some basic statistics on the 'patient.xlsx' file. # # * Check if there are empty/NaN values on the dataframe. # * Find out if there is a gender balance among our patients. # * Plot the gender occurrencies. # * Add a new column 'age' in the dataframe. The age of each patient can be computed from 'dob' column. # + id="KnUiRniAFYdY" #read 'patient.xlsx' file into a DataFrame. df1 = pd.read_excel('patients.xlsx', sheet_name='Sheet1') print(df1.head(10)) # - #check if there are empty/NaN values check_empty = df1.empty check_empty #count and print the occurencies of male and female patients df1['gender'].value_counts() #plot their occurencies using one of the specified plotting libraries sns.countplot(x='gender',data=df1) #compute age from 'dob' column: # --> (a) use to_datetime() method to convert 'dob' to datetime format datetime_format = pd.to_datetime(df1["dob"]) # --> (b) create a function that returns the age from 'dob' def age(val): a = (pd.to_datetime('now') - df1['dob']).astype('<m8[Y]') return a # --> (c) apply the function to the column 'dob' df1['age'] = age(df1['dob']) df1.head() # + [markdown] id="xf_DvWHyfsez" # ## Basic data analysis on EHR information using Python # # In this part, you will analyse the EHR information found in 'noteevents.xlsx' file. # # * Find out how many distinct categories are found in 'notevents.xlsx' file. # * Merge noteevents and patient dataframe based on patient_id. # * Using pandas groupby() method print the mean age per gender. # * Filter the dataframe to return information only for male patients whose age is more than 50 years old. # * Plot which category has the highest amount of requests and this corresponding amount per gender. # # # + id="q4cxCan6hzQ9" #read 'noteevents.xlsx' file into a DataFrame. df2 = pd.read_excel('noteevents.xlsx', sheet_name='Sheet1') df2.head(10) # - #print the unique values of 'category' column print(df2['category'].unique()) #merge noteevents and patient dataframe based on the patient_id merged_data = pd.merge(df1,df2, on='subject_id') merged_data #groupby() to show the mean age per gender gk = merged_data.groupby('gender') gk.age.mean() #filter the dataframe to return information only for patients whose age is more than 50 years old. merged_data[(merged_data.age>50)] #plot which category has the highest amount of requests and this corresponding amount per gender gk['category'].value_counts() category_wise_size = merged_data.groupby(["category"],as_index=False)[['subject_id']].count().sort_values(by=['subject_id'],ascending=False) category_with_max_requests = category_wise_size.iloc[0,0] gender_vise_data = merged_data[(merged_data.category == category_with_max_requests)].groupby('gender')['subject_id'].count() gender_vise_data.plot(kind='bar') # + [markdown] id="2RIAtvipgJKU" # --- # --- # #Requesting access to MIMIC-III # --- # # --- # # # > During the first exercise session, all students (from both BME and MACs program) will need to complete the CITI “Data or Specimens Only Research” course which will can take 2.5 hours approximately. All the knowledge you will learn while completing the report will help you to understand better the importance of ethics, privacy, confidentiality etc in health information systems. Each group, must insert in the cell below a screenshot of your CITI completion report (each student should do this individually and independently, screenshots from both students should be attached below). Students enrolled in BME master program, in addition will need to request access to MIMIC-III dataset developed by the MIT Lab. This database includes clinical notes, demographics, vital signs, laboratory tests and more which you will be using during some of the lab sessions or/and in your project. The dataset can not be downloaded directly, but one needs to submit a request first — which is usually approved within a couple of days. All the required information on how to request access can be found [here](https://mimic.physionet.org/gettingstarted/access/). Detailed information about each step to follow can be found in this [link](https://towardsdatascience.com/getting-access-to-mimic-iii-hospital-database-for-data-science-projects-791813feb735). You will need to attach the CITI completion report during your request submission. After succesfully submitting your request, you should recieve an email with subject "PhysioNet credentialing application notification" from PhysioNet confirming that you have succesfuly submitted your request. In addition to the CITI completion report, you must insert in the cell below a screenshot of this confirmation email to show that you already submitted the request to get access to the database (both students should submit!). # # --- # - from IPython.display import Image img1 = 'img1.png' Image(url=img1, width=400, height=400,) img2 = 'img2.png' Image(url=img2, width=400, height=400,)
Health Information Analysis/WPO_1/Practical_session_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/RajeevAtla/N2E-Python/blob/main/Python_Logic.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="I4G-dOM5NENP" outputId="ea701349-9471-45d1-bf06-94023fdc0500" k = int(input()) # + colab={"base_uri": "https://localhost:8080/"} id="cEl0a4pajVa8" outputId="be680dca-eb0b-4f7d-b494-43f1adf50ae7" int("10") # + id="-gWamRfJVTLy" k=3 # + id="6AXa1vTQVUJW" if k == 1: print(2) elif k == 3: print(9) elif k == 9: print(10) else: print(5) # NO SWITCH STATEMENTS # + colab={"base_uri": "https://localhost:8080/"} id="PnVjYjRulioK" outputId="8e98ad90-80d9-4bd8-e39f-4a34d9c8ae43" x = 50 y = 10 print((x==90) and (y==90)) # + colab={"base_uri": "https://localhost:8080/"} id="_NwI8i5WmFDc" outputId="6c91f91e-a179-4a85-8d3d-c1210fff9ce5" x = False print(not x) # + colab={"base_uri": "https://localhost:8080/"} id="Bic_M6qCWrNg" outputId="4b6c0ed8-c5c8-445c-f01e-572770a20a12" for i in range(5): print(i) # range(5) = (0, 1, 2, 3, 4) # range(n) = (0, 1, ..., n-1) # + colab={"base_uri": "https://localhost:8080/"} id="jtBnIM9MX6Sb" outputId="566adedf-89e1-4064-c549-e3a679054f7f" n = 10 while(n > 0): print(n) n -= 1 # + id="XibgDSXaqE1m" n = 10 n += 1
Python_Logic.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %load_ext autoreload # %autoreload 2 import molsysmt as msm # # Copy h5file = msm.demo['pentalanine']['traj.h5'] molecular_system = msm.convert(h5file, to_form='molsysmt.MolSys') msm.info(molecular_system) molecular_system_2 = msm.copy(molecular_system) msm.info(molecular_system_2) # Are both systems different python objects? id(molecular_system)!= id(molecular_system_2) # Are both molecular systems equal? msm.compare(molecular_system, molecular_system_2, comparison='all', rule='A_eq_B') # The method works also with systems in files. In this case `msm.copy()` accepts a second input argument: `output_filepath`. msm.copy(h5file, output_filename='pentalanine_copy.h5')
docs/contents/user/tools/basic/copy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd df = pd.read_csv('icu.csv') df.shape df x = df.iloc[:,1:-1].values y = df.iloc[:,-1].values # + from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [0])],remainder='passthrough') x=np.array(columnTransformer.fit_transform(x)) columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [7])],remainder='passthrough') x=np.array(columnTransformer.fit_transform(x)) # - from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = .25,random_state = 0) # + from sklearn.preprocessing import StandardScaler sc = StandardScaler() x_train = sc.fit_transform(x_train) x_test = sc.fit_transform(x_test) # - # # DT # + from sklearn.tree import DecisionTreeClassifier classifier1 = DecisionTreeClassifier(random_state = 0, criterion='gini') classifier1.fit(x_train, y_train) y_pred_1 = classifier1.predict(x_test) # - from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred_1) print(cm) print(accuracy_score(y_test, y_pred_1)) # + classifier1 = DecisionTreeClassifier(random_state = 0, criterion='entropy') classifier1.fit(x_train, y_train) y_pred_1 = classifier1.predict(x_test) # - from sklearn.metrics import confusion_matrix, accuracy_score cm = confusion_matrix(y_test, y_pred_1) print(cm) print(accuracy_score(y_test, y_pred_1)) # # LR # + from sklearn.linear_model import LogisticRegression classifier2 = LogisticRegression(random_state = 0) classifier2.fit(x_train, y_train) y_pred_2 = classifier2.predict(x_test) # - cm = confusion_matrix(y_test, y_pred_2) print(cm) print(accuracy_score(y_test, y_pred_2)) # # KNN # + from sklearn.neighbors import KNeighborsClassifier classifier3 = KNeighborsClassifier(n_neighbors=15, metric='minkowski', p=2) classifier3.fit(x_train, y_train) y_pred_3 = classifier3.predict(x_test) # - cm = confusion_matrix(y_test, y_pred_3) print(cm) print(accuracy_score(y_test, y_pred_3)) # # SVM # + from sklearn.svm import SVC classifier4 = SVC(kernel='rbf') classifier4.fit(x_train,y_train) y_pred_4 = classifier4.predict(x_test) # - cm = confusion_matrix(y_test, y_pred_4) print(cm) print(accuracy_score(y_test, y_pred_4)) # # NB # + from sklearn.naive_bayes import GaussianNB classifier5 = GaussianNB() classifier5.fit(x_train, y_train) y_pred_5 = classifier5.predict(x_test) # - cm = confusion_matrix(y_test, y_pred_5) print(cm) print(accuracy_score(y_test, y_pred_5)) # # RF # + from sklearn.ensemble import RandomForestClassifier classifier6 = RandomForestClassifier(n_estimators=10) classifier6.fit(x_train,y_train) y_pred_6 = classifier6.predict(x_test) # - cm = confusion_matrix(y_test, y_pred_6) print(cm) print(accuracy_score(y_test, y_pred_6))
mortality_prediction_classification.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- from __future__ import print_function # # Exceptions # # Python raises exceptions when it encounters an error. The idea is that you can trap these exceptions and take an appropriate action instead of causing the code to crash. The mechanism for this is `try` / `except`. Here's an example that causes an exception, `ZeroDivisionError`: a = 1/0 # and here we handle this # + try: a = 1/0 except ZeroDivisionError: print("warning: you divided by zero") a = 1 a # - # another example&mdash;trying to access a key that doesn't exist in a dictionary: dict = {"a":1, "b":2, "c":3} print(dict["d"]) # `KeyError` is the exception that was raised. We can check for this and take the appropriate action instead # + try: val = dict["d"] except KeyError: val = None print(val) # - # To catch and print all exception try: 1/0 except Exception as e: print(e)
day1/06. Python - Exceptions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import warnings; warnings.simplefilter('ignore') import pandas as pd import numpy as np import keras from keras import backend as K from keras.models import Sequential from keras.layers import Dense from sklearn import model_selection import math import tensorflow as tf import horovod.keras as hvd from liz_models import distance_generation from liz_models import weights_generation df = pd.DataFrame() df['distances'] = distance_generation() df['weights'] = weights_generation() df[['distances','weights']].count() df['prices'] = np.array([((df['distances'][i] * df['weights'][i])/100) for i in range(len(df['distances']))]) df.head() hvd.init() config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.visible_device_list = str(hvd.local_rank()) K.set_session(tf.Session(config=config)) batch_size = 128 num_classes = 10 epochs = int(math.ceil(120.0) / hvd.size()) x, x_val, y, y_val = model_selection.train_test_split(df['prices'], df['distances'], test_size=0.2, random_state=42) dlce = lambda l: [v for v in l if v >= 0] x = np.array(dlce(x)) x_val = np.array(dlce(x_val)) y = np.array(dlce(y)) y_val = np.array(dlce(y_val)) opt = keras.optimizers.RMSprop(1.0 * hvd.size()) opt = hvd.DistributedOptimizer(opt) model = Sequential() model.add(Dense(1, input_dim=1)) model.compile(optimizer=opt, loss=keras.losses.mse,metrics=['accuracy']) callbacks = [hvd.callbacks.BroadcastGlobalVariablesCallback(0)] if hvd.rank() == 0: callbacks.append(keras.callbacks.ModelCheckpoint('./checkpoints/checkpoint-{epoch}.h5')) model.fit(x, y, batch_size=batch_size, callbacks=callbacks, epochs=epochs, verbose=1, validation_data=(x_val, y_val)) score = model.evaluate(x_val, y_val, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) print(model.predict(np.array([np.random.randint(10,100) for _ in range(5)]))) model.save_weights('travel-price.hdf5') with open('travel-price.json','w') as f: f.write(model.to_json()) f.close()
private/models/travel-price-prediction-gpu.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Creating clustered polygons from GAEZ ascii grid # # **Original code:** [<NAME>](https://github.com/akorkovelos) <br /> # #### This notebook creates vector polygons covering a clusterized area of interest # # We focus on three types of clusters: # # - Based on admin level 1 # - Based on admin level 2 # - Based on CLEWs clusters (read more about that [here](https://clews-gis.readthedocs.io/en/latest/) # # The latter is the reason we use GAEZ ascii grid as an input; that is, to be able to provide a spatial index to the CLEWs derived clusters, which are defined based on the row, col of that grid. # # The polygons provide higher flexibility in extracting numerical and (especially) categorical raster layer stats, which might come at various spatial resolutions. # # In brief, the process has as follows: # # - First (**Step 1**), we import a sample ascii grid file using rasterio and convert it into a tif. We use a bundle of functions to parse the tif in the form of an array, and use gdal to convert the array to a point vector. Together with the coordinates for each vector point, we extract the equivalent row/col index from the initial file. This allows to create an "id" which can be used as a merger attribute with data that do not have spatial index (e.g. CLEWs clusters). # - Having that in place, we are then (**Step 2**) able to assign cluster name for each vector point based on location and/or id (for the case of CLEWs clusters). # - In **Step 3** we convert the vector points to polygons; there are two suggested approaches here a) based on median lat and b) based on each feature lat/lon. # - In **Step 4**, we do a simple analysis including clipping to the AoI extent and making sure that polygons at the admin borders are assigned to the nearest cluster and are properly attributes (e.g. area). # - Finally, in **Step 5** we calibrate the area of each polygon in order to match the total national area estimated by the admin source. # # After merging and cleaning and final checking the notebook yields a vector polygon layer with the spatial resolution of the input ascii layer. The output layer creates the base for further spatially explicit information extraction! # ## Import necessary modules # + code_folding=[0] # Importing modules # Numerical import numpy as np import pandas as pd import math from math import * # Spatial import geopandas as gpd import rasterio from shapely.geometry import Polygon, Point from shapely.ops import nearest_points import ogr, gdal, osr from pyproj import CRS # System & Other import os #Plotting import matplotlib.pyplot as plt # %matplotlib inline # - # ## Provide country code | type | projection system | clustering method # + code_folding=[] # Country name country_name = "eth" # suggent using UN 3 letter ISO code # Topological classification landlocked = 1 # 1 for landlocked countries (e.g. Ethiopia); 0 for coastal or island countries (e.g. Sri Lanka) ## Coordinate and projection systems crs_WGS84 = CRS("EPSG:4326") # Originan WGS84 coordinate system crs_proj = CRS("EPSG:32637") # Projection system for the selected country -- see http://epsg.io/ for more info clust_method = 3 # choose 1 for admin level 1 clustering, 2 for admin level 2 clustering and 3 for CLEWs clustering # - # ## Provide paths and file names # # Make sure that your root directory has a folder under the same code name; in that folder you should have two sub-directories for "input" and "output". # + code_folding=[0] # Directories ROOT_DIR = os.path.abspath(os.curdir) in_path = os.path.join(ROOT_DIR, country_name + "\\"+ 'input') out_path = os.path.join(ROOT_DIR, country_name + "\\"+ 'output') # ascii file name asci_nm = '{}_data.asc'.format(country_name) # administrative boundaries of the AoI admin0_nm = '{}_adm0.gpkg'.format(country_name) admin1_nm = '{}_adm1.gpkg'.format(country_name) admin2_nm = '{}_adm2.gpkg'.format(country_name) # raster name raster_nm = "{}_data.tif".format(country_name) # vector point name shp_nm = "{}_data.shp".format(country_name) # CLEWs cluster name clust_nm = "{}_clews_clusters.csv".format(country_name) # Final shp product layer out_nm_1 = "{}_vector_admin1_clusters".format(country_name) out_nm_2 = "{}_vector_admin2_clusters".format(country_name) out_nm_3 = "{}_vector_clews_clusters".format(country_name) # - # # # ## Step 1. Provide spatial index to the tabular cluster data # ### Open an ascii grid file | re-write as tif # # This is a pre-requisite step if one starts with an ascii base grid. The step can be omitted if the base grid is already a tiff # + code_folding=[0] # Import ascii and export as tif with rasterio.open(in_path + '\\' + asci_nm) as src: data = src.read(1) # The number defined the band, not that changing data might require change of band #Export ascii as tif for easier processing with rasterio.open(out_path +"\\" + raster_nm, 'w', driver='GTiff', height=data.shape[0], width=data.shape[1], count=data.shape[1], dtype=data.dtype, crs=src.crs, transform=src.transform) as dst: dst.write(data, 3) resolution = src.res[0] # - plt.figure(figsize = (12,12)) plt.imshow(data, cmap='viridis') plt.show() # **Note!** # # Rasterio imports raster files as 2-d arrays. The dimensions of the array are related to the spatial resolution of the imported layer. Individual values can be access in common practice as in numpy arrays. # ### Import tif and transform it to point vector # + code_folding=[0] # Define functions def pixelOffset2coord(raster, xOffset,yOffset): geotransform = raster.GetGeoTransform() originX = geotransform[0]+(geotransform[1]/2) # this is to get the center of each pixel; remove all after + for getting the corners of the pixel originY = geotransform[3]+(geotransform[5]/2) # this is to get the center of each pixel; remove all after + for getting the corners of the pixel pixelWidth = geotransform[1] pixelHeight = geotransform[5] coordX = originX+pixelWidth*xOffset coordY = originY+pixelHeight*yOffset return coordX, coordY def raster2array(rasterfn, band_no): raster = gdal.Open(rasterfn) band = raster.GetRasterBand(band_no) # Be aware of the band you need here array = band.ReadAsArray() return array def array2shp(array,outSHPfn,rasterfn): # max distance between points raster = gdal.Open(rasterfn) geotransform = raster.GetGeoTransform() pixelWidth = geotransform[1] srs = osr.SpatialReference() srs.ImportFromWkt(raster.GetProjection()) # wkbPoint shpDriver = ogr.GetDriverByName("ESRI Shapefile") if os.path.exists(outSHPfn): shpDriver.DeleteDataSource(outSHPfn) outDataSource = shpDriver.CreateDataSource(outSHPfn) outLayer = outDataSource.CreateLayer(outSHPfn, geom_type=ogr.wkbPoint, srs=srs ) featureDefn = outLayer.GetLayerDefn() outLayer.CreateField(ogr.FieldDefn("VALUE", ogr.OFTString)) # array2dict point = ogr.Geometry(ogr.wkbPoint) row_count = array.shape[0] for ridx, row in enumerate(array): if ridx % 10 == 0: print ("{0} of {1} rows processed".format(ridx, row_count)) for cidx, value in enumerate(row): index = str(ridx) + "_" + str(cidx) Xcoord, Ycoord = pixelOffset2coord(raster,cidx,ridx) point.AddPoint(Xcoord, Ycoord) # Create the feature and set values outFeature = ogr.Feature(featureDefn) outFeature.SetGeometry(point) outFeature.SetField("VALUE", str(index)) outLayer.CreateFeature(outFeature) outFeature.Destroy() #outDS.Destroy() print ("\nProcess completed!") def main(rasterfn,outSHPfn, band_no): array = raster2array(rasterfn, band_no) array2shp(array,outSHPfn,rasterfn) # + code_folding=[0] # Provide the input raster and give a name to the output transformed vector raster = out_path + "\\" + raster_nm outSHP = out_path + "\\" + shp_nm # Run the function main(raster,outSHP, band_no=3) # - # ### Import vector point layer into a geo-dataframe # + code_folding=[0] # Create a new geo-dataframe data_gdf = gpd.read_file(out_path + "\\" + shp_nm) # Assign crs data_gdf.crs = crs_WGS84 # - data_gdf.head(3) # **Note!** # # VALUE has been retrieved from the ascii file; it denotes the number of row and column in the initial layer, split by the underscore delimiter. We may use the following function to a) split them into two different columns and b) create a tuple from their combination (this is needed in case we follow the CLEWs clustering approach). # + code_folding=[0] def create_rowcol_columns(df): # Split the Value to rows and columns split = df["VALUE"].str.split("_", n = 1, expand = True) # Drop the VALUE as it has served its purpose df = df.drop(["VALUE"], axis=1) # Add the separate columns back to the dataframe df["row"] = split[0] df["col"] = split[1] # Change dtype of columns from str to int df["row"] = df["row"].astype(np.int) df["col"] = df["col"].astype(np.int) # Create a tuple id to use for merging later on df["id"] = list(zip(df.row, df.col)) return df # - data_gdf = create_rowcol_columns(data_gdf) data_gdf.head(3) # # # ## Step 2. Assign cluster name to points # + code_folding=[0] def cleaning_string_attributes(df, column_name): df[column_name].replace("-", '_', regex=True, inplace=True) df[column_name].replace(" ", '_', regex=True, inplace=True) df[column_name].replace("/", '_', regex=True, inplace=True) df[column_name].replace("'", '_', regex=True, inplace=True) df[column_name].replace("é", 'e', regex=True, inplace=True) df[column_name].replace("î", 'i', regex=True, inplace=True) df[column_name].replace("ï", 'i', regex=True, inplace=True) df[column_name].replace("ô", 'o', regex=True, inplace=True) df[column_name].replace("è", 'e', regex=True, inplace=True) df[column_name].replace("à", 'a', regex=True, inplace=True) df[column_name].replace("", 'NaN', regex=True, inplace=True) df[column_name].fillna(value=np.nan, inplace=True) return df # - # **Note!** # # The admin column names used in the code (e.g. "ADM1_NAME, or "NAME_0) might require changing depending on the source of those layers. # + code_folding=[0] ## Import admin layer accordingly if clust_method == 1: ## Read admin layer as geodataframe admin = gpd.read_file(in_path + "\\" + admin1_nm) admin = admin.to_crs(crs_WGS84) admin = cleaning_string_attributes(admin, "ADM1_NAME") #Spatial join data_gdf_admin = gpd.sjoin(data_gdf, admin[["geometry", "ADM1_NAME"]], op='within').drop(['index_right'], axis=1) data_gdf_admin.rename(columns={'ADM1_NAME': 'cluster'}, inplace=True) # merge datasets on id clustered_GAEZ_gdf = data_gdf.merge(data_gdf_admin, on=["id"], how="left").drop(['id','row_y', 'col_y', "geometry_y"], axis=1) clustered_GAEZ_gdf.rename(columns={'row_x': 'row', 'col_x': 'col', 'geometry_x': 'geometry'}, inplace=True) clustered_GAEZ_gdf = gpd.GeoDataFrame(clustered_GAEZ_gdf, geometry="geometry") elif clust_method == 2: ## Read admin layer as geodataframe admin = gpd.read_file(in_path + "\\" + admin2_nm) admin = admin.to_crs(crs_WGS84) admin = cleaning_string_attributes(admin, "ADM2_NAME") #Spatial join data_gdf_admin = gpd.sjoin(data_gdf, admin[["geometry", "ADM2_NAME"]], op='within').drop(['index_right'], axis=1) data_gdf_admin.rename(columns={'ADM2_NAME': 'cluster'}, inplace=True) # merge datasets on id clustered_GAEZ_gdf = data_gdf.merge(data_gdf_admin, on=["id"], how="left").drop(['id','row_y', 'col_y', "geometry_y"], axis=1) clustered_GAEZ_gdf.rename(columns={'row_x': 'row', 'col_x': 'col', 'geometry_x': 'geometry'}, inplace=True) clustered_GAEZ_gdf = gpd.GeoDataFrame(clustered_GAEZ_gdf, geometry="geometry") elif clust_method == 3: ## Read admin layer as geodataframe admin = gpd.read_file(in_path + "\\" + admin0_nm) admin = admin.to_crs(crs_WGS84) admin = cleaning_string_attributes(admin, "NAME_0") # Import csv as pandas dataframe cluster_data = pd.read_csv(in_path + "\\" + clust_nm) # Create a tuple id to be used for merging cluster_data['id'] = list(zip(cluster_data.row, cluster_data.col)) # merge datasets on id clustered_GAEZ_gdf = data_gdf.merge(cluster_data, on=["id"], how="left").drop(['id','row_y', 'col_y'], axis=1) clustered_GAEZ_gdf.rename(columns={'row_x': 'row', 'col_x': 'col'}, inplace=True) else: print ("Please specify clustering method to proceed") # - clustered_GAEZ_gdf.sample(3) # At this point each vector point represents a particular location on the map -it has certain coordinates- and is categorized into a cluster based on the users selection. # # # ## Step 3. Converting points to polygons # This allows further flexibility in the extraction of raster values using stats. In any case we have the lat,lon coordinates of each point so it is easy to revert to the point geometry. Here, we create a rectangular, buffer-based polygon around each point. # # The buffered polygon shall split "equally" the area between neighbor points; therefore, the buffer used shall be the half of the distance between two neighbor points. This, in turn depends on the location of the AoI on earth and the projection system used. # # We suggest two approaches described below. # ### Assigning CRS | projecting | adding lat, lon coordinates in degrees clustered_GAEZ_gdf.crs = crs_WGS84 clustered_GAEZ_gdf["lon"] = clustered_GAEZ_gdf.geometry.centroid.x clustered_GAEZ_gdf["lat"] = clustered_GAEZ_gdf.geometry.centroid.y clustered_GAEZ_gdf.head(2) # ### Estimating buffer radious # **Approach 1** (suggested) # # Here, we estimate the buffer by calculating the haversine distance between two neighbor points; we use the median value of lat. # + code_folding=[0] def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers. Use 3956 for miles return c * r # + code_folding=[0] # We select a randon set of neighbors; the gdf should be sorted thus here using the median index index_1 = clustered_GAEZ_gdf[clustered_GAEZ_gdf.lat == clustered_GAEZ_gdf.lat.median()].index.tolist()[1] index_2 = int(index_1 + 1) # Note! We multiply by 1000 for meters and devide by 2 as we want half of the distance between the two points clustered_GAEZ_gdf['buf_val_1'] = round(haversine(clustered_GAEZ_gdf["lon"][index_1], clustered_GAEZ_gdf["lat"][index_1], clustered_GAEZ_gdf["lon"][index_2], clustered_GAEZ_gdf["lat"][index_2])*1000/2) # - # **Approach 2** # # Here we use an empirical formula to estimate the "latmeters". That is, we estimate the equivalent value of a degree magnitude in meters based on the latitude of a location. Therefore, each point in the dataframe is assigned a slightly different buffer. # + code_folding=[0] def find_buffer_from_lat(lat, res=resolution): """ Calculate meters per latitude value INPUT lat: latitude in degrees res: resolution of original raster layer OUTPUT latlen: Estimated value of buffer for polygon creation in meters """ latlen = (111132.954 - 559.822 * cos(2*lat) + 1.175 * cos(4*lat))*res/2 return latlen # Emperical formula retrieved from https://gis.stackexchange.com/questions/75528/understanding-terms-in-length-of-degree-formula # + ## Un-comment to run #clustered_GAEZ_gdf['buf_val_2'] =clustered_GAEZ_gdf['lat'].apply(find_buffer_from_lat) # - # ### Create polygons based on identified buffer # #### Project dataframe to the proper coordinate system # # In order to select your own coordinate system go to [epsg.io](http://epsg.io/) and type in your area of interest, this will give you a list of coordinate systems to choose from. Once you have selected your coordinate system replace the numbers below with the numbers from your coordinate system **(keep the "EPSG" part)**. # # **NOTE** When selecting your coordinate system make sure that you select a system with the unit of meters, this is indicated for all systems on [epsg.io](http://epsg.io/) clustered_GAEZ_gdf_prj = clustered_GAEZ_gdf.to_crs(crs_proj) # #### ... and create the polygons # # Note! You can replace *'buf_val_1'* to *'buf_val_2'* if you find the second approach fit for purpose. ## cap_style refers to the type of geometry generated; 3=rectangular (see shapely documectation for more info -- https://shapely.readthedocs.io/en/stable/manual.html) clustered_GAEZ_gdf_prj['geometry'] = clustered_GAEZ_gdf_prj.apply(lambda x: x.geometry.buffer(x.buf_val_1, cap_style=3), axis=1) # **... and revert the dataframe to the original CRS** clustered_GAEZ_gdf = clustered_GAEZ_gdf_prj.to_crs(crs_WGS84) # **Note!** Several features are not classified into a cluster. While points away of the administrative borders will be cut out of the analysis, some points right next to the outer administrative borders might create inconsistency when calculating area. In the following section we are dealing with this problem. # # # ## Step 4. Fixing missing values # ### Adding an index column # (for easier identification/selection later on) clustered_GAEZ_gdf['index'] = range(1, len(data_gdf)+1) # ### Reduce running types | reassure expected output # **Note** # # The following part may lead to varying running times. In favor of reducing running times, we may clip of the vector polygons to the country extent using **national administrative boundaries** # # Clipping will not create any problems to landlocked countries (e.g. Ethiopia) as their borders are mostly covered by land. Therefore recommended in such cases. # # However, for coastal or island countries (e.g. Sri Lanka) the algorithm may miss border clusters with very little land cover (e.g. few disperse, small islands). In order to prevent this from happening, we run the nearest neighbor algorithm over the whole extent of the gridded country and clip to the country extent at the end. # # You may run either of the versions as you see necessary; here we use the *"landlocked"* variable to make a simple distinction between the two. # + code_folding=[] # Clip based on topology of the selected country if landlocked == 1: clustered_GAEZ_gdf = gpd.clip(clustered_GAEZ_gdf, admin) else: clustered_GAEZ_gdf = clustered_GAEZ_gdf # - # ### Split vector points based on cluster assignment # Change type of cluster column to string for next step's selection clustered_GAEZ_gdf.cluster = clustered_GAEZ_gdf.cluster.astype(str) # Points within admin boundaries that are assigned to a cluster clustered_GAEZ_gdf_non_nan = clustered_GAEZ_gdf[clustered_GAEZ_gdf["cluster"] != "nan"] clustered_GAEZ_gdf_non_nan.geometry = clustered_GAEZ_gdf_non_nan.geometry.centroid clustered_GAEZ_gdf_non_nan.head(3) # Points within admin boundaries but not assigned to a cluster clustered_GAEZ_gdf_nan = clustered_GAEZ_gdf[clustered_GAEZ_gdf["cluster"] == "nan"] clustered_GAEZ_gdf_nan.geometry = clustered_GAEZ_gdf_nan.geometry.centroid clustered_GAEZ_gdf_nan.head(3) # ### Get nearest neighbor for points not assigned # + code_folding=[] # Simple function getting the nearest hub for a given set of points def calculate_nearest(row, destination, val, col="geometry"): dest_unary = destination["geometry"].unary_union nearest_geom = nearest_points(row[col], dest_unary) match_geom = destination.loc[destination.geometry == nearest_geom[1]] match_value = match_geom[val].to_numpy()[0] return match_value # - # Apply fuction to the non cluster points dataframe clustered_GAEZ_gdf_nan["index_nn"] = clustered_GAEZ_gdf_nan.apply(calculate_nearest, destination=clustered_GAEZ_gdf_non_nan, val="index", axis=1) # The dataframe has now been attributed with the index of the nearest neighbor clustered_GAEZ_gdf_nan.head(3) # ### Merge the two split dataframe # # This action works similar to the VLOOKUP fuction in excel. For each index_nn in the first dataframe looks at the index of the second dataframe and assigns attributes to the primer as per need. In this case, we assign the cluster name of the nearest neighbor. clustered_GAEZ_gdf_nan_n = clustered_GAEZ_gdf_nan.merge(clustered_GAEZ_gdf_non_nan[['index','cluster']], how = "left", left_on = "index_nn", right_on='index').drop(["index_nn", "cluster_x","index_x"], axis=1) clustered_GAEZ_gdf_nan_n.rename(columns={'index_y': 'index', 'cluster_y': 'cluster'}, inplace=True) # ### Concatenate the two split dataframes into a single one # (updating the original clipped dataframe) clustered_GAEZ_gdf_new = clustered_GAEZ_gdf_non_nan.append(clustered_GAEZ_gdf_nan_n) clustered_GAEZ_gdf_new.head(2) # ### And finally, merge back to the clipped polygon layer using spatial join # (this is to re-gain the polygon geometry) #Spatial join final_clustered_GAEZ_gdf = gpd.sjoin(clustered_GAEZ_gdf_new, clustered_GAEZ_gdf[["geometry"]], op='within', how='right') # ### Clip results in case of coastal or island countries if landlocked == 1: final_clustered_GAEZ_gdf = final_clustered_GAEZ_gdf else: final_clustered_GAEZ_gdf = gpd.clip(final_clustered_GAEZ_gdf, admin) # # # ## Step 5. Total area re-estimation & calibration # # This step estimates and calibrates the area (in square km) based on the area provided by the admin layer used in the analysis (e.g. clipping). # project datasets to proper crs final_clustered_GAEZ_gdf_prj = final_clustered_GAEZ_gdf.to_crs(crs_proj) admin_proj = admin.to_crs(crs_proj) final_clustered_GAEZ_gdf_prj["sqkm"] = final_clustered_GAEZ_gdf_prj['geometry'].area/10**6 # + code_folding=[0] def get_multiplier(estimated, official): if official == estimated: return 1 try: return official / estimated except ZeroDivisionError: return 0 # + estimated_area = final_clustered_GAEZ_gdf_prj.sqkm.sum() official_area = admin_proj.geometry.area.sum()/10**6 # Estimate column multipler multiplier = get_multiplier(estimated_area, official_area) # - final_clustered_GAEZ_gdf_prj.sqkm = final_clustered_GAEZ_gdf_prj.sqkm * multiplier print ("Our modelling exercise yields a total area of {0:.1f} sqkm for the country".format(estimated_area)) print ("The admin layer indicates {0:.1f} sqkm".format(official_area)) print ("After calibration the total area is set at {0:.1f} sqkm".format(final_clustered_GAEZ_gdf_prj.sqkm.sum())) # # ## Final check and Export # #### Revert to original CRS final_clustered_GAEZ_gdf = final_clustered_GAEZ_gdf_prj.to_crs(crs_WGS84) # #### Make a final check before exporting final_clustered_GAEZ_gdf.head(2) # #### Finally export the output layer # + code_folding=[] # Export as shapefile if clust_method == 1: final_clustered_GAEZ_gdf.to_file(os.path.join(out_path,"{c}.gpkg".format(c=out_nm_1)), driver="GPKG") elif clust_method == 2: final_clustered_GAEZ_gdf.to_file(os.path.join(out_path,"{c}.gpkg".format(c=out_nm_2)), driver="GPKG") else: final_clustered_GAEZ_gdf.to_file(os.path.join(out_path,"{c}.gpkg".format(c=out_nm_3)), driver="GPKG") print ("Process complete!", "\U0001F60E")
archive/Creating clustered polygons from ascii grid.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import cv2 def color_op(): src = cv2.imread('butterfly.jpg', cv2.IMREAD_COLOR) if src is None: print('Image load failed!') return print('src.shape:', src.shape) print('src.dtype:', src.dtype) # b, g, r = src[0, 0] print('The pixel value [B, G, R] at (0, 0) is', src[0, 0]) if __name__ == '__main__': color_op() def color_inverse(): src = cv2.imread('butterfly.jpg', cv2.IMREAD_COLOR) if src is None: print('Image load failed!') return dst = np.zeros(src.shape, src.dtype) for j in range(src.shape[0]): for i in range(src.shape[1]): p1 = src[j, i] p2 = dst[j, i] p2[0] = 255 - p1[0] p2[1] = 255 - p1[1] p2[2] = 255 - p1[2] cv2.imshow('src', src) cv2.imshow('dst', dst) cv2.waitKey() cv2.destroyAllWindows() if __name__ == '__main__': color_inverse() def color_grayscale(): src = cv2.imread('butterfly.jpg', cv2.IMREAD_COLOR) if src is None: print('Image load failed!') return dst = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) cv2.imshow('src', src) cv2.imshow('dst', dst) cv2.waitKey() cv2.destroyAllWindows() if __name__ == '__main__': color_grayscale() def color_split(): src = cv2.imread('candies.png', cv2.IMREAD_COLOR) if src is None: print('Image load failed!') return b_plane, g_plane, r_plane = cv2.split(src) bgr_planes = cv2.split(src) cv2.imshow('src', src) cv2.imshow('B_plane', bgr_planes[0]) cv2.imshow('G_plane', bgr_planes[1]) cv2.imshow('R_plane', bgr_planes[2]) cv2.waitKey() cv2.destroyAllWindows() if __name__ == '__main__': color_split()
10. Opencv_Tutorials/Color_Inverse.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/Sangee-28/TaskMongoDB/blob/main/Guvi_Tasks_Numpy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="xlH8O4bOfyM5" # # Numpy # # # + id="favm8uZ8gIvK" # + [markdown] id="i_7nJMPKfyM-" # #### 1. Import the numpy package under the name `np` (★☆☆) # (**hint**: import … as …) # + id="vWszmKcMfyM_" import numpy as np # + [markdown] id="qJ71pxiefyM_" # #### 2. Print the numpy version and the configuration (★☆☆) # (**hint**: np.\_\_version\_\_, np.show\_config) # + id="aidI3REzfyNA" np.__version__ np.show_config # + [markdown] id="NSjxczabfyNA" # #### 3. Create a null vector of size 10 (★☆☆) # (**hint**: np.zeros) # + id="PqIp3BahfyNB" zeros_array =np.zeros(10, dtype='int') zeros_array # + [markdown] id="3UEnIACxfyNB" # #### 4. How to find the memory size of any array (★☆☆) # (**hint**: size, itemsize) # + id="CTOCD5_DfyNC" print(np.size(zeros_array)) print(zeros_array.itemsize) # + [markdown] id="VucgFz_1fyNC" # #### 5. How to get the documentation of the numpy add function from the command line? (★☆☆) # (**hint**: np.info) # + id="wt3crFDQfyND" np.info # + [markdown] id="hTSvuHdWfyND" # #### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆) # (**hint**: array\[4\]) # + id="vSVRLu1LfyND" zeros_array1 =np.zeros(10, dtype='int') zeros_array1[5]=1 print(zeros_array1) # + [markdown] id="SBDJ-fWDfyNE" # #### 7. Create a vector with values ranging from 10 to 49 (★☆☆) # (**hint**: np.arange) # + id="QZjPBWuhfyNE" array1=np.arange(10,50) print(array1) # + [markdown] id="kxN7Ea7UfyNF" # #### 8. Reverse a vector (first element becomes last) (★☆☆) # (**hint**: array\[::-1\]) # + id="wQWuiFK1fyNF" array1[::-1] # + [markdown] id="IbCft7BJfyNF" # #### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) # (**hint**: reshape) # + id="oBKekWGwfyNG" array2=np.arange(0,9) array3=array2.reshape(3,3) print(array3) # + [markdown] id="HWABFUqnfyNG" # #### 10. Find indices of non-zero elements from \[1,2,0,0,4,0\] (★☆☆) # (**hint**: np.nonzero) # + id="tTyUi0mLfyNG" array4=[1,2,0,0,4,0] np.nonzero(array4) # + [markdown] id="RxNc2s2GfyNG" # #### 11. Create a 3x3 identity matrix (★☆☆) # (**hint**: np.eye) # + id="g2URr3olfyNG" identity_matrix= np.eye(3,3,dtype='int') identity_matrix # + [markdown] id="sZ8rgwCJfyNH" # #### 12. Create a 3x3x3 array with random values (★☆☆) # (**hint**: np.random.random) # + id="05z7XnlEfyNH" random_array = np.random.random(size=(3,3,3)) print(random_array) # + [markdown] id="eacQdkdffyNH" # #### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) # (**hint**: min, max) # + id="ZTVp4qgFfyNH" colab={"base_uri": "https://localhost:8080/"} outputId="76e15162-13ee-40dc-b526-338d171c6344" random_array_1 = np.random.random(size=(10,10)) print(np.min(random_array_1)) # + [markdown] id="IOW9sbR9fyNH" # #### 14. Create a random vector of size 30 and find the mean value (★☆☆) # (**hint**: mean) # + id="-FRc18WxfyNH" colab={"base_uri": "https://localhost:8080/"} outputId="dec3c436-cf16-439f-9172-48b21ee60feb" random_array_2 = np.random.random(30) print(np.mean(random_array_2)) # + id="g1FKJE21fyNI" #Create a 2d array with 1 on the border and 0 inside import numpy as np x = np.ones((5,5)) print("Original array:") print(x) print("1 on the border and 0 inside in the array") x[1:-1,1:-1] = 0 print(x) # + [markdown] id="DZBPHBK3fyNI" # #### 16. How to add a border (filled with 0's) around an existing array? (★☆☆) # (**hint**: np.pad) # + id="kHH_1ZZ3fyNI" import numpy as np x = np.ones((3,3)) print("Original array:") print(x) print("0 on the border and 1 inside in the array") x = np.pad(x, pad_width=1, mode='constant', constant_values=0) print(x) # + [markdown] id="dqqZ4nQefyNI" # #### 17. What is the result of the following expression? (★☆☆) # (**hint**: NaN = not a number, inf = infinity) # + [markdown] id="LtO-UQTmfyNI" # ```python # 0 * np.nan # np.nan == np.nan # np.inf > np.nan # np.nan - np.nan # 0.3 == 3 * 0.1 # ``` # + id="05DmfTzEfyNI" colab={"base_uri": "https://localhost:8080/"} outputId="7ae4c1a9-ab5e-4c27-d91c-29f56650ffe6" 0 * np.nan np.nan == np.nan np.inf > np.nan np.nan - np.nan 0.3 == 3 * 0.1 # + [markdown] id="SM7lNkmTfyNJ" # #### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) # (**hint**: np.diag) # + id="jz4NL38UfyNJ" colab={"base_uri": "https://localhost:8080/"} outputId="ca94e44f-6a4d-49ea-b19d-caecc78010a1" Z = np.diag(1+np.arange(4), k = -1) print (Z) # + [markdown] id="zcb8XFwAfyNJ" # #### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) # (**hint**: array\[::2\]) # + id="PKQ8IAQ_fyNJ" colab={"base_uri": "https://localhost:8080/"} outputId="cd70f96e-5840-499d-dacb-b52d407e8141" x = np.ones((3,3)) print("Checkerboard pattern:") x = np.zeros((8,8),dtype=int) x[1::2,::2] = 1 x[::2,1::2] = 1 print(x) # + [markdown] id="NDFbQTGafyNJ" # #### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? # (**hint**: np.unravel_index) # + id="kOrNAu-0fyNJ" colab={"base_uri": "https://localhost:8080/"} outputId="dba6ce0d-d0ce-49cb-b986-269dd6b5f953" print (np.unravel_index(100, (6,7,8))) # + [markdown] id="AVyOZUwufyNJ" # #### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆) # (**hint**: np.tile) # + id="nkLagShkfyNK" colab={"base_uri": "https://localhost:8080/"} outputId="33b75abd-46d1-45ce-e9c5-dbebb07c615f" Checkerboard_array= np.array([[0,1], [1,0]]) Z = np.tile(Checkerboard_array,(4,4)) print (Z) # + [markdown] id="nG-VSU-TfyNK" # #### 22. Normalize a 5x5 random matrix (★☆☆) # (**hint**: (x - min) / (max - min)) # + id="BWacGnd9fyNK" random_matrix=np.random.random((5,5)) norm_random_matrix=(random_matrix-np.min(random_matrix))/(np.max(random_matrix)-np.min(random_matrix)) print(norm_random_matrix) # + [markdown] id="C6fZ21PSfyNK" # #### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) # (**hint**: np.dtype) # + id="Afk8LCLzfyNK" # + [markdown] id="B6K3fsaQfyNK" # #### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) # (**hint**: np.dot | @) # + id="sQ5TaAccfyNK" colab={"base_uri": "https://localhost:8080/"} outputId="e4474101-d269-4d8d-ae83-4d04ec03086f" Matrix_multiply = np.dot(np.ones((5,3), dtype='int'), np.ones((3,2), dtype='int')) print (Matrix_multiply) # + [markdown] id="83bhvd7-fyNK" # #### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) # (**hint**: >, <=) # + id="b41eZtdHfyNK" # + [markdown] id="YyRW7OGSfyNL" # #### 26. What is the output of the following script? (★☆☆) # (**hint**: np.sum) # + [markdown] id="3bmCOn4QfyNL" # ```python # # Author: <NAME> # # print(sum(range(5),-1)) # from numpy import * # print(sum(range(5),-1)) # ``` # + id="rxmhNB6ufyNL" print(sum(range(5),-1)) from numpy import * print(sum(range(5),-1)) # + [markdown] id="Xvl9YudefyNL" # #### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆) # + [markdown] id="KAHk2i0XfyNL" # ```python # Z**Z # 2 << Z >> 2 # Z <- Z # 1j*Z # Z/1/1 # Z<Z>Z # ``` # + id="LFKJ07eZfyNL" # + [markdown] id="RzJBDzF0fyNM" # #### 28. What are the result of the following expressions? # + [markdown] id="Yx2rsxi1fyNM" # ```python # np.array(0) / np.array(0) # np.array(0) // np.array(0) # np.array([np.nan]).astype(int).astype(float) # ``` # + id="2moMzFfJfyNM" np.array(0) / np.array(0) np.array(0) // np.array(0) np.array([np.nan]).astype(int).astype(float) # + [markdown] id="QCGu9W0AfyNN" # #### 29. How to round away from zero a float array ? (★☆☆) # (**hint**: np.uniform, np.copysign, np.ceil, np.abs) # + id="QJ8XpvfBfyNN" colab={"base_uri": "https://localhost:8080/"} outputId="85b8ecaa-8eb6-41ec-d814-95aacae18470" a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) np.ceil(a) array([-1., -1., -0., 1., 2., 2., 2.]) # + [markdown] id="FTQgR2-wfyNN" # #### 30. How to find common values between two arrays? (★☆☆) # (**hint**: np.intersect1d) # + id="tw851KeSfyNN" colab={"base_uri": "https://localhost:8080/"} outputId="3f52c02b-db90-4a01-cb2e-386564a3dc24" import numpy as np x = np.array([0, 1, 2, 3, 4]) y = np.array([0, 2, 4]) print(np.intersect1d(x, y)) # + [markdown] id="qhCA88HafyNO" # #### 31. How to ignore all numpy warnings (not recommended)? (★☆☆) # (**hint**: np.seterr, np.errstate) # + id="kBWub42ffyNO" # + [markdown] id="ORIHUBSNfyNO" # #### 32. Is the following expressions true? (★☆☆) # (**hint**: imaginary number) # + [markdown] id="iM0UgBzLfyNO" # ```python # np.sqrt(-1) == np.emath.sqrt(-1) # ``` # + id="4hfDSBqzfyNP" # + [markdown] id="dFQImftCfyNP" # #### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆) # (**hint**: np.datetime64, np.timedelta64) # + id="z2sORE_qfyNP" # + [markdown] id="jKQHFH6afyNP" # #### 34. How to get all the dates corresponding to the month of July 2016? (★★☆) # (**hint**: np.arange(dtype=datetime64\['D'\])) # + id="4a3225JifyNQ" # + [markdown] id="Rm97nBwCfyNQ" # #### 35. How to compute ((A+B)\*(-A/2)) in place (without copy)? (★★☆) # (**hint**: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)) # + id="gkiuaXxWfyNQ" # + [markdown] id="ue429nPVfyNQ" # #### 36. Extract the integer part of a random array using 5 different methods (★★☆) # (**hint**: %, np.floor, np.ceil, astype, np.trunc) # + id="SmCGzvVAfyNR" # + [markdown] id="21VcSECWfyNR" # #### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) # (**hint**: np.arange) # + id="Wu8yI3fQfyNR" colab={"base_uri": "https://localhost:8080/"} outputId="fcf34f96-d2c7-4c6b-f9e5-bbbe27bf6d0a" a1= np.zeros((5,5)) a1 += np.arange(5) print(a1) # + [markdown] id="B9kdzRa3fyNR" # #### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆) # (**hint**: np.fromiter) # + id="j6Vw1dvJfyNR" colab={"base_uri": "https://localhost:8080/"} outputId="a206246a-791d-4e97-d4c6-4914091af53a" def generate(): for x in range(10): yield x a2 = np.fromiter(generate(), dtype=float, count=-1) print (a2) # + [markdown] id="t3t6UEKtfyNS" # #### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) # (**hint**: np.linspace) # + id="e2nkw2QMfyNS" colab={"base_uri": "https://localhost:8080/"} outputId="5526de1f-502f-4ed1-91d8-e349fce2a12d" a3 = np.linspace(0,1,12,endpoint=True)[1:-1] print(a3) # + [markdown] id="lw1yn4-gfyNS" # #### 40. Create a random vector of size 10 and sort it (★★☆) # (**hint**: sort) # + id="O-aBw6UHfyNS" colab={"base_uri": "https://localhost:8080/"} outputId="c19ddcf9-869a-495e-d58a-a6b0c1963945" a4 = np.random.random(10) a4.sort() print(a4) # + [markdown] id="GKoUOP9pfyNS" # #### 41. How to sum a small array faster than np.sum? (★★☆) # (**hint**: np.add.reduce) # + id="nQh31hw_fyNS" # + [markdown] id="sMRhyDZ7fyNS" # #### 42. Consider two random array A and B, check if they are equal (★★☆) # (**hint**: np.allclose, np.array\_equal) # + id="7KHAkf74fyNT" colab={"base_uri": "https://localhost:8080/"} outputId="e766ca61-ca7d-4e77-e42a-b04bbe398d8b" A = np.random.randint(0,2,5) B = np.random.randint(0,2,5) equal = np.allclose(A,B) print(equal) # + [markdown] id="TT46MFE1fyNT" # #### 43. Make an array immutable (read-only) (★★☆) # (**hint**: flags.writeable) # + id="CbiA0j9ufyNT" a5 = np.zeros(10) a5.flags.writeable = False a5[0] = 1 # + [markdown] id="FgXyFYppfyNT" # #### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) # (**hint**: np.sqrt, np.arctan2) # + id="zRZkmqNufyNT" colab={"base_uri": "https://localhost:8080/"} outputId="81023cea-0079-465f-a815-f8aca19d73e4" a6 = np.random.random((10,2)) X,Y = Z[:,0], Z[:,1] R = np.sqrt(X**2+Y**2) T = np.arctan2(Y,X) print(R) print(T) # + [markdown] id="vQbmLSBlfyNT" # #### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆) # (**hint**: argmax) # + id="FVU9fJ1ZfyNT" colab={"base_uri": "https://localhost:8080/"} outputId="ec44c1da-3d43-49d6-df31-52d74c4ad821" a7 = np.random.random(10) a7[a7.argmax()] = 0 print(a7) # + [markdown] id="KuPqIDWufyNU" # #### 46. Create a structured array with `x` and `y` coordinates covering the \[0,1\]x\[0,1\] area (★★☆) # (**hint**: np.meshgrid) # + id="Ve8eCg_zfyNU" a8 = np.zeros((10,10), [('x',float),('y',float)]) a8['x'], a8['y'] = np.meshgrid(np.linspace(0,1,10), np.linspace(0,1,10)) print(a8) # + [markdown] id="_rCqtgumfyNU" # #### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) # (**hint**: np.subtract.outer) # + id="xnBBsPd9fyNU" # + [markdown] id="ELb73W2tfyNU" # #### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆) # (**hint**: np.iinfo, np.finfo, eps) # + id="9aCBGNI6fyNU" for dtype in [np.int8, np.int32, np.int64]: print(np.iinfo(dtype).min) print(np.iinfo(dtype).max) for dtype in [np.float32, np.float64]: print(np.finfo(dtype).min) print(np.finfo(dtype).max) print(np.finfo(dtype).eps) # + [markdown] id="GTyojxsQfyNU" # #### 49. How to print all the values of an array? (★★☆) # (**hint**: np.set\_printoptions) # + id="Msv4sFE-fyNU" # + [markdown] id="HY3K8A79fyNV" # #### 50. How to find the closest value (to a given scalar) in a vector? (★★☆) # (**hint**: argmin) # + id="daaVw3VCfyNV" colab={"base_uri": "https://localhost:8080/"} outputId="517e8161-6876-4bcd-ab8f-5221774b891f" a10 = np.arange(100) v = np.random.uniform(0,100) index = (np.abs(a10-v)).argmin() print(a10[index]) # + [markdown] id="r8I-cWmwfyNV" # #### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆) # (**hint**: dtype) # + id="4FQn3zpUfyNV" colab={"base_uri": "https://localhost:8080/"} outputId="c6161129-4d36-4618-ce9d-4fe778a7414f" a11 = np.zeros(10, [ ('position', [ ('x', float, 1), ('y', float, 1)]), ('color', [ ('r', float, 1), ('g', float, 1), ('b', float, 1)])]) print(a11) # + [markdown] id="tl_fPFeQfyNV" # #### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) # (**hint**: np.atleast\_2d, T, np.sqrt) # + id="drdq1ZxVfyNV" Z = np.random.random((10,2)) X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1]) D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) print(D) # Much faster with scipy import scipy # Thanks <NAME> (#issue 1) import scipy.spatial Z = np.random.random((10,2)) D = scipy.spatial.distance.cdist(Z,Z) print(D) # + [markdown] id="qfyUtgL7fyNV" # #### 53. How to convert a float (32 bits) array into an integer (32 bits) in place? # (**hint**: astype(copy=False)) # + id="lWyTCJh0fyNW" a12 = np.arange(10, dtype=np.int32) a12= a12.astype(np.float32, copy=False) # + [markdown] id="boT3PLmHfyNW" # #### 54. How to read the following file? (★★☆) # (**hint**: np.genfromtxt) # + [markdown] id="553rJ86pfyNW" # ``` # 1, 2, 3, 4, 5 # 6, , , 7, 8 # , , 9,10,11 # ``` # + id="-dLD3sRyfyNW" # + [markdown] id="S4-xUYfCfyNW" # #### 55. What is the equivalent of enumerate for numpy arrays? (★★☆) # (**hint**: np.ndenumerate, np.ndindex) # + id="fdQU4tmnfyNW" a14 = np.arange(9).reshape(3,3) for index, value in np.ndenumerate(a14): print(index, value) for index in np.ndindex(a14.shape): print(index, a14[index]) # + [markdown] id="zCZDP1OZfyNW" # #### 56. Generate a generic 2D Gaussian-like array (★★☆) # (**hint**: np.meshgrid, np.exp) # + id="aN2urh72fyNW" X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) D = np.sqrt(X*X+Y*Y) sigma, mu = 1.0, 0.0 G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) print(G) # + [markdown] id="3YFEyaYUfyNX" # #### 57. How to randomly place p elements in a 2D array? (★★☆) # (**hint**: np.put, np.random.choice) # + id="Msi9_c01fyNX" colab={"base_uri": "https://localhost:8080/"} outputId="29c6a98c-6f70-4e1e-db61-21c80df2bc64" n = 10 p = 3 a15 = np.zeros((n,n)) np.put(a15, np.random.choice(range(n*n), p, replace=False),1) print (a15) # + [markdown] id="ZwhotWQsfyNX" # #### 58. Subtract the mean of each row of a matrix (★★☆) # (**hint**: mean(axis=,keepdims=)) # + id="qxnOGU2VfyNX" X = np.random.rand(5, 10) # Recent versions of numpy a16 = X - X.mean(axis=1, keepdims=True) # Older versions of numpy a16 = X - X.mean(axis=1).reshape(-1, 1) a16 # + [markdown] id="UGIWj6vffyNX" # #### 59. How to sort an array by the nth column? (★★☆) # (**hint**: argsort) # + id="HqKhyAFjfyNX" colab={"base_uri": "https://localhost:8080/"} outputId="1fc39eba-fafe-49db-f5a1-49f0bb44a8da" a17 = np.random.randint(0,10,(3,3)) print(a17) print(a17[a17[:,1].argsort()]) # + [markdown] id="nHwJTSuGfyNX" # #### 60. How to tell if a given 2D array has null columns? (★★☆) # (**hint**: any, ~) # + id="Rvx7AMW0fyNX" a18= np.random.randint(0,3,(3,10)) print((~a18.any(axis=0)).any()) # + [markdown] id="j2XpwQHpfyNX" # #### 61. Find the nearest value from a given value in an array (★★☆) # (**hint**: np.abs, argmin, flat) # + id="IiMTMjO-fyNY" a19 = np.random.uniform(0,1,10) z = 0.5 m = a19.flat[np.abs(a19 - z).argmin()] print(m) # + [markdown] id="snfFyCF_fyNY" # #### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆) # (**hint**: np.nditer) # + id="DwD18U16fyNY" colab={"base_uri": "https://localhost:8080/"} outputId="dd53ce06-8384-4a68-a3d2-809e39ab9621" a20 = np.ones(10) I = np.random.randint(0,len(a20),20) a20 += np.bincount(I, minlength=len(a20)) print(a20) # + [markdown] id="t5rStE9ffyNY" # #### 63. Create an array class that has a name attribute (★★☆) # (**hint**: class method) # + id="OSEbowN7fyNY" # + [markdown] id="bQoWRemrfyNY" # #### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) # (**hint**: np.bincount | np.add.at) # + id="fQ40sx0kfyNY" colab={"base_uri": "https://localhost:8080/"} outputId="1e2bbf26-d3fd-4ab4-fddb-9d2a4dbdc2ca" Z = np.ones(10) I = np.random.randint(0,len(Z),20) Z += np.bincount(I, minlength=len(Z)) print(Z) # + [markdown] id="XdjmEZMOfyNY" # #### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) # (**hint**: np.bincount) # + id="muGngBuyfyNY" colab={"base_uri": "https://localhost:8080/"} outputId="3c3fa5b2-1de4-4cb5-a47c-f280634987cc" X = [1,2,3,4,5,6] I = [1,3,9,3,4,1] F = np.bincount(I,X) print(F) # + [markdown] id="-tQKVDoofyNZ" # #### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★) # (**hint**: np.unique) # + id="1uD85y-mfyNZ" colab={"base_uri": "https://localhost:8080/"} outputId="f5211fbf-4e6c-4cf5-d710-7bfbe7dca400" w,h = 16,16 I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte) F = I[...,0]*256*256 + I[...,1]*256 +I[...,2] n = len(np.unique(F)) print(np.unique(I)) # + [markdown] id="ZlkO-WxCfyNZ" # #### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) # (**hint**: sum(axis=(-2,-1))) # + id="sFQhPU3YfyNZ" colab={"base_uri": "https://localhost:8080/"} outputId="f4634339-e12d-4c38-856e-a7152cba4ebc" A = np.random.randint(0,10,(3,4,3,4)) sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) print(sum) # + [markdown] id="9vSCc1JsfyNZ" # #### 68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★) # (**hint**: np.bincount) # + id="oKiuKsM0fyNZ" colab={"base_uri": "https://localhost:8080/"} outputId="547ad5c3-0201-4863-93d3-ee14ff0e9a4b" D = np.random.uniform(0,1,100) S = np.random.randint(0,10,100) D_sums = np.bincount(S, weights=D) D_counts = np.bincount(S) D_means = D_sums / D_counts print(D_means) # + [markdown] id="PuXVLAB4fyNZ" # #### 69. How to get the diagonal of a dot product? (★★★) # (**hint**: np.diag) # + id="xpbx_7SffyNZ" colab={"base_uri": "https://localhost:8080/"} outputId="9b581f6d-d6bb-430c-f3ea-319527d610df" A = np.random.randint(0,10,(3,3)) B= np.random.randint(0,10,(3,3)) np.diag(np.dot(A, B)) # + [markdown] id="LQmOabCIfyNa" # #### 70. Consider the vector \[1, 2, 3, 4, 5\], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) # (**hint**: array\[::4\]) # + id="MyG6nnz6fyNa" colab={"base_uri": "https://localhost:8080/"} outputId="25aeee64-acb5-4d17-8d9e-b0d36691bf02" Z = np.array([1,2,3,4,5]) nz = 3 Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) Z0[::nz+1] = Z print(Z0) # + [markdown] id="eosXxIc_fyNa" # #### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★) # (**hint**: array\[:, :, None\]) # + id="eucVOUoafyNa" A = np.ones((5,5,3)) B = 2*np.ones((5,5)) print(A * B[:,:,None]) # + [markdown] id="6uIUc722fyNa" # #### 72. How to swap two rows of an array? (★★★) # (**hint**: array\[\[\]\] = array\[\[\]\]) # + id="iTzbCUNufyNa" colab={"base_uri": "https://localhost:8080/"} outputId="0dc63b31-2dda-4d0d-8e72-119a750294c0" A = np.arange(25).reshape(5,5) A[[0,1]] = A[[1,0]] print(A) # + [markdown] id="tFOrEOrQfyNa" # #### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) # (**hint**: repeat, np.roll, np.sort, view, np.unique) # + id="cxPAN6WdfyNb" faces = np.random.randint(0,100,(10,3)) F = np.roll(faces.repeat(2,axis=1),-1,axis=1) F = F.reshape(len(F)*3,2) F = np.sort(F,axis=1) G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] ) G = np.unique(G) print(G) # + [markdown] id="ntVlRsHvfyNb" # #### 74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) # (**hint**: np.repeat) # + id="Tjur5xfKfyNb" C = np.bincount([1,1,2,3,4,4,6]) A = np.repeat(np.arange(len(C)), C) print(A) # + [markdown] id="pvN3E65TfyNb" # #### 75. How to compute averages using a sliding window over an array? (★★★) # (**hint**: np.cumsum) # + id="X6jC-CK5fyNb" def moving_average(a, n=3) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n Z = np.arange(20) print(moving_average(Z, n=3)) # + [markdown] id="Zwkj41TffyNb" # #### 76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z\[0\],Z\[1\],Z\[2\]) and each subsequent row is shifted by 1 (last row should be (Z\[-3\],Z\[-2\],Z\[-1\]) (★★★) # (**hint**: from numpy.lib import stride_tricks) # + id="zFKJaZuKfyNc" def rolling(a, window): shape = (a.size - window + 1, window) strides = (a.itemsize, a.itemsize) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) A1 = rolling(np.arange(10), 3) print(A1) # + [markdown] id="lf_RSR7RfyNc" # #### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★) # (**hint**: np.logical_not, np.negative) # + id="J9rQ8McefyNc" Z = np.random.randint(0,2,100) print ('original: ') print (Z) print('Negating a boolean: ') print(np.logical_not(Z, out=Z)) Z = np.random.uniform(-1.0,1.0,10) print ('original: ') print (Z) print ('Change the sign of float inplace: ') print(np.negative(Z, out=Z)) # + [markdown] id="_tpIrtf_fyNc" # #### 78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0\[i\],P1\[i\])? (★★★) # + id="vOo-Q1EgfyNc" def distance(P0, P1, p): T = P1 - P0 L = (T**2).sum(axis=1) U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L U = U.reshape(len(U),1) D = P0 + U*T - p return np.sqrt((D**2).sum(axis=1)) P0 = np.random.uniform(-10,10,(10,2)) P1 = np.random.uniform(-10,10,(10,2)) p = np.random.uniform(-10,10,( 1,2)) print(distance(P0, P1, p)) # + [markdown] id="h4zyY7EVfyNc" # #### 79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P\[j\]) to each line i (P0\[i\],P1\[i\])? (★★★) # + id="QKed2mMpfyNc" P0 = np.random.uniform(-10, 10, (5,2)) P1 = np.random.uniform(-10,10,(5,2)) p = np.random.uniform(-10, 10, (5,2)) print (np.array([distance(P0,P1,p_i) for p_i in p])) # + [markdown] id="LZZliNbDfyNc" # #### 80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★) # (**hint**: minimum, maximum) # + id="1zInPh_qfyNd" Z = np.random.randint(0,10,(10,10)) shape = (5,5) fill = 0 position = (1,1) R = np.ones(shape, dtype=Z.dtype)*fill P = np.array(list(position)).astype(int) Rs = np.array(list(R.shape)).astype(int) Zs = np.array(list(Z.shape)).astype(int) R_start = np.zeros((len(shape),)).astype(int) R_stop = np.array(list(shape)).astype(int) Z_start = (P-Rs//2) Z_stop = (P+Rs//2)+Rs%2 R_start = (R_start - np.minimum(Z_start,0)).tolist() Z_start = (np.maximum(Z_start,0)).tolist() R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist() Z_stop = (np.minimum(Z_stop,Zs)).tolist() r = [slice(start,stop) for start,stop in zip(R_start,R_stop)] z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)] R[r] = Z[z] print(Z) print(R) # + [markdown] id="ZC1BtqM4fyNd" # #### 81. Consider an array Z = \[1,2,3,4,5,6,7,8,9,10,11,12,13,14\], how to generate an array R = \[\[1,2,3,4\], \[2,3,4,5\], \[3,4,5,6\], ..., \[11,12,13,14\]\]? (★★★) # (**hint**: stride\_tricks.as\_strided) # + id="5OXIVgNifyNd" Z = np.arange(1,15,dtype=int) def rolling(a, window): shape = (a.size - window + 1, window) strides = (a.itemsize, a.itemsize) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) R = rolling(Z, 4) print ('original: ') print (Z) print ('after strides: ') print(R) # + [markdown] id="Qwc5h2tUfyNd" # #### 82. Compute a matrix rank (★★★) # (**hint**: np.linalg.svd) (suggestion: np.linalg.svd) # + id="YEIjj5XQfyNd" Z = np.random.uniform(0,1,(10,10)) U, S, V = np.linalg.svd(Z) # Singular Value Decomposition rank = np.sum(S > 1e-10) print (rank) # + [markdown] id="bnpm6xb7fyNd" # #### 83. How to find the most frequent value in an array? # (**hint**: np.bincount, argmax) # + id="skle-Z1ofyNd" Z = np.random.randint(0,10,50) print (Z) print('rank:', np.bincount(Z).argmax()) # + [markdown] id="V_Q2uAa8fyNd" # #### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) # (**hint**: stride\_tricks.as\_strided) # + id="i0mw6eAjfyNe" Z = np.random.randint(0,5,(6,6)) n = 3 i = 1 + (Z.shape[0]-3) j = 1 + (Z.shape[1]-3) C = np.lib.stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides) print(C) # + [markdown] id="ACufzoLafyNe" # #### 85. Create a 2D array subclass such that Z\[i,j\] == Z\[j,i\] (★★★) # (**hint**: class method) # + id="QTbpfu-OfyNe" colab={"base_uri": "https://localhost:8080/"} outputId="fca43553-5543-46fc-f811-06e4b94ce29c" # + [markdown] id="QLBWETtzfyNe" # #### 86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★) # (**hint**: np.tensordot) # + id="IRisGle1fyNe" colab={"base_uri": "https://localhost:8080/"} outputId="6ec08170-56a7-482f-f97f-2e99f7e879ef" p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S) # + [markdown] id="WQVVSJKOfyNe" # #### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) # (**hint**: np.add.reduceat) # + id="Y5iPdREzfyNe" Z = np.ones((16,16)) k = 4 S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), np.arange(0, Z.shape[1], k), axis=1) print ('input array') print (Z) print ('block sum') print (S) # + [markdown] id="NA69YfPqfyNe" # #### 88. How to implement the Game of Life using numpy arrays? (★★★) # + id="5pm_7vl3fyNf" def iterate(Z): # Count neighbours N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] + Z[1:-1,0:-2] + Z[1:-1,2:] + Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:]) # Apply rules birth = (N==3) & (Z[1:-1,1:-1]==0) survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1) Z[...] = 0 Z[1:-1,1:-1][birth | survive] = 1 return Z Z = np.random.randint(0,2,(50,50)) for i in range(100): Z = iterate(Z) # + [markdown] id="wrn1vYjofyNf" # #### 89. How to get the n largest values of an array (★★★) # (**hint**: np.argsort | np.argpartition) # + id="DKTqTrL4fyNf" colab={"base_uri": "https://localhost:8080/"} outputId="64b475dc-9e2b-425f-d49d-b69fee66ed3e" Z = np.arange(10000) np.random.shuffle(Z) n = 5 print (Z[np.argsort(Z)[-n:]]) # + [markdown] id="hHL5Q-XVfyNf" # #### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★) # (**hint**: np.indices) # + id="O-KxZVeBfyNf" def cartesian(arrays): arrays = [np.asarray(a) for a in arrays] shape = (len(x) for x in arrays) ix = np.indices(shape, dtype=int) ix = ix.reshape(len(arrays), -1).T for n, arr in enumerate(arrays): ix[:, n] = arrays[n][ix[:, n]] return ix print (cartesian(([1, 2, 3], [4, 5], [6, 7]))) # + [markdown] id="fwBH3_M5fyNf" # #### 91. How to create a record array from a regular array? (★★★) # (**hint**: np.core.records.fromarrays) # + id="asO2hAdWfyNf" Z = np.array([("Hello", 2.5, 3), ("World", 3.6, 2)]) R = np.core.records.fromarrays(Z.T, names='col1, col2, col3', formats = 'S8, f8, i8') # + [markdown] id="WAQYZtbFfyNf" # #### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) # (**hint**: np.power, \*, np.einsum) # + id="TgZ03h9xfyNg" # + [markdown] id="s8zfIuvRfyNg" # #### 93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★) # (**hint**: np.where) # + id="qCP9pGW8fyNg" A = np.random.randint(0,5,(8,3)) B = np.random.randint(0,5,(2,2)) C = (A[..., np.newaxis, np.newaxis] == B) rows = (C.sum(axis=(1,2,3)) >= B.shape[1]).nonzero()[0] print(rows) # + [markdown] id="xhumB30XfyNg" # #### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. \[2,2,3\]) (★★★) # + id="W6HKZ_HkfyNg" Z = np.random.randint(0,5,(10,3)) E = np.logical_and.reduce(Z[:,1:] == Z[:,:-1], axis=1) U = Z[~E] print(Z) print(U) # + [markdown] id="OK3Db6zifyNg" # #### 95. Convert a vector of ints into a matrix binary representation (★★★) # (**hint**: np.unpackbits) # + id="zifK9w_RfyNg" I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) print(B[:,::-1]) # + [markdown] id="kQIUQrRSfyNh" # #### 96. Given a two dimensional array, how to extract unique rows? (★★★) # (**hint**: np.ascontiguousarray) # + id="Jrycn6w2fyNh" colab={"base_uri": "https://localhost:8080/"} outputId="571a0ac1-a6c1-4c77-b8e7-bd5bbc677cad" Z = np.random.randint(0,2,(6,3)) T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1]))) _, idx = np.unique(T, return_index=True) uZ = Z[idx] print(uZ) # + [markdown] id="lgLIeYs7fyNh" # #### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) # (**hint**: np.einsum) # + id="OEM1B2MsfyNh" colab={"base_uri": "https://localhost:8080/"} outputId="b257fc06-1390-4cd7-c7cc-ebc6ba45442b" A= np.arange(3) B = np.arange(12).reshape(3,4) print (A) # + [markdown] id="eXhaSDBkfyNh" # #### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? # (**hint**: np.cumsum, np.interp) # + id="06t77xXRfyNh" phi = np.arange(0, 10*np.pi, 0.1) a = 1 x = a*phi*np.cos(phi) y = a*phi*np.sin(phi) dr = (np.diff(x)**2 + np.diff(y)**2)**.5 r = np.zeros_like(x) r[1:] = np.cumsum(dr) r_int = np.linspace(0, r.max(), 200) x_int = np.interp(r_int, r, x) y_int = np.interp(r_int, r, y) # + [markdown] id="C2o_x65HfyNh" # #### 99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★) # (**hint**: np.logical\_and.reduce, np.mod) # + id="gMWZDYlmfyNh" # + [markdown] id="gGFrYT9kfyNh" # #### 100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★) # (**hint**: np.percentile) # + id="lpaI0z7CfyNh"
Guvi_Tasks_Numpy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="J6ENQJye2tIY" #Individual #Baixe o arquivo brasil.csv disponibilizado em https://bit.ly/insper-pc-aula3 ou em anexo #Programa: #Crie um programa para percorrer todos os registros (linhas, com exceção do cabeçalho) do arquivo e mostrar na tela o seguinte padrão: #O município X/Y possui uma densidade demográfica de Z hab/km² #Onde: #X: nome do município (segunda coluna) #Y: sigla da unidade federativa (primeira coluna) #Z: densidade demográfica (calculada a partir das colunas 3 e 4: habitantes / área) #Opcional: crie uma versão modificada do programa que mostra apenas os municípios com mais de 1.000 hab/km² #Utilize apenas os conceitos aprendidos nas aulas de 1 a 3 #Envie pelo BlackBoard o arquivo no formato gerado pelo Google Colab (.ipynb) #Não serão aceitas submissões fora do prazo, pois esse exercício será corrigido durante a aula 4 # + id="rT14cPav248e" brasil = open("brasil.csv") # + colab={"base_uri": "https://localhost:8080/"} id="cnt5USV03Gkn" outputId="2fd00a27-c417-48f0-cd32-fc50bffdbd39" for linha in brasil: partes = linha.strip().split(",") #print(partes) uf = partes[0] nm_municipio = partes[1] habitantes = partes[2] area = partes[3] densidade = float(int(habitantes) / float(area)) #print(f'O município {nm_municipio}/{uf} possui uma densidade demográfica de {densidade:.2f} hab/km²') if densidade > 1000: print(f'O município {nm_municipio}/{uf} possui uma densidade demográfica de {densidade:.2f} hab/km²')
python_exercicio_27ago2021/exercicio_3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline import time # # Euler Project 解題原則(V):1 min內給出答案,否則就要algorithm # + start = time.time() end = time.time() print('time:',end-start) # - # # 1. Multiples of 3 and 5 (V) # + start = time.time() multipliers = [] for i in range(1000): if i % 3 == 0 : multipliers.append(i) elif i % 5 == 0 : multipliers.append(i) print(np.sum(multipliers)) end = time.time() print('time:',end-start) # - # # 2. Even Fibonacci numbers (V) # + def fib(n): if n == 1: return 1 if n == 2: return 2 if n > 2: return fib(n-1) + fib(n-2) for i in range(10): print(fib(i)) # + start = time.time() i = 1 fib_list = [] while fib(i) <= 4000000: fib_list.append(fib(i)) i += 1 even_num = [] for num in fib_list: if num % 2 == 0: even_num.append(num) print(np.sum(even_num)) end = time.time() print('time:',end-start) # + start = time.time() i = 1 fib_list = [] sum = 0 while fib(i) <= 4000000: if fib(i) % 2 == 0: sum += fib(i) i += 1 print(sum) end = time.time() print('time:',end-start) # - # # 3. Largest prime factor (V): 注意if a and b,a的條件要比較快速篩檢~ # + def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True n = 13195 primes = [] for i in range(n): if prime(i): primes.append(i) prime_facts = [] for prime in primes: if n % prime == 0: prime_facts.append(prime) print(prime_facts[-1]) # + def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True n = 13195 primes = [] for i in range(int(np.sqrt(n))): #找到開根號就好了 if prime(i): primes.append(i) #想從大的除,除到第一個就答案 primes_reverse = reversed(primes) for prime in primes_reverse: if n % prime == 0: print(prime) break # + def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True n = 13195 primes = [] for i in range(int(np.sqrt(n)),2,-1): #從開根號的由大到小往下找 if prime(i) and n % i == 0: print(i) break # + start = time.time() def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True n = 600851475143 primes = [] for i in range(int(np.sqrt(n))): #只需要找到sqrt(n)的大小的質數就可以了 if prime(i): primes.append(i) #想從大的除,除到第一個就答案 primes_reverse = reversed(primes) for prime in primes_reverse: if n % prime == 0: print(prime) break end = time.time() print('time:',end-start) # + start = time.time() def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False break i += 1 return True n = 600851475143 primes = [] for i in range(int(np.sqrt(n)),2,-1): #從開根號的由大到小往下找,邊找邊除,除到第一個就答案 if n % i == 0 and prime(i): #if A and B 和 if B and A不一樣,順序一對調,馬上秒殺!! print(i) break end = time.time() print('time:',end-start) # - # # 4. Largest palindrome product (V) # + start = time.time() def palindromic(num): s = str(num) for i in range(len(s)//2): if s[i] != s[len(s)-i-1]: return False return True palin_list = [] j_max = 100 #最小值就是100 for i in range(999,j_max,-1): #從999由大到小找 for j in range(i,j_max,-1): #從i的數值由大到小找到j_max為止,然後就break,因為再往下只會更小而已 if palindromic(i*j): #print(i*j) palin_list.append(i*j) if j > j_max: j_max = j break print(np.max(palin_list)) end = time.time() print('time:',end-start) # - # # 5. Smallest multiple # + def divisible(num, n): for i in range(1, n+1, 1): if num%i != 0: return False return True num = 1 n = 10 while True: if divisible(num, 10): print(num) break else: num +=1 # - # ## 質因數分解 # + def Is_prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True # n是我們要分解的數字 def GetChildren(n): primes = [] for i in range(n+1): if Is_prime(i): primes.append(i) facts = [] for prime in primes: while n % prime == 0: facts.append(prime) n = n / prime return facts for i in range(1,21,1): print(GetChildren(i)) # - (2**4)*(3**2)*(5)*7*11*13*17*19 #土法煉鋼XDD # # 6. Sum square difference (V) # + start = time.time() n = 100 sum_a = 0 tmp = 0 for i in range(1,n+1,1): sum_a += i**2 for i in range(1,n+1,1): tmp += i sum_b = tmp**2 print(sum_b-sum_a) end = time.time() print('time:', end-start) # - # # 7. 10001st prime (V) # + start = time.time() def Is_prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True count = 0 n = 2 primes = [] while count<10001: if Is_prime(n): primes.append(n) count += 1 n += 1 else: n += 1 print(primes[-1]) end = time.time() print('time:', end-start) # - # # 8. Largest product in a series (V) # + start = time.time() digits = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' int_digits = [] for digit in digits: int_digits.append(int(digit)) prod_sum = [] for i in range(len(int_digits)-12): prod_sum.append(int_digits[i]*int_digits[i+1]*int_digits[i+2]*int_digits[i+3]*int_digits[i+4]*int_digits[i+5]*int_digits[i+6]*int_digits[i+7]*int_digits[i+8]*int_digits[i+9]*int_digits[i+10]*int_digits[i+11]*int_digits[i+12]) print(np.max(prod_sum)) end = time.time() print('time:', end-start) # - # # 9. Special Pythagorean triplet # + start = time.time() for i in range(1, int(1000/3)): for j in range(i,1000-i-i): #可想而知i一定是最小的,所以做到1000-i-i就可以了 if i**2 + j**2 == (1000-i-j)**2: print(i,j,1000-i-j) print(i*j*(1000-i-j)) end = time.time() print('time:', end-start) # - # # 10. Summation of primes (V) 才疏學淺,沒想到最快速質數方法博大精深 # + start = time.time() def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False break i += 1 return True n = 2000000 primes = [] sum = 0 for i in range(n+1): if prime(i): sum += i #是prime就加到sum裡面去 print(sum) end = time.time() print('time:', end-start) # + ## 網路上最快的找<n的質數方法 start = time.time() def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes n = 2000000 print(np.sum(get_primes(n))) end = time.time() print('time:', end-start) # + def prime(num): if num == 1: return False if num == 2: return True if num > 2 : i = 2 while i <= np.sqrt(num): if num % i == 0: return False i += 1 return True n = 10 primes = [] for i in range(n+1): if prime(i): primes.append(i) np.sum(primes) # - # # 11. Largest product in a grid # # 12. Highly divisible triangular number (X) 答案會對,但執行時間過長... # + #網路上最快的找<n的質數方法 def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes #質因數分解 def GetChildren(n): facts = [] primes = get_primes(n) for prime in primes: while n % prime == 0: facts.append(prime) n = n / prime return facts from collections import Counter #算出全部的因數個數 def all_facts_num(n): facts = GetChildren(n) facts_matrix = Counter(facts).most_common() num = 1 for i in range(len(facts_matrix)): num *= (facts_matrix[i][1]+1) return num all_facts_num(10) # + num = 1 sum_ = 1 while all_facts_num(sum_) <= 5: num += 1 sum_ += num #print(sum_) print(sum_) # + #執行時間世界無敵長!! start = time.time() num = 1 sum_ = 1 while all_facts_num(sum_) <= 500: num += 1 sum_ += num #print(sum_) print(sum_) end = time.time() print('time:', end-start) # - sum_ all_facts_num(sum_) # # 13. Large sum (V) # + start = time.time() digits = open("digits.txt", "r") lines = [] for line in digits.readlines(): #依次读取每行 line = line.strip() #去掉每行头尾空白 lines.append(line) #print(lines) sum = 0 for line in lines: sum += int(line) print(str(sum)[0:10]) end = time.time() print('time:',end-start) # - # # 14. Longest Collatz sequence (V),但是約莫花了5分鐘 # + start = time.time() def Collatz_seq(n): if n == 1: return 1 elif n%2 == 0: return n/2 else: return 3*n+1 count = 1 i = 13 list = [i] while Collatz_seq(i) != 1: list.append(Collatz_seq(i)) #print(Collatz_seq(i)) count += 1 i = Collatz_seq(i) list.append(1.0) print(list) print(len(list)) end = time.time() print('time:',end-start) # + start = time.time() def Collatz_seq(n): if n == 1: return 1 elif n%2 == 0: return n/2 else: return 3*n+1 n= 1000000 dict_s_len = {} longest_i = 0 longest_len = 1 for i in range(5,n,1): start = i list_num = [i] while Collatz_seq(i) != 1: list_num.append(Collatz_seq(i)) i = Collatz_seq(i) if longest_len < (len(list_num)+1): longest_len = len(list_num)+1 longest_i = start print(longest_i, longest_len) end = time.time() print('time:',end-start) # - # # 15. Lattice Path (V) # + import math right = 20 down = 20 math.factorial(right+down)/ (math.factorial(right)*math.factorial(down)) # - # # 16. Power digit Sum (V) # + n = 1000 digit_list = [] for i in range(len(str(2**n))): digit_list.append(int(str(2**n)[i])) print(sum(digit_list)) # - # # 20. Factorial digit sum # + import math digit_list = [] for i in range(len(str(math.factorial(100)))): digit_list.append(int(str(math.factorial(100))[i])) print(sum(digit_list)) # -
Euler Project.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:anaconda3] # language: python # name: conda-env-anaconda3-py # --- # + from keras.models import load_model import numpy as np import sys import os import pickle as pk import pandas as pd from os import listdir from os.path import isfile, join from keras.utils import to_categorical ,Sequence from keras import losses, models, optimizers from keras.activations import relu, softmax from keras.callbacks import (EarlyStopping, LearningRateScheduler, ModelCheckpoint, TensorBoard, ReduceLROnPlateau) from keras.layers import (Convolution1D, Dense, Dropout, GlobalAveragePooling1D, GlobalMaxPool1D, Input, MaxPool1D, concatenate) from keras.layers import (Convolution2D, GlobalAveragePooling2D, BatchNormalization, Flatten, GlobalMaxPool2D, MaxPool2D, concatenate, Activation) from keras import backend as K # calculate accuracy from sklearn.metrics import accuracy_score # - # fname = df['fname'].tolist() # label = df['label'].tolist() # map_dict = pk.load(open('data/map.pkl' , 'rb')) # fname # # ensemble for public_csv # + map_dict = pk.load(open('data/map.pkl' , 'rb')) folder_path = 'result/public/' csv_files = [join(folder_path, f) for f in listdir(folder_path) if isfile(join(folder_path, f))] acc_df = pd.read_csv('result/public_acc.csv') acc_df.columns = ['csv','acc','weight'] mean = acc_df['acc'].mean() std = acc_df['acc'].std() print(mean , std) result = np.zeros((9400 , 41)) for p in csv_files: try: ratio = acc_df[acc_df['csv'] == p.split('/')[-1]]['acc'].values[0] weights = acc_df[acc_df['csv'] == p.split('/')[-1]]['weight'].values[0] except: # print(p) continue # ratio = ratio * weight print(p,weights) if ratio > (mean + std): ratio = (ratio*weights + mean + std)*(10/6) elif ratio > mean: ratio = (ratio*weights + mean)*(10/8) elif ratio > (mean - std): ratio = (ratio*weights + mean - std)*1 else: ratio = (ratio*weights - std)*0.8 df = pd.read_csv(p) label = df['label'].tolist() predict = [x.split() for x in label] # convert to label for i,d in enumerate(predict): a = [] for label in d: a.append(map_dict[label]) predict[i] = a # convert to one-hot one_hot = np.zeros((df.shape[0] , 41)) for i , d in enumerate( predict): for top ,label in enumerate( d ) : # 0 -> 1-(0 * 0.2) = 1 # 1 -> 1-(1* 0.2) = 0.8 # 2 -> 1-(2 *0.2) = 0.6 if top==0: weight = 1 * ratio elif top==1: weight=0.8 * ratio #0.5 elif top==2: weight = 0.6 * ratio #0.33 one_hot[i][label] = weight result += one_hot fname = df['fname'].tolist() print(mean+std) # - result[1600] , weights # # Create ans.csv # + output = [] reverse_dict = pk.load(open('data/map_reverse.pkl' , 'rb')) for i , d in enumerate( result): top3 = d.argsort()[-3:][::-1] result = [reverse_dict[x] for x in top3] s = ' '.join(result) output.append(s) df = pd.DataFrame(output , columns = ['label']) df.insert(0,'fname' , fname) df.to_csv('result/public_voting_final.csv', index=False) print(df.head(10)) # - fname label 0 00063640.wav Shatter Keys_jangling Tambourine 1 0013a1db.wav Flute Trumpet Violin_or_fiddle 2 002bb878.wav Bass_drum Knock Gunshot_or_gunfire 3 002d392d.wav Bass_drum Knock Double_bass 4 00326aa9.wav Oboe Clarinet Bass_drum 5 0038a046.wav Bass_drum Electric_piano Knock 6 003995fa.wav Squeak Clarinet Telephone 7 005ae625.wav Acoustic_guitar Cello Clarinet 8 007759c4.wav Clarinet Flute Telephone 9 008afd93.wav Saxophone Flute Cello # # kernel ens # * reproduce kernel result # **Ensembling 1D Conv Predictions** train = pd.read_csv("data/train_label.csv") LABELS = list(train.label.unique()) pred_list = [] for i in range(10): pred_list.append(np.load("data/kernel/freesound-prediction-file/test_predictions_%d.npy"%i)) prediction = np.ones_like(pred_list[0]) for pred in pred_list: prediction = prediction*pred prediction = prediction**(1./len(pred_list)) # Make a submission file top_3 = np.array(LABELS)[np.argsort(-prediction, axis=1)[:, :3]] predicted_labels = [' '.join(list(x)) for x in top_3] test = pd.read_csv('data/sample_submission.csv') test['label'] = predicted_labels test[['fname', 'label']].to_csv("result/1d_conv_ensembled_submission.csv", index=False) test # **Ensembling 2D Conv Predictions** pred_list = [] for i in range(10): pred_list.append(np.load("data/kernel/freesound-prediction-data-2d-conv-reduced-lr/test_predictions_%d.npy"%i)) prediction = np.ones_like(pred_list[0]) for pred in pred_list: prediction = prediction*pred prediction = prediction**(1./len(pred_list)) # Make a submission file top_3 = np.array(LABELS)[np.argsort(-prediction, axis=1)[:, :3]] predicted_labels = [' '.join(list(x)) for x in top_3] test = pd.read_csv('data/sample_submission.csv') test['label'] = predicted_labels test[['fname', 'label']].to_csv("result/2d_conv_ensembled_submission.csv", index=False) test # **Ensembling 1D Conv and 2D Conv Predictions** pred_list = [] for i in range(10): pred_list.append(np.load("data/kernel/freesound-prediction-data-2d-conv-reduced-lr/test_predictions_%d.npy"%i)) for i in range(10): pred_list.append(np.load("data/kernel/freesound-prediction-file/test_predictions_%d.npy"%i)) prediction = np.ones_like(pred_list[0]) for pred in pred_list: prediction = prediction*pred prediction = prediction**(1./len(pred_list)) # Make a submission file top_3 = np.array(LABELS)[np.argsort(-prediction, axis=1)[:, :3]] predicted_labels = [' '.join(list(x)) for x in top_3] test = pd.read_csv('data/sample_submission.csv') test['label'] = predicted_labels test[['fname', 'label']].to_csv("result/1d_2d_ensembled_submission.csv", index=False) test
leo/public_voting.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="M8HCd_fgs4r6" # # 3.3 モデルの実装 # + [markdown] colab_type="text" id="aU-H4_An1qzF" # ### 共通事前処理 # + colab={} colab_type="code" id="rluUyAqg1qzG" # 日本語化ライブラリ導入 # !pip install japanize-matplotlib | tail -n 1 # + colab={} colab_type="code" id="YdEDB0EbtAHq" # 共通事前処理 # 余分なワーニングを非表示にする import warnings warnings.filterwarnings('ignore') # 必要ライブラリのimport import pandas as pd import numpy as np import matplotlib.pyplot as plt # matplotlib日本語化対応 import japanize_matplotlib # データフレーム表示用関数 from IPython.display import display # 表示オプション調整 # numpyの浮動小数点の表示精度 np.set_printoptions(suppress=True, precision=4) # pandasでの浮動小数点の表示精度 pd.options.display.float_format = '{:.4f}'.format # データフレームですべての項目を表示 pd.set_option("display.max_columns",None) # グラフのデフォルトフォント指定 plt.rcParams["font.size"] = 14 # 乱数の種 random_seed = 123 # + [markdown] colab_type="text" id="9xyj5tgy1qzN" # ### 乳がん疾患データセット # + [markdown] colab_type="text" id="89d59gas1qzN" # [UCIデータセットサイト](https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Diagnostic)) # + [markdown] colab_type="text" id="4hLrMm_71qzO" # #### 分析データイメージ # <img src="https://www.researchgate.net/profile/Nick_Street/publication/2512520/figure/fig2/AS:279373199495169@1443619169198/Snakes-After-Convergence-to-Cell-Nucleus-Boundaries-These-contours-are-the-nal.png" alt="Drawing" width="40%" align="left"> # # + [markdown] colab_type="text" id="QFRu16rLaVMK" # ### 3.3.1 (1) データ読み込み # + colab={} colab_type="code" id="6nDUWh6dsrrx" # ガン疾患データセットのロード # ライブラリのimport from sklearn.datasets import load_breast_cancer # データのロード cancer = load_breast_cancer() # データの注釈を読む print(cancer.DESCR) # + colab={} colab_type="code" id="Sf_A259BtYDq" # データフレームへの取り込み columns = [ '半径_平均', 'きめ_平均', '周長_平均', '面積_平均', '平滑度_平均','コンパクト度_平均', '凹面_平均', '凹点_平均', '対称性_平均', 'フラクタル度_平均', '半径_標準誤差', 'きめ_標準誤差', '周長_標準誤差', '面積_標準誤差', '平滑度_標準誤差', 'コンパクト度_標準誤差', '凹面_標準誤差', '凹点_標準誤差', '対称性_標準誤差', 'フラクタル度_標準誤差', '半径_最大', 'きめ_最大', '周長_最大', '面積_最大', '平滑度_最大','コンパクト度_最大', '凹面_最大', '凹点_最大', '対称性_最大', 'フラクタル度_最大' ] # ロードしたデータのデータフレームへの取り込み df = pd.DataFrame(cancer.data, columns=columns) # 正解データの取得 y = pd.Series(cancer.target) # + [markdown] colab_type="text" id="C-ddEokd1qzU" # ### 3.3.2 (2) データ確認 # + colab={} colab_type="code" id="LKD5Nj8Xtw_j" # 入力データの表示 # 入力データの先頭20行目から24行目までの表示 display(df[20:25]) # + colab={} colab_type="code" id="Lfo3Toco5tQY" # 正解データの表示 # 正解データの先頭20行目から24行目の表示 print(y[20:25]) # + colab={} colab_type="code" id="DmWwsLdPyXJ7" # データの統計情報確認 # 入力データの行数、列数の確認 print(df.shape) print() # 正解データの1と0の個数確認 print(y.value_counts()) # + colab={} colab_type="code" id="BblWBEaj92eC" # 散布図描画の準備 # データを正解データ=0のグループと正解データ=1のグループに分割する # 正解データ = 0 (悪性)のデータ抽出 df0 = df[y==0] # 正解データ = 1(良性)のデータ抽出 df1 = df[y==1] display(df0.head()) display(df1.head()) # + colab={} colab_type="code" id="pCm4vGsw-kOG" # 散布図表示 # グラフのサイズ設定 plt.figure(figsize=(6,6)) # 目的変数が0のデータを散布図表示 plt.scatter(df0['半径_平均'], df0['きめ_平均'], marker='x', c='b', label='悪性') # 目的変数が1のデータを散布図表示 plt.scatter(df1['半径_平均'], df1['きめ_平均'], marker='s', c='k', label='良性') # 格子表示 plt.grid() # ラベル表示 plt.xlabel('半径_平均') plt.ylabel('きめ_平均') # 凡例表示 plt.legend() # グラフ表示 plt.show() # + [markdown] colab_type="text" id="aqIx-ZNmau5R" # ### 3.3.3 (3) データ前処理 # + colab={} colab_type="code" id="95nHMEf_xd6g" # 入力データを2項目だけに絞り込む input_columns = ['半径_平均', 'きめ_平均'] x = df[input_columns] display(x.head()) # + [markdown] colab_type="text" id="EUlb2hLb1qzl" # ### 3.3.4 (4) データ分割 # + colab={} colab_type="code" id="0b9yh-rMNKCL" # 訓練用データと検証用データの分割 from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, test_size=0.3, random_state=random_seed) # + colab={} colab_type="code" id="BkHtxn--OEwu" # 分割結果の確認 (要素数) print(x_train.shape) print(x_test.shape) print(y_train.shape) print(y_test.shape) # + colab={} colab_type="code" id="PtJYmh1-jFFP" # 分割結果の確認 (データの内容) display(x_train.head()) display(x_test.head()) display(y_train.head()) display(y_test.head()) # + [markdown] colab_type="text" id="8xpwIVSZbKFS" # ### 3.3.5 (5) アルゴリズム選択 # + colab={} colab_type="code" id="38pyzBSA-sZo" # アルゴリズム選定 from sklearn.linear_model import LogisticRegression algorithm = LogisticRegression(random_state=random_seed) # + [markdown] colab_type="text" id="Sw1ksbvj1qzx" # ### 3.3.6 (6) 学習 # + colab={} colab_type="code" id="KgGL_5uxbsnG" # 学習 algorithm.fit(x_train, y_train) print(algorithm) # + [markdown] colab_type="text" id="YXLsnizH1qzz" # ### 3.3.7 (7) 予測 # + colab={} colab_type="code" id="YyBEtP_EEBz9" # 予測 # predict関数の呼出し y_pred = algorithm.predict(x_test) # 結果の確認 print(y_pred) # + [markdown] colab_type="text" id="B0SoYJcp1qz3" # ### 3.3.8 (8) 評価 # + colab={} colab_type="code" id="sE0vi8a6A0VM" # 正解データと予測結果の比較 # 正解データ 先頭から10個 # y_testはDataFrameなので、valuesによりNumPyに変換しておく y_test10 = y_test[:10].values print(y_test10) # 予測結果 先頭から20個 y_pred10 = y_pred[:10] print(y_pred10) # + colab={} colab_type="code" id="leq0Iov-Gr-T" # 正解数のカウント # 正解データ = 予測結果  w1 = (y_test10 == y_pred10) print(w1) # 正解データの数 w2 = w1.sum() print(w2) # + colab={} colab_type="code" id="Wvh2jKELHmHg" # 精度の計算 # 正解数の計算 w = (y_test.values == y_pred) correct = w.sum() # 検証データ全体数の計算 N = len(w) # 精度 = (正解数) / (検証データ全体数) score = correct / N # 結果表示 print(f'精度: {score:.04f}') # + colab={} colab_type="code" id="gUqIk9QtH6pj" # score関数の利用 # 実は精度は score関数で簡単に計算できる score = algorithm.score(x_test, y_test) print(f'score: {score:.04f}') # + [markdown] colab_type="text" id="C_dGu1VG06Yk" # ### 3.3.9 (9) チューニング # + colab={} colab_type="code" id="HoFTZxRJ1Aeq" # モデルの精度を上げる # オリジナルの30項目の入力データを使って、訓練データ、検証データを作り直す x2_train, x2_test, y_train, y_test = train_test_split(df, y, train_size=0.7, test_size=0.3, random_state=random_seed) # ロジスティック回帰モデルのインスタンスを新たに作り直す algorithm2 = LogisticRegression(random_state=random_seed) # 訓練データで学習 algorithm2.fit(x2_train, y_train) # 検証データで精度を確認 score2 = algorithm2.score(x2_test, y_test) print(f'score: {score2:.04f}') # + [markdown] colab_type="text" id="xnkzq46K1q0B" # ## (補足) 決定境界の表示 # 以下のセルでは、決定境界を表示するためのコードと、なぜそのような実装になるかの簡単な解説を記載しています。 # かなり高度は内容ですので、あまりPythonに詳しくない読者は、飛ばしてもらって構いません。 # Pytho実装に関心のある読者は参考とするようにしてください。 # + [markdown] colab_type="text" id="a9s00TJn1q0C" # ### ロジスティック回帰の内部構造 # # ロジスティック回帰モデルとは、 # (1) 入力変数を一次関数にかけて実数値を導出 # (2) (1)で得られた一次関数値をシグモイド関数と呼ばれる関数にかけて確率値を算出 # (3) (2)の結果が0.5より大きいか小さいかで予測結果が1か0かを判断 # という処理を内部的に行っています。 # # (1)で使われる一次関数の傾きと切片はそれぞれ変数coef_とintercept_で取得可能です。 # 以下のコードではこの性質を使って、内部変数値を取得しています。 # # なお、このモデルでは多値分類用に、複数の内部変数を保持できるようになっています。 # そのため、配列が2次元になっていますが、今回利用するのは2値分類なので、最初の要素([0])の値のみ利用します。 # # # + [markdown] colab_type="text" id="RR798xZ61q0C" # ### 内部変数値の取得 # + colab={} colab_type="code" id="dDzUoI-j1q0C" # モデルの内部変数(切片と係数)の取得 # x1とx2の係数 w1 = algorithm.coef_[0][0] w2 = algorithm.coef_[0][1] # 切片の値 w0 = algorithm.intercept_[0] # 値の確認 print(f'w0 = {w0:.4f} w1 = {w1:.4f} w2 = {w2:.4f}') # + [markdown] colab_type="text" id="KGo9rmBN1q0F" # ### boundary関数の定義 # + [markdown] colab_type="text" id="Cw7089Tt1q0G" # ここで得られた w0, w1, w2の値を用いると、散布図上に決定境界を示すための関数boundaryを決めることができます。 # 具体的な関数と、それを導出するための式を以下のセルで示しました。 # + colab={} colab_type="code" id="GUNtZtbQ1q0G" # 決定境界計算用関数 # 決定境界計算用関数 # 0 = w0 + w1 * x + w2 * y をyについて解くと以下の式になる # y = -(w0 + w1 * x)/ w2 def boundary(algorithm, x): w1 = algorithm.coef_[0][0] w2 = algorithm.coef_[0][1] w0 = algorithm.intercept_[0] y = -(w0 + w1 * x)/w2 return y # + [markdown] colab_type="text" id="6cWhsERP1q0J" # ### 決定境界の端点値の計算 # + [markdown] colab_type="text" id="am0xrlpv1q0J" # 次に示すコードは、上で定義したboundary関数を利用して、決定境界を構成する端点の座標を求めるためのものです。 # あわせて、元のデータフレームからyの最小値と最大値を求め、グラフの見栄えをよくします 。 # + colab={} colab_type="code" id="fqVsJ71D1q0J" # 決定境界の端点値計算 # 決定境界の端点のx座標 x_range = np.array((df['半径_平均'].min(), df['半径_平均'].max())) # 決定境界の端点のy座標 y_range = boundary(algorithm, x_range) # yの上限、下限は散布図の点を元に決める y_lim = (df['きめ_平均'].min(), df['きめ_平均'].max()) # 結果確認 print('端点のx座標: ', x_range) print('端点のy座標: ', y_range) print('グラフのy領域: ', y_lim) # + [markdown] colab_type="text" id="B168GkhX1q0M" # ### 散布図と決定境界の表示 # + [markdown] colab_type="text" id="mJLTtmbA1q0M" # これですべての準備は整いました。 # 次に示すコードでは、コード3-8で表示した学習データの散布図と、今求めた決定境界を重ね描きしています。 # + colab={} colab_type="code" id="RdDhJGH91q0N" # 散布図と決定境界の表示 # グラフのサイズ設定 plt.figure(figsize=(6,6)) # 目的変数が0のデータを散布図表示 plt.scatter(df0['半径_平均'], df0['きめ_平均'], marker='x', c='b', label='悪性') # 目的変数が1のデータを散布図表示 plt.scatter(df1['半径_平均'], df1['きめ_平均'], marker='s', c='k', label='良性') # 決定境界 plt.plot(x_range, y_range, c='b', label='決定境界') # 範囲指定 plt.ylim(y_lim) # ラベル表示 plt.xlabel('半径_平均') plt.ylabel('きめ_平均') # 凡例表示 plt.legend() # 方眼表示 plt.grid() # グラフ表示 plt.show() # + colab={} colab_type="code" id="HsVKymrC1q0X"
notebooks/ch03_03_first_ml.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/YianKim/2022_uncertainty_aware_semisupervise/blob/main/Keras_UncertaintyBootstrap.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="AiCmW9OvtVfs" outputId="ebff3e37-c298-4c50-f8f1-296036425dd5" pip install tensorflow_addons # + id="Ik7Qx5iO8lQ_" import matplotlib.pyplot as plt from tensorflow import keras import numpy as np from sklearn.model_selection import train_test_split from tensorflow.keras.models import clone_model import PIL from PIL import Image import pickle import random from tqdm import tqdm from collections import Counter from keras.layers.core import Lambda from keras import backend as K from keras.models import Sequential from keras.layers import Conv2D from keras.layers import BatchNormalization from keras.regularizers import l2 from keras.layers import Activation from keras.layers import Dropout from keras.layers import MaxPooling2D, AveragePooling2D from keras.layers import Flatten from keras.layers import Dense from keras.layers import Reshape from keras import optimizers from keras.callbacks import * from sklearn.metrics import * from keras.models import load_model import tensorflow_addons as tfa from torchvision import transforms import tensorflow as tf import tensorflow.keras.backend as backend import math import gc # + [markdown] id="0Hmq32hTH-Jv" # # SVHN # + colab={"base_uri": "https://localhost:8080/"} id="CCUaBhoYMQHF" outputId="67446332-df3b-4871-bf21-b5095f309b73" from google.colab import drive drive.mount('/content/drive') # + id="HUCvct_dH5m1" from scipy.io import loadmat train_raw = loadmat('/content/drive/MyDrive/SVHN/train_32x32.mat') test_raw = loadmat('/content/drive/MyDrive/SVHN/test_32x32.mat') # + id="XzWKzGmGtk2h" def dummy_labels(labels): zero_labels = np.zeros([labels.shape[0], 10], np.int8) for i in range(labels.shape[0]): zero_labels[i][labels[i]] = 1 return(zero_labels) # + id="65QFu6LVMxl9" train_images = train_raw['X'] train_labels = train_raw['y'] test_images = test_raw['X'] test_labels = dummy_labels(test_raw['y']-1) train_images = train_images.swapaxes(2,3).swapaxes(1,2).swapaxes(0,1) test_images = test_images.swapaxes(2,3).swapaxes(1,2).swapaxes(0,1) # + id="fm_NgimXNonL" temp = [0,0,0,0,0,0,0,0,0,0] label_indx = [] unlabel_indx = [] for i in range(73257) : if temp[(train_labels).reshape([-1])[i]-1] < 25 : temp[(train_labels).reshape([-1])[i]-1] += 1 label_indx.append(i) else : unlabel_indx.append(i) # + id="3ZADJPIIOZD2" lbl_train_images = train_images[label_indx] lbl_train_labels = dummy_labels(train_labels[label_indx]-1) # + id="fHe18DTWUu3-" ubl_train_images = train_images[unlabel_indx] ubl_train_labels = dummy_labels(train_labels[unlabel_indx]-1) # + [markdown] id="VCGWSJL0MJ3W" # # CIFAR 10 # + id="LAzGxvve8pgp" cifar10 = keras.datasets.cifar10 (train_images, train_labels), (test_images, test_labels) = cifar10.load_data() train_images = train_images/255 test_images = test_images/255 # + id="zqUm92WTGW3p" def dummy_labels(labels): zero_labels = np.zeros([labels.shape[0], 10], np.int8) for i in range(labels.shape[0]): zero_labels[i][labels[i]] = 1 return(zero_labels) # + id="vFVXfHQNGtmq" train_labels = dummy_labels(train_labels) test_labels = dummy_labels(test_labels) # + id="WOqDJtXCG2ov" # 1000 labeled, 49000 unlabeled random.seed(10) indx = random.sample(range(train_labels.shape[0]),train_labels.shape[0]) lbl_train_images = train_images[indx[:1000]] ubl_train_images = train_images[indx[1000:]] lbl_train_labels = train_labels[indx[:1000]] ubl_train_labels = train_labels[indx[1000:]] # valids1 = train_images[indx[800:1000]] # valids2 = train_labels[indx[800:1000]] # + [markdown] id="Q7hfth6hMMxW" # #MAin # # + id="iKyn6Njs7vqa" class SGDR(Callback): def __init__(self, min_lr=0.0, max_lr=0.03, base_epochs=20, mul_epochs=2): super(SGDR, self).__init__() self.min_lr = min_lr self.max_lr = max_lr self.base_epochs = base_epochs self.mul_epochs = mul_epochs self.cycles = 0. self.cycle_iterations = 0. self.trn_iterations = 0. self._reset() def _reset(self, new_min_lr=None, new_max_lr=None, new_base_epochs=None, new_mul_epochs=None): """Resets cycle iterations.""" if new_min_lr != None: self.min_lr = new_min_lr if new_max_lr != None: self.max_lr = new_max_lr if new_base_epochs != None: self.base_epochs = new_base_epochs if new_mul_epochs != None: self.mul_epochs = new_mul_epochs self.cycles = 0. self.cycle_iterations = 0. def sgdr(self): cycle_epochs = self.base_epochs * (self.mul_epochs ** self.cycles) tide = ((self.cycles == 0) * 1) * (self.cycle_iterations*self.max_lr + (self.base_epochs - self.cycle_iterations)*self.min_lr) / self.base_epochs + ((self.cycles != 0) * 1)*(self.min_lr + 0.5 * (self.max_lr - self.min_lr) * (1 + np.cos(np.pi * (self.cycle_iterations + 1) / cycle_epochs))) return tide def on_train_begin(self, logs=None): if self.cycle_iterations == 0: K.set_value(self.model.optimizer.lr, self.max_lr) else: K.set_value(self.model.optimizer.lr, self.sgdr()) def on_epoch_end(self, epoch, logs=None): logs = logs or {} logs['lr'] = K.get_value(self.model.optimizer.lr) self.trn_iterations += 1 self.cycle_iterations += 1 if self.cycle_iterations >= self.base_epochs * (self.mul_epochs ** self.cycles): self.cycles += 1 self.cycle_iterations = 0 K.set_value(self.model.optimizer.lr, self.max_lr) else: K.set_value(self.model.optimizer.lr, self.sgdr()) # + id="YRCDNliwfudJ" def PermaDropout(rate): return Lambda(lambda x: K.dropout(x, level=rate)) def create_cnn_13(): inputlayer = keras.Input(shape=(32, 32, 3)) conv1a = Conv2D(128, (5,5), padding = 'same') bn1a = BatchNormalization() conv1b = Conv2D(64, (5,5), padding = 'same') bn1b = BatchNormalization() conv1c = Conv2D(32, (5,5), padding = 'same') bn1c = BatchNormalization() pl1 = MaxPooling2D(2, 2) MCdrop1 = PermaDropout(0.5) fc1 = Dense(1024) fc2 = Dense(10) activ = keras.layers.LeakyReLU(0.1) model = Sequential([ inputlayer, tfa.layers.WeightNormalization(conv1a), bn1a, activ, pl1, tfa.layers.WeightNormalization(conv1b), bn1b, activ, pl1, tfa.layers.WeightNormalization(conv1c), bn1c, activ, pl1, MCdrop1, Flatten(), fc1, fc2 ]) return model def compile_cnn_13(model): opt = keras.optimizers.SGD(0.03, momentum=0.9) model.compile( optimizer = opt, loss=keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'] ) return model def cnn_13(): model = create_cnn_13() model = compile_cnn_13(model) return model def fit_and_labeling_cnn_13(Epoch, Batch): lr_reducer = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=3) early_stopper = EarlyStopping(monitor='val_loss', min_delta=0, patience=30, mode='auto') sgdr = SGDR(min_lr=0.0, max_lr=0.03, base_epochs=20) #스케줄러 model.fit( x=X, y=y, epochs=Epoch, verbose=1, batch_size=Batch, callbacks=[sgdr] ) model_test_eval(model, test_images, test_labels) T = 1 for predsamples in (range(10)): if predsamples == 0 : predictions = np.array(tf.nn.softmax(model.predict(ubl_train_images)/T)) predictions = predictions.reshape((1,) + predictions.shape) else: pred = np.array(tf.nn.softmax(model.predict(ubl_train_images)/T)) pred = pred.reshape((1,) + pred.shape) predictions = np.concatenate((predictions, pred)) return predictions def model_test_eval(model, test_images, test_labels): T = 1 pred = np.array(tf.nn.softmax(model.predict(test_images)/T)) for i in range(1,10): pred += np.array(tf.nn.softmax(model.predict(test_images))) acc = (np.argmax(pred,axis=1) == np.argmax(test_labels,axis=1))*1 acc = sum(acc)/len(acc) print("test set 성능 : " + str(acc)) # + colab={"base_uri": "https://localhost:8080/"} id="vz5CFL960tsP" outputId="ba4422fd-0edc-4337-b74d-5f530457816d" model = cnn_13() X = lbl_train_images y = lbl_train_labels predictions = fit_and_labeling_cnn_13(500, 64) # + id="7EJw4va52LSK" pseudo = np.argmax(np.mean(predictions, axis=0), axis=1) conf = np.max(np.mean(predictions, axis=0), axis=1) uncert = np.std(predictions, axis=0) uncert = np.array([uncert[i][pseudo[i]] for i in range(len(pseudo))]) # + id="kuQG35C02Pip" score = conf - uncert score = (score-min(score))/(max(score)-min(score)) score = score/sum(score) # + id="SwHqAN6l3XpN" # indx = np.random.choice(len(score), 50000, p = score) indx = np.random.choice(len(score), 50000) # + id="IRSxVnSu3sQd" X = ubl_train_images[indx] y = ubl_train_labels[indx] # + id="pIVovxoP39EF" X = np.concatenate([lbl_train_images, X]) y = np.concatenate([lbl_train_labels, y]) # + colab={"base_uri": "https://localhost:8080/"} id="LJlkc45958vz" outputId="f1fafad4-af23-4ec0-aad3-c298ab8d3d51" predictions = fit_and_labeling_cnn_13(100, 64) # + id="mFnGc8yJ593w" # + id="H34xm2v1BKXo" pseudo = np.argmax(np.mean(predictions, axis=0), axis=1) conf = np.max(np.mean(predictions, axis=0), axis=1) uncert = np.std(predictions, axis=0) uncert = np.array([uncert[i][pseudo[i]] for i in range(len(pseudo))]) # + id="hqavnFS1BKXo" score = conf - uncert score = (score-min(score))/(max(score)-min(score)) score = score/sum(score) # + id="PRWiDTfVBKXo" # indx = np.random.choice(len(score), 200000, p = score) indx = np.random.choice(len(score), 200000) # + id="tlm2F_RVBKXo" X = ubl_train_images[indx] y = ubl_train_labels[indx] # + id="Y92u3FRdBKXo" X = np.concatenate([lbl_train_images, X]) y = np.concatenate([lbl_train_labels, y]) # + colab={"base_uri": "https://localhost:8080/"} outputId="0c681572-ad79-46b5-b332-a42dc9dea1f6" id="Tq1XYBkdBKXp" predictions = fit_and_labeling_cnn_13(100, 64) # 0.9195 (score 사용) # # + id="tXrsbiY1BUg_"
Keras_UncertaintyBootstrap.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="wvsLhjHi9ZTd" import matplotlib.pyplot as plt import numpy as np # + [markdown] id="uMKxiWhcJJiB" # # Questão 1 # # Compare o número de iterações efetuadas pelos métodos de Newton e de Broyden para resolver o sistema # de equações não-lineares # # $$ # F(x, y, z) = # \begin{bmatrix} # 16x^4 + 16y^4 + z^4 - 16 \\ # x^2 + y^2 + z^2 - 3 \\ # x^3 − y # \end{bmatrix} = # \begin{bmatrix} # 0 \\ # 0 \\ # 0 # \end{bmatrix} # $$ # # da atividade anterior com aproximação inicial $(1, 1, 1)$ para ambos os métodos e a matriz # # $ # B(0) = [F(2, 1, 1) − F(1, 1, 1), F(1, 2, 1) − F(1, 1, 1), F(1, 1, 2) − F(1, 1, 1)] # $ # , # no método de Broyden. Comente os aspectos positivos e negativos do método de Broyden. # # + id="uQ11Y3G5OiV8" F3 = lambda x, y, z: np.array([16*x**4 + 16*y**4 + z**4 - 16, x**2 + y**2 + z**2 - 3, x**3 - y]) B0 = np.array([F3(2,1,1) - F3(1,1,1), F3(1,2,1) - F3(1,1,1), F3(1,1,2) - F3(1,1,1)]) # + colab={"base_uri": "https://localhost:8080/"} id="Gy9EmrGVPChO" outputId="70b03538-0ee2-4bfc-b2a8-7c17ed7c1ec1" B0 # + [markdown] id="aPbZuRI4WCnH" # ## Cálculo de $J(x)$ # # Realizando as derivadas parciais adequadas, podemos determinar a matriz Jacobiana $J(x)$. # # $$J(x) = # \begin{bmatrix} # 64x^3 & 64y^3 & 4z^3 \\ # 2x & 2y & 2z \\ # 3x^2 & − 1 & 0 # \end{bmatrix} # $$ # + id="NXyKYEHyVkUZ" F = lambda x: np.array([16*x[0]**4 + 16*x[1]**4 + x[2]**4 - 16, x[0]**2 + x[1]**2 + x[2]**2 - 3, x[0]**3 - x[1]]) J = lambda x: np.array([[64*x[0]**3, 64*x[1]**3, 4*x[2]**3], [2*x[0], 2*x[1], 2*x[2]], [3*x[0]**2, - np.ones_like(x[1]), np.zeros_like(x[2])]]) # + [markdown] id="lhddNmfDidgP" # ## Método de Newton # # Segue a função e evocação do Método de Newton. # + id="Il1tS_caZG-0" def MetodoNewtonSNL(F,J,X0,kmax=100,tau=1.e-6, epsilon=1.e-6): k = 0 Er = [tau+1] X = [X0] FX = F(X0) while (k <= kmax) and (Er[-1] > tau) and (np.linalg.norm(FX,np.inf) > epsilon): k += 1 s = np.linalg.solve(J(X[-1]), -F(X[-1])) X.append(X[-1] + s) Er.append(np.linalg.norm(s,np.inf)) FX = F(X[-1]) print("Iteração (%d): ||s||_inf = %.7f" %(k, np.linalg.norm(s,np.inf))) return X,Er # + colab={"base_uri": "https://localhost:8080/"} id="QalaS4_3a2xG" outputId="e05d736e-d55e-4e36-e2fb-f2b21c014d21" X0 = np.array([1.0, 1.0, 1.0]) X_N, Er_N = MetodoNewtonSNL(F, J, X0) # + colab={"base_uri": "https://localhost:8080/"} id="FU_8YFItcOz9" outputId="2261fddb-bb68-44be-b676-8a86a1e1b6c1" X_N[-1], F(X_N[-1]) # + [markdown] id="4VUEnSfciyff" # O Método de Newton encontrou uma solução válida e convergiu rapidamente, com apenas cinco iterações. # + [markdown] id="TMco65BpimnW" # ## Método de Broyden # # Segue a função e a invocação do Método de Broyden. # + id="PT-ncTQRSVAN" def MetodoBroyden(F,B,x,kmax=1000,tau=1.e-6,epsilon=1.e-6): x_list = [x] n = x.shape[0] k = 0 Fx = F(x) Dr = [tau+1] while (k <= kmax) and (np.linalg.norm(Fx,np.inf) > epsilon) and (Dr[-1] > tau): k += 1 s = np.linalg.solve(B,-Fx) x = x + s x_list.append(x) Dr.append(np.linalg.norm(s,np.inf)) Fx = F(x) B = B + (1/(s.T@s))*(Fx.reshape(n,1)@s.reshape(1,n)) print("Iteração (%d): ||s||_inf = %.7f" %(k, np.linalg.norm(s,np.inf))) return np.array(x_list),Dr # + colab={"base_uri": "https://localhost:8080/"} id="W9ysN-HeT14I" outputId="83879ed7-be46-4094-ddfe-bdf3a043ad58" X_B, Er_B = MetodoBroyden(F, B0, X0) # + colab={"base_uri": "https://localhost:8080/"} id="yWTMjHx7VkHK" outputId="69e59de7-c611-4284-c5f1-119450014e65" X_B[-1], F(X_B[-1]) # + [markdown] id="wTFKCSU_aVhZ" # O método obteve uma solução válida, embora menos precisa do que a obtida pelo Método de Newton. Para isso, efetuou 142 iterações, o que é um número muito superior às cinco iterações do outro método. # + colab={"base_uri": "https://localhost:8080/", "height": 309} id="3_6gT8H9UpDn" outputId="01b6481b-9d70-4d61-a5cf-1c8d779b8a63" plt.semilogy(Er_N, label="Newton") plt.semilogy(Er_B, label="Broyden") plt.legend(loc="upper center") plt.title("Comparação entre Newton e Broyden", fontdict={"size":20}) plt.xlabel("Iteração $k$", fontdict={"size":15}) plt.ylabel("Erro $||s||_\infty$", fontdict={"size":15}) plt.show() # + [markdown] id="FvCmhzvBZPKH" # ### Aspectos Positivos e Negativos # # Sabemos que o Método de Broyden realiza menos operações por iteração do que o Método de Newton, o que é um aspecto positivo. # # Contudo, ele não garante a convergência quadrática como o Método de Newton, o que é uma característica negativa. No caso particular, sequer houve convergência linear. No gráfico comparativo entre os métodos, nota-se que houve certas iterações, mesmo longe do início, em que o erro aumentou. Isso resultou em um número de iterações $28.4$ ($=142/5$) vezes maior. # + [markdown] id="QMc6H7uWbXdQ" # # Questão 2 # # Considere o problema de valor inicial (PVI): # # $$ # \begin{cases} # y' = −2ty^2 \\ # y(0) = 1. # \end{cases} # $$ # # Estime o valor de $y(0.5)$ usando os métodos de Euler e da série de Taylor de ordem 2 com passo $h = 0.25$. # + [markdown] id="L84ip0vefd6_" # ## Calculando derivadas parciais de $f(t, y)$ # # $y' = f(t, y) = - 2 t y^2$ # # $f_t(t, y) = \frac{d}{dt} [- 2 t y^2] = - 2 y^2 \frac{d}{dt}[t] = - 2 y^2$ # # $f_y(t, y) = \frac{d}{dy} [- 2 t y^2] = - 2 t \frac{d}{dy}[y^2] = - 2 t \times 2 y = - 4 t y$ # + id="UVkg_c77ci_m" f = lambda t, y: -2 * t * y**2 ft = lambda t, y: -2 * y**2 fy = lambda t, y: -4 * t * y # + [markdown] id="SpGlijSlfZnG" # ## Método de Euler # # Abaixo seguem a função e a invocação do Método de Euler. # # De acordo com o PVI, $x_0 = 0$, $y_0 = 1$, $x_f = 0.5$ e $h = 0.25$. # + id="h2s1rNkLcr2w" def MetodoEuler(f,x0,xf,y0,h): k = 0 x = [x0] y = [y0] while (x[-1] < xf): x.append(x[k] + h) y.append(y[k] + h*f(x[k],y[k])) k = k+1 print(f"Iteração ({k}): ({x[k]}, {y[k]})") return x,y # + id="-OhIeUJJhNBH" x0 = 0 y0 = 1 xf = 0.5 h = 0.25 # + colab={"base_uri": "https://localhost:8080/"} id="1a3B5PDkg1fj" outputId="25e9888c-eaac-4877-d9b2-9bd0ca4eb64e" tE, yE = MetodoEuler(f, x0, xf, y0, h) # + [markdown] id="M2aJSyQWjLiC" # ## Método de Taylor de ordem 2 # + id="zPzY54aCjQt6" def MetodoTaylor2(f,fx,fy,x0,xf,y0,h): k = 0 x = [x0] y = [y0] while x[-1]<xf: x.append(x[k]+h) y.append(y[k] + h*f(x[k],y[k]) + (h**2/2)*(fx(x[k],y[k]) + fy(x[k],y[k])*f(x[k],y[k]))) k = k+1 print(f"Iteração ({k}): ({x[k]}, {y[k]})") return x,y # + colab={"base_uri": "https://localhost:8080/"} id="LTCscmCkjkg_" outputId="e24e81a9-d6b6-4a35-adf0-59fa85046f99" tT, yT = MetodoTaylor2(f, ft, fy, x0, xf, y0, h) # + [markdown] id="ndVmMkArj76w" # ## Resolvendo o TVI analiticamente # # De $y' = - 2 t y^2$, $-\frac{dy}{y^2} = 2 t dt$. # # Assim, $\frac{1}{y} = t^2 + C \iff y(t) = \frac{1}{t^2 + C}$. # # Como $y(0) = 1$, $1 = \frac{1}{C} \iff C = 1$. # # Logo, $y(t) = \frac{1}{t^2 + 1}$. # # Portanto, $y(0.5) = \frac{1}{0.5^2 + 1} = \frac{1}{1.25}= 0.8$ # + [markdown] id="KCnnHXmZlAsp" # ## Comparando Métodos # # Conforme esperado, o Método de Taylor de ordem $2$ obteve uma aproximação melhor, uma vez que o valor $0.79$ obtido se aproxima mais da resposta correta $0.8$ do que o número encontrado pelo Método de Euler, $0.875$
Atividade 07.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="XBJ2ogPsC-WA" colab_type="code" colab={} import tensorflow as tf from tensorflow import keras # + id="3Y7jGef3EDx3" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="95df9b85-8099-4b73-b181-187ddde7285a" # !pip install -q tensorflow-text # + id="nfux8uoyEMcj" colab_type="code" colab={} import tensorflow_text as text # + id="sO7ONymqEP0i" colab_type="code" colab={} docs = tf.constant([u'Everything not saved will be lost.'.encode('UTF-16-BE'), u'Sad☹'.encode('UTF-16-BE')]) utf8_docs = tf.strings.unicode_transcode(docs, input_encoding='UTF-16-BE', output_encoding='UTF-8') # + id="mCBkxGVwEsWT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 105} outputId="fdf615df-2377-4e6f-906b-7ae1b9147b8b" tokenizer = text.WhitespaceTokenizer() tokens = tokenizer.tokenize(['everything not saved will be lost.', u'Sad☹'.encode('UTF-8')]) print(tokens.to_list()) # + id="naMeQOyLFD2z" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="2fcfab25-2881-4170-d7d3-fd2df01e2f24" tokenizer = text.UnicodeScriptTokenizer() tokens = tokenizer.tokenize(['everything not saved will be lost.', u'Sad☹'.encode('UTF-8')]) print(tokens.to_list()) # + id="zzo1HL7NFUD6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="e82115b7-e65c-4e49-e867-2f9e9fcfec9e" tokens = tf.strings.unicode_split([u"仅今年前".encode('UTF-8')], 'UTF-8') print(tokens.to_list()) # + id="-o-twC-wFgE7" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 88} outputId="eb28abef-2dfa-4e46-c830-2f24c5cb1a0a" tokenizer = text.UnicodeScriptTokenizer() (tokens, offset_starts, offset_limits) = tokenizer.tokenize_with_offsets(['everything not saved will be lost.', u'Sad☹'.encode('UTF-8')]) print(tokens.to_list()) print(offset_starts.to_list()) print(offset_limits.to_list()) # + id="rqOGNkEZGT0i" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="7b6aeece-5560-4beb-d8a0-0d5f9ef78c56" docs = tf.data.Dataset.from_tensor_slices([['Never tell me the odds.'], ["It's a trap!"]]) tokenizer = text.WhitespaceTokenizer() tokenized_docs = docs.map(lambda x: tokenizer.tokenize(x)) iterator = iter(tokenized_docs) print(next(iterator).to_list()) print(next(iterator).to_list()) # + id="zAfY6SyaGg2E" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 85} outputId="4a9e331d-ba5f-47a0-fa93-a4a0cd281506" tokenizer = text.WhitespaceTokenizer() tokens = tokenizer.tokenize(['Everything not saved will be lost.', u'Sad☹'.encode('UTF-8')]) f1 = text.wordshape(tokens, text.WordShape.HAS_TITLE_CASE) f2 = text.wordshape(tokens, text.WordShape.IS_UPPERCASE) f3 = text.wordshape(tokens, text.WordShape.HAS_SOME_PUNCT_OR_SYMBOL) f4 = text.wordshape(tokens, text.WordShape.IS_NUMERIC_VALUE) print(f1.to_list()) print(f2.to_list()) print(f3.to_list()) print(f4.to_list()) # + id="1WXqZgALHZJC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="bba77347-775c-47c2-bd0c-f4be7a78fbb6" tokenizer = text.WhitespaceTokenizer() tokens = tokenizer.tokenize(['Everything not saved will be lost.', u'Sad☹'.encode('UTF-8')]) bigrams = text.ngrams(tokens, 2, reduction_type=text.Reduction.STRING_JOIN) print(bigrams.to_list())
tensorflow/data/TF_Text.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.8.0 64-bit ('env') # name: python380jvsc74a57bd08596b8d3b26ce6616e7811b8163daf9aea7ff6167af31daab1e43667f4f6ff84 # --- # + import os from pathlib import Path import numpy as np import dotenv import tensorflow as tf import h5py import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import Normalize import seaborn as sns from src.models.fetch_data_from_hdf5 import get_tf_data from src.models.train_model_2d import CustomLoss # + project_dir = Path("../") dotenv_path = project_dir / ".env" dotenv.load_dotenv(str(dotenv_path)) path_clinical_info = Path(os.environ["CLINIC_INFO_PATH"]) model = "model__a_0-75__splc_40__wplc_1__wt_0__wl_0" model_path = project_dir / f"models/clean_model/{model}" path_volume_csv = project_dir / f"data/plc_volume/{model}.csv" bs = 4 image_size = (256, 256) # + clinical_df = pd.read_csv(path_clinical_info).set_index("patient_id") volume_pred_df = pd.read_csv(path_volume_csv) volume_pred_df["patient_id"] = volume_pred_df["patient_id"].astype(int) volume_pred_df = volume_pred_df.set_index("patient_id") df = pd.concat([clinical_df, volume_pred_df], axis=1) df = df.dropna(axis=0) # - def get_trainval_patient_list(df_path): df = pd.read_csv(df_path).set_index("patient_id") id_train = df[df["train_val_test"] == 0].index id_val = df[df["train_val_test"] == 1].index id_test = df[df["train_val_test"] == 2].index patient_list_test = [f"PatientLC_{i}" for i in id_test] patient_list_val = [f"PatientLC_{i}" for i in id_val] patient_list_train = [f"PatientLC_{i}" for i in id_train] return patient_list_train, patient_list_val, patient_list_test, df (patient_list_train, patient_list_val, patient_list_test, clinical_df) = get_trainval_patient_list("/home/val/python_wkspce/plc_seg/data/split.csv") df["plc_volume_cubed"] = df["plc_volume"].map(lambda x: np.cbrt(x)) # df_test = df.loc[map(lambda x: int(x.split("_")[-1]), patient_list_test), :] sns.catplot(x='plc_status',y='plc_volume_cubed', height=5,kind='box', width=0.1, aspect=1, data=df) sns.swarmplot(x='plc_status',y='plc_volume_cubed', data=df, color="black") # + file = h5py.File( "/home/val/python_wkspce/plc_seg/data/processed/2d_pet_normalized/test.hdf5", "r") data_test = get_tf_data( file, clinical_df, output_shape_image=(256, 256, 3), random_slice=False, label_to_contain="GTV L", return_complete_gtvl=True, return_patient=True, return_plc_status=True, # patient_list=patient_list_test ).batch(2) # - model = tf.keras.models.load_model(model_path, compile=False) optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3) model.compile( loss=CustomLoss(), optimizer=optimizer, run_eagerly=False, ) for x, y_true, plc_status, patient_id in data_test.as_numpy_iterator(): y_pred = model(x).numpy() print(f"Dynamic range of ct [{np.min(x[...,0])}, {np.max(x[...,0])}]\n" f"Dynamic range of pt [{np.min(x[...,1])}, {np.max(x[...,1])}]\n" # f"Dynamic range of third channel [{np.min(x[...,2])}, {np.max(x[...,2])}]" ) # + for x, y_true, plc_status, patient_id in data_test.as_numpy_iterator(): y_pred = model(x) for i in range(x.shape[0]): fig, axs = plt.subplots(1, 3, figsize=(16,8)) fig.subplots_adjust(left=0.05, bottom=0.06, right=0.95, top=0.94, wspace=0.4) im1 = axs[0].axis('off') im1 = axs[0].imshow(x[i,:,:,0],cmap='gray') im1 = axs[0].imshow(y_true[i, :,:,4], cmap='jet', alpha=0.5) axs[0].set_title("VOI L") im2 = axs[1].axis('off') im2 = axs[1].imshow(x[i,:,:,0],cmap='gray') im2 = axs[1].imshow(x[i, :,:,1], cmap='hot', alpha=0.5, norm=Normalize(vmin=0.0, vmax=2.5, clip=True)) axs[1].margins(2,2) cax2 = fig.add_axes([axs[1].get_position().x1+0.01,axs[1].get_position().y0,0.02,axs[1].get_position().height]) plt.colorbar(im2, cax=cax2) # Similar to fig.colorbar(im, cax = cax) axs[1].set_title("PET/CT") im3 = axs[2].axis('off') im3 = axs[2].imshow(x[i,:,:,0],cmap='gray') im3 = axs[2].imshow(y_pred[i, :,:,1], cmap='jet', alpha=0.5, norm=Normalize(vmin=0.0, vmax=0.5, clip=True)) cax3 = fig.add_axes([axs[2].get_position().x1+0.01,axs[2].get_position().y0,0.02,axs[2].get_position().height]) plt.colorbar(im3, cax=cax3) # Similar to fig.colorbar(im, cax = cax) axs[2].set_title("Prediction") p_id = patient_id[i].decode('utf-8') volume = volume_pred_df[volume_pred_df["patient_name"]==p_id]["plc_volume"].values[0] fig.suptitle(f"{patient_id[i].decode('utf-8')}\nPLC status: {int(plc_status[i,0])}" f"\nPredicted volume {volume} [mm$^3$]", fontsize=20) path_to_save = f"/home/val/python_wkspce/plc_seg/reports/figures/{p_id}.png" fig.savefig(path_to_save, transparent=False, facecolor="white") plt.close(fig=fig) # - im3 = axs[2].axis('off') # + # file_train.close() file_test.close() # + file_train = h5py.File( "/home/val/python_wkspce/plc_seg/data/processed/2d_pet_normalized/train.hdf5", "r") patient_list = list(file_train.keys()) patient_list = [p for p in patient_list if p not in ["PatientLC_63"]] data_train = get_tf_data( file_train, clinical_df, output_shape=(256, 256), random_slice=False, label_to_center="GTV L", return_complete_gtvl=True, return_patient=True, return_plc_status=True, patient_list=patient_list, ).batch(4) # - for x, y_true, plc_status, patient_id in data_train.as_numpy_iterator(): y_pred = model(x).numpy() for i in range(x.shape[0]): fig, axs = plt.subplots(1, 3, figsize=(16,8)) fig.subplots_adjust(left=0.05, bottom=0.06, right=0.95, top=0.94, wspace=0.4) im1 = axs[0].axis('off') im1 = axs[0].imshow(x[i,:,:,0],cmap='gray') im1 = axs[0].imshow(y_true[i, :,:,4], cmap='jet', alpha=0.5) axs[0].set_title("VOI L") im2 = axs[1].axis('off') im2 = axs[1].imshow(x[i,:,:,0],cmap='gray') im2 = axs[1].imshow(x[i, :,:,1], cmap='hot', alpha=0.5, norm=Normalize(vmin=0.0, vmax=2.5, clip=True)) axs[1].margins(2,2) cax2 = fig.add_axes([axs[1].get_position().x1+0.01,axs[1].get_position().y0,0.02,axs[1].get_position().height]) plt.colorbar(im2, cax=cax2) # Similar to fig.colorbar(im, cax = cax) axs[1].set_title("PET/CT") im3 = axs[2].axis('off') im3 = axs[2].imshow(x[i,:,:,0],cmap='gray') im3 = axs[2].imshow(y_pred[i, :,:,1], cmap='jet', alpha=0.5, norm=Normalize(vmin=0.0, vmax=0.5, clip=True)) cax3 = fig.add_axes([axs[2].get_position().x1+0.01,axs[2].get_position().y0,0.02,axs[2].get_position().height]) plt.colorbar(im3, cax=cax3) # Similar to fig.colorbar(im, cax = cax) axs[2].set_title("Prediction") p_id = patient_id[i].decode('utf-8') fig.suptitle(f"{patient_id[i].decode('utf-8')}\nPLC status: {int(plc_status[i,0])}" f"\nTRAIN", fontsize=20) path_to_save = f"/home/val/python_wkspce/plc_seg/reports/figures_train/{p_id}.png" fig.savefig(path_to_save, transparent=False, facecolor="white") plt.close(fig=fig) clinical_df.iloc[np.isnan(clinical_df["sick_lung_axis"].values),:] file_train.keys()
notebooks/visual_results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.6 # language: python # name: python3 # --- # # Predicting Loan Risk using SparkML on IBM Cloud Pak for Data as a Service # We'll use this notebook to create a machine learning model to predict customer churn. In this notebook we will build the prediction model using the SparkML library. # # This notebook walks you through these steps: # # - Load and Visualize data set. # - Build a predictive model with SparkML API # - Save the model in the ML repository # ## 1.0 Install required packages # # There are a couple of Python packages we will use in this notebook. # # WML Client: http://ibm-wml-api-pyclient.mybluemix.net/ # ### 1.1 Package Installation import warnings warnings.filterwarnings('ignore') # + # !pip uninstall watson-machine-learning-client -y | tail -n 1 # !pip uninstall watson-machine-learning-client-V4 -y | tail -n 1 # !pip install --upgrade ibm-watson-machine-learning==1.0.22 --user --no-cache | tail -n 1 # !pip install --upgrade pyspark==2.4.0 --user --no-cache | tail -n 1 # - # ### 1.2 Package Imports from ibm_watson_machine_learning import APIClient import pandas as pd import numpy as np import json import os # ## 2.0 Load and Clean data # # We'll load our data as a pandas data frame. # # **<font color='red'><< FOLLOW THE INSTRUCTIONS BELOW TO LOAD THE DATASET >></font>** # # * Highlight the cell below by clicking it. # * Click the `01/00` "Find data" icon in the upper right of the notebook. # * Add the locally uploaded file `german_credit_data.csv` by choosing the `Files` tab. Then choose the `german_credit_data.csv`. Click `Insert to code` and choose `pandas DataFrame`. # * The code to bring the data into the notebook environment and create a Pandas DataFrame will be added to the cell below. # * Run the cell # # + # Place cursor below and insert the Pandas DataFrame for the Credit Risk data import types import pandas as pd from botocore.client import Config import ibm_boto3 def __iter__(self): return 0 # @hidden_cell # The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials. # You might want to remove those credentials before you share the notebook. client_42566de6c062499c8afc68156fe822fd = ibm_boto3.client(service_name='s3', ibm_api_key_id='<KEY>', ibm_auth_endpoint="https://iam.cloud.ibm.com/oidc/token", config=Config(signature_version='oauth'), endpoint_url='https://s3-api.us-geo.objectstorage.service.networklayer.com') body = client_4***********************d.get_object(Bucket='creditriskproject-donotdelete-pr-atqrxmoe8zw0sw',Key='german_credit_data.csv')['Body'] # add missing __iter__ method, so pandas accepts body as file-like object if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType( __iter__, body ) df_data_2 = pd.read_csv(body) df_data_2.head() # - # We'll use the Pandas naming convention df for our DataFrame. Make sure that the cell below uses the name for the dataframe used above. For the locally uploaded file it should look like df_data_1 or df_data_2 or df_data_x. # # **<font color='red'><< UPDATE THE VARIABLE ASSIGNMENT TO THE VARIABLE GENERATED ABOVE. >></font>** # Replace df_data_1 with the variable name generated above. df = df_data_2 # ### 2.1 Drop Some Features # Some columns are data attributes that we will not want to use in the machine learning model. We can drop those columns / features: # # - CustomerID feature (column) # - Personal Attributes: first_name,last_name,email,street_address,city,state,postal_code #Drop some columns, ignoring errors for missing keys in case we use different data sets. df = df.drop(columns=['CustomerID', 'FirstName', 'LastName', 'Email', 'StreetAddress', 'City', 'State', 'PostalCode', '_ID'], axis=1, errors='ignore') df.head(5) # ### 2.2 Examine the data types of the features df.info() # Statistics for the columns (features). Set it to all, since default is to describe just the numeric features. df.describe(include = 'all') # We see that the loan amounts range from 250 to ~11,600. That the age range for applicants is between 19 and 74. etc. # ### 2.3 Check for missing data # # We should check if there are missing values in our dataset. There are various ways we can address this issue: # # - Drop records with missing values # - Fill in the missing value with one of the following strategies: Zero, Mean of the values for the column, Random value, etc). # Check if we have any NaN values and see which features have missing values that should be addressed print(df.isnull().values.any()) df.isnull().sum() # If there are any missing values from the output above, the sample below would be one approach to handle this issue by imputing the values for the column that reported missing data (i.e the `CurrentResidenceDuration` column in the code as an example): # # + ## Handle missing values for nan_column (CurrentResidenceDuration) #from sklearn.impute import SimpleImputer ## Find the column number for TotalCharges (starting at 0). #target_idx = df.columns.get_loc("CurrentResidenceDuration") #imputer = SimpleImputer(missing_values=np.nan, strategy="mean") #df.iloc[:, target_idx] = imputer.fit_transform(df.iloc[:, target_idx].values.reshape(-1, 1)) #df.iloc[:, target_idx] = pd.Series(df.iloc[:, target_idx]) # - # ### 2.4 Categorize Features # # We will categorize some of the columns / features based on whether they are categorical values or continuous (i.e numerical) values. We will use this in later sections to build visualizations. # + TARGET_LABEL_COLUMN_NAME = 'Risk' columns_idx = np.s_[0:] # Slice of first row(header) with all columns. first_record_idx = np.s_[0] # Index of first record string_fields = [type(fld) is str for fld in df.iloc[first_record_idx, columns_idx]] # All string fields all_features = [x for x in df.columns if x != TARGET_LABEL_COLUMN_NAME] categorical_columns = list(np.array(df.columns)[columns_idx][string_fields]) categorical_features = [x for x in categorical_columns if x != TARGET_LABEL_COLUMN_NAME] continuous_features = [x for x in all_features if x not in categorical_features] print('All Features: ', all_features) print('\nCategorical Features: ', categorical_features) print('\nContinuous Features: ', continuous_features) print('\nAll Categorical Columns: ', categorical_columns) # - # ### 2.5 Visualize data # # Data visualization can be used to find patterns, detect outliers, understand distribution and more. We can use graphs such as: # # - Histograms, boxplots, etc: To find distribution / spread of our continuous variables. # - Bar charts: To show frequency in categorical values. # # + import seaborn as sns import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder # %matplotlib inline sns.set(style="darkgrid") sns.set_palette("hls", 3) # - # First, we get a high level view of the distribution of Risk. What percentage of applicants in our dataset represent Risk vs No Risk. print(df.groupby([TARGET_LABEL_COLUMN_NAME]).size()) risk_plot = sns.countplot(data=df, x=TARGET_LABEL_COLUMN_NAME, order=df[TARGET_LABEL_COLUMN_NAME].value_counts().index) plt.ylabel('Count') for p in risk_plot.patches: height = p.get_height() risk_plot.text(p.get_x()+p.get_width()/2., height + 1,'{0:.0%}'.format(height/float(len(df))),ha="center") plt.show() # We can get use frequency counts charts to get an understanding of the categorical features relative to Risk # # - We can see in the `CheckingStatus` visualization, loan applications with 'no_checking' have a higher occurence of Risk versus loans with other checking status values. # - We can see in the `CreditHistory` visualization, the loans that have no credits (i.e. all credit has been paid back) have no occurences of Risk (at least in this dataset). There is a small count of Risk for those applicants that have paid back all credit to date. And there is a higher frequency or ratio of Risk for applicants that have existing credit (i.e outstanding credit). # # ### NOTE: The creation of these plots can take several minutes # + # Categorical feature count plots f, ((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8), (ax9, ax10), (ax11, ax12), (ax13, ax14)) = plt.subplots(7, 2, figsize=(25, 25)) ax = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11, ax12, ax13, ax14 ] for i in range(len(categorical_features)): sns.countplot(x = categorical_features[i], hue=TARGET_LABEL_COLUMN_NAME, data=df, ax=ax[i]) # - # We can use histogram and boxplots to get an understanding of the distribution of our continuous / numerical features relative to Risk. # # - We can see that for loans that have Risk, the `InstallmentPercent` tends to be higher (i.e. the loans with Risk tend to have loan amounts with higher percentage of the loan applicants disposable income). # - We can see that those with 'No Risk' seem to be those with fewer existing credit loans at the bank (`ExistingCreditCount`) # # Continuous feature histograms. f, ((ax1, ax2),(ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4, 2, figsize=(25, 25)) ax = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8] for i in range(len(continuous_features)): #sns.distplot(df[continuous_features[i]], bins=20, color="blue", hist=True, ax=ax[i]) sns.distplot(df[df.Risk == 'Risk'][continuous_features[i]], bins=20, color="Red", hist=True, ax=ax[i]) sns.distplot(df[df.Risk == 'No Risk'][continuous_features[i]], bins=20, color="blue", hist=True, ax=ax[i]) # Plot boxplots of numerical columns. More variation in the boxplot implies higher significance. f, ((ax1, ax2),(ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4, 2, figsize=(25, 25)) ax = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8] for i in range(len(continuous_features)): sns.boxplot(x = TARGET_LABEL_COLUMN_NAME, y = continuous_features[i], data=df, ax=ax[i]) # ## 3.0 Create a model # # Now we can create our machine learning model. You could use the insights / intuition gained from the data visualization steps above to decide what kind of model to create or which features to use. We will create a simple classification model. # + from pyspark.sql import SparkSession import pandas as pd import json spark = SparkSession.builder.getOrCreate() df_data = spark.createDataFrame(df) df_data.head() # - # ### 3.1 Split the data into training and test sets # + spark_df = df_data (train_data, test_data) = spark_df.randomSplit([0.8, 0.2], 24) print("Number of records for training: " + str(train_data.count())) print("Number of records for evaluation: " + str(test_data.count())) # - # ### 3.2 Examine the Spark DataFrame Schema # Look at the data types to determine requirements for feature engineering spark_df.printSchema() # ### 3.3 Use StringIndexer to encode a string column of labels to a column of label indices # # We are using the Pipeline package to build the development steps as pipeline. # We are using StringIndexer to handle categorical / string features from the dataset. StringIndexer encodes a string column of labels to a column of label indices # # We then use VectorAssembler to asemble these features into a vector. Pipelines API requires that input variables are passed in a vector # + from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.feature import OneHotEncoder, StringIndexer, IndexToString, VectorAssembler, SQLTransformer from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml import Pipeline, Model #Create StringIndexer columns whose names are same as the categorical column with an appended _IX. categorical_num_features = [x + '_IX' for x in categorical_features] si_list = [StringIndexer(inputCol=nm_in, outputCol=nm_out) for nm_in, nm_out in zip(categorical_features, categorical_num_features)] # - # Encode our target label column (i.e Risk or No Risk). # Also, creates an label convert which performs an inverse map to get back a 'Risk' or 'No Risk' label from the encoded prediction. si_label = StringIndexer(inputCol=TARGET_LABEL_COLUMN_NAME, outputCol="label").fit(spark_df) label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=si_label.labels) # Construct all encoded categorical features plus continuous features into a vector va_features = VectorAssembler(inputCols=categorical_num_features + continuous_features, outputCol="features") # ### 3.4 Create a pipeline, and fit a model using RandomForestClassifier # Assemble all the stages into a pipeline. We don't expect a clean linear regression, so we'll use RandomForestClassifier to find the best decision tree for the data. # # The pipeline will consist of: the feature string indexing step, the label string indexing step, vector assembly of all features step, random forest classifier, label converter step, and ending with a feature filter step. # # **Note: If you want filter features from model output, you could use the feature filter by replacing `*` with feature names to be retained in SQLTransformer statement.** # + classifier = RandomForestClassifier(featuresCol="features") feature_filter = SQLTransformer(statement="SELECT * FROM __THIS__") pipeline = Pipeline(stages= si_list + [si_label, va_features, classifier, label_converter, feature_filter]) model = pipeline.fit(train_data) # + predictions = model.transform(test_data) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction", metricName='areaUnderROC') area_under_curve = evaluatorDT.evaluate(predictions) evaluatorDT = BinaryClassificationEvaluator(rawPredictionCol="prediction", metricName='areaUnderPR') area_under_PR = evaluatorDT.evaluate(predictions) #default evaluation is areaUnderROC print("areaUnderROC = %g" % area_under_curve, "areaUnderPR = %g" % area_under_PR) # - # ### 3.5 evaluate more metrics by exporting them into pandas and numpy from sklearn.metrics import classification_report y_pred = predictions.toPandas()['prediction'] y_pred = ['Risk' if pred == 1.0 else 'No Risk' for pred in y_pred] y_test = test_data.toPandas()[TARGET_LABEL_COLUMN_NAME] print(classification_report(y_test, y_pred, target_names=['Risk', 'No Risk'])) # ## 4.0 Save the model # # Now the model can be saved for future deployment. The model will be saved using the Watson Machine Learning client, to a deployment space. # ### 4.1 Connection to WML # # To authenticate the Watson Machine Learning service on IBM Cloud, you need to provide a platform `api_key` and an endpoint URL. Where the endpoint URL is based on the `location` of the WML instance. To get these values you can use either the IBM Cloud CLI or the IBM Cloud UI. # # #### IBM Cloud CLI # # You can use the [IBM Cloud CLI](https://cloud.ibm.com/docs/cli/index.html) to create a platform API Key and retrieve your instance location. # # - To generate the Cloud API Key, run the following commands: # ``` # ibmcloud login # ibmcloud iam api-key-create API_KEY_NAME # ``` # - Copy the value of `api_key` from the output. # # # - To retrieve the location of your WML instance, run the following commands: # ``` # ibmcloud login --apikey API_KEY -a https://cloud.ibm.com # ibmcloud resource service-instance "WML_INSTANCE_NAME" # ``` # > Note: WML_INSTANCE_NAME is the name of your Watson Machine Learning instance and should be quoted in the command. # # - Copy the value of `Location` from the output. # #### IBM Cloud UI # # To generate Cloud API key: # - Go to the [**Users** section of the Cloud console](https://cloud.ibm.com/iam#/users). # - From that page, click your name in the top right corner, scroll down to the **API Keys** section, and click **Create an IBM Cloud API key**. # - Give your key a name and click **Create**, then copy the created key and to use it below. # # To retrieve the location of your WML instance: # - Go to the [**Resources List** section of the Cloud console](https://cloud.ibm.com/resources). # - From that page, expand the **Services** section and find your Watson Machine Learning Instance. # - Based on the Location displayed in that page, select one of the following values for location variable: # |Displayed Location|Location| # |-|-| # |Dallas|us-south| # |London|eu-gb| # |Frankfurt|eu-de| # |Tokyo|jp-tok| # # **<font color='red'><< Enter your `api_key` and `location` in the following cell. >></font>** api_key = '******************************' location = 'us-south' wml_credentials = { "apikey": api_key, "url": 'https://' + location + '.ml.cloud.ibm.com' } wml_client = APIClient(wml_credentials) wml_client.spaces.list() # ### 4.2 Use the desired space as the `default_space` # # **<font color='red'><< UPDATE THE VARIABLE 'MODEL_NAME' TO A UNIQUE NAME>></font>** # # **<font color='red'><< UPDATE THE VARIABLE 'DEPLOYMENT_SPACE_NAME' TO THE NAME OF THE DEPLOYMENT SPACE CREATED PREVIOUSLY>></font>** # # You should copy the name of your deployment space from the output of the previous cell to the variable in the next cell. The deployment space ID will be looked up based on the name specified below. If you do not receive a space GUID as an output to the next cell, do not proceed until you have created a deployment space. MODEL_NAME = "JRTCreditRiskSparkModel1014v1" DEPLOYMENT_SPACE_NAME = "CreditRiskDeploymentSpace" # + wml_client.spaces.list() all_spaces = wml_client.spaces.get_details()['resources'] space_id = None for space in all_spaces: if space['entity']['name'] == DEPLOYMENT_SPACE_NAME: space_id = space["metadata"]["id"] print("\nDeployment Space ID: ", space_id) if space_id is None: print("WARNING: Your space does not exist. Create a deployment space before proceeding to the next cell.") #space_id = client.spaces.store(meta_props={client.spaces.ConfigurationMetaNames.NAME: space_name})["metadata"]["guid"] # - # Now set the default space to the ID for your deployment space. If this is successful, you will see a 'SUCCESS' message. wml_client.set.default_space(space_id) # ### 4.3 (Optional) Remove Existing Model and Deployment # + #models = wml_client.repository.get_model_details() #model_uid = None #for model_in in models['resources']: # if MODEL_NAME == model_in['metadata']['name']: # model_uid = model_in['metadata']['id'] # print('Deleting model id', model_uid) # wml_client.repository.delete(model_uid) # break # #wml_client.repository.list_models() # - # ### 4.4 Save the Model # + software_spec_uid = wml_client.software_specifications.get_id_by_name("spark-mllib_2.4") print("Software Specification ID: {}".format(software_spec_uid)) metadata = { wml_client.repository.ModelMetaNames.NAME: MODEL_NAME, wml_client._models.ConfigurationMetaNames.SPACE_UID: space_id, wml_client.repository.ModelMetaNames.TYPE: 'mllib_2.4', wml_client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: software_spec_uid } published_model_details = wml_client.repository.store_model(model, metadata, training_data=df_data, pipeline=pipeline) model_uid = wml_client.repository.get_model_uid(published_model_details) print(json.dumps(published_model_details, indent=3)) # - wml_client.repository.list_models() wml_client.deployments.list() # ## Congratulations, you have created and saved a machine learning model !
notebooks/with-output/machinelearning-creditrisk-sparkmlmodel-with-output.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # [Link](https://www.programiz.com/python-programming/assert-statement) # **What is Assertion?** # Assertions are statements that assert or state a fact confidently in your program. For example, while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not equal to zero. # # Assertions are simply boolean expressions that checks if the conditions return true or not. If it is true, the program does nothing and move to the next line of code. However, if it's false, the program stops and throws an error. # # It is also a debugging tool as it brings the program on halt as soon as any error is occurred and shows on which point of the program error has occurred. # <img src="Python Assert Statement.jpg"> # **Python assert Statement** # Python has built-in assert statement to use assertion condition in the program. assert statement has a condition or expression which is supposed to be always true. If the condition is false assert halts the program and gives an AssertionError. # # Syntax for using Assert in Pyhton: # **assert condition** # **assert condition,error message** # In Python we can use assert statement in two ways as mentioned above. # # assert statement has a condition and if the condition is not satisfied the program will stop and give AssertionError. # assert statement can also have a condition and a optional error message. If the condition is not satisfied assert stops the program and gives AssertionError along with the error message. # ## Using assert without Error Message # + def printList(marks): assert len(marks) != 0 return len(marks) mark2 = [55,88,78,90,79] print("No. of Elements:",printList(mark2)) mark1 = [] print("No. of Elements:",printList(mark1)) # - # No. of Elements: 5 # AssertionError: # ## 2. Using assert with Error Message # + def avg(marks): assert len(marks) != 0,"*** List is empty. ***" return sum(marks)/len(marks) mark2 = [55,88,78,90,79] print("Average of mark2:",avg(mark2)) mark1 = [] print("Average of mark1:",avg(mark1)) # - # Average of mark2: 78.0 # AssertionError: *** List is empty. ***
18. Adv Python Exception Handling/12. Assertions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## For a given layer # * How many resources required? # * How long is the latency? # test layer test_layer = {"nix": 224, "niy": 224, "nif": 64, "nof": 64, "kernel": 3, "type": "conv"} # ## Resource Cost # * DSP # * $n^2 \times P_n \times P_m$ # * $n^2$: panel size of IFM; $P_m$: parallel input channel; $P_n$: parallel output channel # * BRAM # * BRAM18K: width = 18-bits; depth = 1024 # * For example, buffer size = $32(bits) \times 512$, concatenating two units of BRAM18K to have wider datawidth # * Weight buffer: $r^2 \times T_n \times T_m$. # * IFM buffer: $W\times T_m\times n$ # * IFM Line Buffer Temp: tile overlap area, $W\times T_m\times m$ # * OFM buffer: $2\times C \times T_n \times m$ # * Banks: 一個 Cycle 可存取的 data 量 # * Weight: $r^2 \times P_n \times P_m$ # * IFM: $n^2 \times P_m$ # * IFM Temp: $n\times m \times P_m$ # * OFM: $2\times m^2 \times P_n$, multiply by 2 since 32-bits accumulator # * Depth: $\frac{\text{buffer size}}{\text{banks}}$ # * Weight: $\frac{r^2 \times T_n \times T_m}{r^2 \times P_n \times P_m} = \frac{T_n}{p_n}\times\frac{T_m}{p_m}$ # * IFM: $\frac{W\times T_m\times n}{n^2 \times P_m} = \frac{W}{n} \times \frac{T_m}{P_m}$ # * IFM Temp: $\frac{W\times T_m\times m}{n\times m \times P_m} = \frac{W}{n}\times\frac{T_m}{P_m}$ # * OFM: $\frac{2\times C \times T_n \times m}{2\times m^2 \times P_n} = \frac{C}{m}\times\frac{T_n}{P_n}$ # # * Total BRAM units: $\frac{\text{datawidth}}{18} \times \frac{\text{depth}}{1024}$, $\text{datawidth} = \text{banks}\times 16(\text{bits})$ # * Weight: $\frac{r^2 \times P_n \times P_m\times 16}{18} \times \frac{\frac{T_n}{p_n}\times\frac{T_m}{p_m}}{1024}$ # * IFM: $\frac{n^2 \times P_m \times 16}{18} \times \frac{\frac{W}{n} \times \frac{T_m}{P_m}}{1024}$ # * IFM Temp: $\frac{n\times m \times P_m \times 16}{18} \times \frac{\frac{W}{n}\times\frac{T_m}{P_m}}{1024}$ # * OFM: $\frac{m^2 \times P_n \times 32}{18} \times \frac{\frac{C}{m}\times\frac{T_n}{P_n}}{1024}$ # # # + from math import ceil def dsp_cost(n, Pn, Pm): return (n**2) * Pn * Pm def bram_cost(W, C, r, n, m, Tn, Tm, Pn, Pm, precision = 16, double_buffering = True): weight = ceil(((r**2) * Pn * Pm * precision)/18) * ceil((ceil(Tn/Pn)*ceil(Tm/Pm)) / 1024) IFM = ceil(((n**2) * Pm * precision)/18) * ceil((ceil(W/n) * ceil(Tm/Pm))/1024) IFM_temp = ceil((n*m*Pm*precision) / 18) * ceil((ceil(W/n)*ceil(Tm/Pm))/1024) OFM = ceil(((m**2)*Pn*32)/18) * ceil((ceil(C/m)*ceil(Tn/Pn))/1024) print(weight, IFM, IFM_temp, OFM) factor = 1 if double_buffering: factor = 2 return factor*(weight + IFM + IFM_temp + OFM) # - W = 224; C=224; r=3; n=6; m=4; Tn=128; Tm=128; Pn=8; Pm=8; precision = 16 bram_cost(W, C, r, n, m, Tn, Tm, Pn, Pm, precision) # ## Modeling Performance # * Tile comutation latency for one tile # * $T_{\text{compute}} = (\frac{C}{m} \times \frac{T_m}{P_m} \times \frac{T_n}{P_n} \times \text{II} + P_{\text{depth}}) \times \frac{1}{\text{Freq}}$ # * $\text{II} = 1$ # # * Data transfer time: for input and output data # * $T_{\text{transfer}} = \frac{n \times W \times \max(T_n, T_m) \times 16}{\text{datawidth}}$ # # * Initial time: loading IFM and WGT # * $T_{\text{init}} = \frac{(T_m \times T_n \times r^2 + n \times W \times T_m) \times 16}{\text{datawidth}}$ # # * Total Latency # * $T_{\text{total}} = \frac{M}{T_m} \times \frac{N}{T_n} \times (\frac{H}{m} \times T_{\text{compute}} + T_{\text{init}})$ # + def latency_tile(W, C, n, m, Tn, Tm, Pn, Pm, datawidth, II=1, precision=16, freq=0.2): compute_time = (ceil(C/m) * ceil(Tm / Pm) * ceil(Tn/Pn) * II) * (1/freq) * (10**(-6)) transfer_time = ceil((n*W*max(Tn,Tm)*precision)/datawidth) * (1/freq) * (10**(-6)) print("compute_time > transfer_time:", compute_time > transfer_time) return max(compute_time, transfer_time) def latency_init(W, r, n , Tn, Tm, datawidth, precision=16, freq = 16): init_time = ceil((Tm*Tn*r*r + n*W*Tm)*precision / datawidth) * (1/freq) * (10**(-6)) return init_time def latency_total(W, C, M, N, H, r, n, m, Tn, Tm, Pn, Pm, datawidth, II=1, precision = 16, freq = 0.2): total_time = ceil(M/Tm) * ceil(N/Tn) * (ceil(H/m) * \ latency_tile(W, C, n, m, Tn, Tm, Pn, Pm, datawidth, II, precision, freq) + \ latency_init(W, r, n , Tn, Tm, datawidth, precision)) return total_time; # - W = 224; H=224; C=112; M = 20; N = 64; r=7; n=8; m=6; Tn=64; Tm=64; Pn=2; Pm=2; II=1; datawidth=512; precision = 16 latency_total(W, C, M, N, H, r, n, m, Tn, Tm, Pn, Pm, datawidth) # IFM (8*6*6*16)/18 # IFM temp (4*6*8*16)/18 # OFM (2*4*4*8*16)/18 # WGT (9*8*8*16)/18 256.0 + 170.66666666666666 + 227.55 + 512.0 2479/32
fast_convolution/single layer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <center> # <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DL0110EN-SkillsNetwork/Template/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" /> # </center> # # <h1>Digit Classification with Softmax</h1> # # <h2>Objectives</h2> # # <ul> # <li>Download the Training and Validation MNIST Digit Images</li> # <li>Create a Softmax Classifier using PyTorch</li> # <li>Create a Criterion, Optimizer, and Data Loaders</li> # <li>Create a Data Loader and set the Batch Size</li> # <li>Train a Model</li> # <li>Analyze Results and Model</li> # </ul> # # <h2>Table of Contents</h2> # <p>In this lab, you will use a single-layer Softmax Classifier to classify handwritten digits from the MNIST database.</p> # # <ul> # <li><a href="https://#Makeup_Data">Make some Data</a></li> # <li><a href="https://#Classifier">Build a Softmax Classifier</a></li> # <li><a href="https://#Model">Define Softmax, Criterion Function, Optimizer, and Train the Model</a></li> # <li><a href="https://#Result">Analyze Results</a></li> # </ul> # <p>Estimated Time Needed: <strong>25 min</strong></p> # # <hr> # # <h2>Preparation</h2> # # We'll need the following libraries # # + # Import the libraries we need for this lab # Using the following line code to install the torchvision library # # !conda install -y torchvision # PyTorch Library import torch # PyTorch Neural Network import torch.nn as nn # Allows us to transform data import torchvision.transforms as transforms # Allows us to get the digit dataset import torchvision.datasets as dsets # Creating graphs import matplotlib.pylab as plt # Allows us to use arrays to manipulate and store data import numpy as np # - # Use the following function to plot out the parameters of the Softmax function: # # + # The function to plot parameters def PlotParameters(model): W = model.state_dict()['linear.weight'].data w_min = W.min().item() w_max = W.max().item() fig, axes = plt.subplots(2, 5) fig.subplots_adjust(hspace=0.01, wspace=0.1) for i, ax in enumerate(axes.flat): if i < 10: # Set the label for the sub-plot. ax.set_xlabel("class: {0}".format(i)) # Plot the image. ax.imshow(W[i, :].view(28, 28), vmin=w_min, vmax=w_max, cmap='seismic') ax.set_xticks([]) ax.set_yticks([]) # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show() # - # Use the following function to visualize the data: # # + # Plot the data def show_data(data_sample): plt.imshow(data_sample[0].numpy().reshape(28, 28), cmap='gray') plt.title('y = ' + str(data_sample[1].item())) # - # <!--Empty Space for separating topics--> # # <h2 id="Makeup_Data">Make Some Data</h2> # # Load the <em>training</em> dataset by setting the parameters <code>train</code> to <code>True</code> and convert it to a tensor by placing a transform object in the argument <code>transform</code>. # # + # Create and print the training dataset train_dataset = dsets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor()) print("Print the training dataset:\n ", train_dataset) # - # Load the <em>testing</em> dataset and convert it to a tensor by placing a transform object in the argument <code>transform</code>. # # + # Create and print the validation dataset validation_dataset = dsets.MNIST(root='./data', download=True, transform=transforms.ToTensor()) print("Print the validation dataset:\n ", validation_dataset) # - # We can access the data by indexing the train_dataset and test_dataset # # + # Print the first image and label print("First Image and Label", show_data(train_dataset[0])) # - # Each element in the rectangular tensor corresponds to a number which represents a pixel intensity, as demonstrated by the following image: # # <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/chapter3/3.32_image_values.png" width="550" alt="MNIST elements" /> # # In this image, the values are inverted i.e black represents white. # # Print out the label of the fourth element: # # + # Print the label print("The label: ", train_dataset[3][1]) # - # The result shows the number in the image is 1 # # Plot the fourth sample: # # + # Plot the image print("The image: ", show_data(train_dataset[3])) # - # You see that it is a 1. Now, plot the third sample: # # + # Plot the image show_data(train_dataset[2]) # - # <!--Empty Space for separating topics--> # # <h2 id="#Classifier">Build a Softmax Classifer</h2> # # Build a Softmax classifier class: # # Define softmax classifier class # Inherits nn.Module which is the base class for all neural networks class SoftMax(nn.Module): # Constructor def __init__(self, input_size, output_size): super(SoftMax, self).__init__() # Creates a layer of given input size and output size self.linear = nn.Linear(input_size, output_size) # Prediction def forward(self, x): # Runs the x value through the single layers defined above z = self.linear(x) return z # The Softmax function requires vector inputs. Note that the vector shape is 28x28. # # + # Print the shape of the training dataset train_dataset[0][0].shape # - # Flatten the tensor as shown in this image: # # <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/chapter3/3.3.2image_to_vector.gif" width="550" alt="Flattern Image" /> # # The size of the tensor is now 784. # # <img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/chapter3/3.3.2Imagetovector2.png" width="550" alt="Flattern Image" /> # # Set the input size and output size: # # + # Set input size and output size input_dim = 28 * 28 output_dim = 10 # - # <!--Empty Space for separating topics--> # # <h2 id="Model">Define the Softmax Classifier, Criterion Function, Optimizer, and Train the Model</h2> # # Create the model # Input dim is 28*28 which is the image converted to a tensor # Output dim is 10 because there are 10 possible digits the image can be model = SoftMax(input_dim, output_dim) print("Print the model:\n ", model) # View the size of the model parameters: # # + # Print the parameters print('W: ',list(model.parameters())[0].size()) print('b: ',list(model.parameters())[1].size()) # - # You can convert the model parameters for each class to a rectangular grid: # # <a> <img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/chapter3/3.3.2paramaters_to_image.gif" width = 550, align = "center"></a> # # Plot the model parameters for each class as a square image: # # + # Plot the model parameters for each class # Since the model has not been trained yet the parameters look random PlotParameters(model) # - # We can make a prediction # # First we get the X value of the first image X = train_dataset[0][0] # We can see the shape is 1 by 28 by 28, we need it to be flattened to 1 by 28 * 28 (784) print(X.shape) X = X.view(-1, 28*28) print(X.shape) # Now we can make a prediction, each class has a value, and the higher it is the more confident the model is that it is that digit model(X) # Define the learning rate, optimizer, criterion, data loader: # # + # Define the learning rate, optimizer, criterion, and data loader learning_rate = 0.1 # The optimizer will updates the model parameters using the learning rate optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) # The criterion will measure the loss between the prediction and actual label values # This is where the SoftMax occurs, it is built into the Criterion Cross Entropy Loss criterion = nn.CrossEntropyLoss() # Created a training data loader so we can set the batch size train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100) # Created a validation data loader so we can set the batch size validation_loader = torch.utils.data.DataLoader(dataset=validation_dataset, batch_size=5000) # - # ### How Cross Entropy Loss uses SoftMax # # We have X which is the X values of the first image and `actual` which is the the digit class the image belongs to. The output `model_output` is the value the model assigns to each class for that image. # # + model_output = model(X) actual = torch.tensor([train_dataset[0][1]]) show_data(train_dataset[0]) print("Output: ", model_output) print("Actual:", actual) # - # The criterion will take these values and return a loss # criterion(model_output, actual) # Cross Entropy Loss takes probabilities and we can see that `model_output` are not probabilities, this is where softmax comes in # softmax = nn.Softmax(dim=1) probability = softmax(model_output) print(probability) # Now that we have probabilities, we can just calculate the negative log of the probability of the class that this image belongs to. The image belongs to the target class so we calculate the negative log of the probability at the target index. # -1*torch.log(probability[0][actual]) # As you can see the result above matches the result of the criterion, this is how Cross Entropy Loss uses Softmax. # # ### Train # # Train the model and determine validation accuracy **(should take a few minutes)**: # # + # Number of times we train our model useing the training data n_epochs = 10 # Lists to keep track of loss and accuracy loss_list = [] accuracy_list = [] # Size of the validation data N_test = len(validation_dataset) # Function to train the model based on number of epochs def train_model(n_epochs): # Loops n_epochs times for epoch in range(n_epochs): # For each batch in the train loader for x, y in train_loader: # Resets the calculated gradient value, this must be done each time as it accumulates if we do not reset optimizer.zero_grad() # Makes a prediction based on the image tensor z = model(x.view(-1, 28 * 28)) # Calculates loss between the model output and actual class loss = criterion(z, y) # Calculates the gradient value with respect to each weight and bias loss.backward() # Updates the weight and bias according to calculated gradient value optimizer.step() # Each epoch we check how the model performs with data it has not seen which is the validation data, we are not training here correct = 0 # For each batch in the validation loader for x_test, y_test in validation_loader: # Makes prediction based on image tensor z = model(x_test.view(-1, 28 * 28)) # Finds the class with the higest output _, yhat = torch.max(z.data, 1) # Checks if the prediction matches the actual class and increments correct if it does correct += (yhat == y_test).sum().item() # Calculates the accuracy by dividing correct by size of validation dataset accuracy = correct / N_test # Keeps track loss loss_list.append(loss.data) # Keeps track of the accuracy accuracy_list.append(accuracy) # Function call train_model(n_epochs) # - # <!--Empty Space for separating topics--> # # <h2 id="Result">Analyze Results</h2> # # Plot the loss and accuracy on the validation data: # # + # Plot the loss and accuracy fig, ax1 = plt.subplots() color = 'tab:red' ax1.plot(loss_list,color=color) ax1.set_xlabel('epoch',color=color) ax1.set_ylabel('total loss',color=color) ax1.tick_params(axis='y', color=color) ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('accuracy', color=color) ax2.plot( accuracy_list, color=color) ax2.tick_params(axis='y', color=color) fig.tight_layout() # - # View the results of the parameters for each class after the training. You can see that they look like the corresponding numbers. # # + # Plot the parameters PlotParameters(model) # - # We Plot the first five misclassified samples and the probability of that class. # # Plot the misclassified samples Softmax_fn=nn.Softmax(dim=-1) count = 0 for x, y in validation_dataset: z = model(x.reshape(-1, 28 * 28)) _, yhat = torch.max(z, 1) if yhat != y: show_data((x, y)) plt.show() print("yhat:", yhat) print("probability of class ", torch.max(Softmax_fn(z)).item()) count += 1 if count >= 5: break # <!--Empty Space for separating topics--> # # We plot the first five correctly classified samples and the probability of that class. We see the probability is much larger. # # Plot the classified samples Softmax_fn=nn.Softmax(dim=-1) count = 0 for x, y in validation_dataset: z = model(x.reshape(-1, 28 * 28)) _, yhat = torch.max(z, 1) if yhat == y: show_data((x, y)) plt.show() print("yhat:", yhat) print("probability of class ", torch.max(Softmax_fn(z)).item()) count += 1 if count >= 5: break # <a href="https://dataplatform.cloud.ibm.com/registration/stepone?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkCV0101ENCoursera25797139-2021-01-01&context=cpdaas&apps=data_science_experience%2Cwatson_machine_learning"><img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DL0110EN-SkillsNetwork/Template/module%201/images/Watson_Studio.png"/></a> # # <h2>About the Authors:</h2> # # <a href="https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkCV0101ENCoursera25797139-2021-01-01"><NAME></a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD. # # Other contributors: <a href="https://www.linkedin.com/in/michelleccarey/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkCV0101ENCoursera25797139-2021-01-01"><NAME></a>, <a href="https://www.linkedin.com/in/jiahui-mavis-zhou-a4537814a?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkCV0101ENCoursera25797139-2021-01-01"><NAME></a> # # ## Change Log # # | Date (YYYY-MM-DD) | Version | Changed By | Change Description | # | ----------------- | ------- | ---------- | ----------------------------------------------------------- | # | 2020-09-23 | 2.0 | Shubham | Migrated Lab to Markdown and added to course repo in GitLab | # # <hr> # # ## <h3 align="center"> © IBM Corporation 2020. All rights reserved. <h3/> #
3. Introduction to Computer Vision and Image Processing/2. Machine Learning Image Classification/Digit Classification with Softmax.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %load_ext notifyg.magics # %notifyg_init from datetime import datetime # %notifyg str(datetime.now()) # !conda install --yes matplotlib import time import matplotlib.pyplot as plt import numpy as np from IPython.display import Image # + # %%notifyg time.sleep(10) x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.savefig('test.png') Image(filename='test.png') # - # %%notifyg test
notebooks/BinderExampleOfMagics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + [markdown] deletable=true editable=true # # Pedersen N07 neutral case with heat flux # # Comparison between Nalu-wind and Pedersen (2014) # # **Note**: To convert this notebook to PDF, use the command # ```bash # $ jupyter nbconvert --TagRemovePreprocessor.remove_input_tags='{"hide_input"}' --to pdf postpro_n07.ipynb # ``` # + deletable=true editable=true tags=["hide_input"] # %%capture # Important header information naluhelperdir = '../../utilities/' # Import libraries import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(1, naluhelperdir) import plotABLstats import yaml as yaml from IPython.display import Image from matplotlib.lines import Line2D import matplotlib.image as mpimg # %matplotlib inline # + deletable=true editable=true # Nalu-wind parameters rundir = '/ascldap/users/lcheung/GPFS1/2020/amrcodes/testruns/neutral_n07' statsfile = 'abl_statistics.nc' avgtimes = [82800,86400] # + deletable=true editable=true # Load nalu-wind data data = plotABLstats.ABLStatsFileClass(stats_file=rundir+'/'+statsfile); Vprof, vheader = plotABLstats.plotvelocityprofile(data, None, tlims=avgtimes, exportdata=True) Tprof, theader = plotABLstats.plottemperatureprofile(data, None, tlims=avgtimes, exportdata=True) # + deletable=true editable=true # Pedersen parameters datadir = '../pedersen2014_data' ped_umag = np.loadtxt(datadir+'/Pedersen2014_N07_velocity.csv', delimiter=',') ped_T = np.loadtxt(datadir+'/Pedersen2014_N07_temperature.csv', delimiter=',') h = 757 # + deletable=true editable=true # Plot the velocity profile comparisons plt.figure(figsize=(10,8)); plt.rc('font', size=14) plt.plot(Vprof[:,4], Vprof[:,0]/h, 'b', label='Nalu-wind (Smag)') plt.plot(ped_umag[:,0], ped_umag[:,1], 'r', label='Pedersen(2014)') # Construct a legend plt.legend() plt.ylim([0, 1.5]); plt.xlim([0, 12]) plt.xlabel('Velocity [m/s]') plt.ylabel('Z/h') #plt.grid() plt.title('N07 Wind speed') # + deletable=true editable=true # Plot the temperature profile comparisons plt.figure(figsize=(10,8)); plt.rc('font', size=14) plt.plot(Tprof[:,1], Tprof[:,0], 'b', label='Nalu-wind (Smag)') plt.plot(ped_T[:,0], ped_T[:,1], 'r', label='Pedersen(2014)') # Construct a legend plt.legend() plt.ylim([0, 1500]); #plt.xlim([0, 12]) plt.xlabel('Temperature [K]') plt.ylabel('Z [m]') #plt.grid() plt.title('N07 Temperature') # - # Extract TKE and Reynolds stresses REstresses, REheader = plotABLstats.plottkeprofile(data, None, tlims=avgtimes, exportdata=True) # Extract the fluxes tfluxes, tfluxheader = plotABLstats.plottfluxprofile(data, None, tlims=avgtimes, exportdata=True) # Extract the fluxes sfstfluxes, sfstfluxheader= plotABLstats.plottfluxsfsprofile(data, None, tlims=[avgtimes[-1]-1, avgtimes[-1]], exportdata=True) # Extract Utau avgutau = plotABLstats.avgutau(data, None, tlims=avgtimes) print('Avg Utau = %f'%avgutau) # Calculate the inversion height zi, utauz = plotABLstats.calcInversionHeight(data, [1400.0], tlims=avgtimes) print('zi = %f'%zi) # + deletable=true editable=true # Export the Nalu-Wind data for other people to compare np.savetxt('NaluWind_N07_velocity.dat', Vprof, header=vheader) np.savetxt('NaluWind_N07_temperature.dat', Tprof, header=theader) np.savetxt('NaluWind_N07_reynoldsstresses.dat', REstresses, header=REheader) np.savetxt('NaluWind_N07_temperaturefluxes.dat', tfluxes, header=tfluxheader) np.savetxt('NaluWind_N07_sfstemperaturefluxes.dat', sfstfluxes, header=sfstfluxheader) # - # Write the YAML file with integrated quantities import yaml savedict={'zi':float(zi), 'ustar':float(avgutau)} f=open('istats.yaml','w') f.write('# Averaged quantities from %f to %f\n'%(avgtimes[0], avgtimes[1])) f.write(yaml.dump(savedict, default_flow_style=False)) f.close() # + deletable=true editable=true # Extract Utau utau, utheader = plotABLstats.plotutauhistory(data, None, tlims=avgtimes, exportdata=True) print('Avg Utau = %f'%np.mean(utau[:,1]))
Pedersen_N07/NaluWindRun01/postpro_n07.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # # Text Classification using TextVectorization layer PYTHON ONLY # > Multiclass text classification from scratch using the new Keras TextVectorization layer PYTHON ONLY # # - toc: true # - badges: true # - comments: true # - categories: ["Natural language processing"] # - image: images/keras.png # + colab_type="code" id="8RZOuS9LWQvv" colab={} tags=[] # !pip3 install -q tf-nightly import tensorflow as tf # + colab_type="code" id="2ew7HTbPpCJH" colab={} tags=[] import numpy as np from tensorflow.keras import preprocessing print(tf.__version__) # + [markdown] id="Jxfg2FcfsD8f" colab_type="text" # ### Download the BigQuery dataset # + id="k8eRO0ng5r1A" colab_type="code" colab={} tags=[] # !gsutil cp gs://tensorflow-blog-rnn/so_posts_4labels_blank_80k.tar.gz . # !tar -xf so_posts_4labels_blank_80k.tar.gz # + id="lkqtzHOb51ff" colab_type="code" colab={} tags=[] batch_size = 32 raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( 'train', batch_size=batch_size, validation_split=0.2, subset='training', seed=42) raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory( 'train', batch_size=batch_size, validation_split=0.2, subset='validation', seed=42) raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory( 'test', batch_size=batch_size) # + [markdown] id="yRLs33z1tUi_" colab_type="text" # ### Explore the data # + id="vQlq9CmP6tJX" colab_type="code" colab={} tags=[] import time for text_batch, label_batch in raw_train_ds.take(1): for i in range(5): print(text_batch.numpy()[i]) print(label_batch.numpy()[i]) # + [markdown] id="qmXSZZBNt8aU" colab_type="text" # ### Prepare data for training # + id="VKVrmuB-7fAm" colab_type="code" colab={} from tensorflow.keras.layers.experimental.preprocessing import TextVectorization max_features = 5000 embedding_dim = 128 sequence_length = 500 vectorize_layer = TextVectorization( max_tokens=max_features, output_mode='int', output_sequence_length=sequence_length) # + id="aqO9ZzPV7kOL" colab_type="code" colab={} # Make a text-only dataset (no labels) and call adapt text_ds = raw_train_ds.map(lambda x, y: x) vectorize_layer.adapt(text_ds) # + [markdown] id="fX6zq78yu3Fv" colab_type="text" # ### Vectorize the data # # # + id="H3gXSDzt7qni" colab_type="code" colab={} def vectorize_text(text, label): text = tf.expand_dims(text, -1) return vectorize_layer(text), label # Vectorize the data. train_ds = raw_train_ds.map(vectorize_text) val_ds = raw_val_ds.map(vectorize_text) test_ds = raw_test_ds.map(vectorize_text) # Do async prefetching / buffering of the data for best performance on GPU. train_ds = train_ds.cache().prefetch(buffer_size=10) val_ds = val_ds.cache().prefetch(buffer_size=10) test_ds = test_ds.cache().prefetch(buffer_size=10) # + id="YQb51U7gRhYd" colab_type="code" colab={} tags=[] for text_batch, label_batch in train_ds.take(1): for i in range(5): print(text_batch.numpy()[i]) print(label_batch.numpy()[i]) # + [markdown] id="evYhQerxvAq9" colab_type="text" # ### Build the model # + id="FMQEUVGM74iQ" colab_type="code" colab={} from tensorflow.keras import layers # A integer input for vocab indices. inputs = tf.keras.Input(shape=(None,), dtype='int64') x = layers.Embedding(max_features + 1, embedding_dim)(inputs) x = layers.Bidirectional(layers.LSTM(128))(x) predictions = layers.Dense(4, activation='softmax', name='predictions')(x) model = tf.keras.Model(inputs, predictions) model.compile( loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # + [markdown] id="_AHy6MOCvbm9" colab_type="text" # ### Train the model # + id="Gs78f_N58MO9" colab_type="code" colab={} tags=[] epochs = 5 # Fit the model using the train and test datasets. history = model.fit( train_ds, validation_data=val_ds, epochs=epochs) # + id="w5XaJfR1Pucj" colab_type="code" colab={} model.summary() # + [markdown] id="Hm8g4isKvebz" colab_type="text" # ### Evaluate the model # + id="WbGYQ8sERUT7" colab_type="code" colab={} loss, accuracy = model.evaluate(test_ds) print("Loss: ", loss) print("Accuracy: ", accuracy)
_notebooks/2020-06-25-text-classifier-with-textvectorization-layer-code-ONLY.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="WCgF-8XpkE-G" import matplotlib import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np # + colab={"base_uri": "https://localhost:8080/"} id="YKyGrvFz1hXj" outputId="74363188-380b-4a27-a545-7d010c4b7ba8" from google.colab import drive drive.mount('/content/drive') # + colab={"base_uri": "https://localhost:8080/"} id="lXy6AX1qkMdw" outputId="8fff10be-1e3e-460d-e054-703efc8e5937" #First we generate the piano roll from y_test_pred, that has been predicted by the model arr = np.load('/content/drive/MyDrive/Model2.npy') arr=np.squeeze(arr, axis=-2) print(np.shape(arr)) # + colab={"base_uri": "https://localhost:8080/"} id="cZ7J8-82XMF1" outputId="fb4f6772-2fa5-4d86-9bd2-19ba791c8ea2" #converting boolean to binary matrix with entries 0 and 1 arr2 = np.empty((578322, 88), dtype = int) X=arr for i in range(X.shape[0]): for j in range(X.shape[1]): if X[i,j]==False: arr2[i,j]=int(0) int(arr2[i,j]) elif X[i,j]==True: arr2[i,j]=int(1) print(arr2) # + colab={"base_uri": "https://localhost:8080/"} id="Su38BL8FXWGi" outputId="18eceff1-5773-4303-a9e2-46e8143239c4" # !pip install midiutil # + id="A9futyqCXW8P" from midiutil.MidiFile import MIDIFile mf = MIDIFile(1) track = 0 time = 0 delta = 0.000005 mf.addTrackName(track, time, "Output") mf.addTempo(track, time, 120) channel = 0 volume = 100 duration = 0.01 for i in range(10000): time=time + i*delta for j in range(arr2.shape[1]): if X[i][j] == 1: pitch = j mf.addNote(track, channel, pitch, time, duration, volume) # + id="XMw5So8UtCKB" #generate the MIDI file for y_test_pred with open("output_final.mid", 'wb') as outf: mf.writeFile(outf) # + colab={"base_uri": "https://localhost:8080/"} id="IVa3HkOuXZ9E" outputId="286655c5-3e7e-41d4-9952-e7cbb106712b" # !pip install pretty_midi # + colab={"base_uri": "https://localhost:8080/"} id="GVxuYJI_XcY-" outputId="d2553359-0365-4aa7-9547-e32c7b435d0f" import pretty_midi import pandas as pd path = "output_final.mid" midi_data = pretty_midi.PrettyMIDI(path) midi_list = [] pretty_midi.pretty_midi.MAX_TICK = 1e10 midi_data.tick_to_time(14325216) for instrument in midi_data.instruments: for note in instrument.notes: start = note.start end = note.end pitch = note.pitch velocity = note.velocity midi_list.append([start, end, pitch, velocity, instrument.name]) midi_list = sorted(midi_list, key=lambda x: (x[0], x[2])) df = pd.DataFrame(midi_list, columns=['Start', 'End', 'Pitch', 'Velocity', 'Instrument']) print(df) # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="3nSlxNnHXpu7" outputId="b2cd9077-7b2b-4c6f-bfb1-cc4e9fcd2a94" fig, ax = plt.subplots() i = 0 while(i<52657) : start = float(midi_list[i][0]) pitch = float(midi_list[i][2]) duration = float(midi_list[i][1]-midi_list[i][0]) rect = matplotlib.patches.Rectangle((start, pitch),duration, 1, ec='black', linewidth=1) ax.add_patch(rect) i+=1 plt.xlim([0, 130]) plt.ylim([0, 88]) plt.grid(color='grey',linewidth=1) print('From Model') plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="JW38_pX3azpC" outputId="e3c3943a-bbd6-4b36-b695-cb51b2cbb3be" #Now we generate the piano roll from y_test to check if it matches with the prediction arr3 = np.load('/content/drive/MyDrive/CQT files/Ytestfinal.npy') arr3=np.squeeze(arr3, axis=-2) print(np.shape(arr3)) # + colab={"base_uri": "https://localhost:8080/"} id="uNyysS4Qa_Vr" outputId="32be538d-f4d8-4e42-ddac-4e2dec20c004" #again backtracking to convert 3D array to 2D X2=[] i=0 for i in range(15219): if i==0: X2=arr3[0] else: X2=np.concatenate((X2, arr3[i]), axis=0) print(X2.shape) # + colab={"base_uri": "https://localhost:8080/"} id="cJZPQrhobCgL" outputId="ea3afd0c-b137-44d8-f08c-ba38d9dd8733" arr4 = np.empty((578322, 88), dtype = int) for i in range(X2.shape[0]): for j in range(X.shape[1]): if X2[i,j]==False: arr4[i,j]=int(0) int(arr4[i,j]) elif X2[i,j]==True: arr4[i,j]=int(1) print(arr4) # + id="qF_lbBmBbDCV" print(np.count_nonzero(arr4)) # + id="WC90zDMfbHix" mf = MIDIFile(1) track = 0 time = 0 delta = 0.000005 mf.addTrackName(track, time, "Output") mf.addTempo(track, time, 120) channel = 0 volume = 100 duration = 0.01 for i in range(10000): time=time + i*delta for j in range(arr4.shape[1]): if X2[i][j] == 1: pitch = j mf.addNote(track, channel, pitch, time, duration, volume) # + id="CjVUMkW9bKgT" with open("output_final_actual.mid", 'wb') as outf: mf.writeFile(outf) # + colab={"base_uri": "https://localhost:8080/"} id="jSiHR42tbQlw" outputId="a55faa07-1e10-4b4c-8275-0a701b73a1a0" path = "output_final_actual.mid" midi_data = pretty_midi.PrettyMIDI(path) midi_list = [] pretty_midi.pretty_midi.MAX_TICK = 1e10 midi_data.tick_to_time(14325216) for instrument in midi_data.instruments: for note in instrument.notes: start = note.start end = note.end pitch = note.pitch velocity = note.velocity midi_list.append([start, end, pitch, velocity, instrument.name]) midi_list = sorted(midi_list, key=lambda x: (x[0], x[2])) df = pd.DataFrame(midi_list, columns=['Start', 'End', 'Pitch', 'Velocity', 'Instrument']) print(df) # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="YHHCMsWVbTer" outputId="9e024e2b-881d-49e0-915f-1a3b1f4c1404" fig, ax = plt.subplots() i = 0 while(i<53602) : start = float(midi_list[i][0]) pitch = float(midi_list[i][2]) duration = float(midi_list[i][1]-midi_list[i][0]) rect = matplotlib.patches.Rectangle((start, pitch),duration, 1, ec='black', linewidth=1) ax.add_patch(rect) i+=1 plt.xlim([0, 130]) plt.ylim([0, 88]) plt.grid(color='grey',linewidth=1) print('Actual') plt.show()
MODEL -2 (CNN)/CNN-PostProcessing-2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Map SNPs from dbSNP to 3D structures from PDB. # This notebook is a prototype for visualizing the positions of missense mutations mapped from [dbSNP](https://www.ncbi.nlm.nih.gov/projects/SNP/) (GRCh37 build) to 3D protein structures in the Protein Data Bank. import warnings warnings.filterwarnings("ignore") # numpy version issue? from pyspark.sql import Row, SparkSession from pyspark.sql.functions import collect_set, collect_list, concat_ws from mmtfPyspark.datasets import dbSnpDataset import pandas as pd from ipywidgets import interact, IntSlider, widgets from IPython.display import display import py3Dmol # #### Setup widgets # + code_folding=[0, 3] # setup widgets for query parameters field = widgets.Dropdown(options=('none','snp_id', 'pdbChainId','uniprotId','sqlQuery'),description='Select field:') selection = widgets.Textarea(description='Enter id(s):', value=('')) significance = widgets.SelectMultiple(description='Significance:', \ options=('All', 'Benign', 'Likely benign', 'Likely pathogenic', \ 'Pathogenic', 'drug-response', 'untested', \ 'Uncertain significance', 'other', 'null'), \ value=('Benign', 'Likely benign', 'Likely pathogenic', \ 'Pathogenic', 'drug-response')) # - # ## Select clinical significance # Select one of more significance level from ClinVar (MacOS: hold command key to select multiple criteria). # # Default: Benign, Likely benign, Likely pathogenic, Pathogenic, drug-response. display(significance) # ## Optionally, filter dataset # Select a query field and enter a comma separated list of identifiers: # # Example queries below are for missense mutations in the Cystic Fibrosis [CFTR2 gene](https://www.cftr2.org/mutations_history). # # * none: no filtering (Default) # * snp_id: 397508256, 397508796 (also called the rsId, e.g. rs397508256) # * pdbChainId: 5UAK.A # * uniprotId: P13569 # * sqlQuery: any valid sql query (e.g., chr = 7 AND pos = 117149089) # + code_folding=[] # show widgets display(field) display(selection) # - # #### Construct query # + code_folding=[0] # create query strings if significance.value and not 'All' in significance.value: sig_query = "clinsig IN " + str(significance.value).replace(",)", ")") print("Query:", sig_query) if field.value == 'sqlQuery': query = selection.value print("Query:", query) elif field.value != 'none': query = field.value + " IN " + str(tuple(selection.value.split(","))).replace(",)", ")") print("Query:", query) # - # #### Initialize Spark spark = SparkSession.builder.master("local[*]").appName("dbSNPTo3DChain").getOrCreate() # ## Read file with dbSNP info # The following dataset was created from the SNP3D_PDB_GRCH37 dataset by mapping non-synonymous SNPs to human proteins with >= 95% sequence identity in the PDB. ds = dbSnpDataset.get_cached_dataset() ds.count() # #### Run query # + code_folding=[] if significance.value and not 'All' in significance.value: ds = ds.filter(sig_query) if field.value in ['snp_id','pdbChainId','uniprotId','sqlQuery']: ds = ds.filter(query) print("Results: ", ds.count()) # - # #### Show some sample results ds.toPandas().head(20) # ## Aggregate SNP data on the residue and chain level # + code_folding=[0] # aggregate data ds = ds.groupBy("pdbChainId","pdbResNum","master_res","uniprotId").agg(collect_set("master_var").alias("master_var"),collect_set("clinsig").alias("clinsig")) ds = ds.withColumn("master_var", concat_ws((""), ds.master_var)) ds = ds.withColumn("clinsig", concat_ws((","), ds.clinsig)) ds = ds.withColumn("snps", concat_ws(("->"), ds.master_res, ds.master_var)) ds = ds.drop("master_res") ds = ds.groupBy("pdbChainId","uniprotId").agg(collect_list("pdbResNum").alias("pdbResNums"), \ collect_list("snps").alias("snps"), \ collect_list("clinsig").alias("clinsig")) # - df = ds.toPandas() df.head(20) # ### Setup visualization # + code_folding=[0] def view_modifications(df, cutoff_distance, *args): def view3d(show_bio_assembly=False, show_surface=False, show_labels=True, i=0): pdb_id, chain_id = df.iloc[i]['pdbChainId'].split('.') res_num = df.iloc[i]['pdbResNums'] labels = df.iloc[i]['snps'] sigs = df.iloc[i]['clinsig'] sig_dir = {'Benign':'green', 'Likely benign':'turquoise', 'Likely pathogenic':'palevioletred', \ 'Pathogenic':'red', 'drug-response':'plum', 'untested':'white', \ 'Uncertain significance': 'lightgray', 'other':'white', 'null':'white'} # print header print ("PDB Id: " + pdb_id + " chain Id: " + chain_id) # print any specified additional columns from the dataframe for a in args: print(a + ": " + df.iloc[i][a]) all_residues = {'resi': res_num, 'chain': chain_id} # select neigboring residues by distance surroundings = {'chain': chain_id, 'resi': res_num, 'byres': True, 'expand': cutoff_distance} viewer = py3Dmol.view(query='pdb:' + pdb_id, options={'doAssembly': show_bio_assembly}) # polymer style viewer.setStyle({'cartoon': {'colorscheme': 'chain', 'width': 0.6, 'opacity':0.9}}) # non-polymer style viewer.setStyle({'hetflag': True}, {'stick':{'radius': 0.3, 'singleBond': False}}) # residues surrounding mutation positions viewer.addStyle(surroundings,{'stick':{'colorscheme':'orangeCarbon', 'radius': 0.15}}) # mutation positions for label, res, sig in zip(labels, res_num, sigs): sig1 = sig.split(',')[0] # if multiple values, use the first one col = (sig_dir[sig1]) mod_res = {'resi': res, 'chain': chain_id} c_col = col + "Carbon" viewer.addStyle(mod_res, {'stick':{'colorscheme':c_col, 'radius': 0.2}}) viewer.addStyle(mod_res, {'sphere':{'color':col, 'opacity': 0.6}}) if show_labels: viewer.addLabel(label + " " + sig, {'fontSize':10,'fontColor':col,'backgroundColor':'ivory'}, {'resi': res, 'chain': chain_id}) viewer.zoomTo(all_residues) if show_surface: viewer.addSurface(py3Dmol.SES,{'opacity':0.8,'color':'lightblue'}) return viewer.show() s_widget = IntSlider(min=0, max=len(df)-1, description='Structure', continuous_update=False) return interact(view3d, show_bio_assembly=False, show_surface=False, show_labels=True, i=s_widget) # - # ## Visualize locations of missense mutations # Residues affected by mutations are rendered in as sticks and transparent spheres, and colored by ClinVar significance. Each mutated residue position is labeled by the PDB residue number and ClinVar significance. Residues surrounding mutation sites (within 6 A) are rendered as thin orange sticks. Small molecules within the structure are rendered as gray sticks. # * Move the slider to browse through the structures # * Hold down left mouse button to rotate and zoom 3D structure # * Turn off the labels for an unobstructed view view_modifications(df, 6, 'uniprotId'); # ## Alternative visualization # + code_folding=[0] def view_surface(df, cutoff_distance, *args): def view3d(show_bio_assembly=False, show_surface=False, show_labels=True, i=0): pdb_id, chain_id = df.iloc[i]['pdbChainId'].split('.') res_num = df.iloc[i]['pdbResNums'] labels = df.iloc[i]['snps'] sigs = df.iloc[i]['clinsig'] sig_dir = {'Benign':'green', 'Likely benign':'turquoise', 'Likely pathogenic':'palevioletred', \ 'Pathogenic':'red', 'drug-response':'plum', 'untested':'white', \ 'Uncertain significance': 'lightgray', 'other':'white', 'null':'white'} # print header print ("PDB Id: " + pdb_id + " chain Id: " + chain_id) # print any specified additional columns from the dataframe for a in args: print(a + ": " + df.iloc[i][a]) viewer = py3Dmol.view(query='pdb:' + pdb_id, options={'doAssembly': show_bio_assembly}) all_residues = {'resi': res_num, 'chain': chain_id} # polymer style viewer.setStyle({'sphere': {'colorscheme': 'chain', 'opacity':0.6}}) # non-polymer style viewer.setStyle({'hetflag': True}, {'stick':{'radius': 0.3, 'singleBond': False}}) # mutation style for label, res, sig in zip(labels, res_num, sigs): sig1 = sig.split(',')[0] # if multiple values, use the first one col = (sig_dir[sig1]) mod_res = {'resi': res, 'chain': chain_id} viewer.setStyle(mod_res, {'sphere':{'color':col}}) if show_labels: viewer.addLabel(label + " " + sig, {'fontSize':10,'fontColor':col,'backgroundColor':'ivory'}, {'resi': res, 'chain': chain_id}) viewer.zoomTo(all_residues) if show_surface: viewer.addSurface(py3Dmol.SES,{'opacity':0.8,'color':'lightblue'}) return viewer.show() s_widget = IntSlider(min=0, max=len(df)-1, description='Structure', continuous_update=False) return interact(view3d, show_bio_assembly=False, show_surface=False, show_labels=True, i=s_widget) # - view_surface(df, 6, 'uniprotId'); spark.stop()
dbsnp/dbSNPTo3DChain.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Building a 19th c. Notes & Queries Full Text Search Engine # # Having got various pieces in place, we're now in a position to attempt to create a comprehensive full text search engine over 19th century issue of *Notes & Queries*. As we use the database, there may well be "optimisations" we can make, for example in trying to tidy up the content a little. But for now, let's just put the pieces we've already assembled together and see how it looks. # # Start off by loading some essentially packages, as well as package files we created for ourselves previously: # + from pathlib import Path from sqlite_utils import Database from ia_utils.create_db_table_metadata import create_db_table_metadata from ia_utils.open_metadata_records import open_metadata_records from ia_utils.add_patched_metadata_records_to_db import add_patched_metadata_records_to_db from ia_utils.create_db_table_issues import create_db_table_issues from ia_utils.create_db_table_pages_metadata import create_db_table_pages_metadata # - # It takes several hours to download the datafiles, so if we already have a full database file, we may want to put in some guards so we don't overwrite it an lose all that previously downloaded data: # + RECREATE_FULL_DB = False full_db_name = "full_nq.db" db_exists = Path("full_nq.db").is_file() dirname = "ia-downloads" p = Path(dirname) # Extra cautious... if RECREATE_FULL_DB and not db_exists: db_full = Database(full_db_name, recreate=True) create_db_table_metadata(db_full) data_records = open_metadata_records() add_patched_metadata_records_to_db(db_full, data_records) create_db_table_issues(db_full) create_db_table_pages_metadata(db_full) db_full["pages_metadata"].add_column("page_text", str) db_full["pages_metadata_fts"].drop(ignore=True) db_full["pages_metadata"].enable_fts(["id", "page_idx", "page_text"], create_triggers=True, tokenize="porter") else: db_full = Database(full_db_name) # + from pandas import read_sql # Get the records for a particular year q = """ SELECT id, title, date, is_index FROM metadata WHERE is_index = 0 AND strftime('%Y', datetime) = '{year}'; """ results_19th_cent = read_sql(q.format(year=1849), db_full.conn) results_19th_cent # - # We now need to: # # - iterate through the records; # - download the issue; # - carve it into various parts; # - add the parts to the database. # # We have all the pieces we need, so let's do it: # + # Dowload the tqdm progrss bar tools from tqdm.notebook import tqdm #And enable the pandas extensions tqdm.pandas() from ia_utils.download_and_extract_text import download_and_extract_text from ia_utils.download_ia_records_by_format import download_ia_records_by_format from ia_utils.add_page_metadata_to_db import add_page_metadata_to_db from ia_utils.chunk_page_text import chunk_page_text # Extra cautious if RECREATE_FULL_DB and not db_exists: # Iterate through all the years we want to search over for year in tqdm(range(1849, 1900)): # Get issues by year results_by_year = read_sql(q.format(year=str(year)), db_full.conn) # Download issue content by year results_by_year['content'] = results_by_year["id"].apply(download_and_extract_text, verbose=False) # Add issues content to database results_by_year[["id", "content"]].to_sql("issues", db_full.conn, index=False, if_exists="append") # For each issue, we need to grab the metadata and store it in the database download_ia_records_by_format(results_by_year.to_dict(orient="records"), p) add_page_metadata_to_db(db_full, results_by_year.to_dict(orient="records"), verbose=False) for record_id_val in results_by_year['id'].to_list(): updated_pages = chunk_page_text(db_full, record_id_val) db_full["pages_metadata"].upsert_all(updated_pages, pk=("id", "page_idx")) # + q = """ SELECT COUNT(*) FROM pages_metadata; """ read_sql(q, db_full.conn) # + q = """ SELECT COUNT(*) FROM issues; """ read_sql(q, db_full.conn) # + search_term = "sin eater" #q = f""" #SELECT * FROM pages_metadata_fts #WHERE pages_metadata_fts MATCH {db.quote(search_term)}; #""" q = """ SELECT id, snippet(pages_metadata_fts, -1, "__", "__", "...", 10) as clip FROM pages_metadata_fts WHERE pages_metadata_fts MATCH {query} ; """ read_sql(q.format(query=db_full.quote(search_term)), db_full.conn) # -
Notes_and_Queries_DB_PART_3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # URL: http://bokeh.pydata.org/en/latest/docs/gallery/stocks.html # # Most examples work across multiple plotting backends, this example is also available for: # # * [Bokeh - stocks example](../bokeh/stocks_example.ipynb) import numpy as np import pandas as pd import holoviews as hv hv.extension('matplotlib') # %output fig='svg' dpi=120 # # Defining the data # + from holoviews.operation.timeseries import rolling from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT def get_curve(data, label=''): df = pd.DataFrame(data) df['date'] = df.date.astype(np.datetime64) return hv.Curve(df, ('date', 'Date'), ('adj_close', 'Price'), label=label) hv.Dimension.type_formatters[np.datetime64] = '%Y' aapl = get_curve(AAPL, label='AAPL') goog = get_curve(GOOG, label='GOOG') ibm = get_curve(IBM, label='IBM') msft = get_curve(MSFT, label='MSFT') avg_curve = rolling(aapl, rolling_window=30).relabel('Average') avg_scatter = hv.Scatter(avg_curve, label='close') color_cycle = hv.Cycle(values=['#A6CEE3', '#B2DF8A','#33A02C', '#FB9A99']) # - # ## Plot # + plot_opts = dict(aspect=1, fig_size=200, legend_position='top_left') hv.Store.options(backend='matplotlib').Curve = hv.Options('style', color=color_cycle) scatter_style = dict(alpha=0.2, size=4, color='darkgrey') curve_style = dict(color='navy') (aapl * goog * ibm * msft).opts(plot=plot_opts) +\ (avg_scatter(style=scatter_style) * avg_curve(style=curve_style)).opts(plot=plot_opts)
examples/gallery/demos/matplotlib/stocks_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Qiskit v0.34.2 (ipykernel) # language: python # name: python3 # --- # + import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ, QuantumRegister, ClassicalRegister, execute, BasicAer from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() # - import math # %matplotlib inline # Set up the program signal = QuantumRegister(4, name='signal') qc = QuantumCircuit(signal) def main(): ## prepare the signal qc.h(signal); qc.rz(math.radians(180), signal[1]); qc.barrier() QFT(signal) # + def QFT(qreg): ## This QFT implementation is adapted from IBM's sample: ## https://github.com/Qiskit/qiskit-terra/blob/master/examples/python/qft.py ## ...with a few adjustments to match the book QFT implementation exactly n = len(qreg) for j in range(n): for k in range(j): qc.cu1(-math.pi/float(2**(j-k)), qreg[n-j-1], qreg[n-k-1]) qc.h(qreg[n-j-1]) # Now finish the QFT by reversing the order of the qubits for j in range(n//2): qc.swap(qreg[j], qreg[n-j-1]) main() # - backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) for i,amp in enumerate(outputstate): if abs(amp) > 0.000001: prob = abs(amp) * abs(amp) print('|{}> {} probability = {}%'.format(i, amp, round(prob * 100, 5))) qc.draw() # draw the circuit
QC Programming/QFT square wave.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Define belly regime for N' and N'' (increasing with depth) # # $C(z)=C_0 + C'(z-z_0) + C''(z-z_0)^2$, where $N_0$ is the concentration at $z_0$. I will start with $z_0=H_s$, so $C_0$ is a reference concentration at shelf break depth. # import matplotlib.pyplot as plt # %matplotlib inline import numpy as np import sympy as sym import seaborn as sns sym.init_printing() # enable fancy printing # Set appearance options seaborn sns.set_style('white') sns.set_context('notebook') C1,C2,z,Co,Hs,tau,Z = sym.symbols('C1,C2,z,Co,Hs,tau, Z') func = Co + C1*(z-Hs) + C2*((z-Hs)**2) func # ### What should be the value of $\hat{C''}$ to get maxima, minima or inflectio points within Hd? # # i.e. Profiles with 'bellies' (max, mins or inflection points) # # There are bellies wherever # # $d\hat{C}/dz=\hat{C'}+2\hat{C''}(z-Hs)=0$. (1) # # I want these points (I'll call them $z_{belly}$) to be within my profile ($0\le z \le Hd$), so I have the condition: # # $0 \le z_{belly} \le 400$ (2), # # but solving (1) for $z_{belly}$ gives, # # $z_{belly}=\frac{-\hat{C'}}{2\hat{C''}}+Hs$ (3). # # The inequalities (2) and (3) give: # # (4) $\frac{\hat{C'}}{2Hs}\lt {\hat{C''}}$ and (5) $\frac{\hat{C'}}{2(Hs-Hd)}\gt {\hat{C''}}$, # # for a given $ 0\le\hat{C'}$ (since I want increasing profiles) # # The region that satisfies conditions (4) and (5) is the triangle plotted below. Also, these hold for the dimensional parameters $C'$ and $C''$, where $ 0 \le C'$ # # # # p2 = sym.plot_implicit(sym.Or(C1/(2*(147.5-400)) > C2,C1/(2*147.5) < C2),(C1,0,0.5),(C2,-0.005,0.005), title='C2 values as a function of C1 values') # Let's see if it works... # + func = 0 + C1*(z-Hs) + C2*((z-Hs)**2) hand = sym.plot(func.subs({C1:0.00005,Hs:147.5,C2:0.0005/(2*147.5)}), func.subs({C1:0.003,Hs:147.5,C2:0.03/(2*147.5)}), func.subs({C1:0.005,Hs:147.5,C2:-0.005/(2*147.5)}), func.subs({C1:0.01,Hs:147.5,C2:-0.0067/(2*147.5)}),(z, 0, 400), xlabel='Depth (m)', ylabel='Concentration (nd)', title='Using the upper bound of C2', show=False) hand[1].line_color='r' hand[2].line_color='g' hand[3].line_color='purple' hand.show() # - # ## $\tau_v$ as a function of N' and N'' # # $$\frac{\tau}{Z}=\frac{\delta^2_vN}{\delta_vN}=Z\frac{\delta^2_vN}{\delta_vN}\rvert_{z=Hs}=\frac{2N''}{N'}$$ # # We have some bounds for N' and N'': we imposed $0\le N'$ and $N'/2Hs\gt N''$ and $N''\lt N'/(2(Hs-400))$ to have a profile with a max, min or inflection point above 400 m. # # Using these bounds, we can now bound the values of \tau_v/Z: # # $$\frac{\tau}{Z}=\frac{2N''}{N'} \gt \frac{2N'}{2HsN'} = \frac{1}{Hs}$$ # # and # # $$\frac{\tau}{Z}=\frac{2N''}{N'} \lt \frac{2N'}{2N'(Hs-Hd)} = \frac{1}{(Hs-Hd)}$$ # # These bounds do not depend on N' or N'', only on Hs. # # So, # # $$ \frac{1}{Hs-Hd} \gt \frac{\tau}{Z} \gt \frac{1}{Hs}$$ # # Hs=0 and Hd are asymptotes, but that is fine. If Hs = 0 it means you don't even have a shelf and if Hs=400 m you probbaly care about not having bellies deeper than that, so 400 m wouldn't even be an asymptote in the first place. p2 = sym.plot_implicit(sym.Or(1/Hs < tau, 1/(Hs-400)> tau), (Hs, 0, 400),(tau,-0.1,0.1), title='Tau/Z as a function of Hs', ylabel='Tau/Z') # In the idealized bathymetry Hs=147.5 m, so the bounds are: $-0.004 \gt \frac{\tau}{Z} or \frac{\tau}{Z}\gt 0.007$, units are m$^{-1}$. If I say that Z can be between 0 and 100 m then the values of $\tau_v$ can be: p2 = sym.plot_implicit(sym.Or(Z/147.5 < tau, Z/(147.5-400)> tau), (Z, 0, 160),(tau,-0.8,1.5), title='Tau as a function of Z', ylabel='Tau') # ### Regime definition # # Now we have all the elements to define a range of values for $N'$, $N''$ and $\tau_v$: # # (1) Linear profiles that increase with depth: # # $$0 \le N'$$. # # # (2) A maximum, minimum or inflection point above 400 m given an $N'$: # # $$\frac{\hat{N'}}{2Hs}\lt {\hat{N''}} \,and \, \frac{\hat{N'}}{2(Hs-400)}\gt {\hat{N''}}$$. # # Using these bounds, the regime of values of $\tau/Z$ is: # # $$ \frac{1}{Hs-400} \gt \frac{\tau}{Z}$$, or $$\frac{\tau}{Z} \gt \frac{1}{Hs}$$. # # For our value of Hs, # # $$ -0.004 \gt \frac{\tau}{Z}$$, or $$\frac{\tau}{Z} \gt 0.007$$. # # # # # + Hs = 147.5 No = 0 Nprime = np.array([0.1, 0.05,0.02,0.01,0.005,0.001]) z = np.linspace(0,400,50) labels = ['C1=%1.1e'% Nprime[0],'C1=%1.1e'% Nprime[1],'C1=%1.1e'% Nprime[2], 'C1=%1.1e'% Nprime[3],'C1=%1.1e'% Nprime[4],'C1=%1.1e'% Nprime[5]] colors = ['blue','green','purple','red','orange','pink'] fig,ax = plt.subplots(1,1,figsize=(6,8)) for N1,lab,cc in zip(Nprime,labels,colors): N2min = (N1/(2*(Hs-400))-0.001) N2max = (N1/(2*Hs))+0.001 Nmin = No + N1*(z-Hs) + N2min*(z-Hs)**2 Nmax = No + N1*(z-Hs) + N2max*(z-Hs)**2 ax.plot(Nmin,z, '--', color=cc) ax.plot(Nmax,z,'-', color=cc, label=lab) Tau_max = 2*N2max/(N1) Tau_min = 2*N2min/(N1) print('N1=%1.4f, N2min=%1.3e, Tau/Z=%1.3e \n N1=%1.4f, N2max=%1.3e, Tau/Z=%1.3e \n ' %(N1,N2min,Tau_min,N1,N2max,Tau_max)) ax.set_xlabel('Concentration ($\mu$M)') ax.set_ylabel('Depth (m)') ax.invert_yaxis() ax.axvline(0, color='k') ax.legend(loc=0) # - # The linear profile I have used for all runs has: # # $C'=(2.2\mu M-45.3\mu M)/(0m-1200m)=0.359 \mu M m^{-1}$ # # so, ${C'}=0.3 \mu M m^{-1}$ # # + Hs = 147.5 No = 7.49 Nprime = np.array([0.3/No]) z = np.linspace(0,400,50) labels = ['C1=0.047'] colors = ['blue','green','purple','red','orange','pink'] fig,ax = plt.subplots(1,1,figsize=(6,8)) for N1,lab,cc in zip(Nprime,labels,colors): N2min =(N1/(2*(Hs-400))) - 0.001 N2max = (N1/(2*Hs))+0.001 N2mean = (N2max-N2min)/2 Nmean = No + N1*(z-Hs) Nmax = No + N1*(z-Hs) + N2max*(z-Hs)**2 Nmin = No + N1*(z-Hs) + N2min*(z-Hs)**2 ax.plot(Nmean,z,'-', color=cc, label='lin profile') ax.plot(Nmax,z,':', color=cc, label='max curv') ax.plot(Nmin,z,'--', color=cc, label='min curv') Tau_mean = 2*N2mean/(N1) print('N1=%1.4f, N2mean=%1.3e, Tau/Z=%1.3e \n' %(N1,N2min,Tau_mean)) ax.set_xlabel('Concentration ($\mu$M)') ax.set_ylabel('Depth (m)') ax.invert_yaxis() ax.axvline(0, color='k') ax.legend(loc=0) # -
NutrientProfiles/SystematicProfile_belly_regime.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Ray-Triangle Intersection # --- # - Author: <NAME> # - GitHub: [github.com/diegoinacio](https://github.com/diegoinacio) # - Notebook: [ray-intersection_triangle.ipynb](https://github.com/diegoinacio/creative-coding-notebooks/blob/master/Computer-Graphics/ray-intersection_triangle.ipynb) # --- # Implementation of ray-triangle intersection algorithm. # %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np np.seterr(divide='ignore', invalid='ignore') plt.rcParams['figure.figsize'] = (16, 4) # ## Primitives # --- # The first thing is to define the ray origin $O$ and direction $\large ê$, where the unit vector $\large ê = \frac{\vec{e}}{\parallel \vec{e} \parallel}$. # # ![image 01](sourceimages/ray-intersection_triangle_01.jpg) ## Ray O = np.array([0, 0, 0]) # Origin pont e = np.array([0.1, 0.1, 1]) # Ray direction e_ = e/np.linalg.norm(e) # Unit vector (versor) of e => ê # Next step is to define the 3D triangle in counter-clockwise order in relation to the direction of the face. # # ![image 02](sourceimages/ray-intersection_triangle_02.jpg) # Triangle A = np.array([0 , 1, 1.50]) # Point A B = np.array([1 , 0, 1.25]) # Point B C = np.array([-1, 0, 1.00]) # Point C # ## Intersection # --- # To find the ray intersection, the next step is to define the triangle normal $\hat{n}$, where: # # $$ \large # \hat{n} = \frac{\vec{AB} \times \vec{AC}}{\parallel \vec{AB} \times \vec{AC} \parallel} # $$ # # *p.s.: to calculate ray-triangle intersection it is **not** necessary to normalize the normal vector.* # # ![image 03](sourceimages/ray-intersection_triangle_03.jpg) AB = B - A # Oriented segment A to B AC = C - A # Oriented segment A to C n = np.cross(AB, AC) # Normal vector n_ = n/np.linalg.norm(n) # Normalized normal # The *supporting plane* is what the triangle lies on, sharing the same normal vector. Given the plane equation: # # $$ \large # ax + by + cz + d = 0 # $$ # # Having the vector normal as $\hat{n} = [a b c]^T$ and $P = [x y z]^T$ as any point on the plane, we can define $d$ as follows: # # $$ \large # \hat{n} \cdot P + d = 0 \quad \therefore \quad d = - \hat{n} \cdot P # $$ # # *p.s.: in this case any known point can be used. Lets use the point $A$ so $P = A$* # # ![image 04](sourceimages/ray-intersection_triangle_04.jpg) # Using the point A to find d d = - np.dot(n_, A) # Before finding the intersection point $P$ on the plane, we must calculate the parameter $t$. We start by looking at the parametric equation of a line segment, which has the same direction of $ê$ and origin from $O$: # # $$ \large # P(P_x, P_y, P_z) = O + ê t # $$ # # where: # # $$ # \large P_x = O_x + ê_x t \\ # \large P_y = O_y + ê_y t \\ # \large P_z = O_z + ê_z t # $$ # # Using this concept on the plane equation, we have: # # $$ # \large ax + by + cz + d = 0 \\ # \large aP_x + bP_y + cP_z + d = 0 \\ # \large a(O_x + ê_x t) + b(O_y + ê_y t) + c(O_z + ê_z t) + d = 0 \\ # \large aO_x + aê_x t + bO_y + bê_y t + cO_z + cê_z t + d = 0 \\ # \large (aê_x + bê_y + cê_z)t + (aO_x + bO_y + cO_z) + d = 0 \\ # \large (\hat{n} \cdot \hat{e})t + \hat{n} \cdot O + d = 0 \\ # \large t = - \frac{\hat{n} \cdot O + d}{\hat{n} \cdot \hat{e}} # $$ # # ![image 05](sourceimages/ray-intersection_triangle_05.jpg) # + # Finding parameter t t = - (np.dot(n_, O) + d)/np.dot(n_, e_) # Finding P P = O + t*e_ # - # To figure out if the plane intersection point is inside or outside the triangle, we basically have to define the vector from each vertices to $P$ and cross it with its oriented edge segment (for each vertex). If the intersection point is outside the triangle, the resulting vector will be in the opposite direction from the normal one. # # $$ # \large [(B - A) \times (P - A)] \cdot \hat{n} \geq 0 \\ # \large [(B - B) \times (P - B)] \cdot \hat{n} \geq 0 \\ # \large [(B - C) \times (P - C)] \cdot \hat{n} \geq 0 # $$ # # If all these conditionals are obeyed, we can conclude that the point $P$ is inside the triangle. Otherwise, the point is going to be outiside toward to the edges of the negative values. # # ![image 06](sourceimages/ray-intersection_triangle_06.jpg) # + # Get the resulting vector for each vertex # following the construction order Pa = np.dot(np.cross(B - A, P - A), n_) Pb = np.dot(np.cross(C - B, P - B), n_) Pc = np.dot(np.cross(A - C, P - C), n_) if(t < 0): # Means that the triangle has the normal in the opposite direction (same # direction from the ray) or the triangle is behind the ray origin print('Backface intersection!') elif(Pa < 0 and Pb < 0 and Pc < 0): print('Intersection point is outside the triangle') else: print(f'Intersections at {P}') # - # ## 3D Intersection # --- # Apply same model for each pixel of an image plane as the origin and the ray direction is based on the perspective camera model: # # ![image 07](sourceimages/ray-intersection_triangle_07.jpg) # + N, M = 256j, 512j O = np.ones((int(N.imag), int(M.imag), 3)) # Init image plane origin O[..., 1], O[..., 0] = np.mgrid[0.5:-0.5:N, 1:-1:M] # Image plane uvw coordinates e_ = O/np.linalg.norm(O, axis=2)[:,:,np.newaxis] # Normalized ray directon e_ # Triangle A = np.array([0 , 2.2 , 5]) # Point A B = np.array([6.7 , -3 , 8]) # Point B C = np.array([-1.5, -0.5, 2]) # Point C AB = B - A # Oriented segment A to B AC = C - A # Oriented segment A to C n = np.cross(AB, AC) # Normal vector n_ = n/np.linalg.norm(n) # Normalized normal # Using the point A to find d d = - np.dot(n_, A) # Finding parameter t vec_dot = np.vectorize(np.dot, signature='(n),(m)->()') # Vectorize dot product function t = - (vec_dot(n_, O) + d)/vec_dot(n_, e_) # Get t for each pixel # Finding P P = O + t[..., np.newaxis]*e_ # Get the resulting vector for each vertex # following the construction order Pa = vec_dot(np.cross(B - A, P - A), n_) # Resulting vector of A Pb = vec_dot(np.cross(C - B, P - B), n_) # Resulting vector of B Pc = vec_dot(np.cross(A - C, P - C), n_) # Resulting vector of C output = np.zeros((int(N.imag), int(M.imag), 3)) # Init output image cond = np.logical_and(np.logical_and(Pa >= 0, Pb >= 0), Pc >= 0) # Inside the triangle conditionals fr = vec_dot(n_, -e_)[..., np.newaxis] # Compute the facing ratio output[cond] = (0.15, 0.35, 0.9)*fr[cond] # Shade with color and fr # Visualization fig, ax = plt.subplots(figsize=(16, 10)) ax.imshow(output) plt.show() # - # ## Barycentric coordinates # --- # The barycentric coordinates will help us to interpolate in-between vertex values. To do that we have to calculate the area of all resulting triangles. Any triangle area can be calculated as follows: # # $$ # \large \text{Area}_{ABC} = \frac{\parallel (B - A) \times (C - A) \parallel}{2} # $$ # # Next step is to find the weight of each point so that we can use it to interpolate any desired values. # # $$ # \large \alpha = \frac{\text{Area}_{BCP}}{\text{Area}_{ABC}} = \frac{\parallel (C - B) \times (P - B) \parallel}{\parallel (B - A) \times (C - A) \parallel} \\\\ # \large \beta = \frac{\text{Area}_{CAP}}{\text{Area}_{ABC}} = \frac{\parallel (A - C) \times (P - C) \parallel}{\parallel (B - A) \times (C - A) \parallel} \\\\ # \large \gamma = \frac{\text{Area}_{ABP}}{\text{Area}_{ABC}} = \frac{\parallel (B - A) \times (P - A) \parallel}{\parallel (B - A) \times (C - A) \parallel} # $$ # # Have the weights we can interpolate any kind of value (color, for example) by using: # # $$ \large # V = \frac{\alpha V_A + \beta V_B + \gamma V_C}{\alpha + \beta + \gamma} # $$ # # ![image 08](sourceimages/ray-intersection_triangle_08.jpg) # + N, M = 256j, 512j O = np.ones((int(N.imag), int(M.imag), 3)) # Init image plane origin O[..., 1], O[..., 0] = np.mgrid[0.5:-0.5:N, 1:-1:M] # Image plane uvw coordinates e_ = O/np.linalg.norm(O, axis=2)[..., np.newaxis] # Normalized ray directon e_ # Triangle A = np.array([0 , 1.25 , 3]) # Point A B = np.array([2 , -1.25, 3]) # Point B C = np.array([-2, -1.25, 3]) # Point C AB = B - A # Oriented segment A to B AC = C - A # Oriented segment A to C n = np.cross(AB, AC) # Normal vector n_ = n/np.linalg.norm(n) # Normalized normal # Using the point A to find d d = - np.dot(n_, A) # Finding parameter t vec_dot = np.vectorize(np.dot, signature='(n),(m)->()') # Vectorize dot product function t = - (vec_dot(n_, O) + d)/vec_dot(n_, e_) # Get t for each pixel # Finding P P = O + t[..., np.newaxis]*e_ # Get the resulting vector for each vertex # following the construction order Pa = vec_dot(np.cross(B - A, P - A), n_) # Resulting vector of A Pb = vec_dot(np.cross(C - B, P - B), n_) # Resulting vector of B Pc = vec_dot(np.cross(A - C, P - C), n_) # Resulting vector of C cond = np.logical_and(np.logical_and(Pa >= 0, Pb >= 0), Pc >= 0) # Inside the triangle conditionals # Calculate barycentric coordinates Aa = np.cross(B - A, P - A) # Resulting vector of A and P Aa = np.linalg.norm(Aa, axis=2) # Area of triangle ABP Ab = np.cross(C - B, P - B) # Resulting vector of B and P Ab = np.linalg.norm(Ab, axis=2) # Area of triangle BCP Ac = np.cross(A - C, P - C) # Resulting vector of C and P Ac = np.linalg.norm(Ac, axis=2) # Area of triangle CAP At = np.cross(C - A, B - A) # Resulting vector of triangle At = np.linalg.norm(At) # Area of triangle ABC # Getting the barycenter weights alpha = (Ab/At)[..., np.newaxis] beta = (Ac/At)[..., np.newaxis] gamma = (Aa/At)[..., np.newaxis] # Output image output = np.zeros((int(N.imag), int(M.imag), 3)) # Init output image Ca = np.array([1, 0, 0.4]) # Color vertex A Cb = np.array([0.4, 1, 0]) # Color vertex B Cc = np.array([0, 0.4, 1]) # Color vertex C Cd = (alpha*Ca + beta*Cb + gamma*Cc)/(alpha + beta + gamma) # Interpolated color based on barycentric coordinates output[cond] = Cd[cond] # Shade with the interpolated colors # Visualization fig, ax = plt.subplots(figsize=(16, 10)) ax.imshow(output) plt.show()
Computer-Graphics/ray-intersection_triangle.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Raw Classes # + class TestRepr(object): def __init__(self, text): self.text = text test = TestRepr('Hello World') test # - # # Python Representation # + class TestRepr2(object): def __init__(self, text): self.text = text def __repr__(self): return self.text test = TestRepr2('Hello World') test # - # # HTML # + class TestRepr3(object): def __init__(self, text): self.text = text def _repr_html_(self): return f'<b>Test</b> (text="{self.text}")' test = TestRepr3('Hello World') test # - # # Adding CSS # + class ProgressBar(object): def __init__(self, progress): self.progress = progress def _repr_html_(self): style = f""" .outer {{ height: 24px; border: 1px black solid; }} .inner {{ width: {self.progress * 100}%; height: 100%; background-color: black; color: white; padding-left: 5px; }} """ html = f""" <div class="outer"> <div class="inner"> {self.progress * 100} % </div> </div> """ return f'<style>{style}</style>{html}' bar = ProgressBar(0.75) bar # - # # Adding JS import uuid class DynamicProgressBar(object): def __init__(self, progress): self.progress = progress self.displayed = False self.uuid = str(uuid.uuid1()) def display_init(self): style = f""" .outer{self.uuid} {{ height: 24px; border: 1px black solid; }} .inner{self.uuid} {{ width: {self.progress * 100}%; height: 100%; background-color: black; color: white; padding-left: 5px; overflow: hidden; transition: width 5s; }} """ html = f""" <div class="outer{self.uuid}"> <div class="inner{self.uuid}" id="progress_bar{self.uuid}"> {self.progress * 100} % </div> </div> """ return f'<style>{style}</style>{html}' def display_update(self): js = f""" document.getElementById("progress_bar{self.uuid}").style.width = "{self.progress*100}%"; document.getElementById("progress_bar{self.uuid}").innerText = "{self.progress*100}%"; """ return f"<script>{js}</script>" def _repr_html_(self): if not self.displayed: self.displayed = True return self.display_init() else: return self.display_update() def set_progress(self, progress): self.progress = progress return self bar = DynamicProgressBar(0.25) bar bar.set_progress(0.75) # # Appendix # Can also use: # * _repr_json() # * _repr_jpeg() # * _repr_png() # * _repr_svg() # * _repr_latex() # And there is even more: _IPython.display._ # * Audio # * FileLink # * IFrame # * Image # * YouTubeVideo # * ...
02_rich_visualizations/02_custom.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Week 3 - Segmenting and Clustering Neighbourhooods in Toronto # + import numpy as np # library to handle data in a vectorized manner import pandas as pd # library for data analsysis pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) import json # library to handle JSON files # #!conda install -c conda-forge geopy --yes # uncomment this line if you haven't completed the Foursquare API lab from geopy.geocoders import Nominatim # convert an address into latitude and longitude values import requests # library to handle requests from pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe # Matplotlib and associated plotting modules import matplotlib.cm as cm import matplotlib.colors as colors # import k-means from clustering stage from sklearn.cluster import KMeans # #!conda install -c conda-forge folium=0.5.0 --yes # uncomment this line if you haven't completed the Foursquare API lab import folium # map rendering library print('Libraries imported.') # - # ## Part 1 - Creating the pandas DataFrame df = pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0] df.rename(columns={'Neighbourhood':'Neighborhood'}, inplace=True) df.head(10) # Ignore cells without a borough assigned df = df[df['Borough'] != 'Not assigned'] df.head(10) #C Group data by the postal Code df_new = df.groupby('Postal Code', sort=False).agg(', '.join) df_new.head(10) #Replace cells with a borough but a NOt assigned neighborhood with the neighborhood same as the borough df_new.loc[df_new['Neighborhood'] =='Not assigned', 'Neighborhood'] = df_new.loc[df_new['Neighborhood'] =='Not assigned', 'Borough'] df_new.reset_index(inplace=True) df_new.head(10) df_new.shape # ## Part 2 - Adding the Latitudes and Longitude Coordinates df_new['Latitude'] = None df_new['Longitude'] = None df_new.head(5) # + # #!pip install geocoder #import geocoder #print('Done') for i, pc in enumerate(df_new['Postal Code']): lat_lng_coords = None while(lat_lng_coords is None): g = geocoder.arcgis('{}, Toronto, Ontario'.format(pc)) lat_lng_coords = g.latlng if lat_lng_coords: latitude = lat_lng_coords[0] longitude = lat_lng_coords[1] df_new.loc[i, 'Latitude'] = latitude df_new.loc[i, 'Longitude'] = longitude df_new.head(10) # - address = 'Toronto, CA' geolocator = Nominatim(user_agent="my-Toronto") location = geolocator.geocode(address) latitude = location.latitude longitude = location.longitude print('The geograpical coordinate of Toronto are {}, {}.'.format(latitude, longitude)) # ### Visualize a map of Toronto with neighbourhoods superimposed # + # create map of New York using latitude and longitude values map_toronto = folium.Map(location=[latitude, longitude], zoom_start=10) # add markers to map for lat, lng, borough, neighborhood in zip(df_new['Latitude'], df_new['Longitude'], df_new['Borough'], df_new['Neighborhood']): label = '{}, {}'.format(neighborhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, popup=label, color='blue', fill=True, fill_color='#3186cc', fill_opacity=0.7, parse_html=False).add_to(map_toronto) map_toronto # - # ### Four square Credentials # + CLIENT_ID = 'PDGX0B2DRB4TG0FDDVMCZC43OT5KTTDGFTASV15XW4KDXPCR' # your Foursquare ID CLIENT_SECRET = '<KEY>' # your Foursquare Secret VERSION = '20201227' # Foursquare API version LIMIT = 100 # A default Foursquare API limit value print('Your credentails:') print('CLIENT_ID: ' + CLIENT_ID) print('CLIENT_SECRET:' + CLIENT_SECRET) # - # ### Function to process all neighbourhoods and return nearby venues # + import requests LIMIT = 50 radius = 500 def getNearbyVenues(names, latitudes, longitudes, radius=500): venues_list=[] for name, lat, lng in zip(names, latitudes, longitudes): #print(name) # create the API request URL url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format( CLIENT_ID, CLIENT_SECRET, VERSION, lat, lng, radius, LIMIT) # make the GET request results = requests.get(url).json()["response"]['groups'][0]['items'] # return only relevant information for each nearby venue venues_list.append([( name, lat, lng, v['venue']['name'], v['venue']['location']['lat'], v['venue']['location']['lng'], v['venue']['categories'][0]['name']) for v in results]) nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list]) nearby_venues.columns = ['Neighborhood', 'Neighborhood Latitude', 'Neighborhood Longitude', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category'] return(nearby_venues) # - venues = getNearbyVenues(names=df_new['Neighborhood'], latitudes=df_new['Latitude'], longitudes=df_new['Longitude']) print(venues.shape) venues.head venues.groupby('Neighborhood', as_index=False).count() # + # Check unique categories print('There are {} uniques categories.'.format(len(venues['Venue Category'].unique()))) # - venues['Venue Category'] # # Part 3 - Analysis # + # one hot encoding venues_onehot = pd.get_dummies(venues[['Venue Category']], prefix="", prefix_sep="") #Adding the neighbourhood column into venues venues_onehot['Neighborhood'] = venues['Neighborhood'] venues_onehot.head() temp = list(venues_onehot.columns) if 'Neighborhood' in temp: temp.remove('Neighborhood') fixed_columns = ['Neighborhood'] + temp venues_onehot = venues_onehot[fixed_columns] venues_onehot.head() # - # Examine dataframe size venues_onehot.shape venues_grouped = venues_onehot.groupby('Neighborhood').mean().reset_index() venues_grouped.shape # Sort venues in descneding order function def return_most_common_venues(row, num_top_venues): row_categories = row.iloc[1:] row_categories_sorted = row_categories.sort_values(ascending=False) return row_categories_sorted.index.values[0:num_top_venues] # + num_top_venues = 10 indicators = ['st', 'nd', 'rd'] # create columns according to number of top venues columns = ['Neighborhood'] for ind in np.arange(num_top_venues): try: columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind])) except: columns.append('{}th Most Common Venue'.format(ind+1)) # create a new dataframe neighborhoods_venues_sorted = pd.DataFrame(columns=columns) neighborhoods_venues_sorted['Neighborhood'] = venues_grouped['Neighborhood'] for ind in np.arange(venues_grouped.shape[0]): neighborhoods_venues_sorted.iloc[ind, 1:] = return_most_common_venues(venues_grouped.iloc[ind, :], num_top_venues) neighborhoods_venues_sorted.head() # - # ## Cluster Neighbourhoods # + # set number of clusters kclusters = 5 toronto_grouped_clustering = venues_grouped.drop('Neighborhood', axis = 1) # run k-means clustering kmeans = KMeans(n_clusters=kclusters, random_state=67).fit(toronto_grouped_clustering) # check cluster labels generated for each row in the dataframe kmeans.labels_[0:10] # + # add clustering labels neighborhoods_venues_sorted.insert(0, 'Cluster Labels', kmeans.labels_) toronto_merged = df_new # merge manhattan_grouped with manhattan_data to add latitude/longitude for each neighborhood toronto_merged = toronto_merged.join(neighborhoods_venues_sorted.set_index('Neighborhood'), on='Neighborhood') toronto_merged.dropna(inplace=True) toronto_merged['Cluster Labels'] = toronto_merged['Cluster Labels'].astype(int) toronto_merged # check the last columns! # - # ## Visualize Data # + # create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(kclusters) ys = [i + x + (i*x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers to the map markers_colors = [] for lat, lon, poi, cluster in zip(toronto_merged['Latitude'], toronto_merged['Longitude'], toronto_merged['Neighborhood'], toronto_merged['Cluster Labels']): label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( [lat, lon], radius=5, popup=label, color=rainbow[cluster-1], fill=True, fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(map_clusters) map_clusters # - # ## Examine Clusters # ### Cluster 1 toronto_merged.loc[toronto_merged['Cluster Labels'] == 0, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]] # ### Cluster 2 toronto_merged.loc[toronto_merged['Cluster Labels'] == 1, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]] # ### Cluster 3 toronto_merged.loc[toronto_merged['Cluster Labels'] == 2, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]] # ### Cluster 4 toronto_merged.loc[toronto_merged['Cluster Labels'] == 3, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]] # ### Cluster 5 toronto_merged.loc[toronto_merged['Cluster Labels'] == 4, toronto_merged.columns[[1] + list(range(5, toronto_merged.shape[1]))]]
Segmenting and clustering Neighbourhoods in Toronto.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Investigate the converge performance w.r.t the iteration number # - Author: <NAME> (<EMAIL>) # - Date: Aug 1st, 2021 # + # perform the experiments from deformpiv import * import numpy as np kernel_methods = ['openpiv', 'opticalflow', 'deeppiv'] warping_methods = ['FDI', 'CDI', 'CDDI', 'FDDI'] case = './PIG/sin_5.0.npz' runs = np.arange(16) # run number data = np.load(case) img1 = data['img1'] img2 = data['img2'] ut, vt = data['u'], data['v'] def compute_error(x, y, u, v): if ut.shape != u.shape: temp_ut = remap(ut, x, y) temp_vt = remap(vt, x, y) else: temp_ut, temp_vt = ut.copy(), vt.copy() err = np.sqrt((u-temp_ut)**2+(v-temp_vt)**2) # don't evaluate the error within the image boundary err[:3,:], err[-3:,:], err[:,:3], err[:,-3:] = np.nan, np.nan, np.nan, np.nan if err.shape[0]>100: err[0:30,:], err[-30:,:], err[:,:30], err[:,-30:] = np.nan, np.nan, np.nan, np.nan return err result = [] for run in runs: print(f"Computing for number of runs: {run}") result.append([]) for kernel in kernel_methods: result[-1].append([]) for warp in warping_methods: config = AttrDict() config.pivmethod = kernel config.deform = warp config.runs = run piv = DeformPIV(config) x, y, u, v = piv.compute(img1, img2) err = compute_error(x, y, u, v) rmse = np.sqrt(np.nanmean(err**2)) result[-1][-1].append([rmse]) result = np.array(result) # + # visualize the results import seaborn as sns sns.set_style("whitegrid") markers = ['-^', '--d', '-.s', '-o'] for i in range(result.shape[1]): fig = plt.figure(figsize=(5, 5*0.5)) data = result[:, i, :, 0] for j in range(result.shape[2]): plt.plot(runs, result[:, i, j, 0], markers[j], label=warping_methods[j]) plt.legend(loc=1) plt.xlabel("Iteration number") plt.ylabel("RMSE [pixel]") plt.xlim([runs[0]-0.1,runs[-1]+0.1]) plt.gcf().subplots_adjust(left=0.2, bottom=0.19) plt.grid('on') plt.savefig(f"output/{kernel_methods[i]}_runs_error.pdf") plt.show() # -
Exp1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: itk-unstable # language: python # name: venv-itk5 # --- # # Convolution over a Region of Interest # # Convolution is an important concept in image processing in which a kernel is applied over an image, typically as a window that slides along pxiels. In FFT convolution image and kernel spatial data is transformed into the frequency domain, multiplied, and transformed back into the spatial domain. This process offers a certain degree of speedup when accelerated with exterior GPU hardware for large images. # # ITK FFT filters always apply operations over the largest possible region in the input image in order to accurately represent the image in the frequency domain. While sound, this approach reduces potential speedup when attempting to operate on only a small region of a much larger input image, such as in the case of generating multiscale pyramids for image registration. A workaround for this is to crop the input image to the image subregion size padded by the kernel width so that the same information is operated on by convolution in either the spatial or frequency domain. # # This notebook serves to demonstrate spatial vs frequency approaches and compare outputs to validate accuracy. # # Note that default notebook output uses ITK Vnl FFT backends without VkFFT speedup so that it is easier to compare FFT convolution runtime between full and cropped images. Developers are invited to install itk-vkfft and re-run for accelerated performance. # + import time import itk import numpy as np import matplotlib.pyplot as plt itk.auto_progress(2) # Load relevant modules in advance itk.FFTConvolutionImageFilter # + # Define types dimension = 2 pixel_type = itk.F image_type = itk.Image[pixel_type, dimension] region_type = itk.ImageRegion[dimension] # - # ## Generate Inputs # # Define a basic input image and region of interest for convolution, along with a kernel for blurring. Note that numpy and ITK use reversed conventions for indexing (KJI versus IJK). # + # Generate an input image and visualize ROI def make_image() -> image_type: """Use numpy to generate an input image""" arr = np.ones([150, 150], dtype=np.float32) arr[20:80, 20:80] = 5 arr[70:120, 60:100] = 0 arr[30:60, 50:120] = 10 image = itk.image_from_array(arr) return image def make_roi() -> region_type: """Generate the region of interest with ITK""" region = region_type() region.SetSize([80, 50]) region.SetIndex([30, 50]) return region largest_image = make_image() roi = make_roi() # The input image depicts total available spatial data plt.title("Input Image") plt.imshow(largest_image) plt.colorbar() plt.show() # The region of interest represents the spatial region that we want after blurring. # Here we visualize that region by cropping the input image accordingly. # Convolution requires information extending beyond the bounds of the region, so # we cannot crop the input to the exact region of interest when we use it in our pipeline. print( f"Image region of interest starts at {roi.GetIndex()} and has size {roi.GetSize()}" ) input_region_of_interest = itk.region_of_interest_image_filter( largest_image, region_of_interest=roi ) plt.title("Input Region of Interest") plt.imshow(input_region_of_interest) plt.colorbar() plt.show() # + # Generate a kernel for convolution. # Here we use a Gaussian kernel for blurring. def generate_kernel() -> image_type: """Generate a Gaussian kernel image with ITK""" kernel_source = itk.GaussianImageSource[image_type].New() kernel_source.SetSize(15) kernel_source.SetMean(7) kernel_source.SetSigma(3.0) kernel_source.SetScale(1.0) kernel_source.SetNormalized(True) kernel_source.Update() return kernel_source.GetOutput() # Note that the size of the spatial kernel image is significantly less than that of the input image. # In spatial convolution this kernel will "slide" as a window along the input image. # In convolution in the frequency domain the kernel frequency representation will be transformed to # the same size as the input image's frequency representation. kernel_image = generate_kernel() print(f"Kernel image has size {itk.size(kernel_image)}") plt.title("Kernel Image") plt.imshow(kernel_image) plt.colorbar() plt.show() # - # ## Demonstrate Spatial Convolution # # Here we show that convolution results within the output ROI do not differ significantly when the image is cropped to a subregion that is the ROI padded to the kernel width. This padding effectively provides all relevant input signal to the convolution. # + def convolve_then_crop( image, kernel, region, filter_fn=itk.convolution_image_filter ) -> image_type: """Brute-force: Run spatial convolution on the entire image, then crop the output to the region of interest""" starttime = time.time() print(f"Running {filter_fn}") blurred = filter_fn(image, kernel_image=kernel) print(f"Cropping to region of size {list(region.GetSize())}") cropped = itk.region_of_interest_image_filter(blurred, region_of_interest=region) print(f"Pipeline ran in {time.time() - starttime:0.3f}s") return cropped largest_result = convolve_then_crop(largest_image, kernel_image, roi) plt.title("Convolve entire image in space, then crop to ROI") plt.imshow(largest_result) plt.colorbar() plt.show() # + def crop_then_convolve_then_crop( image, kernel, region, filter_fn=itk.convolution_image_filter ) -> image_type: """Crop input as close as possible to the output ROI without removing relevant boundaries for convolution kernel width""" starttime = time.time() # Pad region by kernel radius on all sides kernel_radius = [int((itk.size(kernel)[dim] - 1) / 2) for dim in range(dimension)] roi_first = region_type() roi_first.SetIndex( [int(region.GetIndex()[dim] - kernel_radius[dim]) for dim in range(dimension)] ) roi_first.SetSize( [ region.GetSize()[dim] + (itk.size(kernel)[dim] - 1) for dim in range(dimension) ] ) roi_second = region_type() roi_second.SetSize(region.GetSize()) roi_second.SetIndex([kernel_radius[dim] for dim in range(dimension)]) print(f"Cropping to region of size {list(roi_first.GetSize())}") cropped_first = itk.region_of_interest_image_filter( image, region_of_interest=roi_first ) print(f"Running {filter_fn}") blurred = filter_fn(cropped_first, kernel_image=kernel) print(f"Cropping to region of size {list(roi_second.GetSize())}") cropped_second = itk.region_of_interest_image_filter( blurred, region_of_interest=roi_second ) print(f"Pipeline ran in {time.time() - starttime:0.3f}s") return cropped_second cropped_result = crop_then_convolve_then_crop(largest_image, kernel_image, roi) plt.title("Crop to ROI margins, then convolve, then crop to ROI") plt.imshow(cropped_result) plt.colorbar() plt.show() # - # Compare results to show that difference in output is negligible diff = itk.array_from_image(cropped_result) - itk.array_from_image(largest_result) print(f"Max difference: {np.max(diff)}") plt.title("Difference") plt.imshow(diff) plt.colorbar() plt.show() # ## Demonstrate FFT Convolution # # Here we take a similar approach to show that convolution in the frequency domain produces the same results in the region of interest if run on the entire image and cropped or run on a specific subregion and cropped. # Blur entire image with FFT convolution, then crop to ROI largest_result = convolve_then_crop( largest_image, kernel_image, roi, filter_fn=itk.fft_convolution_image_filter ) plt.title("Convolve entire image, then crop to ROI") plt.imshow(largest_result) plt.colorbar() plt.show() # Crop to a specific subregion padded for the kernel, then run FFT convolution, then crop remaining to ROI cropped_result = crop_then_convolve_then_crop( largest_image, kernel_image, roi, filter_fn=itk.fft_convolution_image_filter ) plt.title("Crop to ROI margins, then convolve, then crop to ROI") plt.imshow(cropped_result) plt.colorbar() plt.show() # Compare results to show that difference in output is negligible diff = itk.array_from_image(cropped_result) - itk.array_from_image(largest_result) print(f"Max difference: {np.max(diff):.3f}") plt.title("Difference") plt.imshow(diff) plt.colorbar() plt.show() # ## Compare Spatial and FFT Convolution Accuracy # # Here we demonstrate equivalence between the results of spatial and FFT convolution. Colorbars show that image differences are negligible in pixel magnitude. # + spatial_largest = convolve_then_crop( largest_image, kernel_image, roi, filter_fn=itk.convolution_image_filter ) fft_largest = convolve_then_crop( largest_image, kernel_image, roi, filter_fn=itk.fft_convolution_image_filter ) spatial_cropped = crop_then_convolve_then_crop( largest_image, kernel_image, roi, filter_fn=itk.convolution_image_filter ) fft_cropped = crop_then_convolve_then_crop( largest_image, kernel_image, roi, filter_fn=itk.fft_convolution_image_filter ) plt.title("Spatial/FFT largest-region diff") plt.imshow(itk.array_from_image(spatial_largest) - itk.array_from_image(fft_largest)) plt.colorbar() plt.show() plt.title("Spatial/FFT cropped-input diff") plt.imshow(itk.array_from_image(spatial_cropped) - itk.array_from_image(fft_cropped)) plt.colorbar() plt.show()
example/FFTConvolutionOverRegionOfInterest.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # How Pandas Work Under the Hood # # As with any program language, it’s important to understand what is going on underneath because it helps you write more explicit, simpler, performant, and correct code. # Pandas is a wrapper around NumPy and NumPy is a wrapper around C; thus, pandas gets its performance from running things in C and not in Python. This concept is fundamental to everything you do in pandas. When you are in C, you are fast, and when you are in Python, you are slow. # The same requirements present for working with NumPy arrays hold true when working with pandas DataFrames—namely, the Python code must be translatable to C code; this includes the types that hold the data and the operations performed on the data. # Here is a table of pandas types to NumPy types. Note that `datetime`s and `timedelta`s don’t translate into NumPy types. This is because C does not have a datetime data structure, and so in cases where operations must be made on `datetime` data, it is more performant to, instead, convert the `datetime`s to an `int` type of seconds since the epoch. # |pandas type | NumPy type| # |:--|:--| # |`object` | `string_`, `unicode_`| # |`int64` | `int_`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`| # |`float64` | `float_`, `float16`, `float32`, `float64`| # |`bool` | `bool_`| # |`datetime64` | `datetime64[ns]`| # |`timedelta[ns]` | N/A| # |`category` | N/A| # Note that `category` is also not translatable into C. `category` is similar to a `tuple` in that it is intended to hold a collection of categorical variables, meaning metadata with a fixed unique set of values. Because it’s not translatable into C, it should never be used to hold data that needs to be analyzed. Its advantage mainly comes in its ability to sort things in a custom sort order efficiently and simply. Underneath it looks like a data array of indexes where the indexes correspond to a unique value in an array of categories. The documentation claims that it can result in a huge memory savings when using string categories. Of course, we know that Python already has a built-in string cache that does that for us automatically for certain strings so this would really only make a difference if the strings contained characters other than alphanumeric and underscore. # Below shows an example of a `category` and its representation in memory. Note that it uses integers to represent the value and those integers map to an `index` in the `category` array. This is a common method of conserving memory in pandas. We’ll run into this again later when we look at multi-indexing. import pandas as pd produce = pd.Series( ["apple", "banana", "carrot", "apple"], dtype="category" ) produce # Operations must also be translatable into C in order to take advantage of NumPy’s performance optimizations. This means custom functions like the one below will not be performant because they will run in Python and not in C. We’ll dig more into this example and the apply function specifically in later sections. def grade(values): if 70 <= values["score"] < 80: values["score"] = "C" elif 80 <= values["score"] < 90: values["score"] = "B" elif 90 <= values["score"]: values["score"] = "A" else: values["score"] = "F" return values scores = pd.DataFrame({"score": [89, 70, 71, 65, 30, 93, 100, 75]}) scores.apply(grade, axis=1)
Introduction/3. Pandas/5. How Pandas Work Under the Hood.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Mod 4 Project - Starter Notebook # # This notebook has been provided to you so that you can make use of the following starter code to help with the trickier parts of preprocessing the Zillow dataset. # # The notebook contains a rough outline the general order you'll likely want to take in this project. You'll notice that most of the areas are left blank. This is so that it's more obvious exactly when you should make use of the starter code provided for preprocessing. # # **_NOTE:_** The number of empty cells are not meant to infer how much or how little code should be involved in any given step--we've just provided a few for your convenience. Add, delete, and change things around in this notebook as needed! # # # Some Notes Before Starting # # This project will be one of the more challenging projects you complete in this program. This is because working with Time Series data is a bit different than working with regular datasets. In order to make this a bit less frustrating and help you understand what you need to do (and when you need to do it), we'll quickly review the dataset formats that you'll encounter in this project. # # ## Wide Format vs Long Format # # If you take a look at the format of the data in `zillow_data.csv`, you'll notice that the actual Time Series values are stored as separate columns. Here's a sample: # # <img src='~/../images/df_head.png'> # # You'll notice that the first seven columns look like any other dataset you're used to working with. However, column 8 refers to the median housing sales values for April 1996, column 9 for May 1996, and so on. This This is called **_Wide Format_**, and it makes the dataframe intuitive and easy to read. However, there are problems with this format when it comes to actually learning from the data, because the data only makes sense if you know the name of the column that the data can be found it. Since column names are metadata, our algorithms will miss out on what dates each value is for. This means that before we pass this data to our ARIMA model, we'll need to reshape our dataset to **_Long Format_**. Reshaped into long format, the dataframe above would now look like: # # <img src='~/../images/melted1.png'> # # There are now many more rows in this dataset--one for each unique time and zipcode combination in the data! Once our dataset is in this format, we'll be able to train an ARIMA model on it. The method used to convert from Wide to Long is `pd.melt()`, and it is common to refer to our dataset as 'melted' after the transition to denote that it is in long format. # # # Helper Functions Provided # # Melting a dataset can be tricky if you've never done it before, so you'll see that we have provided a sample function, `melt_data()`, to help you with this step below. Also provided is: # # * `get_datetimes()`, a function to deal with converting the column values for datetimes as a pandas series of datetime objects # * Some good parameters for matplotlib to help make your visualizations more readable. # # Good luck! # # # # Step 1: Load the Data/Filtering for Chosen Zipcodes # !pip install -U fsds_100719 # + from fsds_100719.imports import * pd.set_option('display.max_columns',0) import warnings warnings.filterwarnings('ignore') plt.style.use('seaborn-notebook') # - #df = pd.read_csv('https://raw.githubusercontent.com/learn-co-students/dsc-mod-4-project-online-ds-ft-10072019/master/zillow_data.csv') df = pd.read_csv('zillow_data.csv') df.head().style.set_caption("Original Wide Format") import functions_mod4proj as ji help(ji) # + def melt_data(df): melted = pd.melt(df, id_vars = ['RegionID', 'RegionName', 'City', 'State', 'Metro', 'CountyName', 'SizeRank'],var_name = 'Month', value_name = 'MeanValue') melted['Month'] = pd.to_datetime(melted['Month'], format='%Y-%m') melted = melted.dropna(subset = ['MeanValue']) return melted # - df = melt_data(df) df.head().style.set_caption("MELTED LONG FORMAT") # # Step 2: Data Preprocessing # + def make_dateindex(df_to_add_index, index_col='Month', index_name = 'date', drop = True, verbose = True): '''Converts the index_col to a datetime index with nae = index_name''' # Copy input df and reset index df = df_to_add_index.copy() df.reset_index(drop=True) # Make datetime column to make an index df[index_name] = pd.to_datetime(df[index_col], errors = 'coerce') # assign index df = df.set_index(index_name, drop = drop) if verbose: display(df.index) return df df = make_dateindex(df, index_col = 'Month', index_name = 'date') df # - # # Step 3: EDA and Visualization # + font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) # NOTE: if you visualizations are too cluttered to read, try calling 'plt.gcf().autofmt_xdate()'! # - # # Step 4: Reshape from Wide to Long Format def melt_data(df): melted = pd.melt(df, id_vars=['RegionName', 'City', 'State', 'Metro', 'CountyName'], var_name='time') melted['time'] = pd.to_datetime(melted['time'], infer_datetime_format=True) melted = melted.dropna(subset=['value']) return melted.groupby('time').aggregate({'value':'mean'}) # # Step 5: ARIMA Modeling # # Step 6: Interpreting Results
mod_4_starter_notebook.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Quickstart # If you have a working version of [Anaconda Python](https://www.anaconda.com/distribution) installed on your system, it is easy to install Lightkurve and its dependencies using the ``conda`` package manager. In a terminal window, type: # ``` # $ conda install --channel conda-forge lightkurve # ``` # # If you are using a different Python distribution, you can also install Lightkurve using `pip install lightkurve`. See our [installation instructions](about/install.html) page for details and troubleshooting information. # # With Lightkurve installed, it is easy to extract brightness time series data (astronomers call this a *light curve*) # from the tiny images of stars collected by NASA's Kepler and TESS planet-hunting telescopes. # # For example, let's download and display the pixels of a famous star named [KIC 8462852](https://en.wikipedia.org/wiki/KIC_8462852), also known as *Tabby's Star* or *Boyajian's Star*, which is known to show unusual light fluctuations. # # First, we start Python and use the `search_targetpixelfile` function to obtain the Kepler pixel data for the star from the [data archive](https://archive.stsci.edu/kepler/): from lightkurve import search_targetpixelfile pixelfile = search_targetpixelfile(8462852, quarter=16).download(quality_bitmask='hardest'); # Next, let's display the first image in this data set: pixelfile.plot(frame=1); # It looks like the star is an isolated object, so we can extract a lightcurve by simply summing up all the pixel values in each image: lc = pixelfile.to_lightcurve(aperture_mask='all'); # The above method returned a `KeplerLightCurve` object which gives us access to the flux over time, which are both available as array objects. The time is in units of *days* and the flux is in units *electrons/second*. lc.time, lc.flux # We can plot these data using the `plot()` method: lc.plot(); # The plot reveals a short-lived 20% dip in the brightness of the star. It looks like we re-discovered one of the [intriguing dips in Tabby's star](https://en.wikipedia.org/wiki/KIC_8462852#Luminosity). # # Congratulations, you are now able to make new discoveries in Kepler and TESS data! # # Next, head to our [tutorials section](https://docs.lightkurve.org/tutorials) to be guided through more detailed examples of carrying out science with Lightkurve!
docs/source/quickstart.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="VAWgApr3qJ6l" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 408} outputId="193adcd0-58ac-4b84-c1b1-209fcf514874" import numpy as np sigmoid = lambda x:1/(1 + np.exp(-x)) relu = lambda x:(x>0).astype(float)*x weights = np.array([[1,4],[4,1]]) activation = sigmoid(np.array([1,0.01])) print("Sigmoid activations") activations = list() for iter in range(10): activation = sigmoid(activation.dot(weights)) activations.append(activation) print(activation) print("\n Sigmoid gradients") gradient = np.ones_like(activation) for activation in reversed(activations): gradient = (activation * (1 - activation) * gradient) gradient = gradient.dot(weights.transpose()) print(gradient) # + id="T-xihRA8qOx2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 408} outputId="dcdd4aa6-071a-48dc-9673-6b1cee17119c" print("Relu Activations") activations = list() for iter in range(10): activation = relu(activation.dot(weights)) activations.append(activation) print(activation) print("\nRelu Gradients") gradient = np.ones_like(activation) for activation in reversed(activations): gradient = ((activation > 0) * gradient).dot(weights.transpose()) print(gradient)
LSTM/RNN_vanishing_&_exploading_gradients.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np data = csv.reader('n') # + # %matplotlib notebook def fn(x, y): """Custom fuction to determine the colour (potential?) of the point""" return (x + y) / 2 # use average as a placeholder fig = plt.figure() ax = fig.add_subplot(111, projection='3d') size = 11 # range 0 to 10 # Make the 3D grid X, Y, Z = np.meshgrid(np.arange(0, size, 1), np.arange(0, size, 1), np.arange(0, size, 1)) # calculate a colour for point(x,y,z) zs = np.array([fn(x, y) for x, y in zip(np.ravel(X), np.ravel(Y))]) ZZ = zs.reshape(X.shape) # this is used below # create the surface xx, yy = np.meshgrid(np.arange(0, size, 1), np.arange(0, size, 1)) # Calcule the surface Z value, e.g. average of the colours calculated above zzs = np.array([np.average(ZZ[x][y]) for x, y in zip(np.ravel(xx), np.ravel(yy))]) zz= zzs.reshape(xx.shape) cube = ax.scatter(X, Y, Z, zdir='z', c=zs, cmap=plt.cm.seismic) cbar = fig.colorbar(cube, shrink=0.6, aspect=5) # Add a color bar plt.show() # -
code/projects/people_as_galaxies/plot_cube.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import json import gzip from collections import Counter df = pd.read_json('../data/original/DNA_DATA_FULL.gz', compression='gzip') # <h2><b>Getting only the columns that deal with the company codes</b></h2> #Looking only at the company columns companies = df[['company_codes', 'company_codes_occur', 'company_codes_about', 'company_codes_lineage', 'company_codes_association', 'company_codes_relevance']] #There are no values in this column so it will not be part of the validating process print(companies['company_codes_association'].value_counts()) companies = df[['company_codes', 'company_codes_occur', 'company_codes_about', 'company_codes_lineage', 'company_codes_relevance']] # <h2><b>Creating a profile table for validity</b></h2> #For validating, I will be taking each unique company code in all of the columns and checking to see if each one is in the company codes dictionary #The dataframe below will keep track of the % of valid company codes profile = pd.DataFrame({"Validity": np.zeros(len(companies.columns))}).set_index(companies.columns) profile # <h2><b>Creating validity function</b></h2> #Here is the validity function I will be using #returns the sum of True and divides by the length of the unique list def checkValidity(ls, col = code_dict.code.tolist()): return sum([code in col for code in ls]) / len(ls) # <h2><b>Getting unique codes for each column</b></h2> # + #Getting the unique company codes unique_company_codes = set() for value in companies['company_codes']: unique_company_codes.update(value.split(",")) #Convert set back to list unique_company_codes = list(unique_company_codes) unique_company_codes = unique_company_codes[1:] #The first element was '', so I didn't include it in the final list unique_company_codes = [word.upper() for word in unique_company_codes] print(unique_company_codes[0:10]) print("There are {} unique company codes".format(len(unique_company_codes))) # + #Unique companies from company_codes_occur unique_companies_occur = set() for value in df['company_codes_occur']: unique_companies_occur.update(value.split(",")) unique_companies_occur = list(unique_companies_occur) unique_companies_occur = unique_companies_occur[1:] unique_companies_occur = [word.upper() for word in unique_companies_occur] print(unique_companies_occur[0:10]) print("There are {} unique companies in unique_companies_occur".format(len(unique_companies_occur))) # + #unique companies from company_codes_about unique_companies_about = set() for value in df['company_codes_about']: unique_companies_about.update(value.split(",")) unique_companies_about = list(unique_companies_about) unique_companies_about = unique_companies_about[1:] unique_companies_about = [word.upper() for word in unique_companies_about] print(unique_companies_about[0:10]) print("There are {} unique companies in unique_companies_about".format(len(unique_companies_about))) # + #unique companies from company_codes_relevance unique_companies_relevance = set() for value in df['company_codes_relevance']: unique_companies_relevance.update(value.split(",")) unique_companies_relevance = list(unique_companies_relevance) unique_companies_relevance = unique_companies_relevance[1:] unique_companies_relevance = [word.upper() for word in unique_companies_relevance] print(unique_companies_relevance[0:10]) print("There are {} unique companies in unique_companies_relevance".format(len(unique_companies_relevance))) # + #unique companies from company_codes_lineage unique_companies_lineage = set() for value in df['company_codes_lineage']: unique_companies_lineage.update(value.split(",")) unique_companies_lineage = list(unique_companies_lineage) unique_companies_lineage = unique_companies_lineage[1:] #Convert to uppercase bc data dictionary has all codes in upper case unique_companies_lineage = [word.upper() for word in unique_companies_lineage] print(unique_companies_lineage[0:10]) print("There are {} unique companies in unique_companies_lineage".format(len(unique_companies_lineage))) # - # <h2><b>Loading in company code dictionary</b></h2> # #Uploading the data dictionary into a dataframe code_dict = pd.read_csv("../data/original/companies.csv") # <h2><b>Checking validity for each column and applying the result to the profile table</b></h2> #print(checkValidity(unique_companies_lineage)) profile.iloc[3] = checkValidity(unique_companies_lineage) profile.iloc[0] = checkValidity(unique_company_codes) profile.iloc[2] = checkValidity(unique_companies_about) profile.iloc[1] = checkValidity(unique_companies_occur) profile.iloc[4] = checkValidity(unique_companies_relevance) # <h2><b>Company Code Validity Results</b></h2> profile # <h2><b>Getting the invalid company codes</b></h2> #Getting all the invalid company codes invalid_company_codes = np.array([]) for co in unique_company_codes: if co not in code_dict.code.tolist(): invalid_company_codes = np.append(invalid_company_codes, co) print("There are {} company codes in the company codes column that are not in the dictionary".format(len(invalid_company_codes))) # <h2><b>Double checking to make sure that no codes in the invalid_company_codes list are valid (Should get 0% valid)</b></h2> print(checkValidity(invalid_company_codes)) # <h2><b>Listing some of the invalid codes (aka codes in the dataset but not in the dictionary)</b></h2> invalid_company_codes[0:30] df['Row'] = np.arange(0, len(df)) # <h2><b>Filtering through the dataset and keeping track of rows with at least one invalid company in them</b></h2> # + #subset1 = df[0:100000] # - invalid_row = [] for row in df.itertuples(): for code in row.company_codes.split(","): if code.upper() in invalid_company_codes: invalid_row.append(row.Row) print("There are {} rows with at least one invalid company code in the company_codes column, which is about {}% of the entire dataset".format(len(invalid_row), len(invalid_row) / len(df) * 100)) #First 100 invalid rows print(invalid_row[0:100])
src/Profiling/.ipynb_checkpoints/CompanyValidity-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="q0RuNvT1mjUA" colab_type="text" # # Big Data Application and Analytics - Project Overview <a name="1"></a> # # **Google Cloud & NCAA® ML Competition 2018-Men's # Apply Machine Learning to NCAA® March Madness® # Kaggle Competition** # # **<NAME>, <NAME>** # # The goal of our project is to predict the outcomes of college basketball games during a season based on key performance variables for each team. There are ~5500 Men's Division 1 basketball games each year. Our intent is to train our model on the first 80% of games played using 16 key performance variables recorded during the game by each team, and compare to the outcome of the game. We will then predict the winners of the remaining 20% of games. # # The interesting part of this project is determining how to deal with the 'test data' for the final 20% of the games. We can not simply use the performance variables captured during the 'test' games to predict the winner, because in reality you would not know these parameters until after the game is played (steals, shot percentage, total points, etc.). Instead we will have to 'predict' each teams expected game performance features based on their previous history, and then run the model using those features to create the ultimate target: the game winner. # # We are utilizing data from a Kaggle competition based on predicting the 2018 NCAA Mens College Basketball Tourney results. We will re-purpose the data for our study. The key data set that we will utilize will include the 16 key performance indicators for each team during every game of the season. This data set contains every game going back to 2003. We will treat each season as a separate study. Our intent is to predict the 2017-2018 season, but our stretch goal is to predict additional years and see whether the optimal method is the same or different across years. # # We believe that logarithmic regressors with log loss metrics should be the first approaches to explore in order to generate a percentage chance of winning. However, we will test many of the different methodologies studied during the course to find the best predictor. # # Here's the [link](https://www.kaggle.com/c/mens-machine-learning-competition-2018#description) to the Kaggle competition # # + id="L__dSdLbtrOX" colab_type="code" outputId="33839ec7-5181-4112-82ee-4a81aa34ead0" colab={"base_uri": "https://localhost:8080/", "height": 34} # Run this cell to mount your Google Drive. from google.colab import drive drive.mount('/content/drive') # + [markdown] id="qheXiWdwmjUC" colab_type="text" # # + [markdown] id="ANP0fkQqmjUC" colab_type="text" # # # -- safsd## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigm ## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalarasdasd## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy sigmoid - Standard Scalar## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy - adam optimizer - sigmoid - Standard ScalarRe-Run The Baseline Model With Data Preparation - TUNING - StandardScalerRe-Run The Baseline Model With Data Preparation - TUNING - StandardScaler # + id="_MCY80oOmjUD" colab_type="code" colab={} import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import sys import seaborn as sns import time import warnings warnings.simplefilter('ignore') from collections import Counter from scipy import sparse, stats from sklearn import preprocessing as prep from sklearn.base import BaseEstimator, TransformerMixin from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import Lasso, LinearRegression, LogisticRegression, Ridge, SGDClassifier from sklearn.metrics import accuracy_score, mean_squared_error, mean_absolute_error, r2_score from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, ShuffleSplit, StratifiedKFold from sklearn.pipeline import FeatureUnion, Pipeline from sklearn.preprocessing import Imputer, LabelEncoder, StandardScaler, OneHotEncoder, MinMaxScaler from sklearn.svm import SVC, SVR from sklearn.utils import check_array from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import log_loss, confusion_matrix import logging # %matplotlib inline # + [markdown] id="F2BD5IyqmjUN" colab_type="text" # # ETL Phase: Load and Preprocess Data # # All the data can be found on Kaggle [here](https://www.kaggle.com/c/mens-machine-learning-competition-2018/data). We used RegularSeasonDetailedResults.csv # # + id="R7oYqMT3mjUO" colab_type="code" colab={} #Results = pd.read_csv(r'RegularSeasonDetailedResults.csv') Results = pd.read_csv(r'/content/drive/My Drive/BDAA_Project/RegularSeasonDetailedResults.csv') #Results = pd.read_csv(r'C:\Data\RegularSeasonDetailedResults.csv') # + id="--9FCbjkmjUP" colab_type="code" colab={} Results2017 = Results.loc[Results.Season == 2017] # + id="tAmbV8symjUR" colab_type="code" colab={} HomeWin = Results2017.loc[:,['Season','DayNum','WTeamID','WScore','LTeamID','LScore','WLoc']].loc[Results.WLoc=='H'] AwayWin = Results2017.loc[:,['Season','DayNum','LTeamID','LScore','WTeamID','WScore','WLoc']].loc[Results.WLoc=='A'] HomeWin2 = pd.concat([HomeWin,Results2017.loc[:,['WFGM','WFGA','WFGM3','WFGA3','WFTM','WFTA','WOR','WDR','WAst','WTO','WStl','WBlk','WPF']].loc[Results.WLoc=='H']], axis=1) HomeWin3 = pd.concat([HomeWin2,Results2017.loc[:,['LFGM','LFGA','LFGM3','LFGA3', 'LFTM','LFTA','LOR','LDR','LAst','LTO','LStl','LBlk','LPF']].loc[Results.WLoc=='H']], axis=1) AwayWin2 = pd.concat([AwayWin,Results2017.loc[:,['LFGM','LFGA','LFGM3','LFGA3','LFTM','LFTA','LOR','LDR','LAst','LTO','LStl','LBlk','LPF']].loc[Results.WLoc=='A']], axis=1) AwayWin3 = pd.concat([AwayWin2,Results2017.loc[:,['WFGM','WFGA','WFGM3','WFGA3', 'WFTM','WFTA','WOR','WDR','WAst','WTO','WStl','WBlk','WPF']].loc[Results.WLoc=='A']], axis=1) # + [markdown] id="NU9vohJOmjUT" colab_type="text" # Use train test split on neutral site games # # Spliting neutral site winners between 'Home' and 'Away' with the same ratio as home team winners # + id="1lkqKDuJmjUT" colab_type="code" colab={} Neut = Results2017.loc[Results.WLoc=='N'] nw, nl = train_test_split(Neut, test_size = .36, random_state = 36) nw = nw.drop(columns=['NumOT']) Neutral = nl.loc[:,['Season','DayNum','LTeamID','LScore','WTeamID','WScore','WLoc']] nl2 = pd.concat([Neutral,nl.loc[:,['LFGM','LFGA','LFGM3','LFGA3', 'LFTM','LFTA','LOR','LDR','LAst','LTO','LStl','LBlk','LPF']]], axis=1) nl3 = pd.concat([nl2,nl.loc[:,['WFGM','WFGA','WFGM3','WFGA3', 'WFTM','WFTA','WOR','WDR','WAst','WTO','WStl','WBlk','WPF']]], axis=1) nw3 = nw # + id="PEhgKKGhmjUV" colab_type="code" colab={} HomeWin3['WON'] = 1 AwayWin3['WON'] = 0 nw3['WON'] = 1 nl3['WON'] = 0 HomeWin3['NEUTRAL'] = 0 AwayWin3['NEUTRAL'] = 0 nw3['NEUTRAL'] = 1 nl3['NEUTRAL'] = 1 ############################################################################### HomeWin3.columns = ['Season','DayNum','HTeamID','HScore','ATeamID','AScore','WLoc','HFGM','HFGA','HFGM3','HFGA3','HFTM','HFTA','HOR','HDR','HAst','HTO','HStl','HBlk','HPF','AFGM','AFGA','AFGM3','AFGA3','AFTM','AFTA','AOR','ADR','AAst','ATO','AStl','ABlk','APF','WON','NEUTRAL'] AwayWin3.columns = ['Season','DayNum','HTeamID','HScore','ATeamID','AScore','WLoc','HFGM','HFGA','HFGM3','HFGA3','HFTM','HFTA','HOR','HDR','HAst','HTO','HStl','HBlk','HPF','AFGM','AFGA','AFGM3','AFGA3','AFTM','AFTA','AOR','ADR','AAst','ATO','AStl','ABlk','APF','WON','NEUTRAL'] nw3.columns = ['Season','DayNum','HTeamID','HScore','ATeamID','AScore','WLoc','HFGM','HFGA','HFGM3','HFGA3','HFTM','HFTA','HOR','HDR','HAst','HTO','HStl','HBlk','HPF','AFGM','AFGA','AFGM3','AFGA3','AFTM','AFTA','AOR','ADR','AAst','ATO','AStl','ABlk','APF','WON','NEUTRAL'] nl3.columns = ['Season','DayNum','HTeamID','HScore','ATeamID','AScore','WLoc','HFGM','HFGA','HFGM3','HFGA3','HFTM','HFTA','HOR','HDR','HAst','HTO','HStl','HBlk','HPF','AFGM','AFGA','AFGM3','AFGA3','AFTM','AFTA','AOR','ADR','AAst','ATO','AStl','ABlk','APF','WON','NEUTRAL'] HomeAwayResults = pd.concat([HomeWin3,AwayWin3,nw3,nl3]) # + [markdown] id="yIQ0DquamjUW" colab_type="text" # Notebook Cleanup - deleting old/temporary variables # + id="zCViEtfHmjUX" colab_type="code" colab={} del AwayWin del AwayWin2 del AwayWin3 del HomeWin del HomeWin2 del HomeWin3 del Neutral del Neut del nl del nl2 del nl3 del nw del nw3 # + [markdown] id="McKee-XVmjUa" colab_type="text" # # Exploritory Data Analysis # + id="sJbmpg5DmjUa" colab_type="code" outputId="b0d83d13-9336-42dc-d422-55a7802f9af4" colab={"base_uri": "https://localhost:8080/", "height": 223} HomeAwayResults.head() # + id="IdcoFg90mjUd" colab_type="code" outputId="2ff454b8-4016-4b3d-e2d7-00e607abfd38" colab={"base_uri": "https://localhost:8080/", "height": 703} Results2017.info() # + id="9bCQ7JJ6mjUi" colab_type="code" outputId="d2c04120-3dbb-4737-836c-5ce9a3f46326" colab={"base_uri": "https://localhost:8080/", "height": 316} Results2017.describe() # + id="r35mSS2ymjUk" colab_type="code" outputId="80f9889e-6ab6-4073-ea22-b1e2990545e6" colab={"base_uri": "https://localhost:8080/", "height": 282} Results2017['WScore'].hist() # + id="V8LytR31mjUm" colab_type="code" outputId="180bc11b-e7a6-4279-ceff-3487ec157736" colab={"base_uri": "https://localhost:8080/", "height": 296} Results2017.plot(kind="scatter", x="LScore", y="WScore", alpha=0.1) # + id="DYFl-HpxmjUo" colab_type="code" colab={} # + id="M9qgtti-mjUr" colab_type="code" outputId="6fade30e-07b6-4249-a704-735d969bf738" colab={"base_uri": "https://localhost:8080/", "height": 87} Results2017['WLoc'].value_counts() # + id="lTAKTnZMmjUu" colab_type="code" outputId="690b7fc4-578b-4d07-aad5-5513320c2c22" colab={"base_uri": "https://localhost:8080/", "height": 34} #Average Margin of victory (Results2017['WScore']-Results2017['LScore']).mean() # + id="Q8ICHcg5mjUw" colab_type="code" outputId="71c14146-9fa7-444a-f17a-d83e3ef873d5" colab={"base_uri": "https://localhost:8080/", "height": 34} # Average Turnover Differential (Results2017['LTO']-Results2017['WTO']).mean() # + id="9rKppCXlmjUx" colab_type="code" outputId="0ba29216-9f91-40b8-d5b2-653898be2824" colab={"base_uri": "https://localhost:8080/", "height": 34} # Average 3 Pointer Made Differential (Results2017['WFGM3']-Results2017['LFGM3']).mean() # + id="ZxaxKPXfmjUz" colab_type="code" outputId="9f504492-5c29-43e6-ef20-4462523d1975" colab={"base_uri": "https://localhost:8080/", "height": 34} # Average Assist Differential (Results2017['WAst']-Results2017['LAst']).mean() # + id="233Poc3RmjU2" colab_type="code" outputId="bd3f6bb8-17a1-4914-e4b9-ba1594d62781" colab={"base_uri": "https://localhost:8080/", "height": 34} # Average Free Throw Attempted Differential (Results2017['WFTA']-Results2017['LFTA']).mean() # + [markdown] id="FM7U_4NJmjU4" colab_type="text" # Per Season statistics on game location, home/away winner, and what day of the season 80% of games were completed # + id="3UmOK_nvmjU5" colab_type="code" colab={} SeasonStats = Results['Season'].value_counts() SeasonStats = SeasonStats.rename('NumGames') SeasonStats = pd.concat([SeasonStats,Results['Season'].loc[Results.WLoc == 'N'].value_counts()],axis=1) SeasonStats = SeasonStats.rename(columns={'Season':'NeutralSiteGames'}) SeasonStats = pd.concat([SeasonStats,Results['Season'].loc[Results.WLoc != 'N'].value_counts()],axis=1) SeasonStats = SeasonStats.rename(columns={'Season':'NonNeutralGames'}) SeasonStats = pd.concat([SeasonStats,Results['Season'].loc[Results.WLoc == 'H'].value_counts()],axis=1) SeasonStats = SeasonStats.rename(columns={'Season':'HomeWins'}) SeasonStats = pd.concat([SeasonStats,Results['Season'].loc[Results.WLoc == 'A'].value_counts()],axis=1) SeasonStats = SeasonStats.rename(columns={'Season':'AwayWins'}) SeasonStats['HomeLosePct'] = np.round((SeasonStats.AwayWins / SeasonStats.NonNeutralGames),2) SeasonStats['DayNum80'] = 0 for s in SeasonStats.index: x = Results['DayNum'].loc[Results.Season == s] SeasonStats['DayNum80'].loc[s] = x.iloc[round(len(x)*.8)] # + id="JJY4seUYmjU7" colab_type="code" outputId="64e2a91c-0401-41c0-9fdf-85e1d1c5abbe" colab={"base_uri": "https://localhost:8080/", "height": 543} SeasonStats # + id="4NmuCjAdmjU8" colab_type="code" outputId="c20adab9-ae0e-453e-875d-e130d1cd01b3" colab={"base_uri": "https://localhost:8080/", "height": 879} # %matplotlib inline import matplotlib.pyplot as plt HomeAwayResults.hist(bins=50, figsize=(20,15)) plt.show() # + id="gNVFCqpymjU-" colab_type="code" colab={} # + [markdown] id="LWB79MCQmjVA" colab_type="text" # # Feature Engineering # + [markdown] id="cDc8VxBKmjVA" colab_type="text" # First we removed the team performance variables that directly impact the result of the game. Any of the fields # That indicated points scored was removed. Instead we created new fields that showed the shooting percentage. # Shooting percentage is indicative of performance without giving a 1-to-1 ratio to winning. # # After completing many logistic regressions runs using Lasso and Ridge, we evaluated the most impactful coefficients # We fount that 3-point shooting, defensive rebounds and turnovers seemed to always be the most important. # To capitalize on this, we created many new features that compared the ratio of these variables between the two # competing teams. In our initial runs, we found that these variables increased the overall accuracy of the model by 5% # This looks like a good area to look at in future runs. # + id="dZoYwx5EmjVB" colab_type="code" colab={} ############################################################################### HomeAwayResults['HFGM2']=HomeAwayResults['HFGM'] - HomeAwayResults['HFGM3'] #HOME 2 POINT FIELD GOALS MADE HomeAwayResults['AFGM2']=HomeAwayResults['AFGM'] - HomeAwayResults['AFGM3'] #AWAY 2 POINT FILED GOALS MADE HomeAwayResults['HFGA2']=HomeAwayResults['HFGA'] - HomeAwayResults['HFGA3'] #HOME 2 POINT FIELD GOALS ATTEMPTED HomeAwayResults['AFGA2']=HomeAwayResults['AFGA'] - HomeAwayResults['AFGA3'] #AWAY 2 POINT FIELD GOALS ATTEMPTED HomeAwayResults['HFGP']=HomeAwayResults['HFGM'] / HomeAwayResults['HFGA'] #HOME FIELD GOALS PERCENTAGE MADE - ALL HomeAwayResults['AFGP']=HomeAwayResults['AFGM'] / HomeAwayResults['AFGA'] #AWAY FIELD GOALS PERCENTAGE MADE - ALL HomeAwayResults['HFGP2']=HomeAwayResults['HFGM2'] / HomeAwayResults['HFGA2'] #HOME FIELD GOALS PERCENTAGE MADE - 2 PT HomeAwayResults['AFGP2']=HomeAwayResults['AFGM2'] / HomeAwayResults['AFGA2'] #AWAY FIELD GOALS PERCENTAGE MADE - 2 PT HomeAwayResults['HFGP3']=HomeAwayResults['HFGM3'] / HomeAwayResults['HFGA3'] #HOME FIELD GOALS PERCENTAGE MADE - 3 PT HomeAwayResults['AFGP3']=HomeAwayResults['AFGM3'] / HomeAwayResults['AFGA3'] #AWAY FIELD GOALS PERCENTAGE MADE - 3 PT ############################################################################### # Features created in Phase 1 HomeAwayResults['HTORC']=HomeAwayResults['HTO'] / HomeAwayResults['ATO'] #HOME TURNOVER RATIO VS COMPETITOR HomeAwayResults['ATORC']=HomeAwayResults['ATO'] / HomeAwayResults['HTO'] #AWAY TURNOVER RATIO VS COMPETITOR HomeAwayResults['HDRR']=HomeAwayResults['HDR'] / HomeAwayResults['ADR'] #HOME DEFENSIVE REBOUND RATION VS COMPETITOR HomeAwayResults['ADRR']=HomeAwayResults['ADR'] / HomeAwayResults['HDR'] #AWAY DEFENSIVE REBOUND RATION VS COMPETITOR HomeAwayResults['APFR']=HomeAwayResults['APF'] / HomeAwayResults['HPF'] #AWAY PERSONAL FOUL RATIO VS COMPETITOR HomeAwayResults['HPFR']=HomeAwayResults['HPF'] / HomeAwayResults['APF'] #HOME PERSONAL FOUL RATIO VS COMPETITOR HomeAwayResults['ATODR']=HomeAwayResults['ATO'] + HomeAwayResults['HDR'] #AWAY TEAM LOST POSSESSIONS: TURNOVERS + COMPETITORS DEF REBOUNDS HomeAwayResults['HTODR']=HomeAwayResults['HTO'] + HomeAwayResults['ADR'] #HOME TEAM LOST POSSESSIONS: TURNOVERS + COMPETITORS DEF REBOUNDS HomeAwayResults['ATODRR']=HomeAwayResults['ATODR'] / HomeAwayResults['HTODR'] #HOME TEAM LOST POSSESSIONS RATIO HomeAwayResults['HTODRR']=HomeAwayResults['HTODR'] / HomeAwayResults['ATODR'] #AWAY TEAM LOST POSSESSIONS: RATIO HomeAwayResults['H3VTO']=HomeAwayResults['HFGP3'] / HomeAwayResults['HTODRR'] #HOME 3PTS OVERCOMING TURNOVER RATIO HomeAwayResults['A3VTO']=HomeAwayResults['AFGP3'] / HomeAwayResults['ATODRR'] #AWAY 3PTS OVERCOMING TURNOVER RATIO # + id="11zmhkywmjVG" colab_type="code" colab={} ############################################################################### # New Features Phase 2 ############################################################################### # Number of Possessions HomeAwayResults['HPoss']= (HomeAwayResults['HFGA'] - HomeAwayResults['HOR'] + HomeAwayResults['HTO'] + (0.44 * HomeAwayResults['HFTA'])) # HOME Number of Possessions HomeAwayResults['APoss']= (HomeAwayResults['AFGA'] - HomeAwayResults['AOR'] + HomeAwayResults['ATO'] + (0.44 * HomeAwayResults['AFTA'])) # AWAY Number of Possessions # "Four Factors" HomeAwayResults['HeFGP'] = ((HomeAwayResults['HFGM'] + (0.5*HomeAwayResults['HFGM3'])) / HomeAwayResults['HFGA']) # HOME Effective Field Goal Perc (0.4) HomeAwayResults['AeFGP'] = ((HomeAwayResults['AFGM'] + (0.5*HomeAwayResults['AFGM3'])) / HomeAwayResults['AFGA']) # AWAY Effective Field Goal Perc (0.4) HomeAwayResults['HTOR'] = (HomeAwayResults['HTO'] / HomeAwayResults['HPoss']) # HOME Turnover Perc (0.25) HomeAwayResults['ATOR'] = (HomeAwayResults['ATO'] / HomeAwayResults['APoss']) # AWAY Turnover Perc (0.25) HomeAwayResults['HORR'] = HomeAwayResults['HOR'] / (HomeAwayResults['HOR'] + HomeAwayResults['ADR']) #HOME Off Rebound Rate (0.2) HomeAwayResults['AORR'] = HomeAwayResults['AOR'] / (HomeAwayResults['AOR'] + HomeAwayResults['HDR']) #AWAY Off Rebound Rate (0.2) HomeAwayResults['HFTR'] = (HomeAwayResults['HFTA'] / HomeAwayResults['HFGA']) # HOME Free Throw Rate (0.15) HomeAwayResults['AFTR'] = (HomeAwayResults['AFTA'] / HomeAwayResults['AFGA']) # AWAY Free Throw Rate (0.15) # Off and Def Efficiency HomeAwayResults['HOffEf'] = ((HomeAwayResults['HScore']*100) / HomeAwayResults['HPoss']) # HOME Offensive Efficiency HomeAwayResults['AOffEf'] = ((HomeAwayResults['AScore']*100) / HomeAwayResults['APoss']) # AWAY Offensive Efficiency HomeAwayResults['HDefEf'] = ((HomeAwayResults['AScore']*100) / HomeAwayResults['APoss']) # HOME Defensive Efficiency HomeAwayResults['ADefEf'] = ((HomeAwayResults['HScore']*100) / HomeAwayResults['HPoss']) # HOME Defensive Efficiency ############################################################################### # + [markdown] id="h0X84AQzmjVH" colab_type="text" # # Data Prep # + [markdown] id="uVUF-kEPmjVI" colab_type="text" # Because our problem resembles a time series analysis problem, we won't create a random 80/20 split # of our dataset using train_test_split, or any similar function. # Our training set will be the first 80 percent of games in the season, and our test set will be final # 20 percent of games. # We aren't using the actual game statistics for those games in the test set, but rather each team's # home and away averages from the first 80 percent of games, thus simulating predicting the outcome # of the game before the game starts. # + id="KFPJqkFUmjVI" colab_type="code" colab={} def completeAverages(): TeamAvgH['HFGM2']=TeamSumH['HFGM'] - TeamSumH['HFGM3'] #HOME 2 POINT FIELD GOALS MADE TeamAvgA['AFGM2']=TeamSumA['AFGM'] - TeamSumA['AFGM3'] #AWAY 2 POINT FILED GOALS MADE TeamAvgH['HFGA2']=TeamSumH['HFGA'] - TeamSumH['HFGA3'] #HOME 2 POINT FIELD GOALS ATTEMPTED TeamAvgA['AFGA2']=TeamSumA['AFGA'] - TeamSumA['AFGA3'] #AWAY 2 POINT FIELD GOALS ATTEMPTED TeamAvgH['HFGP']=TeamSumH['HFGM'] / TeamSumH['HFGA'] #HOME FIELD GOALS PERCENTAGE MADE - ALL TeamAvgA['AFGP']=TeamSumA['AFGM'] / TeamSumA['AFGA'] #AWAY FIELD GOALS PERCENTAGE MADE - ALL TeamAvgH['HFGP2']=TeamSumH['HFGM2'] / TeamSumH['HFGA2'] #HOME FIELD GOALS PERCENTAGE MADE - 2 PT TeamAvgA['AFGP2']=TeamSumA['AFGM2'] / TeamSumA['AFGA2'] #AWAY FIELD GOALS PERCENTAGE MADE - 2 PT TeamAvgH['HFGP3']=TeamSumH['HFGM3'] / TeamSumH['HFGA3'] #HOME FIELD GOALS PERCENTAGE MADE - 3 PT TeamAvgA['AFGP3']=TeamSumA['AFGM3'] / TeamSumA['AFGA3'] #AWAY FIELD GOALS PERCENTAGE MADE - 3 PT # Features created in Phase 1 TeamAvgH['HTORC']=TeamSumH['HTO'] / TeamSumA['ATO'] #HOME TURNOVER RATIO VS COMPETITOR TeamAvgA['ATORC']=TeamSumA['ATO'] / TeamSumH['HTO'] #AWAY TURNOVER RATIO VS COMPETITOR TeamAvgH['HDRR']=TeamSumH['HDR'] / TeamSumA['ADR'] #HOME DEFENSIVE REBOUND RATION VS COMPETITOR TeamAvgA['ADRR']=TeamSumA['ADR'] / TeamSumH['HDR'] #AWAY DEFENSIVE REBOUND RATION VS COMPETITOR TeamAvgH['HPFR']=TeamSumH['HPF'] / TeamSumA['APF'] #HOME PERSONAL FOUL RATIO VS COMPETITOR TeamAvgA['APFR']=TeamSumA['APF'] / TeamSumH['HPF'] #AWAY PERSONAL FOUL RATIO VS COMPETITOR TeamAvgH['HTODR']=TeamSumH['HTO'] + TeamSumA['ADR'] #HOME TEAM LOST POSSESSIONS: TURNOVERS + COMPETITORS DEF REBOUNDS TeamAvgA['ATODR']=TeamSumA['ATO'] + TeamSumH['HDR'] #AWAY TEAM LOST POSSESSIONS: TURNOVERS + COMPETITORS DEF REBOUNDS TeamAvgH['HTODRR']=TeamSumH['HTODR'] / TeamSumA['ATODR'] #HOME TEAM LOST POSSESSIONS RATIO TeamAvgA['ATODRR']=TeamSumA['ATODR'] / TeamSumH['HTODR'] #AWAY TEAM LOST POSSESSIONS: RATIO TeamAvgH['H3VTO']=TeamSumH['HFGP3'] / TeamSumH['HTODRR'] #HOME 3PTS OVERCOMING TURNOVER RATIO TeamAvgA['A3VTO']=TeamSumA['AFGP3'] / TeamSumA['ATODRR'] #AWAY 3PTS OVERCOMING TURNOVER RATIO # New Features Phase 2 TeamAvgH['HPoss']= (TeamSumH['HFGA'] - TeamSumH['HOR'] + TeamSumH['HTO'] + (0.44 * TeamSumH['HFTA'])) # HOME Number of Possessions TeamAvgA['APoss']= (TeamSumA['AFGA'] - TeamSumA['AOR'] + TeamSumA['ATO'] + (0.44 * TeamSumA['AFTA'])) # AWAY Number of Possessions # "Four Factors" TeamAvgH['HeFGP'] = ((TeamSumH['HFGM'] + (0.5*TeamSumH['HFGM3'])) / TeamSumH['HFGA']) # HOME Effective Field Goal Perc (0.4) TeamAvgA['AeFGP'] = ((TeamSumA['AFGM'] + (0.5*TeamSumA['AFGM3'])) / TeamSumA['AFGA']) # AWAY Effective Field Goal Perc (0.4) TeamAvgH['HTOR'] = (TeamSumH['HTO'] / TeamSumH['HPoss']) # HOME Turnover Perc (0.25) TeamAvgA['ATOR'] = (TeamSumA['ATO'] / TeamSumA['APoss']) # AWAY Turnover Perc (0.25) TeamAvgH['HORR'] = TeamSumH['HOR'] / (TeamSumH['HOR'] + TeamSumH['ADR']) #HOME Off Rebound Rate (0.2) TeamAvgA['AORR'] = TeamSumA['AOR'] / (TeamSumA['AOR'] + TeamSumA['HDR']) #AWAY Off Rebound Rate (0.2) TeamAvgH['HFTR'] = (TeamSumH['HFTA'] / TeamSumH['HFGA']) # HOME Free Throw Rate (0.15) TeamAvgA['AFTR'] = (TeamSumA['AFTA'] / TeamSumA['AFGA']) # AWAY Free Throw Rate (0.15) # Off and Def Efficiency TeamAvgH['HOffEf'] = ((TeamSumH['HScore']*100) / TeamSumH['HPoss']) # HOME Offensive Efficiency TeamAvgA['AOffEf'] = ((TeamSumA['AScore']*100) / TeamSumA['APoss']) # AWAY Offensive Efficiency TeamAvgH['HDefEf'] = ((TeamSumH['AScore']*100) / TeamSumH['APoss']) # HOME Defensive Efficiency TeamAvgA['ADefEf'] = ((TeamSumA['HScore']*100) / TeamSumA['HPoss']) # HOME Defensive Efficiency def calcDifferences(df): df['eFGP'] = df['HeFGP'] - df['AeFGP'] df['TOR'] = df['HTOR'] - df['ATOR'] df['ORR'] = df['HORR'] - df['AORR'] df['FTR'] = df['HFTR'] - df['AFTR'] df['OffEf'] = df['HOffEf'] - df['AOffEf'] df['DefEf'] = df['HDefEf'] - df['ADefEf'] def reduceFeat(df): df2 = df.loc[:,['HTeamID','ATeamID','NEUTRAL','eFGP','TOR','ORR','FTR','OffEf','DefEf']] return df2 # + id="4ZjnUE0CmjVK" colab_type="code" colab={} X80=HomeAwayResults.loc[HomeAwayResults.DayNum<107] X20=HomeAwayResults.loc[HomeAwayResults.DayNum>=107] y_train = X80["WON"] y_test = X20["WON"] # + id="yQpJb3QRmjVL" colab_type="code" colab={} # Total team averages X20H = X80[['HTeamID','HScore','HFGM', 'HFGA', 'HFGM3', 'HFGA3', 'HFTM', 'HFTA', 'HOR', 'HDR', 'HAst', 'HTO', 'HStl', 'HBlk', 'HPF', 'HFGM2', 'HFGA2', 'HFGP', 'HFGP2', 'HFGP3', 'HTORC','HDRR','HPFR','HTODR','HTODRR','H3VTO', 'HPoss', 'HeFGP', 'HTOR', 'HORR', 'HFTR', 'HOffEf', 'HDefEf','AScore','ADR','APoss']] X20A = X80[['ATeamID','AScore','AFGM', 'AFGA', 'AFGM3', 'AFGA3', 'AFTM', 'AFTA', 'AOR', 'ADR', 'AAst', 'ATO', 'AStl', 'ABlk', 'APF', 'AFGM2', 'AFGA2', 'AFGP', 'AFGP2', 'AFGP3', 'ATORC','ADRR','APFR','ATODR','ATODRR','A3VTO', 'APoss', 'AeFGP', 'ATOR', 'AORR', 'AFTR', 'AOffEf', 'ADefEf','HScore','HDR','HPoss']] # + id="q2W8l5qnmjVN" colab_type="code" colab={} AllStatsA = X20H.copy() AllStatsA.columns = X20A.columns AllStatsA = AllStatsA.append(X20A) AllStatsH = X20A.copy() AllStatsH.columns = X20H.columns AllStatsH = AllStatsH.append(X20H) TeamAvgA = AllStatsA.groupby(['ATeamID']).mean() TeamAvgH = AllStatsH.groupby(['HTeamID']).mean() TeamSumA = AllStatsA.groupby(['ATeamID']).sum() TeamSumH = AllStatsH.groupby(['HTeamID']).sum() # ------------- FILL OUT AVERAGES! ---------- completeAverages() TotAvgH = TeamAvgH.drop(['HScore','AScore','ADR','APoss'], axis=1) TotAvgA = TeamAvgA.drop(['AScore','HScore','HDR','HPoss'], axis=1) # + id="sWxRbFIamjVO" colab_type="code" colab={} # FOR TRAIN XAHtrain = pd.DataFrame(X80[['HTeamID','ATeamID','NEUTRAL']]) XTempA = pd.merge(XAHtrain,TotAvgH, on=['HTeamID'], right_index=True, left_index=False) XTempB = pd.merge(XTempA,TotAvgA, on=['ATeamID'], right_index=True, left_index=False) X_trainAllAvg = XTempB # FOR TEST XAH = pd.DataFrame(X20[['HTeamID','ATeamID','NEUTRAL']]) XTempA = pd.merge(XAH,TotAvgH, on=['HTeamID'], right_index=True, left_index=False) XTempB = pd.merge(XTempA,TotAvgA, on=['ATeamID'], right_index=True, left_index=False) X_testAllAvg = XTempB # + id="TreEU1TomjVQ" colab_type="code" colab={} TeamAvgH = X20H.groupby(['HTeamID']).mean() TeamAvgA = X20A.groupby(['ATeamID']).mean() TeamSumH = X20H.groupby(['HTeamID']).sum() TeamSumA = X20A.groupby(['ATeamID']).sum() # ------------- FILL OUT AVERAGES! ---------- completeAverages() HomeAvg = TeamAvgH.drop(['HScore','AScore','ADR','APoss'], axis=1) AwayAvg = TeamAvgA.drop(['AScore','HScore','HDR','HPoss'], axis=1) # + id="cHlH3Z1NmjVU" colab_type="code" colab={} # FOR TRAIN XAHtrain = pd.DataFrame(X80[['HTeamID','ATeamID','NEUTRAL']]) XTempA = pd.merge(XAHtrain,HomeAvg, on=['HTeamID'], right_index=True, left_index=False) X_trainHAAvg = XTempB # FOR TEST XAH = pd.DataFrame(X20[['HTeamID','ATeamID','NEUTRAL']]) XTempA = pd.merge(XAH,HomeAvg, on=['HTeamID'], right_index=True, left_index=False) XTempB = pd.merge(XTempA,AwayAvg, on=['ATeamID'], right_index=True, left_index=False) X_testHAAvg = XTempB # + id="ilhSuUjqmjVV" colab_type="code" colab={} X_train = X_trainAllAvg.drop(['HTeamID','ATeamID'], axis =1) X_test = X_testAllAvg.drop(['HTeamID','ATeamID'], axis =1) # + [markdown] id="bK6aSGTSmjVW" colab_type="text" # Notebook Cleanup - deleting old/temporary variables # + [markdown] id="mNXTRyGQmjVX" colab_type="text" # # Feature Selection # + [markdown] id="T3RasKt3mjVX" colab_type="text" # ## Feature Correlation Plot # + id="VYPsCPoXmjVX" colab_type="code" colab={} X_train_corr_plot = X_train.drop(['HTORC','ATORC','HDRR','ADRR','HPFR','APFR','HTODRR','ATODRR'],axis=1) # + id="yFs0ZyW8mjVZ" colab_type="code" outputId="c427d50c-77e5-4c9b-ffbd-1afa449d6231" colab={"base_uri": "https://localhost:8080/", "height": 1000} import matplotlib.pyplot as plt # %matplotlib inline fig = plt.figure(figsize=(30,30)) ax = fig.add_subplot(111) ms = ax.matshow(X_train_corr_plot.corr()) fig.colorbar(ms) label_count = list(range(len(X_train_corr_plot.columns))) ax.set_xticks(label_count) ax.set_xticklabels(X_train_corr_plot.columns, rotation=90) ax.set_yticks(label_count) ax.set_yticklabels(X_train_corr_plot.columns) ax.set_title('Visualizing the correlation between features and targets', pad=150, fontsize=14); # + [markdown] id="MR-PQWxRmjVa" colab_type="text" # ## Feature Selection using : sklearn.feature_selection Feature ranking with recursive feature elimination (RFE) # + id="mKxvy8ebmjVa" colab_type="code" outputId="6d3eb49f-cecd-453c-d824-5382899a8650" colab={"base_uri": "https://localhost:8080/", "height": 175} # Feature Selection using Logistic Regression model from sklearn.feature_selection import RFE from sklearn.linear_model import LogisticRegression logreg = LogisticRegression() rfe = RFE(logreg, 20) rfe = rfe.fit(X_train, y_train.values.ravel()) print(rfe.support_) print(rfe.ranking_) # + id="tORqhT_KmjVb" colab_type="code" outputId="c33c1285-e7fd-4e77-d6be-0e9260b6ff93" colab={"base_uri": "https://localhost:8080/", "height": 334} # Feature Selection using DecisionTreeRegressor from sklearn.feature_selection import RFE from sklearn.tree import DecisionTreeRegressor logreg = DecisionTreeRegressor(criterion="mse",min_samples_leaf=5) rfe = RFE(logreg, 20) rfe = rfe.fit(X_train, y_train.values.ravel()) print(X_train.columns) print(rfe.support_) print(rfe.ranking_) # + id="ua2vD021mjVe" colab_type="code" outputId="e99fc20b-bce6-4b66-c917-376103e69384" colab={"base_uri": "https://localhost:8080/", "height": 34} type(rfe.ranking_) # + [markdown] id="YfGcRO1RmjVf" colab_type="text" # ## Based on the ranking on above feature selection logic using RFE - Pick top 10 ranked features. # + id="PYMWg-F7mjVg" colab_type="code" outputId="bc28825d-2f10-4fc1-9764-06b0bd189889" colab={"base_uri": "https://localhost:8080/", "height": 709} X_train_1 = X_train[['NEUTRAL','HFGM2','HTODR','ATO','HPoss','AFGA','AFTA','AOR']] X_test_1 = X_test[['NEUTRAL','HFGM2','HTODR','ATO','HPoss','AFGA','AFTA','AOR']] #Plot for top 10 ranked features: Visualizing the features correlation import matplotlib.pyplot as plt # %matplotlib inline fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111) ms = ax.matshow(X_train_1.corr()) fig.colorbar(ms) label_count = list(range(len(X_train_1.columns))) ax.set_xticks(label_count) ax.set_xticklabels(X_train_1.columns, rotation=90) ax.set_yticks(label_count) ax.set_yticklabels(X_train_1.columns) ax.set_title('Visualizing the correlation between features and targets', pad=150, fontsize=14); # + id="2PekYxg9mjVi" colab_type="code" outputId="ba895c01-c2f4-4077-d166-17b5c76e76a6" colab={"base_uri": "https://localhost:8080/", "height": 1000} m = ~(X_train.corr().mask(np.eye(len(X_train.corr()), dtype=bool)).abs() > 0.75).any() pd.set_option('display.max_rows', 500) print(m) # + [markdown] id="E1-RWBIumjVj" colab_type="text" # ## Analysing Feature with high correlation [ corr greater that 0.75] # + id="9vq_35l_mjVk" colab_type="code" outputId="18f43974-1cdd-416f-f57b-370959143a8d" colab={"base_uri": "https://localhost:8080/", "height": 709} # Features with more than 0.75 correlation. #'NEUTRAL',HFGA',HFGM3',HFGA3',HDR',HAst',HStl',HBlk',HFGA2',HTODR',AFGA',AFGM3',AFGA3',ADR',AAst',AStl',ABlk',AFGA2' X_train_1 = X_train[['NEUTRAL','HFGA','HFGM3','HFGA3','HDR','HAst','HStl','HBlk','HFGA2','HTODR','AFGA','AFGM3','AFGA3','ADR','AAst','AStl','ABlk','AFGA2']] X_test_1 = X_test[['NEUTRAL','HFGA','HFGM3','HFGA3','HDR','HAst','HStl','HBlk','HFGA2','HTODR','AFGA','AFGM3','AFGA3','ADR','AAst','AStl','ABlk','AFGA2']] #Plot for top 10 ranked features: Visualizing the features correlation import matplotlib.pyplot as plt # %matplotlib inline fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(111) ms = ax.matshow(X_train_1.corr()) fig.colorbar(ms) label_count = list(range(len(X_train_1.columns))) ax.set_xticks(label_count) ax.set_xticklabels(X_train_1.columns, rotation=90) ax.set_yticks(label_count) ax.set_yticklabels(X_train_1.columns) ax.set_title('Visualizing correlation greater than 0.75 features only', pad=150, fontsize=14); # + [markdown] id="P8FjGjAOmjVl" colab_type="text" # ## Selecting select_kbest_reg features using f_regression # + id="PHEP45MMmjVl" colab_type="code" outputId="9ee8bfac-3709-4f65-fc24-3bfb73ee1d39" colab={"base_uri": "https://localhost:8080/", "height": 1000} import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import matplotlib import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.datasets import load_boston import pandas as pd from sklearn.feature_selection import SelectKBest, f_regression # SCORE linear regression input variables using correlation producing F scores and corresponding p-values # K is used select top k rated input features def select_kbest_reg(data_frame, target, k=5): """ Selecting K-Best features regression :param data_frame: A pandas dataFrame with the training data :param target: target variable name in DataFrame :param k: desired number of features from the data :returns feature_scores: scores for each feature in the data as pandas DataFrame """ feat_selector = SelectKBest(f_regression, k=k) _ = feat_selector.fit(data_frame.drop(target, axis=1), data_frame[target]) feat_scores = pd.DataFrame() feat_scores["F Score"] = feat_selector.scores_ feat_scores["P Value"] = feat_selector.pvalues_ feat_scores["Support"] = feat_selector.get_support() feat_scores["Attribute"] = data_frame.drop(target, axis=1).columns return feat_scores print(X_train.columns) X_train.head() df = pd.DataFrame(X_train, columns=X_train.columns).copy() df["MEDV"] = y_train per_feat = select_kbest_reg(df, 'MEDV', k=10) per_feat_sorted = per_feat.sort_values(["F Score", "P Value"], ascending=[False, False]) top_k_feature_indices = per_feat_sorted['Attribute'].values.flatten() print("\n Feature Score for a linear regression using correlation\n") print(per_feat_sorted) ##INDUS, RM, TAX, PTRATIO, LSAT print(np.linalg.norm(y_train)) # + [markdown] id="qQPtzOE5mjVn" colab_type="text" # ## Feature - Plot coeffients of the learnt linear regression model - Scoring coefficients - analysis # + id="6TjWPyHMmjVn" colab_type="code" outputId="b2bfea77-4c8d-4c5b-e9e1-b31268067d3f" colab={"base_uri": "https://localhost:8080/", "height": 535} model_sk = LinearRegression() model_sk.fit(X_train, y_train) feat_scores = pd.DataFrame() feat_scores["coefficient"] = model_sk.coef_ feat_scores["ABScoefficient"] = np.abs(model_sk.coef_) feat_scores["Attribute"] = X_train.columns feat_scores = feat_scores.sort_values(["ABScoefficient"], ascending=[False]) feat_scores plt.figure(figsize=(12, 8)) plt.bar(np.arange(model_sk.coef_.shape[0]) - 0.4, feat_scores["coefficient"] ) plt.xticks(np.arange(model_sk.coef_.shape[0]), feat_scores["Attribute"], rotation='vertical') plt.xlim([-1, model_sk.coef_.shape[0]]) plt.grid() plt.title("Sklearn model coefficients"); # + [markdown] id="Rl1KlyiomjVq" colab_type="text" # ## Feature importance using forest.feature_importances_ # + id="7-VhiUY6mjVq" colab_type="code" outputId="03635529-622b-422f-c86a-e6d604b0d8f6" colab={"base_uri": "https://localhost:8080/", "height": 1000} from sklearn.ensemble import RandomForestClassifier feat_labels = X_train.columns forest = RandomForestClassifier(n_estimators=500, random_state=1) forest.fit(X_train, y_train) importances = forest.feature_importances_ indices = np.argsort(importances)[::-1] for f in range(X_train.shape[1]): print("%2d) %-*s %f" % (f+1, 30, feat_labels[indices[f]], importances[indices[f]])) plt.figure(figsize=(12, 6), dpi=80) plt.title('Feature Importance') plt.bar(range(X_train.shape[1]), importances[indices], align='center') plt.xticks(range(X_train.shape[1]), feat_labels[indices], rotation=90) plt.xlim([-1, X_train.shape[1]]) plt.tight_layout() #plt.savefig('images/04_09.png', dpi=300) plt.show() # + id="CKAI7m4emjVt" colab_type="code" outputId="717dd5d9-bad3-4e45-9601-9fb83cde6eb1" colab={"base_uri": "https://localhost:8080/", "height": 34} from sklearn.feature_selection import SelectFromModel sfm = SelectFromModel(forest, threshold=0.1, prefit=True) X_selected = sfm.transform(X_train) print('Number of samples that meet this criterion:', X_selected.shape[0]) for f in range(X_selected.shape[1]): print("%2d) %-*s %f" % (f + 1, 30, feat_labels[indices[f]], importances[indices[f]])) # + [markdown] id="ZuqyzfBPmjVu" colab_type="text" # ## Feature Selection : Sequential feature selection algorithms: Sequential Backward Selection : SBS(knn, k_features=1) # + id="nZSVj5NJmjVu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 297} outputId="2d26f30b-38ae-4328-dc16-155700641520" from sklearn.base import clone from itertools import combinations import numpy as np from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.datasets import load_wine class SBS(): def __init__(self, estimator, k_features, scoring=accuracy_score, test_size=0.25, random_state=1): self.scoring = scoring self.estimator = clone(estimator) self.k_features = k_features self.test_size = test_size self.random_state = random_state def fit(self, X, y): X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=self.test_size, random_state=self.random_state) dim = X_train.shape[1] self.indices_ = tuple(range(dim)) self.subsets_ = [self.indices_] score = self._calc_score(X_train, y_train, X_test, y_test, self.indices_) self.scores_ = [score] while dim > self.k_features: scores = [] subsets = [] for p in combinations(self.indices_, r=dim - 1): score = self._calc_score(X_train, y_train, X_test, y_test, p) scores.append(score) subsets.append(p) best = np.argmax(scores) self.indices_ = subsets[best] self.subsets_.append(self.indices_) dim -= 1 self.scores_.append(scores[best]) self.k_score_ = self.scores_[-1] return self def transform(self, X): return X[:, self.indices_] def _calc_score(self, X_train, y_train, X_test, y_test, indices): self.estimator.fit(X_train[:, indices], y_train) y_pred = self.estimator.predict(X_test[:, indices]) score = self.scoring(y_test, y_pred) return score from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train_std = sc.fit_transform(X_train) X_test_std = sc.transform(X_test) import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5) # selecting features sbs = SBS(knn, k_features=1) sbs.fit(X_train_std, y_train) # plotting performance of feature subsets k_feat = [len(k) for k in sbs.subsets_] plt.plot(k_feat, sbs.scores_, marker='o') plt.ylim([0.7, 1.02]) plt.ylabel('Accuracy') plt.xlabel('Number of features') plt.grid() plt.tight_layout() # plt.savefig('images/04_08.png', dpi=300) plt.show() # + id="co6QKNK6mjVw" colab_type="code" colab={} import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier lr = LogisticRegression(C= 10, penalty= 'l2') # selecting features sbs = SBS(lr, k_features=1) sbs.fit(X_train_std, y_train) # plotting performance of feature subsets k_feat = [len(k) for k in sbs.subsets_] plt.plot(k_feat, sbs.scores_, marker='o') plt.ylim([0.4, 1.02]) plt.ylabel('Accuracy') plt.xlabel('Number of features') plt.grid() plt.tight_layout() # plt.savefig('images/04_08.png', dpi=300) plt.show() # + id="PN9-i6vrmjVx" colab_type="code" colab={} # + [markdown] id="sZxydVB8mjV0" colab_type="text" # # Pipelines # + [markdown] id="gVCn0riNmjV1" colab_type="text" # All of our data was numerical, so our use of a pipeline was straightforward # we used a MinMaxScaler to standardize the data, and used a classifier for the method. # We also used a parameter grid for the penalty and C values, and then put it into a grid. # We have run this dozens of times in order to evaluate our features, but in this first phase we have # not experimented with other types of methods -- we will explore those in future runs. # We will show a few illustrative runs below. # + [markdown] id="vT153gDcmjV1" colab_type="text" # ## Pipeline - grid search using logistic regression model # + id="j43AHtt6mjV2" colab_type="code" colab={} from sklearn import metrics from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, f1_score, accuracy_score, precision_score, confusion_matrix from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer pipe_model = Pipeline([('scaler', MinMaxScaler()), ('classifier', LogisticRegression())]) #Classifier Pipeline pipeline = Pipeline([ ('scaler', MinMaxScaler()), ('classifier', RandomForestClassifier()) ]) # Params for classifier params = {"classifier__max_depth": [2, None], "classifier__max_features": [5,10], # "classifier__min_samples_split": [1, 3, 10], # "classifier__min_samples_leaf": [0, 0.5], # "bootstrap": [True, False], "classifier__criterion": ["gini", "entropy"]} # Grid Search Execute rf_grid = GridSearchCV(estimator=pipeline , param_grid=params) #cv=10 rf_detector = rf_grid.fit(X_train, y_train) print(rf_grid.cv_results_) preds_train = rf_grid.best_estimator_.predict(X_train) preds_test= rf_grid.best_estimator_.predict(X_test) print("best params ",rf_grid.best_params_) print("best_estimator_ ",rf_grid.best_estimator_) # + id="ZY7SYs8lmjV5" colab_type="code" colab={} results = pd.DataFrame(columns=["Accuracy"]) #zero_coef = rf_grid.best_estimator_.named_steps['classifier'].coef_.size - np.count_nonzero(rf_grid.best_estimator_.named_steps['classifier'].coef_) results = results.append(pd.DataFrame( [[np.round(accuracy_score(y_train, preds_train), 3)],[np.round(accuracy_score(y_test, preds_test), 3)]], columns=["Accuracy"], index=["Sklearn-LR-L1-C1 Train-Mod", "Sklearn-LR-L1-C1 Test-Mod"])) results # + [markdown] id="Z8naL0VAmjV6" colab_type="text" # ## CHECKING USING ESTIMATOR - LogisticRegression(), RandomForestClassifier(), GaussianNB() # + id="gEkEYAi2mjV6" colab_type="code" colab={} from sklearn.model_selection import KFold cv = KFold(n_splits=10, shuffle=True, random_state=42) cv_idx = list(cv.split(X_train, y_train)) # + id="nNFFi3DCmjV7" colab_type="code" colab={} from sklearn.pipeline import Pipeline from sklearn.preprocessing import MinMaxScaler from sklearn.naive_bayes import GaussianNB from time import time acc = None cm = None estimator = [LogisticRegression(), RandomForestClassifier(), GaussianNB()] finalAccuracy = 0 for e in estimator: for train_idx, test_idx in cv_idx: # split #X_train, X_test = Results2017.values[train_idx], Results2017.values[test_idx] #y_train, y_test = y[train_idx], y[test_idx] # create logistic regression pipeline model = Pipeline([('scaler', MinMaxScaler()), ('classifier', e)]) t0 = time() model.fit(X_train, y_train) print("done in %0.3fs" % (time() - t0)) y_pred = model.predict(X_test) # evaluate tempAccuracy = np.round(accuracy_score(y_test, y_pred), 3) if tempAccuracy > finalAccuracy : finalAccuracy = tempAccuracy print("Train accuracy :", np.round(accuracy_score(y_train, preds_train), 3)) print("Test accuracy :", np.round(accuracy_score(y_test, y_pred), 3)) print ("finalAccuracy :: " , finalAccuracy) # + id="Eh72xkIrmjV9" colab_type="code" colab={} pd.set_option('display.max_colwidth', -1) runResults = pd.DataFrame(columns=['Model_Description', 'Bagging', 'accuracy_score']) runResults.loc[0] = ['LogisticRegression/RandomForestClassifier/GaussianNB', 'Estimator', finalAccuracy ] # + id="obiW12ZRmjV-" colab_type="code" colab={} runResults # + [markdown] id="Pkxr9ebumjWC" colab_type="text" # ## Bagging - Using DecisionTreeClassifier - Calculate Accuracy # + id="1rpnOQ_ImjWC" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score bag_clf = BaggingClassifier( DecisionTreeClassifier(random_state=42), n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print(accuracy_score(y_test, y_pred)) tree_clf = DecisionTreeClassifier(random_state=42) tree_clf.fit(X_train, y_train) y_pred_tree = tree_clf.predict(X_test) print(accuracy_score(y_test, y_pred_tree)) print("BaggingClassifier - DecisionTreeClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) runResults.loc[1] = ['DecisionTreeClassifier', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[2] = ['BaggingClassifier - DecisionTreeClassifier', 'Yes', accuracy_score(y_test, y_pred)] # + id="G7-j8FhZmjWD" colab_type="code" colab={} runResults # + [markdown] id="VVqDjNKXmjWE" colab_type="text" # ## Bagging - Using Logistic Regression - Calculate Accuracy. # + id="ZGjCr4e4mjWE" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score bag_clf = BaggingClassifier( LogisticRegression(random_state=42), n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print(accuracy_score(y_test, y_pred)) clf = LogisticRegression(random_state=42) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print(accuracy_score(y_test, y_pred_tree)) # + id="iOMM-EY-mjWG" colab_type="code" colab={} runResults.loc[3] = ['LogisticRegression', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[4] = ['BaggingClassifier - LogisticRegression', 'Yes', accuracy_score(y_test, y_pred) ] runResults # + [markdown] id="X9-WsNa1mjWH" colab_type="text" # ## Bagging using sklearn.neighbors.NearestNeighbors # + id="8b2ijALdmjWH" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score bag_clf = BaggingClassifier(KNeighborsClassifier(n_neighbors=5), n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - KNeighborsClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = KNeighborsClassifier(n_neighbors=5, n_jobs=-1) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("KNeighborsClassifier accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[5] = ['KNeighborsClassifier', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[6] = ['BaggingClassifier - KNeighborsClassifier', 'Yes', accuracy_score(y_test, y_pred) ] runResults # + [markdown] id="dAwpnxWrmjWJ" colab_type="text" # ## Bagging using from sklearn.ensemble import RandomForestClassifier # + id="7hQrLCASmjWJ" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', RandomForestClassifier()) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - RandomForestClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = RandomForestClassifier(n_jobs=-1) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("RandomForestClassifier accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[7] = ['RandomForestClassifier-StandardScaler', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[8] = ['BaggingClassifier - RandomForest-StandardScaler', 'Yes', accuracy_score(y_test, y_pred)] runResults # + [markdown] id="llpZtGF8mjWK" colab_type="text" # ## Bagging using from sklearn.ensemble import RandomForestClassifier - MinMaxScaler # + id="LiGrm2TsmjWK" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', MinMaxScaler()), ('classifier', RandomForestClassifier()) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - RandomForestClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = RandomForestClassifier(n_jobs=-1) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("RandomForestClassifier accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[9] = ['RandomForestClassifier-MinMaxScaler', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[10] = ['BaggingClassifier - RandomForest-MinMaxScaler', 'Yes', accuracy_score(y_test, y_pred) ] runResults # + [markdown] id="jeuj-_XUmjWO" colab_type="text" # ## Bagging using from sklearn.ensemble import SVM - StandardScaler # + id="bzFz9OyymjWP" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.svm import SVC from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', SVC()) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - SVC accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = SVC() clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("SVC accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[11] = ['SVC-StdScaler', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[12] = ['BaggingClassifier - SVC-StdMaxScaler', 'Yes', accuracy_score(y_test, y_pred)] runResults # + [markdown] id="le8RLztPmjWQ" colab_type="text" # ## Bagging using from sklearn.ensemble import SVM - MinMaxScaler # + id="DsZdSIDXmjWQ" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.svm import SVC from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', MinMaxScaler()), ('classifier', SVC()) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - SVC accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = SVC() clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("SVC accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[13] = ['SVC-MinMaxScaler', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[14] = ['BaggingClassifier - SVC-MinMaxScaler', 'Yes', accuracy_score(y_test, y_pred) ] runResults # + [markdown] id="hnXB8PPlmjWT" colab_type="text" # ## Bagging using from sklearn.ensemble import SGDClassifier # + [markdown] id="ez-WuxlbmjWU" colab_type="text" # ### SGDClassifier(loss="modified_huber", shuffle=True)) # + id="r95BA_cQmjWU" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', SGDClassifier(loss="modified_huber", shuffle=True)) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - SGDClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = SGDClassifier(loss="modified_huber", shuffle=True) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("SGDClassifier accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[15] = ['SGDClassifier-StandardScaler', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[16] = ['BaggingClassifier - SGDClassifier-StandardScaler', 'Yes', accuracy_score(y_test, y_pred) ] runResults # + [markdown] id="WBO30x1PmjWW" colab_type="text" # ### SGDClassifier(loss="log", shuffle=True) # + id="jSmgzAO9mjWW" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', SGDClassifier(loss="log", shuffle=True)) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - SGDClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = SGDClassifier(loss="log", shuffle=True) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("SGDClassifier accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[17] = ['SGDClassifier-StandardScaler-log', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[18] = ['BaggingClassifier - SGDClassifier-StandardScaler-log', 'Yes', accuracy_score(y_test, y_pred)] runResults # + [markdown] id="yaJ-xeJqmjWZ" colab_type="text" # ### SGDClassifier(loss="hinge", shuffle=True) # + id="hdGW_koTmjWZ" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', SGDClassifier(loss="hinge", shuffle=True)) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - SGDClassifier accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = SGDClassifier(loss="hinge", shuffle=True) clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("SGDClassifier accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[19] = ['SGDClassifier-StandardScaler-hinge', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[20] = ['BaggingClassifier - SGDClassifier-StandardScaler-hinge', 'Yes', accuracy_score(y_test, y_pred)] runResults # + [markdown] id="qtRF4LiWmjWc" colab_type="text" # ## Bagging using from GaussianNB # + id="wszS4aeXmjWc" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', GaussianNB()) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - GaussianNB accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = GaussianNB() clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("GaussianNB accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) runResults.loc[21] = ['GaussianNB-StandardScaler', 'No', accuracy_score(y_test, y_pred_tree)] runResults.loc[22] = ['BaggingClassifier - GaussianNB-StandardScaler', 'Yes', accuracy_score(y_test, y_pred) ] runResults # + [markdown] id="Mtqh8rZPmjWf" colab_type="text" # ## Bagging using from LogisticRegression # + id="yEPCX0QJmjWf" colab_type="code" colab={} from sklearn.ensemble import BaggingClassifier from sklearn.metrics import accuracy_score pipeline = Pipeline([ ('scaler', MinMaxScaler()), ('classifier', LogisticRegression()) ]) bag_clf = BaggingClassifier(pipeline, n_estimators=500, max_samples=100, bootstrap=True, n_jobs=-1) bag_clf.fit(X_train, y_train) y_pred = bag_clf.predict(X_test) print("BaggingClassifier - LogisticRegression accuracy_score :: " , accuracy_score(y_test, y_pred)) clf = LogisticRegression() clf.fit(X_train, y_train) y_pred_tree = clf.predict(X_test) print("LogisticRegression accuracy_score :: " , accuracy_score(y_test, y_pred_tree)) # + [markdown] id="z6_35B4rmjWg" colab_type="text" # ## SUMMARY: # + [markdown] id="w7I2lgOnmjWg" colab_type="text" # We tried following different models and calculated accuracy for each model using various parameters/pipeline process/Bagging approaches etc # # 1. SVC # 2. LogisticRegression # 3. SGDClassifier # 4. GaussianNB # 5. RandomForestClassifier # 6. KNeighborsClassifier # 7. DecisionTreeClassifier # + [markdown] id="srWAfbHHmjWg" colab_type="text" # The next section contains our best model # + [markdown] id="Nls6OdxfmjWh" colab_type="text" # # Best Model # + id="8sET5i_YmjWi" colab_type="code" colab={} #DecisionTreeClassifier pipe_model = Pipeline([('scaler', StandardScaler()), ('classifier', DecisionTreeClassifier())]) param_grid = {'classifier__max_depth': [2],#, 4, 6, 8, 10], 'classifier__max_features': [63] } gs = GridSearchCV(pipe_model, param_grid, cv=5, verbose=1) # + id="qFSMSBF5mjWk" colab_type="code" colab={} # fit and run predictions pipe_model.named_steps['classifier'] gs.fit(X_train, y_train) preds_train = gs.best_estimator_.predict(X_train) preds_test = gs.best_estimator_.predict(X_test) print("best params ",gs.best_params_) # + id="Wxor6UvrmjWl" colab_type="code" colab={} print("Train accuracy:", np.round(accuracy_score(y_train, preds_train), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test), 3)) cm_train = confusion_matrix(y_train, preds_train).astype(np.float32) cm_train /= cm_train.sum(axis=1)[:, np.newaxis] cm_test = confusion_matrix(y_test, preds_test).astype(np.float32) cm_test /= cm_test.sum(axis=1)[:, np.newaxis] print(confusion_matrix(y_train, preds_train).astype(np.float32)) print(confusion_matrix(y_test, preds_test).astype(np.float32)) #np.unique(preds_test, return_counts=True) np.unique(y_test, return_counts=True) # + id="1gWd2NiemjWm" colab_type="code" colab={} plt.figure(figsize=(20, 8)) plt.subplot(121) g = sns.heatmap(cm_train, vmin=0, vmax=1, annot=True, cmap="Reds") plt.xlabel("Predicted", fontsize=14) plt.ylabel("True", fontsize=14) #g.set(xticklabels=class_labels, yticklabels=class_labels) plt.title("Train", fontsize=14) plt.subplot(122) g = sns.heatmap(cm_test, vmin=0, vmax=1, annot=True, cmap="Reds") plt.xlabel("Predicted", fontsize=14) plt.ylabel("True", fontsize=14) #g.set(xticklabels=class_labels, yticklabels=class_labels) plt.title("Test", fontsize=14); # + [markdown] id="02jwHxw3mjWp" colab_type="text" # # Experimental Results Table # + id="sgLwpm3emjWp" colab_type="code" colab={} runResults.loc[23] = ['Grid Search DecisionTreeClassifier Estimator -StandardScaler', 'Yes', accuracy_score(y_test, preds_test) ] runResults # + [markdown] id="GddBpTBZmjWs" colab_type="text" # # Statistical Significance Test # + [markdown] id="K2we_KYXmjWt" colab_type="text" # We compared a vanilla Logistic Regression model with the best model from our Grid Search # + id="iFTqk7gTmjWu" colab_type="code" colab={} from sklearn.model_selection import cross_val_score def display_scores(scores): print("Scores:", scores) print("Mean:", scores.mean()) print("Standard deviation:", scores.std()) # A sampling based bakeoff using *K-fold cross-validation*: # it randomly splits the training set into K distinct subsets (k=30) # this bakeoff framework can be used for regression or classification #Control system is a linear regression based pipeline kFolds=30 #X_train_processed = MinMaxScaler(X_train) #X_train_processed = StandardScaler(X_train) X_train_processed = X_train log_reg = LogisticRegression() log_scores = cross_val_score(log_reg, X_train_processed, y_train, scoring="accuracy", cv=kFolds) #lin_reg = LinearRegression() #lin_scores = cross_val_score(lin_reg, X_train_processed, y_train, # scoring="accuracy", cv=kFolds) control = log_scores #control = lin_scores display_scores(control) #Treatment system is a replica of our grid search model #gs_model = DecisionTreeClassifier(max_depth = 2, max_features = 63) scores = cross_val_score(pipe_model, X_train_processed, y_train, scoring="accuracy", cv=kFolds) treatment = scores display_scores(treatment) #paired t-test; two-tailed p-value (aka two-sided) (t_score, p_value) = stats.ttest_rel(control, treatment) print("The p-value is %0.5f for a t-score of %0.5f." %(p_value, t_score)) #"The p-value is 0.00019 for a t-score of -4.28218." if p_value > 0.05/2: #Two sided print('There is no significant difference between the two machine learning pipelines (Accept H0)') else: print('The two machine learning pipelines are different (reject H0) \n(t_score, p_value) = (%.2f, %.5f)'%(t_score, p_value) ) if t_score < 0.0: print('Machine learning pipeline A is better than B') else: print('Machine learning pipeline B is better than A') # + id="yJlK2Au-Tp9f" colab_type="code" colab={} # do basic histograms plt.title('Train / test data') plt.hist(y_train, label='Train') plt.hist(y_test, label='Test') plt.legend(loc='best') plt.show() # + id="W5pHcV6VT06s" colab_type="code" colab={} # marker PCA, use whole X with diff color for train and test from sklearn.decomposition import PCA X1 = np.concatenate((X_train, X_test)) pca = PCA(n_components=2) p = pca.fit(X1).fit_transform(X1) Ntrain=X_train.shape[0] plt.title('PCA decomposition') plt.scatter(p[0:Ntrain,0], p[0:Ntrain,1], label='Train') plt.scatter(p[Ntrain:,0], p[Ntrain:,1], label='Test', color='orange') plt.legend(loc='best') plt.show() # + [markdown] id="LecykS6RmjWx" colab_type="text" # # Deep Learning Model # + [markdown] id="nzUfYv3mmjWx" colab_type="text" # # + id="g6bqSbWzmjWy" colab_type="code" colab={} import numpy import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline # + id="JRYlzyflmjW0" colab_type="code" colab={} X_train = X_train.loc[:,['NEUTRAL', 'HeFGP', 'HTOR', 'HORR', 'HFTR', 'HOffEf', 'HDefEf', 'AeFGP', 'ATOR', 'AORR', 'AFTR', 'AOffEf', 'ADefEf']] X_test = X_test.loc[:,['NEUTRAL', 'HeFGP', 'HTOR', 'HORR', 'HFTR', 'HOffEf', 'HDefEf', 'AeFGP', 'ATOR', 'AORR', 'AFTR', 'AOffEf', 'ADefEf']] # + id="1tDqxDyjmjW2" colab_type="code" colab={} X = [X_train, X_test] X = pd.concat(X) y = [y_train, y_test] y = pd.concat(y) # + [markdown] id="YNvLbH70mjW3" colab_type="text" # ## DL - BASE MODEL - Nueral Network - Mean Square Errror loss function # + id="t_GrGgs2mjW3" colab_type="code" colab={} from keras.models import Sequential from keras.layers import Dense, Activation # + id="siQicMNMmjW4" colab_type="code" colab={} def baseline_model(): # create model model = Sequential() model.add(Dense(13, input_dim=13, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal')) # Compile model model.compile(loss='mean_squared_error', optimizer='adam') return model # + id="cwgtZOkkmjW5" colab_type="code" colab={} model = baseline_model() model.fit(X_train, y_train, epochs=100, batch_size=100, verbose=0) # + id="jY7nW82ZmjW6" colab_type="code" colab={} preds_train = model.predict(X_train) preds_test = model.predict(X_test) # + id="6WFz9OaNmjW7" colab_type="code" colab={} print("Train accuracy:", np.round(accuracy_score(y_train, preds_train.round()), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test.round()), 3)) # + id="iSWcWQCzXq88" colab_type="code" colab={} runResults.loc[24] = ['DEEP LEARNING BASE model', 'No', accuracy_score(y_test, preds_test) ] # + [markdown] id="yl3nxKQybXBz" colab_type="text" # ## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy - adam optimizer - sigmoid WITHOUT STANDARD SCALAR # + id="cdR6pp2jmjW_" colab_type="code" colab={} ## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy - adam optimizer - sigmoid WITHOUT STANDARD SCALAR import numpy from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier # Function to create model, required for KerasClassifier def create_model(): # create model model = Sequential() model.add(Dense(13, input_dim=13, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # fix random seed for reproducibility # create model model = KerasClassifier(build_fn=create_model, verbose=0) model.fit(X_train,y_train, epochs=100, batch_size=80, validation_split = 0.2) preds_train = model.predict(X_train) preds_test = model.predict(X_test) print("Train accuracy:", np.round(accuracy_score(y_train, preds_train.round()), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test.round()), 3)) # + id="ZRooA0eMXx17" colab_type="code" colab={} runResults.loc[24] = ['DEEP LEARNING BASE model Without standardization', 'No', accuracy_score(y_test, preds_test) ] # + [markdown] id="fWoTVJIdmjXS" colab_type="text" # ## Re-Run The Baseline Model With Data Preparation - TUNING - StandardScaler # + id="CmKBN5wOmjW7" colab_type="code" colab={} ## DL - Base Model with fit, evaluate and plat matrix - binary_crossentropy - adam optimizer - sigmoid - Standard Scalar from keras.layers.advanced_activations import PReLU scale = StandardScaler(with_mean=0, with_std=1) new_X_train = scale.fit_transform(X_train) new_X_test = scale.transform(X_test) model = Sequential() model.add(Dense(13, input_dim=13, kernel_initializer="normal")) model.add(PReLU(alpha_initializer='zero', weights=None)) model.add(Dense(1, kernel_initializer='normal')) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(new_X_train, y_train, epochs=1000, batch_size=len(X_train), validation_split=0.15, verbose=0) scores = model.evaluate(new_X_test, y_test) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) preds_train1 = model.predict(new_X_train) preds_test1 = model.predict(new_X_test) print("Train accuracy:", np.round(accuracy_score(y_train, preds_train1.round()), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test1.round()), 3)) # + id="97ZAQVbwmjW9" colab_type="code" colab={} print(history.history.keys()) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # + [markdown] id="gEbGc43WmjXH" colab_type="text" # ## DL - Base model with binary binary_crossentropy - ESTIMATOR IMPLEMENTATION AND KFOLD # + id="FC0PwyBdmjXJ" colab_type="code" colab={} # define base model def baseline_model(): # create model model = Sequential() model.add(Dense(13, input_dim=13, kernel_initializer='normal', activation='relu')) model.add(Dense(1, kernel_initializer='normal')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam') return model from keras.wrappers.scikit_learn import KerasRegressor from sklearn.model_selection import cross_val_score, KFold # fix random seed for reproducibility seed = 7 np.random.seed(seed) # evaluate model with standardized dataset estimator = KerasRegressor(build_fn=baseline_model, epochs=100, batch_size=5, verbose=0) kfold = KFold(n_splits=10, random_state=seed) results = cross_val_score(estimator, X, y, cv=kfold) print("Results: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100)) param_grid = {'classifier__max_depth': [2, 4, 6, 8, 10], 'classifier__max_features': [13] #[5, 11, 17, 19] #[12,24,36,48,60]# #[9, 11, 12, 13] #[10, 20, 28, 33] } gs = GridSearchCV(estimator, param_grid, cv=5, verbose=1) pipe_model.named_steps['classifier'] gs.fit(X_train, y_train) preds_train = gs.best_estimator_.predict(X_train) preds_test = gs.best_estimator_.predict(X_test) print("best params ",gs.best_params_) # + id="WumgLmTud0fR" colab_type="code" colab={} runResults.loc[25] = ['DEEP LEARNING BASE model - ESTIMAROT AND KFOLD IMPL', 'No', accuracy_score(y_test, preds_test) ] # + [markdown] id="F4CPWmBxmjXb" colab_type="text" # ## Model with Grid Search - KerasClassifier - binary_crossentropy - adam - activation [sigmoid. relu] # + id="UHN8rs0vmjXb" colab_type="code" colab={} import numpy from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier # Function to create model, required for KerasClassifier def create_model(): # create model model = Sequential() model.add(Dense(13, input_dim=13, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model # fix random seed for reproducibility # create model model = KerasClassifier(build_fn=create_model, verbose=0) model.fit(X_train,y_train) # define the grid search parameters batch_size = [10, 20, 40, 60, 80, 100] epochs = [10, 50, 100] param_grid = dict(batch_size=batch_size, epochs=epochs) grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1) #grid_result = grid.fit(X, Y) grid_result = grid.fit(X_train,y_train) # summarize results print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param)) pred = grid.predict(X_test) preds_train = model.predict(X_train) preds_test = model.predict(X_test) print("Train accuracy:", np.round(accuracy_score(y_train, preds_train.round()), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test.round()), 3)) # + id="R6x_qLI6eaR_" colab_type="code" colab={} runResults.loc[26] = ['DEEP LEARNING BASE model - GRID SEARCH BEST PARAM IMPL', 'No', accuracy_score(y_test, preds_test) ] # + id="3bq_oIskP-TF" colab_type="code" colab={} # + [markdown] id="gcVVdDs5cGV1" colab_type="text" # ##Model KerasClassifier - binary_crossentropy - adam - activation [sigmoid. relu] - **Root mean square optimizer** # + id="R8Br2aEuaGVa" colab_type="code" colab={} import numpy from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier # Function to create model, required for KerasClassifier def create_model(): # create model model = Sequential() model.add(Dense(13, activation='relu', input_dim=13)) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy']) return model # fix random seed for reproducibility # create model model = KerasClassifier(build_fn=create_model, verbose=0) model.fit(X_train,y_train, epochs=100, batch_size=80, validation_split = 0.2) preds_train = model.predict(X_train) preds_test = model.predict(X_test) print("Train accuracy:", np.round(accuracy_score(y_train, preds_train.round()), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test.round()), 3)) # + id="AX0yDMbQe1gd" colab_type="code" colab={} runResults.loc[27] = ['DEEP LEARNING BASE model - ROOT MEAN SQUARE OPTIMIZER', 'No', accuracy_score(y_test, preds_test) ] # + [markdown] id="5dcowHLrcaBf" colab_type="text" # ##Model with Grid Search - KerasClassifier - binary_crossentropy - adam - activation [sigmoid. relu] - **Stochastic gradient descent (SGD)** # + id="dZeh5l5QbrOk" colab_type="code" colab={} import numpy from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier # Function to create model, required for KerasClassifier def create_model(): # create model model = Sequential() model.add(Dense(13, activation='relu', input_dim=13)) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='sgd',loss='binary_crossentropy',metrics=['accuracy']) return model # fix random seed for reproducibility # create model model = KerasClassifier(build_fn=create_model, verbose=0) model.fit(X_train,y_train, epochs=100, batch_size=80, validation_split = 0.2) preds_train = model.predict(X_train) preds_test = model.predict(X_test) print("Train accuracy:", np.round(accuracy_score(y_train, preds_train.round()), 3)) print("Test accuracy:", np.round(accuracy_score(y_test, preds_test.round()), 3)) # + id="gSlHKW7Oe_mS" colab_type="code" colab={} runResults.loc[28] = ['DEEP LEARNING BASE model - Stochastic gradient descent (SGD) OPTIMIZER', 'No', accuracy_score(y_test, preds_test) ] # + id="4hfTDOR8fF3C" colab_type="code" colab={} runResults # + [markdown] id="r-jVK2GlmjXe" colab_type="text" # # + [markdown] id="AqmGil2wmjXe" colab_type="text" # # Discussion/Analysis of Results # + [markdown] id="ccDxATUHmjXe" colab_type="text" # We used 31 features for both the home and away teams, plus an indicator for whether the game was played on a neutral court. That equals 63 features available for the model. We expiremented extensively with different combinations of numbers of features, (using all 63, using only raw data, using only features we created), different ways we aggregated the data, (actual game stats, averages, home and away averages, differences in stats between the 2 teams) and with different models, (logistic regression, decisiontreeClassifier, xgboost, etc.). In the end, or best model, which was statistically significant compared to a vanilla logistic regression model, was using the average from the first 80% games of all 63 features for the matchups for both the train and test datasets. It got us to 63.7% accuracy which was better than only picking based on the home team, but was a little short of our goal of 68%. # # We played around a little with deep learning models, but were unable to produce a significant result.
BDAA_FinalProject_ML_DL_NACC_V1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: python3-azureml # kernelspec: # display_name: Python 3.6 - AzureML # language: python # name: python3-azureml # --- # + [markdown] nteract={"transient": {"deleting": false}} # # btc-analysis-1 # # The following analysis shows BTC/USD follows a squareroot trend on logarithmic scale, particularly $e^{-3 + 4\sqrt{t}}$. # # ## interpretation # # As this day of 9/25/201, every BTC trader trusts halvenings to strongly predict price growth. # Halvenings are moments when new BTC generated supply halves. Halvenings occur every 4 years. # The data supports this pattern extremely strongly, as shown through the $4\sqrt{t}$ term. # Essentially, we see that demand is roughly constant as price is almost entirely determined by the BTC generation rate. # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1632603032357} import pandas as pd import matplotlib.pyplot as plt import numpy as np AZURE_ML_DATA_PATH = '/home/azureuser/cloudfiles/code/Users/wdurno/notebooks/btc-analysis-1/btc-usd.csv' ## load data df = pd.read_csv(AZURE_ML_DATA_PATH) n = df.shape[0] print('BTC/USD pairs were gathered manually') print(df) ## fit quadratic ones = np.ones(n) t = df['t'] t2 = np.square(df['t']) x = np.stack((ones, t, t2), axis=1) # design matrix y = np.log(df['btc-usd']) model = np.linalg.lstsq(x, y) ## predict quadratic tt = np.linspace(t[0], t[n-1], 1000) b = model[0] yy = (tt**0)*b[0] + tt*b[1] + (tt**2)*b[2] fig, ax = plt.subplots() plt.title('quadratic is a poor fit') ax.scatter(df['t'], np.log(df['btc-usd'])) # prices ax.plot(tt, yy) # quadratic plt.show() ## try log ones = np.ones(n) t = df['t'] t_log = np.log(df['t']) x = np.stack((ones, t_log), axis=1) # design matrix y = np.log(df['btc-usd']) model = np.linalg.lstsq(x, y) ## predict sqrt tt = np.linspace(t[0], t[n-1], 1000) b = model[0] yy = (tt**0)*b[0] + np.log(tt)*b[1] fig, ax = plt.subplots() plt.title('log is imperfect') ax.scatter(df['t'], np.log(df['btc-usd'])) # prices ax.plot(tt, yy) # log plt.show() ## try sqrt ones = np.ones(n) t = df['t'] t_sqrt = np.sqrt(df['t']) x = np.stack((ones, t_sqrt), axis=1) # design matrix y = np.log(df['btc-usd']) model = np.linalg.lstsq(x, y) ## predict sqrt tt = np.linspace(t[0], t[n-1], 1000) b = model[0] yy = (tt**0)*b[0] + (tt**0.5)*b[1] fig, ax = plt.subplots() plt.title('square root looks perfect') ax.scatter(df['t'], np.log(df['btc-usd'])) # prices ax.plot(tt, yy) # sqrt plt.show() print('weights: '+str(b)) ## define a predictive function def pred(t): return np.exp(-3. + 4.*np.sqrt(t)) print('predictions per year, at Jan, 2022 through 2030:') ttt = [t+.5 for t in range(11, 20)] print(pred(ttt)) ## plot predictions ttt = np.linspace(t[0], 19.5, 1000) yyy = pred(ttt) fig, ax = plt.subplots() plt.title('square plot with predictions') ax.scatter(df['t'], np.log(df['btc-usd'])) # prices ax.plot(ttt, np.log(yyy)) # sqrt plt.show()
btc-analysis-1/.ipynb_aml_checkpoints/btc-log-sqrt-checkpoint2021-8-25-21-2-6Z.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/julianovale/pythonparatodos/blob/main/M%C3%B3dulo07Aula14.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="-Db_QwI6Xt7T" def soma_prod(a,b): c = a+b d = a*b return(c,d) def verif_par(n): # verifica qual par de número cuja soma e produto retornam o mesmo resultado for i in range(1,n+1,1): for j in range(1,n+1,1): c,d = soma_prod(i,j) if (c == d): print('Passou: ({0:d}, {1:d})'.format(i,j)) print('Pois: ({0:d}+{1:d},{0:d}*{1:d})=({2:d},{3:d})'.format(i,j,c,d)) # + colab={"base_uri": "https://localhost:8080/"} id="OBTN11N8YGBM" outputId="7bee459d-ee05-493f-811e-266e340ba61b" j,i = soma_prod(3,4) print(j) print(i) # + colab={"base_uri": "https://localhost:8080/"} id="r5hqqxQnaOsA" outputId="ce3439d8-78d4-4119-a391-46735f1ed7c6" n = 9 verif_par(n)
Módulo07Aula14.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <p><font size="6"><b>04 - Pandas: Working with time series data</b></font></p> # # > *DS Data manipulation, analysis and visualization in Python* # > *May/June, 2021* # > # > *© 2021, <NAME> and <NAME> (<mailto:<EMAIL>>, <mailto:<EMAIL>>). Licensed under [CC BY 4.0 Creative Commons](http://creativecommons.org/licenses/by/4.0/)* # # --- # + import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') # - # # Introduction: `datetime` module # Standard Python contains the `datetime` module to handle date and time data: import datetime dt = datetime.datetime(year=2016, month=12, day=19, hour=13, minute=30) dt print(dt) # .day,... print(dt.strftime("%d %B %Y")) # # Dates and times in pandas # ## The ``Timestamp`` object # Pandas has its own date and time objects, which are compatible with the standard `datetime` objects, but provide some more functionality to work with. # # The `Timestamp` object can also be constructed from a string: ts = pd.Timestamp('2016-12-19') ts # Like with `datetime.datetime` objects, there are several useful attributes available on the `Timestamp`. For example, we can get the month (experiment with tab completion!): ts.month # There is also a `Timedelta` type, which can e.g. be used to add intervals of time: ts + pd.Timedelta('5 days') # ## Parsing datetime strings # ![](http://imgs.xkcd.com/comics/iso_8601.png) # Unfortunately, when working with real world data, you encounter many different `datetime` formats. Most of the time when you have to deal with them, they come in text format, e.g. from a `CSV` file. To work with those data in Pandas, we first have to *parse* the strings to actual `Timestamp` objects. # <div class="alert alert-info"> # <b>REMEMBER</b>: <br><br> # # To convert string formatted dates to Timestamp objects: use the `pandas.to_datetime` function # # </div> pd.to_datetime("2016-12-09") pd.to_datetime("09/12/2016") pd.to_datetime("09/12/2016", dayfirst=True) pd.to_datetime("09/12/2016", format="%d/%m/%Y") # A detailed overview of how to specify the `format` string, see the table in the python documentation: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior # ## `Timestamp` data in a Series or DataFrame column s = pd.Series(['2016-12-09 10:00:00', '2016-12-09 11:00:00', '2016-12-09 12:00:00']) s # The `to_datetime` function can also be used to convert a full series of strings: ts = pd.to_datetime(s) ts # Notice the data type of this series has changed: the `datetime64[ns]` dtype. This indicates that we have a series of actual datetime values. # The same attributes as on single `Timestamp`s are also available on a Series with datetime data, using the **`.dt`** accessor: ts.dt.hour ts.dt.dayofweek # To quickly construct some regular time series data, the [``pd.date_range``](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html) function comes in handy: pd.Series(pd.date_range(start="2016-01-01", periods=10, freq='3H')) # # Time series data: `Timestamp` in the index # ## River discharge example data # For the following demonstration of the time series functionality, we use a sample of discharge data of the Maarkebeek (Flanders) with 3 hour averaged values, derived from the [Waterinfo website](https://www.waterinfo.be/). data = pd.read_csv("data/vmm_flowdata.csv") data.head() # We already know how to parse a date column with Pandas: data['Time'] = pd.to_datetime(data['Time']) # With `set_index('datetime')`, we set the column with datetime values as the index, which can be done by both `Series` and `DataFrame`. data = data.set_index("Time") data # The steps above are provided as built-in functionality of `read_csv`: data = pd.read_csv("data/vmm_flowdata.csv", index_col=0, parse_dates=True) # <div class="alert alert-info"> # <b>REMEMBER</b>: <br><br> # # `pd.read_csv` provides a lot of built-in functionality to support this kind of transactions when reading in a file! Check the help of the read_csv function... # # </div> # ## The DatetimeIndex # When we ensure the DataFrame has a `DatetimeIndex`, time-series related functionality becomes available: data.index # Similar to a Series with datetime data, there are some attributes of the timestamp values available: data.index.day data.index.dayofyear data.index.year # The `plot` method will also adapt its labels (when you zoom in, you can see the different levels of detail of the datetime labels): # %matplotlib widget data.plot() # switching back to static inline plots (the default) # %matplotlib inline # We have too much data to sensibly plot on one figure. Let's see how we can easily select part of the data or aggregate the data to other time resolutions in the next sections. # ## Selecting data from a time series # We can use label based indexing on a timeseries as expected: data[pd.Timestamp("2012-01-01 09:00"):pd.Timestamp("2012-01-01 19:00")] # But, for convenience, indexing a time series also works with strings: data["2012-01-01 09:00":"2012-01-01 19:00"] # A nice feature is **"partial string" indexing**, where we can do implicit slicing by providing a partial datetime string. # # E.g. all data of 2013: data['2013':] # Or all data of January up to March 2012: data['2012-01':'2012-03'] # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>select all data starting from 2012</li> # </ul> # </div> # + clear_cell=true data['2012':] # - # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>select all data in January for all different years</li> # </ul> # </div> # + clear_cell=true data[data.index.month == 1] # - # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>select all data in April, May and June for all different years</li> # </ul> # </div> # + clear_cell=true data[data.index.month.isin([4, 5, 6])] # - # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>select all 'daytime' data (between 8h and 20h) for all days</li> # </ul> # </div> # + clear_cell=true data[(data.index.hour > 8) & (data.index.hour < 20)] # - # ## The power of pandas: `resample` # A very powerfull method is **`resample`: converting the frequency of the time series** (e.g. from hourly to daily data). # # The time series has a frequency of 1 hour. I want to change this to daily: data.resample('D').mean().head() # Other mathematical methods can also be specified: data.resample('D').max().head() # <div class="alert alert-info"> # <b>REMEMBER</b>: <br><br> # # The string to specify the new time frequency: http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases <br> # # These strings can also be combined with numbers, eg `'10D'`... # # </div> data.resample('M').mean().plot() # 10D # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>Plot the monthly standard deviation of the columns</li> # </ul> # </div> # + clear_cell=true data.resample('M').std().plot() # 'A' # - # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>Plot the monthly mean and median values for the years 2011-2012 for 'L06_347'<br><br></li> # </ul> # # __Note__ Did you know <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html"><code>agg</code></a> to derive multiple statistics at the same time? # # </div> # + clear_cell=true subset = data['2011':'2012']['L06_347'] subset.resample('M').agg(['mean', 'median']).plot() # - # <div class="alert alert-success"> # # <b>EXERCISE</b>: # # <ul> # <li>plot the monthly mininum and maximum daily average value of the 'LS06_348' column</li> # </ul> # </div> # + clear_cell=true daily = data['LS06_348'].resample('D').mean() # daily averages calculated # + clear_cell=true daily.resample('M').agg(['min', 'max']).plot() # monthly minimum and maximum values of these daily averages # - # <div class="alert alert-success"> # <b>EXERCISE</b>: # # <ul> # <li>Make a bar plot of the mean of the stations in year of 2013</li> # </ul> # # </div> # + clear_cell=true data['2013':'2013'].mean().plot(kind='barh')
_solved/pandas_04_time_series_data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/Amro-source/Google-Colab/blob/main/Feed_forward_Fault_detection3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="ZBP9taL7vT68" outputId="f7f0f473-ea69-42a7-e2df-d837e4608dbb" colab={"base_uri": "https://localhost:8080/", "height": 34} # Setup plotting import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') # Set Matplotlib defaults plt.rc('figure', autolayout=True) plt.rc('axes', labelweight='bold', labelsize='large', titleweight='bold', titlesize=18, titlepad=10) # Setup feedback system #from learntools.core import binder #binder.bind(globals()) #from learntools.deep_learning_intro.ex1 import * import pandas as pd Prony = pd.read_csv('sample_data/PoutProny.csv', header=None) Prony.head() Prony.shape # (rows, columns) # + id="c1CK4Rc3x0hh" # + id="E6IkcLqpypmz" class2=Prony[362:721] slice=Prony.iloc[:, 0:3] #print(slice) slice2=Prony.iloc[0:360,:] slice2.shape A=slice2.iloc[0:2,:] #print(A.shape) class0=Prony.iloc[0:360,:] class1=Prony.iloc[360:720,:] #class1.head #class1.shape class2=Prony.iloc[720:,:] fruits=11 my_labels = [0,1,2,3,4,5,6,7,8,9,10] trainY=[]; for x in range(1,11): print(x*360) idx=x*360 label=x #my_labels=[my_labels,x] print(label) tmpclass=Prony.iloc[idx:idx+360,:] print(tmpclass.shape) for q in my_labels: for y in range(360): print(q) trainY.append(q) # + id="GkjiVFR4Uc8a" outputId="5ac135ea-a55a-4e79-fcf7-71f120652775" colab={"base_uri": "https://localhost:8080/", "height": 51} #print(trainY) import numpy as np trainy=np.array(trainY) print(trainy.shape) print(trainy) # + id="gpXKBnAlRZyr" outputId="86a7c901-33ab-4b6e-9f76-e537b74e15bd" colab={"base_uri": "https://localhost:8080/", "height": 34} print(my_labels) # + id="2J7UvsJ_wOB7" outputId="dcf8e179-0c72-4f15-b383-ef7cef3328d5" colab={"base_uri": "https://localhost:8080/", "height": 204} Prony.head() # + id="wAq7Lg1ViHyO" outputId="654256af-b495-4c1b-b76e-d6a1602cda16" colab={"base_uri": "https://localhost:8080/", "height": 407} x=Prony.iloc[:,0] y=trainy plt.figure(dpi=100) plt.plot(y, x, 'k') #plt.xlim(-1, 1) #plt.ylim(-1, 1) plt.xlabel("Input: x") plt.ylabel("Target y") #w, b = model.weights # you could also use model.get_weights() here #plt.title("Weight: {:0.2f}\nBias: {:0.2f}".format(w[0][0], b[0])) plt.show() # + id="USpeVs6-Wo4B" outputId="b9caac02-7fe2-440f-c220-e86c0419e56a" colab={"base_uri": "https://localhost:8080/", "height": 272} #Dependencies import keras from keras.models import Sequential from keras.layers import Dense # Neural network model = Sequential() model.add(Dense(21, input_dim=4, activation='relu')) model.add(Dense(11, activation='relu')) #model.add(Dense(4, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) #number of epochs to train for nb_epoch = 120 #amount of data each iteration in an epoch sees batch_size = 128 X_train=Prony Y_train=trainy X_test=X_train Y_test=Y_train print("Let's figure out Data Shapes") print(X_train.shape) print(Y_train.shape) #model.fit(X_train, Y_train, batch_size=batch_size, epochs =nb_epoch, verbose=1, validation_data=(X_test, Y_test)) #score = model.evaluate(X_test, Y_test, verbose=0) #print('Test score:', score[0]) #print('Test accuracy:', score[1]) # + id="oR_61OSA_69X" from tensorflow import keras from tensorflow.keras import layers # YOUR CODE HERE #model = ____ from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential([ layers.Dense(units=1, input_shape=[4]) ]) # YOUR CODE HERE w, b = model.weights # + id="jwcwDCfdAqOV" outputId="d951ab69-08d7-49a3-a55a-1d18ec727939" colab={"base_uri": "https://localhost:8080/", "height": 68} print(A) # + id="f-ZiXJ4LBiac" outputId="9aa71403-7099-4ff2-f806-3bccb68f3f8d" colab={"base_uri": "https://localhost:8080/", "height": 102} B=slice2.iloc[359,:] print(B) # + id="MAomEIF3CDv-" outputId="2dc8e5bd-3e7d-4656-ad0e-be7fa8ca1b1b" colab={"base_uri": "https://localhost:8080/", "height": 34} print(slice2.shape) # + id="YqkYwCWIDde6" outputId="7800bde5-0176-44c1-9be1-f7a8d19d2fad" colab={"base_uri": "https://localhost:8080/", "height": 34} print(class1.shape) # + id="gegPErxDEPen" outputId="383c421c-2feb-4830-b836-f1b00ebaee80" colab={"base_uri": "https://localhost:8080/", "height": 102} QQQ=class1.iloc[0,:] print(QQQ) # + id="vZg-C0jYHm5e" outputId="f996130a-6bcd-4226-89e1-455749f8f744" colab={"base_uri": "https://localhost:8080/", "height": 102} QQQ1=class1.iloc[359,:] print(QQQ1)
Feed_forward_Fault_detection3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # + # Before run this codes, increase data rate by jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 import re import json import pandas as pd import matplotlib.pyplot as plt import numpy as np # %matplotlib notebook pd.options.display.max_rows = 150 pd.options.mode.chained_assignment = None # default='warn' #create the list of dictinary formatted strings by extracting data item #from twitter API scrape #files = ['twtgun3.24.1.txt', 'twtgun3.24.2.txt','twtgun3.24.3.txt', 'twtgun3.24.4.txt'] group = [] for i in range(1,11): with open('twtgun3.24.' + str(i) + '.txt') as fhand: for item in fhand: dic = {} x = re.findall("^{'created_at': \'(.*?)\'", item) if len(x) > 0: dic["created_at"] = str(x[0]) else: dic["created_at"] = None y = re.findall("{'full_text': \'(.*?)\'", item) if len(y) > 0: dic["full_text"] = str(y[0]) else: dic["full_text"] = None z = re.findall(" 'text': \'(.*?)\'", item) if len(z) > 0: dic["text"] = str(z[0]) else: dic["text"] = None a = re.findall("\'location\': \'(.*?)\'", item) if len(a) > 0: dic["location"] = str(a[0]) else: dic["location"] = None b = re.findall("\'time_zone\': \'(.*?)\'", item) if len(b) > 0: dic["time_zone"] = str(b[0]) else: dic["time_zone"] = None group.append(dic) fhand.close() #convert the list into json object with open('data.json', 'w') as fp: json.dump(group, fp) # convert json file into pandas DataFrame df = pd.read_json('data.json') # - df.sample(5) # To check the data #df.to_csv('df.csv') df2 = df.reindex(columns = ['created_at','location','time_zone','text','full_text']) pd.options.display.max_rows=10 df2['text'] = df2['text'].replace(r'\\n', '', regex=True).str.lower() df2['text'] = df2['text'].str.strip() df2['full_text'] = df2['full_text'].replace(r'\\n', '', regex=True).str.lower() df2['full_text'] = df2['full_text'].str.strip() print(df2.head()) # To check the data # + #df2['full_text'].str.findall('\\n') just to make sure no data will be found # - #make copy of df2 and name it df3 df3 = df2 #Take 'full_text' when available, otherwise take 'text' df3['tweet'] = df3['full_text'].where(pd.notna(df3['full_text']), other = df3['text']) pd.isna(df3['tweet']).sum() # Check how many 'tweet' observations are missing #drop columns 'text' & 'full_text' df3 = df3.drop(['text', 'full_text'], axis=1) #Extract hashtag from 'tweet' and create a new cloumn 'hashtag' df3['hashtag'] = df3['tweet'].str.findall(r'#.*?\s') # .findall returns list which causes issues later df3.reindex(columns = ['created_at','location','time_zone','tweet', 'hashtag']) #drop rows where all columns are NaN df3 = df3.dropna(how='all') print(df3.sample(5)) # Convert'created_at' time data rounding to nearest minute df3['created_at'] = df3['created_at'].apply(lambda x: x.round('min')) # Check how many tweets creatd every minute during the data collection period # At this point I just want to check the time trend of the tweets which can be done without time-zone conversion. df3.groupby('created_at').count()['tweet'] #UTC is 5 hours earlier than EST. So in the graph below, tweets were peaked around 15:30pm df3.groupby('created_at').count()['tweet'].plot() # + # As the next step, use regular expression to tokenize tweets emoticons_str = r""" (?: [:=;] # Eyes [oO\-]? # Nose (optional) [D\)\]\(\]/\\OpP] # Mouth )""" regex_str = [ emoticons_str, r'<[^>]+>', # HTML tags r'(?:@[\w_]+)', # @-mentions r"(?:\#+[\w_]+[\w\'_\-]*[\w_]+)", # hash-tags r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs r'(?:(?:\d+,?)+(?:\.?\d+)?)', # numbers r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and ' r'(?:[\w_]+)', # other words r'(?:\S)' # anything else ] # + tokens_re = re.compile(r'('+'|'.join(regex_str)+')', re.VERBOSE | re.IGNORECASE) emoticon_re = re.compile(r'^'+emoticons_str+'$', re.VERBOSE | re.IGNORECASE) def tokenize(s): return tokens_re.findall(s) def preprocess(s, lowercase=False): tokens = tokenize(s) if lowercase: tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens] return tokens # - # Test run using only one tweet tweet = df3['tweet'][10] print(preprocess(tweet)) #success! # Create a new dataframe by dropping rows with NA data df4 = df3.dropna(axis=0, inplace=False) df4.head() # Tokenize tweet data in the dataframe df4['preprocess_tweet'] = df4['tweet'].apply(lambda x : preprocess(x)) df4.head() # + #from nltk download premade stopwords list from nltk.corpus import stopwords import string punc = list(string.punctuation) stop = stopwords.words('english') + punc + ['rt', 'via', '’', 'amp'] # - #Test run using only one tweet terms_nostop = [term for term in preprocess(tweet) if term not in stop] #success! # + # There are 37487 rows in df4. for each item (list) in the 'preprocess_tweet' column, check if it's non-empty, then # remove stop words from the item and append it to the longer 'items' list. Since the data is large, # increase data rate by jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 items = [] for item in df4['preprocess_tweet']: if len(item) !=0: for i in item: if i not in stop and not i.startswith(('#', '@')): items.append(i.strip()) else: continue else: continue print(items[:10]) # + # Listing top 30 most common words in tweets during the data collection period import operator from collections import Counter count_all = Counter() count_all.update(items) print(count_all.most_common(30)) # + # Creating the list of hashtags tweeted during the data colletion period hashlist = [] for item in df4['hashtag']: if len(item) !=0: for i in item: if i.startswith('#'): hashlist.append(i.strip()) else: continue else: continue print(hashlist[:10]) # + #control_pattern = re.compile(r'#guncontrol[\.]|#guncont[r]?ol[\w!]+|#gunreform[.\w]*') control_pattern = re.compile(r'#guncont[r]?ol[\w!]+|#gunreform[.\w]*') clean_hashlist =[] for item in hashlist: i = control_pattern.sub(r'#guncontrol', item) clean_hashlist.append(i) march_pattern = re.compile(r'#march4ourlives|#marchforourlives!|#marchforourlives[\w.]+') clean_hashlist2 =[] for item in clean_hashlist: i = march_pattern.sub(r'#marchforourlives', item) clean_hashlist2.append(i) enough_pattern = re.compile(r'#enough[.\w]+') clean_hashlist3 =[] for item in clean_hashlist2: i = enough_pattern.sub(r'#enough', item) clean_hashlist3.append(i) # + # Listing top 30 most popular hash tags during the data collection period count_hash = Counter() count_hash.update(clean_hashlist3) print(count_hash.most_common(30)) # "#guncontrol', '#guncontrol.', and '#guncontrolnow' should be count toghether. So should '#marchforourlives' and '#march4ourlives' etc # + # to remove emojis from tokens, compile emoji patterns to be removed- Unicode some emoji code -shorter ones- cannot # be compiled. Why? emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F500" # symbols & pictographs u"\U0001F520-\U0001F52F" u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) u"\U0001F910-\U0001F96B" u"\U0001F52B" u"\U0001F5E3" # speech u"\U0001F5F3" # vote u"\U0001F91B-\U0001F939" u"\U0001F191-\U0001F19A" u"\U0001F595" "]+", flags = re.UNICODE) # + # Remove emojis from the list of tokenized words items_noemoji = [] for item in items: i = emoji_pattern.sub(r'', item) items_noemoji.append(i) print(items_noemoji[:10]) # + # Listing top 30 word-pairs tweeted together during the data collection periods from nltk import bigrams terms_bigram = list(bigrams(items_noemoji)) count_bigram = Counter() count_bigram.update(terms_bigram) print(count_bigram.most_common(30)) # + #Visualize top 30 popular hashtags import vincent vincent.core.initialize_notebook() hash_freq = count_hash.most_common(30) #create list of tuples labels, freq = zip(*hash_freq) #seperate the above into 1. tuple of labels & 2. tuple of counts data = {'data': freq, 'x': labels} #create dictionary of tuples bar = vincent.Bar(data, iter_idx='x') bar.display() # + # Create the list of time stamps when #hermosabeach was tweeted beach_hash_time =[] for i in range(len(df4['tweet'])): if '#hermosabeach' in df4['tweet'].iloc[i]: beach_hash_time.append(df4['created_at'].iloc[i]) print(beach_hash_time[:10]) # + # Creating datetimeindex for time series data for pandas. Twitter streaming data is based on UTC time. # From US & Canada ETS time, it's 4 hours earlier. Adjust for daytime savings. from pandas.tseries.offsets import Hour one_hour = Hour(1) idx = pd.DatetimeIndex(beach_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(beach_hash_time) #ones beach_hash = pd.Series(ones, index=idx_est_ds) per_minute = beach_hash.resample('1min').sum().fillna(0) # - #Visualize the frequency of #hermosabeach was tweeted during the data collection period time_chart = vincent.Line(per_minute) time_chart.axis_titles(x='Time', y='Hashtag frequencies') time_chart.display() # + # Prepar hashtag #marchforourlives for the same analysis march_hash_time =[] for i in range(len(df4['tweet'])): if '#marchforourlives' in df4['tweet'].iloc[i]: march_hash_time.append(df4['created_at'].iloc[i]) idx = pd.DatetimeIndex(march_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(march_hash_time) #ones march_hash = pd.Series(ones, index=idx_est_ds) march_per_minute = march_hash.resample('1min').sum().fillna(0) # + # Prepar hashtag #enough for the same analysis enough_hash_time =[] for i in range(len(df4['tweet'])): if '#enough' in df4['tweet'].iloc[i]: enough_hash_time.append(df4['created_at'].iloc[i]) idx = pd.DatetimeIndex(enough_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(enough_hash_time) #ones enough_hash = pd.Series(ones, index=idx_est_ds) enough_per_minute = enough_hash.resample('1min').sum().fillna(0) # + # Prepar hashtag #neveragain for the same analysis again_hash_time =[] for i in range(len(df4['tweet'])): if '#neveragain' in df4['tweet'].iloc[i]: again_hash_time.append(df4['created_at'].iloc[i]) idx = pd.DatetimeIndex(again_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(again_hash_time) #ones again_hash = pd.Series(ones, index=idx_est_ds) again_per_minute = again_hash.resample('1min').sum().fillna(0) # + # Prepar hashtag #guncontrol for the same analysis control_hash_time =[] for i in range(len(df4['tweet'])): if '#guncontrol' in df4['tweet'].iloc[i]: control_hash_time.append(df4['created_at'].iloc[i]) idx = pd.DatetimeIndex(control_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(control_hash_time) #ones control_hash = pd.Series(ones, index=idx_est_ds) control_per_minute = control_hash.resample('1min').sum().fillna(0) # + # Prepar hashtag #gunviolence for the same analysis violence_hash_time =[] for i in range(len(df4['tweet'])): if '#gunviolence' in df4['tweet'].iloc[i]: violence_hash_time.append(df4['created_at'].iloc[i]) idx = pd.DatetimeIndex(violence_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(violence_hash_time) violence_hash = pd.Series(ones, index=idx_est_ds) violence_per_minute = violence_hash.resample('1min').sum().fillna(0) # + # Prepar hashtag #schoolshooting for the same analysis school_hash_time =[] for i in range(len(df4['tweet'])): if '#schoolshooting' in df4['tweet'].iloc[i]: school_hash_time.append(df4['created_at'].iloc[i]) idx = pd.DatetimeIndex(school_hash_time) idx_local = idx.tz_localize(tz='UTC') idx_est = idx_local.tz_convert(tz='US/Eastern') idx_est_ds = idx_est - one_hour #daytime savings adjustment ones = [1]*len(school_hash_time) #ones school_hash = pd.Series(ones, index=idx_est_ds) school_per_minute = school_hash.resample('1min').sum().fillna(0) # - #Visualize the frequency of #shoolshooting was tweeted time_chart = vincent.Line(school_per_minute) time_chart.axis_titles(x='Time', y='Hashtag frequencies') time_chart.display() match_data = dict(Beach=per_minute, March=march_per_minute, Enough=enough_per_minute, Again=again_per_minute, Control=control_per_minute, Violence=violence_per_minute) all_matches = pd.DataFrame(data = match_data,index=march_per_minute.index) all_matches #Visualize and comparing the frequencies of the top 3 the most popular hashtags during the data collection time time_chart_top3 = vincent.Line(all_matches[['March', 'Enough', 'Control']]) time_chart_top3.axis_titles(x='Time', y='Freq') time_chart_top3.legend(title='Top 3 Most popular hashtags') time_chart_top3.display() #Visualize and comparing the frequencies of the next 3 of the most popular hashtags during the data collection time time_chart_next3 = vincent.Line(all_matches[['Violence', 'Again', 'Beach']]) time_chart_next3.axis_titles(x='Time', y='Freq') time_chart_next3.legend(title='Top 4 to 6 Most popular hashtags') time_chart_next3.display() # Analyze number of tweets by geographic locations. Within USA, broken down by states df5 = df4[(df4['time_zone']=='Pacific Time (US & Canada)')|(df4['time_zone']=='Eastern Time (US & Canada)')|(df4['time_zone']=='Central Time (US & Canada)')|(df4['time_zone']=='Mountain Time (US & Canada)')] # + df5['processed_location'] = df5['location'].apply(lambda x: emoji_pattern.sub(r'', x)) hashtag = re.compile(r'(?:\#+[\w_]+[\w\'_\-]*[\w_]+)') number = re.compile(r'(?:(?:\d+,?)+(?:\.?\d+)?)') df5['processed_location2'] = df5['processed_location'].apply(lambda x: hashtag.sub(r'', x)) df5['processed_location3'] = df5['processed_location2'].apply(lambda x: number.sub(r'', x)) df5 = df5.drop(['processed_location2', 'processed_location'], axis=1) # - def pattern(text): x = re.compile(r'[\w\s]+[\s]?[\w]+, ([A-Z][A-Z]+)') match = x.search(text) #return match object if match != None: return match.group(1) else: pass df5['clean_states'] = df5['processed_location3'].apply(lambda text: pattern(text)) def pattern2(text): x = re.compile(r'([\w\s]+[\s]?[\w]+), US[A]?|[\w]+,(Texas), EE.UU.|[\w\s]+[\w]+,(Florida)|(NH)\s USA|Cape\s Cod,(Ma)|Hastings,\s(NE)B|(NY),way|Athens,\s(Georgia)') match = x.search(text) if match != None: return match.group(1) else: pass df5['clean_states2'] = df5['processed_location3'].apply(lambda text : pattern2(text)) # + #df5['clean_states'].to_csv('name2.csv') #df5['clean_states2'].to_csv('name4.csv') # - d = {'Alabama':'AL', 'Alaska':'AK', 'Arizona':'AZ','Arkansas':'AR', 'California':'CA', 'Colorado':'CO', 'Connecticut':'CT', 'Delaware':'DE', 'Florida':'FL', 'Georgia':'GA', 'Hawaii':'HI', 'Idaho':'ID', 'Illinois':'IL', 'Indiana':'IN', 'Iowa':'IA', 'Kansas':'KS', 'Kentucky':'KY', 'Louisiana':'LA', 'Maine':'ME', 'Maryland':'MD', 'Massachusetts':'MA', 'Michigan':'MI', 'Minnesota':'MN', 'Mississippi':'MS', 'Missouri':'MO', 'Montana':'MT', 'Nebraska':'NE', 'Nevada':'NV', 'New Hampshire':'NH', 'New Jersey':'NJ', 'New Mexico':'NM', 'New York':'NY', 'North Carolina':'NC', 'North Dakota':'ND', 'Ohio':'OH', 'Oklahoma':'OK', 'Oregon':'OR', 'Pennsylvania':'PA', 'Rhode Island':'RI', 'South Carolina':'SC', 'Tennessee':'TN', 'Texas':'TX', 'Utah':'UT', 'Vermont':'VT', 'Virginia':'VA', 'Washington':'WA', 'West Virginia':'WV', 'Wisconsin':'WI', 'Wyoming':'WY', 'American Samoa':'AS', 'District of Columbia':'DC', 'Federated States of Micronesia':'FM', 'Guam':'GU', 'Marshall Islands':'MH', 'Northern Mariana Islands':'MP', 'Palau':'PW', 'Puerto Rico':'PR', 'Virgin Islands':'VI'} df5['clean_states2'] = df5['clean_states2'].str.strip() df5['clean_states2'] = df5['clean_states2'].replace(d) df5['clean_states2']=df5['clean_states2'].replace(to_replace=[r'[\w]+\sNew\sYork', r'DC\s[\w\s]+', r'[\w]+\sKentucky', r'[\w]+\sWisconsin', r'[\w]+\sTexas', r'[\w]+\sCalifornia', r'[\w]+\sFlorida',r'[\w]+\sSC',r'[\w]+\sMichigan',r'[\w]+\sIndiana',r'[\w\s]+\sNew\sJersey',r'[\w]+\sWashington\sState',r'Virginia\sand\sFlorida',r'[\w\s]*Jersey\sShore'], value=['NY','DC','KY','WI','TX','CA','FL','SC','MI','IN','NJ','WA','FL','NJ'], regex=True) df5['clean_states2']=df5['clean_states2'].replace(to_replace =['TEXAS','Northern Virginia','Nueva York','ARIZONA','Tenn','South Dakota'], value=['TX','VA','NY','AZ','TN','SD']) df5['clean_states2']=df5['clean_states2'].replace(to_replace =['Boston','Albuquerque','Dallas','Seattle','Philly','Brooklyn','Phoenix'], value=['MA','NM','TX','WA','PA','NY','AZ']) df5['clean_states2']=df5['clean_states2'].replace(to_replace =['West Coast','Southeast','New England','Midwest','Left Coast','Canada'], value=['','','','','','']) df5['states'] = np.where(df5['clean_states'] !="USA", df5['clean_states'], df5['clean_states2']) df5['states']=df5['states'].replace(to_replace =['CALIFORNIA','EE','GODS','NOT','NEB','OHIO','TEXAS'], value=['CA','TX','NH','NY','NE','OH','TX']) df5.to_csv('text.csv')
Data Analysis (Python)/Analysis - Data 3.24.2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## OTG Integration in OTP # # This notebook contains raw data summaries and field interpretations for genetic portal evidence in OTP. # # See [notes.md](notes.md) for more info on the history and methods behind this. # # # ### Summary # # Summary for new OTG evidence records as of v20.06: # # - There are now 393k evidence strings, which expands to about 640k associations # - This "expansion" results from associating the same variants to diseases that are ancestors in EFO of the original phenotype # - For reference, there are 185,865 variant-trait associations in GWAS catalog v1.0.2 # - Frequency of study source: # - GWAS Catalog: **264k (67%)** # - example: https://genetics.opentargets.org/study/GCST007068 # - Neale Lab v2 UKB: **123k (32%)** # - example: https://genetics.opentargets.org/study/NEALE2_30090_raw # - Lee Lab SAIGE UKB: **5.3k (1%)** # - example: https://genetics.opentargets.org/study/SAIGE_415 # - homepage: https://www.leelabsg.org/resources # - Variant type recorded as one of "SNP", "insertion", or "deletion" in `variant.type` # - `variant.rs_id` present in 99.3% of all 1.9M associations # - `evidence.gene2variant.resource_score` contains OTG L2G score # - `evidence.variant2disease.gwas_sample_size` has size from original study # - `evidence.variant2disease.reported_trait` has original trait name # - `evidence.variant2disease.resource_score` contains p-value from GWAS # - `evidence.gene2variant.consequence_code` has VEP consequences with these frequencies: # # | | consequence_code | count | # |---:|:-----------------------------------|--------:| # | 0 | intergenic_variant | 290094 | # | 1 | intron_variant | 67178 | # | 2 | upstream_gene_variant | 11168 | # | 3 | downstream_gene_variant | 10411 | # | 4 | missense_variant | 8036 | # | 5 | 3_prime_UTR_variant | 3699 | # | 6 | synonymous_variant | 1202 | # | 7 | 5_prime_UTR_variant | 877 | # | 8 | splice_region_variant | 338 | # | 9 | non_coding_transcript_exon_variant | 82 | # | 10 | stop_gained | 50 | # | 11 | splice_donor_variant | 23 | # | 12 | inframe_deletion | 22 | # | 13 | frameshift_variant | 21 | # | 14 | inframe_insertion | 20 | # | 15 | splice_acceptor_variant | 5 | # | 16 | start_lost | 4 | # | 17 | coding_sequence_variant | 2 | from dotenv import load_dotenv; load_dotenv() from data_source import catalog from pyspark.sql.session import SparkSession from pyspark.sql import functions as F spark = SparkSession.builder.getOrCreate() cat = catalog.load() # ### GWAS Catalog vs L2G Associations # # The L2G score was first incorporated into OTP in 20.02. This comparison is for L2G in 20.04/20.06 to 19.11, the last release with only lead variants from GWAS Catalog / UKB. # #### Differences # # - `rs_id` now included in variant object # - `resource_score` was added to `evidence.gene2variant` whereas it was only applicable to `evidence.variant2disease` before (not both have it) # - There were 194k variant, target, disease combinations before and now there are: # - 1.931M in 20.04 # - 393k in 20.06 (see https://blog.opentargets.org/2020/06/17/open-targets-platform-20-06-has-been-released/) # - A .05 threshold was added to l2g score to remove so many unimportant associations path = cat.download('otpev', 'l2g', version='v20.06', overwrite=True); print(path) df = spark.read.parquet(path) schema_new = df._jdf.schema().treeString() df.count() path = cat.download('otpev', 'gwas', version='v19.11'); print(path) dfo = spark.read.parquet(path) schema_old = dfo._jdf.schema().treeString() dfo.count() # #### Schemas print(schema_new) print(schema_old) # Schema diff with open('/tmp/schema_new.txt', 'w') as f: f.write(schema_new) with open('/tmp/schema_old.txt', 'w') as f: f.write(schema_old) # !diff /tmp/schema_new.txt /tmp/schema_old.txt # ### Field Stats df.groupBy(F.col('variant.rs_id').isNull()).count().show() df.groupBy('evidence.gene2variant.is_associated', 'evidence.variant2disease.is_associated').count().show() df.select(F.explode('evidence.gene2variant.evidence_codes')).groupBy('col').count().show(truncate=50) df.select(F.explode('evidence.variant2disease.evidence_codes')).groupBy('col').count().show(truncate=50) df.groupBy('evidence.gene2variant.resource_score.method.description').count().show(truncate=50) df.groupBy('evidence.variant2disease.resource_score.method.description').count().show(truncate=50) df.groupBy(F.col('evidence.variant2disease.resource_score.value').isNull()).count().show(truncate=50) df.agg( F.min(F.col('evidence.variant2disease.resource_score.value')), F.max(F.col('evidence.variant2disease.resource_score.value')) ).show() df.groupBy('evidence.variant2disease.resource_score.type').count().show(truncate=50) df.groupBy('evidence.variant2disease.provenance_type.expert.statement').count().show(truncate=50) df.groupBy('evidence.variant2disease.provenance_type.expert.status').count().show(truncate=50) df.groupBy('evidence.variant2disease.reported_trait').count().show(5, truncate=50) df.groupBy('type').count().show() df.groupBy('variant.type').count().show() df.groupBy('variant.source_link').count().show(3, truncate=100) df.groupBy('target.target_type').count().show(3, truncate=100) df.groupBy('target.activity').count().show(3, truncate=100) df.groupBy('sourceID').count().show(3, truncate=100) # #### Variant Consequence df.groupBy('evidence.gene2variant.functional_consequence').count().sort(F.col('count').desc()).show(3, truncate=False) print(df.groupBy('evidence.gene2variant.consequence_code').count().sort(F.col('count').desc()).toPandas().to_markdown()) # #### Studies df.groupBy('unique_association_fields.study').count().sort(F.col('count').desc()).show(25, truncate=100) ( df .select(F.element_at(F.split(F.col('unique_association_fields.study'), '/'), -1).alias('study')) .withColumn('prefix', F.col('study').substr(1, 5)) .groupBy('prefix').count().show() ) ( df.filter(F.col('unique_association_fields.study').contains('SAIGE')) .select('unique_association_fields.study') .show(5, truncate=False) ) ( df .filter(F.col('unique_association_fields.study').contains('NEALE')) .select(F.element_at(F.split(F.col('unique_association_fields.study'), '/'), -1).alias('study')) .withColumn('prefix', F.element_at(F.split(F.col('study'), '_'), 1)) .groupBy('prefix').count().show() )
import/otpev/analysis/otg/summary.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Python for Bioinformatics # ----------------------------- # # ![title](https://s3.amazonaws.com/py4bio/tapabiosmall.png) # # This Jupyter notebook is intented to be used alongside the book [Python for Bioinformatics](http://py3.us/) # # # Chapter 4: Programming: Flow Control # ============== # **Listing 4.1:** ifelse1.py: Basic if-else sample height = float(input('What is height? (in meters): ')) if height > 1.40: print('You can get in') else: print('This ride is not for you') # **Listing 4.2:** ifelse2.py: if-else in action three_letter_code = {'A':'Ala','N':'Asn','D':'Asp','C':'Cys'} aa = input('Enter one letter: ') if aa in three_letter_code: print('The three letter code for {0} is {1}'.format(aa, three_letter_code[aa])) else: print("Sorry, I don't have it in my dictionary") # **Listing 4.3:** elif1.py: Using elif dna = input('Enter your primer sequence: ') seqsize = len(dna) if seqsize < 10: print('The primer must have at least ten nucleotides') elif seqsize < 25: print('This size is OK') else: print('The primer is too long') bool(1=='1') # **Listing 4.4:** nested.py: Nested if dna = raw_input('Enter your DNA sequence: ') seqsize = len(dna) if seqsize < 10: print('Your primer must have at least ten nucleotides') if seqsize == 0: print('You must enter something!') elif seqsize < 25: print('This size is OK') else: print('Your primer is too long') answer=42 answer answer==3 answer==42 # **Listing 4.5:** elif2.py: Nested if dna = raw_input('Enter your DNA sequence: ') seqsize = len(dna) if seqsize == 0: print('You must enter something!') elif 0 < seqsize < 10: print('Your primer must have at least ten nucleotides') elif seqsize < 25: print('This size is OK') else: print('Your primer is too long') # **Listing 4.6:** multiplepart.py: Multiple part condition x = 'N/A' if x != 'N/A' and 5 < float(x) < 20: print('OK') else: print('Not OK') # **Listing 4.7:** multiplepart2.py: Multiple part condition, inverted x = 'N/A' if 5 < float(x) < 20 and x != 'N/A': print('OK') else: print('Not OK') total = 5 items = 2 print("Average = {0}".format(total/items if items != 0 else "N/A")) total = 5 items = 2 if items != 0: print("Average = {0}".format(total/items)) else: print("Average = N/A") bases = ["C", "T", "G", "A"] for x in bases: print(x) bases = ["C", "T", "G", "A"] for n, x in enumerate(bases): print(n, x) for x in range(4): print(x) for n in [0, 1, 2, 3, 4]: print(n) # **Listing 4.8:** protwfor.py: Using for to figure the weight of a protein prot_seq = input("Enter your protein sequence: ") prot_weight = {"A":89, "V":117, "L":131, "I":131, "P":115, "F":165, "W":204, "M":149, "G":75, "S":105, "C":121, "T":119, "Y":181, "N":132, "Q":146, "D":133, "E":147, "K":146, "R":174, "H":155} total_weight = 0 for aa in prot_seq: total_weight = total_weight + prot_weight.get(aa.upper(), 0) total_weight = total_weight - (18 * (len(prot_seq) - 1)) print("The net weight is: {0}".format(total_weight)) a = 10 while a < 40: print(a) a += 10 a = 10 while True: if a < 40: print(a) else: break a += 10 # **Listing 4.9:** seachinlist.py: Searching a value in a list of tuples color_code = [('red', 1), ('green', 2), ('blue', 3), ('black', 4)] name = 'blue' for color_pair in color_code: if name == color_pair[0]: code = color_pair[1] print(code) # **Listing 4.10:** seachinlist2.py: Searching a value in a list of tuples color_code = [('red',1), ('green',2), ('blue',3), ('black',4)] name = 'blue' for color_pair in color_code: if name == color_pair[0]: code = color_pair[1] break print(code) # **Listing 4.11:** seachinlist3.py: Searching a value in a list of tuples color_code = [('red',1), ('green',2), ('blue',3), ('black',4)] name = 'blue' i = 0 while name != color_code[i][0]: i += 1 code = color_code[i][1] print(code) # **Listing 4.12:** seachindict.py: Searching a value in a list of tuples using a dictionary color_code = [('red',1), ('green',2), ('blue',3), ('black',4)] name = 'blue' color_code_d = dict(color_code) print(color_code_d[name]) # **Listing 4.13:** protnetcharge.py: Net charge of a protein prot_seq = input("Enter protein sequence: ").upper() charge = -0.002 aa_charge = {"C":-.045,"D":-.999,"E":-.998,"H":.091, "K":1,"R":1,"Y":-.001} for aa in prot_seq: if aa in aa_charge: charge += aa_charge[aa] print(charge) # **Listing 4.14:** protnetcharge2.py: Net charge of a protein using get prot_seq = input('Enter protein sequence: ').upper() charge = -0.002 aa_charge = {'C':-.045,'D':-.999,'E':-.998,'H':.091, 'K':1,'R':1,'Y':-.001} for aa in prot_seq: charge += aa_charge.get(aa, 0) print(charge) # **Listing 4.15:** lowdeg.py: Search for a low degeneration zone prot_seq = input('Protein sequence: ').upper() prot_deg = {'A':4, 'C':2, 'D':2, 'E':2, 'F':2, 'G':4, 'H':2, 'I':3, 'K':2, 'L':6, 'M':1, 'N':2, 'P':4, 'Q':2, 'R':6, 'S':6, 'T':4, 'V':4, 'W':1, 'Y':2} segs_values = [] for aa in range(len(prot_seq)): segment = prot_seq[aa:aa + 15] degen = 0 if len(segment)==15: for x in segment: degen += prot_deg.get(x, 3.05) segs_values.append(degen) min_value = min(segs_values) minpos = segs_values.index(min_value) print(prot_seq[minpos:minpos + 15]) # **Listing 4.16:** lowdeg2.py: Searching for a low-degeneration zone; version with # while prot_seq = input('Protein sequence: ').upper() prot_deg = {'A':4, 'C':2, 'D':2, 'E':2, 'F':2, 'G':4, 'H':2, 'I':3, 'K':2, 'L':6, 'M':1, 'N':2, 'P':4, 'Q':2, 'R':6, 'S':6, 'T':4, 'V':4, 'W':1, 'Y':2} segs_values = [] segs_seqs = [] segment = prot_seq[:15] a = 0 while len(segment)==15: degen = 0 for x in segment: degen += prot_deg.get(x, 3.05) segs_values.append(degen) segs_seqs.append(segment) a += 1 segment = prot_seq[a:a+15] print(segs_seqs[segs_values.index(min(segs_values))]) # **Listing 4.17:** lowdeg3.py: Searching for a low-degeneration zone without sub-chains prot_seq = input('Protein sequence: ').upper() prot_deg = {'A':4, 'C':2, 'D':2, 'E':2, 'F':2, 'G':4, 'H':2, 'I':3, 'K':2, 'L':6, 'M':1, 'N':2, 'P':4, 'Q':2, 'R':6, 'S':6, 'T':4, 'V':4, 'W':1, 'Y':2} degen_tmp = max(prot_deg.values()) * 15 for n in range(len(prot_seq) - 15): degen = 0 for x in prot_seq[n:n + 15]: degen += prot_deg.get(x, 3.05) if degen <= degen_tmp: degen_tmp = degen seq = prot_seq[n:n + 15] print(seq)
notebooks/Chapter 4 - Programming - Flow Control.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import csv import errno import itertools import os import time from bs4 import BeautifulSoup import click #import dataset #import funcy as fy import requests #from pyquery import PyQuery import time import traceback import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_style("whitegrid") # %matplotlib inline from datetime import datetime import time # - state_id = 0 gender = 0 number_of_results = 40000 headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.8', 'Cache-Control': 'max-age=0', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'http://registration.baa.org', 'Referer': 'http://registration.baa.org/2009/cf/Public/iframe_ResultsSearch.cfm?mode=results', } params = { 'mode': 'results', 'criteria': '', 'StoredProcParamsOn': 'yes', 'VarGenderID': gender, 'VarBibNumber': '', 'VarLastName': '', 'VarFirstName': '', 'VarStateID': state_id, 'VarCountryOfResID': 0, 'VarCountryOfCtzID': 0, 'VarReportingSegID': 1, 'VarAwardsDivID': 0, 'VarQualClassID': 0, 'VarCity': '', 'VarTargetCount': number_of_results, 'records': 25, 'headerexists': 'Yes', 'bordersize': 0, 'bordercolor': '#ffffff', 'rowcolorone': '#FFCC33', 'rowcolortwo': '#FFCC33', 'headercolor': '#ffffff', 'headerfontface': 'Verdana,Arial,Helvetica,sans-serif', 'headerfontcolor': '#004080', 'headerfontsize': '12px', 'fontface': 'Verdana,Arial,Helvetica,sans-serif', 'fontcolor': '#000099', 'fontsize': '10px', 'linkfield': 'FormattedSortName', 'linkurl': 'OpenDetailsWindow', 'linkparams': 'RaceAppID', 'queryname': 'SearchResults', 'tablefields': 'FullBibNumber,FormattedSortName,AgeOnRaceDay,GenderCode,' 'City,StateAbbrev,CountryOfResAbbrev,CountryOfCtzAbbrev,' 'DisabilityGroup', } results = [] for page_number, start in enumerate(itertools.count(1, 25)): # Don't hammer the server. Give it a sec between requests. time.sleep(1.0) click.echo('page %d of %d' % (page_number + 1, number_of_results/25)) response = requests.post( 'http://registration.baa.org/2009/cf/Public/iframe_ResultsSearch.cfm', headers=headers, params=params, data={'start': start, 'next': 'Next 25 Records'}, ) #peopleList = extract_data(response.content) soup = BeautifulSoup(response.text, 'lxml') table = soup.find("table", attrs={"class": "tablegrid_table"}) rows = table.findAll("tr") for row in rows: a = [t.text.strip() for t in row.findAll("td")][0:] #Don't store lines without data if len(a) > 0 and a != [''] and a !=['',''] and a != ['', '', '']: results.append(a) # Only yield if there actually are results. Just found this random # tr_header thing in the HTML of the pages that have results, but not # empty results pages. if 'tr_header' in response.text: (page_number, response.text) else: assert 'Next 25 Records' not in response.text click.echo(' No results found.') break # No more pages! if 'Next 25 Records' not in response.text: break data = [] for i, result in enumerate(results): if i%4 == 0: data.append(results[i] + results[i+1][1:]) filename = 'ws_boston_marathon_results_2009.csv' df = pd.DataFrame(data) df.columns = ['Bib', 'Name', 'Age', 'M/F', 'City', 'State', 'Country', 'Citizen', '', '5K', '10K', '15K', '20K', 'Half', '25K', '30K', '35K', '40K', 'Pace', 'Proj_Time', 'Official_Time', 'Overall', 'Gender', 'Division'] df.head() df.to_csv(filename, index=False)
notebooks/ws_boston_marathon_results_2009.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np df = pd.read_csv('event_type_entity_extract_train.csv', header=None) df.columns = ['index', 'content', 'label', 'entity'] df # + unique_labels = df['label'].unique() temp = {} for i in range(len(unique_labels)): temp[unique_labels[i]] = i np.save('label2index.npy', temp) with open('class.txt', 'w') as f: for i in range(len(unique_labels)): f.write(str(i)+"\n") # - data = df[['content', 'label']] # data.head data['label'] = data['label'].replace(temp) length = int(data.shape[0] * 0.8) data[:length].to_csv('train.txt', sep='\t', index=False, header=False) data[length:].to_csv('test.txt', sep='\t', index=False, header=False) data[length:].to_csv('eval.txt', sep='\t', index=False, header=False)
main/ccks/data/ccks2019_event_entity_extract/Process.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (bayes) # language: python # name: bayes # --- # # Comparison of arrival direction and joint models # # In order to verify the model is working, we fit simulations made under the assumptions of the model. We also compare the differences between a model for only the UHECR arrival directions and one for both the UHECR arrival directions and energies. # <br> # <br> # *This code is used to produce the data shown in Figures 6, 7 and 8 (left panel) in Capel & Mortlock (2019).* # *See the separate notebook in this directory for the actual plotting of figures.* # + import numpy as np import h5py from matplotlib import pyplot as plt from pandas import DataFrame from fancy import Data, Model, Analysis # + # Define location of Stan files stan_path = '../../stan/' # Define file containing source catalogue information source_file = '../../data/sourcedata.h5' table_file = '../../data/integration_tables_50_SBG23.h5' # Define output files sim_output_file = 'output/joint_model_simulation.h5' arrival_output_file = 'output/arrival_direction_fit.h5' joint_output_file = 'output/joint_fit.h5' # Define random seed to match paper results random_seed = 1992071502 # - # ## Simulation # # Set up a simulation using randomly selected sources and the Pierre Auger Observatory as a detector. This simulation will include all the processes described in Section 2 of the paper. # + from fancy.detector.auger2014 import detector_properties, alpha_T, M # Define a source catalogue and detector exposure # In the paper we use the SBG catalogue data = Data() data.add_source(source_file, 'SBG_23') data.add_detector(detector_properties) # Plot the sources in Galactic coordinates data.show(); # + # Define a Stan simulation to run sim_name = stan_path + 'joint_model_sim.stan' # simulate all processes # Define simulation using Model object and compile Stan code if necessary simulation = Model(sim_filename = sim_name, include_paths = stan_path) simulation.compile() # + from fancy.interfaces.stan import get_simulation_input # Define associated fraction f = 0.5 # Simulation input B = 20 # nG alpha = 3.0 Eth = 52 # EeV Eth_sim = 20 # EeV Nsim = 2500 # L in yr^-1, F in km^-2 yr^-1 L, F0 = get_simulation_input(Nsim, f, data.source.distance, M, alpha_T) # To scale between definition of flux in simulations and fits flux_scale = (Eth / Eth_sim)**(1 - alpha) simulation.input(B = B, L = L, F0 = F0, alpha = alpha, Eth = Eth) # + # What is happening summary = b'Simulation using the joint model and SBG catalogue' # must be a byte str # Define an Analysis object to bring together Data and Model objects sim_analysis = Analysis(data, simulation, analysis_type = 'joint', filename = sim_output_file, summary = summary) # - # Build pre-computed values for the simulation as you go # So that you can try out different parameters sim_analysis.build_tables(sim_only = True) # + # Run simulation sim_analysis.simulate(seed = random_seed, Eth_sim = Eth_sim) # Save to file sim_analysis.save() # - # ### Visualise simulation results # Some simple functions are built in to allow quick visualisation of the simulation results. The arrival directions of the UHECRs are shown colour coded by the source component they come from, including the background component. The energy spectrum of the UHECRs is also shown, including the difference between $\tilde{E}$, $E$ and $\hat{E}$. sim_analysis.plot('arrival direction') sim_analysis.plot('energy') # ## Fit the arrival direction model # Define data from simulation data = Data() data.from_file(sim_output_file) data.show(); # + # Arrival direction model model_name = stan_path + 'arrival_direction_model.stan' # Compile model = Model(model_filename = model_name, include_paths = stan_path) model.compile() # Define threshold energy in EeV model.input(Eth = 52) # + # What is happening summary = b'Fit of the arrival direction model to the joint simulation' # Define an Analysis object to bring together Data and Model objects analysis = Analysis(data, model, analysis_type = 'joint', filename = arrival_output_file, summary = summary) # - # Define location of pre-computed values used in fits # (see relevant notebook for how to make these files) # Each catalogue has a file of pre-computed values analysis.use_tables(table_file) # + # Fit the Stan model fit = analysis.fit_model(chains = 4, iterations = 2000, seed = random_seed) # Save to analysis file analysis.save() # - # ## Fit the joint model # # This proceeds exactly as above, just changing the Stan model and output filename. # + data = Data() data.from_file(sim_output_file) model_name = stan_path + 'joint_model.stan' model = Model(model_filename = model_name, include_paths = stan_path) model.compile() model.input(Eth = 52) summary = b'Fit of the joint model to the joint simulation' analysis = Analysis(data, model, analysis_type = 'joint', filename = joint_output_file, summary = summary) analysis.use_tables(table_file) # - fit = analysis.fit_model(chains = 4, iterations = 2000, seed = random_seed) analysis.save() # NB: can ignore warnings for lambda, this is just a generated quantity and not a sampled parameter.
3_fits_to_simulations/arrival_vs_joint/arrival_vs_joint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Machine Learning # - looking for a function from data # ![Screen%20Shot%202019-09-22%20at%208.27.52%20PM.png](attachment:Screen%20Shot%202019-09-22%20at%208.27.52%20PM.png) # # Three steps of machine learning # 1. Define model, a set of functions. # 2. Define goodness of functions # 3. Find the best of function. # # Relation Between Terminology # ![Screen%20Shot%202019-09-22%20at%208.12.38%20PM.png](attachment:Screen%20Shot%202019-09-22%20at%208.12.38%20PM.png)
Machine Learning Introduction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Introduction # This notebook contains a working example to show usage of the API for visual saliency map generation for image blackbox classifiers. # # This example will follow an application-like use-case where we define a functionally rigid process that transforms an input image into a number of saliency heat-maps based on our black-box classifier's output, visualizing the heat-maps over the input image. # We will show that it is easy to change which of our API implementations are used in the application without impacting the application's successful execution, first using a sliding-window, occlusion-based algorithm and then using RISE algorithms. # # This will necessarily require us to define some black-box classification model for us to introspect the saliency of. # We will fill this role here with a PyTorch Imagenet-pretrained ResNet18 network. # This will be wrapped up in an implementation of the `ClassifyImage` interface for input to our "application." # This sub-classing is a means of standardizing classifier operation with our API in order to support the varying ways classification is performed across toolkits and applications. # # ### Table of Contents # * [The test image](#The-test-image) # * [The "application"](#The-"application") # * [Black-box Classifier](#Black-box-Classifier) # * [`xaitk_saliency` Swappable Implementations](#xaitk_saliency-Swappable-Implementations) # * [Calling the Application](#Calling-the-Application) # # ### Miscellaneous # License for test image used may be found in 'COCO-LICENSE.txt'. # # #### References # 1. Zeiler, <NAME>., and <NAME>. "Visualizing and understanding convolutional networks." European conference on computer vision. Springer, Cham, 2014. # # 2. Petsiuk, Vitali, <NAME>, and <NAME>. "Rise: Randomized input sampling for explanation of black-box models." arXiv preprint arXiv:1806.07421 (2018). # # <br> # # To run this notebook in Colab, please use the link below: # # [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/XAITK/xaitk-saliency/blob/master/examples/OcclusionSaliency.ipynb) # # Setup environment # !python -c "import xaitk_saliency" || pip install xaitk-saliency # !python -c "import torch" || pip install "torch==1.9.0" # !python -c "import torchvision" || pip install "torchvision==0.10.0" # # The test image # We will test this application on the following image. # We know that this image contains the ImageNet classes of "boxer" and "tiger cat". # + import PIL.Image import matplotlib.pyplot as plt import urllib.request # Use JPEG format for inline visualizations here. # %config InlineBackend.figure_format = "jpeg" urllib.request.urlretrieve('https://farm1.staticflickr.com/74/202734059_fcce636dcd_z.jpg', "catdog.jpg") test_image_filename = 'catdog.jpg' plt.figure(figsize=(12, 8)) plt.axis('off') _ = plt.imshow(PIL.Image.open(test_image_filename)) # - # # The "Application" # The `xaitk-saliency` package provides a relatively high-level API interface for visual saliency map generation. # This interface defines the following input requirements: # * a reference image # * a black-box classifier that performs inference over images # # As mentioned above, our high-level API accepts black-box classifiers in terms of the `ClassifyImage` interface. # + import matplotlib.pyplot as plt import numpy as np import PIL.Image from smqtk_classifier import ClassifyImage from xaitk_saliency import GenerateImageClassifierBlackboxSaliency def app( image_filepath: str, # Assuming outputs `nClass` length arrays. blackbox_classify: ClassifyImage, gen_bb_sal: GenerateImageClassifierBlackboxSaliency, ): # Load the image ref_image = np.asarray(PIL.Image.open(image_filepath)) sal_maps = gen_bb_sal(ref_image, blackbox_classify) print(f"Saliency maps: {sal_maps.shape}") visualize_saliency(ref_image, sal_maps) def visualize_saliency(ref_image: np.ndarray, sal_maps: np.ndarray) -> None: # Visualize the saliency heat-maps sub_plot_ind = len(sal_maps) + 1 plt.figure(figsize=(12, 6)) plt.subplot(2, sub_plot_ind, 1) plt.imshow(ref_image) plt.axis('off') plt.title('Test Image') # Some magic numbers here to get colorbar to be roughly the same height # as the plotted image. colorbar_kwargs = { "fraction": 0.046*(ref_image.shape[0]/ref_image.shape[1]), "pad": 0.04, } for i, class_sal_map in enumerate(sal_maps): print(f"Class {i} saliency map range: [{class_sal_map.min()}, {class_sal_map.max()}]") # Positive half saliency plt.subplot(2, sub_plot_ind, 2+i) plt.imshow(ref_image, alpha=0.7) plt.imshow( np.clip(class_sal_map, 0, 1), cmap='jet', alpha=0.3 ) plt.clim(0, 1) plt.colorbar(**colorbar_kwargs) plt.title(f"Class #{i+1} Pos Saliency") plt.axis('off') # Negative half saliency plt.subplot(2, sub_plot_ind, sub_plot_ind+2+i) plt.imshow(ref_image, alpha=0.7) plt.imshow( np.clip(class_sal_map, -1, 0), cmap='jet_r', alpha=0.3 ) plt.clim(-1, 0) plt.colorbar(**colorbar_kwargs) plt.title(f"Class #{i+1} Neg Saliency") plt.axis('off') # - # # Black-box Classifier # In this example we will use a basic PyTorch-based pretrained ResNet18 model and use it's softmax output as classification confidences. # Since this model normally outputs 1000 classes, we will, for simplicity of example, constrain the output to the two classes that we happen to know are relevant for our test image. # + # Set up our "black box" classifier using PyTorch and it's ImageNet pretrained ResNet18. # We will constrain the output of our classifier here to the two classes that are relevant # to our test image for the purposes of this example. import os import torch from torch.utils.data import DataLoader, Dataset import torchvision.models as models import torchvision.transforms as transforms CUDA_AVAILABLE = torch.cuda.is_available() model = models.resnet18(pretrained=True) model = model.eval() if CUDA_AVAILABLE: model = model.cuda() # These are some simple helper functions to perform prediction with this model model_input_size = (224, 224) model_mean = [0.485, 0.456, 0.406] model_loader = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(model_input_size), transforms.ToTensor(), transforms.Normalize( mean=model_mean, std=[0.229, 0.224, 0.225] ), ]) # Grabbing the class labels associated with this model. if not os.path.isfile('imagenet_classes.txt'): # !wget https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt -O imagenet_classes.txt f = open("imagenet_classes.txt", "r") categories = [s.strip() for s in f.readlines()] # For this test, we will use an image with both a cat and a dog in it. # Let's only consider the saliency of two class predictions. sal_class_labels = ['boxer', 'tiger cat'] sal_class_idxs = [categories.index(lbl) for lbl in sal_class_labels] class TorchResnet18 (ClassifyImage): """ Blackbox model to output the two focus classes. """ def get_labels(self): return sal_class_labels @torch.no_grad() def classify_images(self, image_iter): # Input may either be an NDaray, or some arbitrary iterable of NDarray images. for img in image_iter: image_tensor = model_loader(img).unsqueeze(0) if CUDA_AVAILABLE: image_tensor = image_tensor.cuda() feature_vec = model(image_tensor) # Converting feature extractor output to probabilities. class_conf = torch.nn.functional.softmax(feature_vec, dim=1).cpu().detach().numpy().squeeze() # Only return the confidences for the focus classes yield dict(zip(sal_class_labels, class_conf[sal_class_idxs])) def get_config(self): # Required by a parent class. return {} blackbox_classifier = TorchResnet18() blackbox_fill = np.uint8(np.asarray(model_mean) * 255) # - # # `xaitk_saliency` Swappable Implementations # Here we will manually import and construct a number of `GenerateImageClassifierBlackboxSaliency` implementations. # Since these all implement the same parent [abstract] class, they effectively all promise to abide by the API it defines. # Thus, we should be able to use them all interchangebly, at least at the functional level. # Their implementations may of course produce different results, as is the point of having varying implementations, but the types and form of the inputs and outputs should be the same. # # Diving deeper into the implementations used here, the implementations used here use a perturbation-occlusion sub-pipelines as shown in this diagram. # ![](figures/perturb_occlude_diagram.svg) # # As mentioned before, we will first construct a sliding-window, occlusion-based implementations and then RISE implementations. # + from xaitk_saliency.impls.gen_image_classifier_blackbox_sal.rise import RISEStack from xaitk_saliency.impls.gen_image_classifier_blackbox_sal.slidingwindow import SlidingWindowStack gen_slidingwindow = SlidingWindowStack((50, 50), (20, 20), threads=4) gen_rise = RISEStack(1000, 8, 0.5, seed=0, threads=4, debiased=False) gen_rise_debiased = RISEStack(1000, 8, 0.5, seed=0, threads=4, debiased=True) # - # # Calling the Application # In the below cells, we will show that we can invoke the same "application" (function) with different `xaitk-saliency` API interface implementations while still successfully executing, visualizing the different results that are generated. # ## Sliding Window Method # + # This generator implementation has a slot for filling background occlusion, # which our choice of classifier should ideally take for best operation. gen_slidingwindow.fill = blackbox_fill app( test_image_filename, blackbox_classifier, gen_slidingwindow, ) # - # ## RISE # + # This generator implementation has a slot for filling background occlusion, # which our choice of classifier should ideally take for best operation. gen_rise.fill = blackbox_fill app( test_image_filename, blackbox_classifier, gen_rise ) # - # ## RISE with Debiasing # + # This generator implementation has a slot for filling background occlusion, # which our choice of classifier should ideally take for best operation. gen_rise_debiased.fill = blackbox_fill app( test_image_filename, blackbox_classifier, gen_rise_debiased, )
examples/OcclusionSaliency.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from joblib import load clf = load('forest_model.joblib') sent_data = [-0.54839782, -0.35184723, 0.17023924, -3.10939288, 0.909047 , 3.53073928, -1.49890445, 1.37163425, -2.58719536, 0.75480169, -0.59832237, -1.24748237, 0.56082062, -0.1370649 , 0.78843122, 0.1627786 , 0.08075539, 0.97238009, 0.14502653, -0.2140704 , 0.01214456, 0.11382656, -0.18937492, 0.99338122, 0.13761257, -0.10732711, 0.00999518, 0.03007495, 7.5 ] len(sent_data) clf.predict([sent_data])[0]
web_api/main/notebooks/check_model_working.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # # 1.1. Verificar que no hay problemas en la importación # modules we'll use import pandas as pd # Veamos de importar datos de proyectos de Kickstarter la plataforma de Crowdsourcing kickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv") # Por defecto Pandas falla si hay errores para leer datos https://pandas.pydata.org/pandas-docs/stable/io.html#error-handling kickstarter_2018 = pd.read_csv("../input/kickstarter-projects/ks-projects-201801.csv") # Veamos los datos cargados en el dataframe kickstarter_2018 # Por defecto solo vemos los valores al comienzo o al final del archivo. # # Tomemos una muestra al azar para ver valores más dispersos # set seed for reproducibility import numpy as np np.random.seed(0) kickstarter_2018.sample(5) # No se observa a simple vista ningún problema. # Veamos la descripción del dataset si se corresponde con lo levantado https://www.kaggle.com/kemical/kickstarter-projects/data pd.DataFrame([["ID", "No description provided", "Numeric"], ["name", "No description provided", "String"], ["category", "No description provided", "String"], ["main_category", "No description provided", "String"], ["currency", "No description provided", "String"], ["deadline", "No description provided", "DateTime"], ["goal", "Goal amount in project currency", "Numeric"], ["launched", "No description provided", "DateTime"], ["pledged", "Pledged amount in the project currency", "Numeric"], ["state", "No description provided", "String"], ["backers", "No description provided", "Numeric"], ["country", "No description provided", "String"], ["usd pledged", "Pledged amount in USD (conversion made by KS)", "Numeric"], ["usd_pledged_real", "Pledged amount in USD (conversion made by fixer.io api)", "Numeric"], ["usd_goal_real", "Goal amount in USD", "Numeric"]], columns=["Field name","Field description", "Type"]) # ## kickstarter_2018.dtypes # Los campos object generalmente son String, entonces parece que no reconoció como fechas en **deadline** y **launched** :( # Veamos los datos un resumen de los datos kickstarter_2018.describe() # Por defecto se ven los datos numéricos, veamos el resto. kickstarter_2018.describe(include=['object']) # Operemos un cacho sobre los datos de lanzamiento kickstarter_2018['launched'].min() # Parece funcionar, pero ahora calculemos el rango de fechas de los proyectos kickstarter_2018['launched'].max() - kickstarter_2018['launched'].min() # Indiquemos que columnas son fechas como indica la [documentación](https://pandas.pydata.org/pandas-docs/stable/io.html#datetime-handling) kickstarter_2018 = pd.read_csv("../input/kickstarter-projects/ks-projects-201801.csv", parse_dates=["deadline","launched"]) kickstarter_2018.dtypes # Ahora vemos que esas columnas fueron reconocidas como fechas # # Veamos la misma muestra de nuevo kickstarter_2018.sample(5) # Y veamos el resumen de los datos kickstarter_2018.describe(include='all') # Podemos ver que tenemos primero y último en el resumen de las columnas de fechas. # # Ahora deberíamos poder calcular el rango de fechas de lanzamietos kickstarter_2018['launched'].max() - kickstarter_2018['launched'].min() # # 1.2. Asegurar de tener ids/claves únicas # Chequear que no hay datos duplicados kickstarter_2018.shape kickstarter_2018 = pd.read_csv("../input/kickstarter-projects/ks-projects-201801.csv", parse_dates=["deadline","launched"], index_col=['ID']) kickstarter_2018 kickstarter_2018.shape kickstarter_2018[kickstarter_2018.duplicated()] csv='1,2\n3,3\n1,3' print(csv) from io import StringIO df = pd.read_csv(StringIO(csv), names=['id','value'], index_col='id') df df[df.duplicated()] df.duplicated() df[df.index.duplicated( keep=False)] kickstarter_2018[kickstarter_2018.index.duplicated()] # # 1.3. Despersonalizar datos y guardarlos en un nuevo archivo # Estrategias de Google API https://cloud.google.com/dlp/docs/deidentify-sensitive-data: # # * **Replacement**: Replaces each input value with a given value. # * **Redaction**: Redacts a value by removing it. # * **Mask with character**: Masks a string either fully or partially by replacing a given number of characters with a specified fixed character. # * **Pseudonymization by replacing input value with cryptographic hash**: Replaces input values with a 32-byte hexadecimal string generated using a given data encryption key. # * **Obfuscation of dates**: Shifts dates by a random number of days, with the option to be consistent for the same context. # * **Pseudonymization by replacing with cryptographic format preserving token**: Replaces an input value with a “token,” or surrogate value, of the same length using format-preserving encryption (FPE) with the FFX mode of operation. # * **Bucket values based on fixed size ranges**: Masks input values by replacing them with “buckets,” or ranges within which the input value falls. # * **Bucket values based on custom size ranges**: Buckets input values based on user-configurable ranges and replacement values. # * **Replace with infoType**: Replaces an input value with the name of its infoType. # * **Extract time data**: Extracts or preserves a portion of Date, Timestamp, and TimeOfDay values. from hashlib import md5 kickstarter_2018['name'].apply(md5) # + def hashit(val): return md5(val.encode('utf-8')) kickstarter_2018['name'].apply(hashit) # + def hashit(val): try: return md5(val.encode('utf-8')) except Exception as e: print(val, type(val)) raise(e) kickstarter_2018['name'].apply(hashit) # + def hashit(val): if isinstance(val, float): return str(val) return md5(val.encode('utf-8')).hexdigest() kickstarter_2018['name'].apply(hashit) # - # # 1.4. Nunca modificar los datos crudos u originales # kickstarter_2018.to_csv("../input/kickstarter-projects/ks-projects-201801-for-pandas.csv")
02_analisis_y_curacion/notebooks/1. Importando los datos.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="-44lu3y8xbZz" # # A/B testing step-by-step guide in Python # > In this notebook we'll go over the process of analysing an A/B test, from formulating a hypothesis, testing it, and finally interpreting results. # # - toc: true # - badges: true # - comments: true # - categories: [ABTest] # - author: "<a href='https://medium.com/@RenatoFillinich/ab-testing-with-python-e5964dd66143'><NAME></a>" # - image: # + [markdown] id="D3XBuKL-xbZ3" # In this notebook we'll go over the process of analysing an A/B test, from formulating a hypothesis, testing it, and finally interpreting results. For our data, we'll use a <a href='https://www.kaggle.com/zhangluyuan/ab-testing?select=ab_data.csv'>dataset from Kaggle</a> which contains the results of an A/B test on what seems to be 2 different designs of a website page (old_page vs. new_page). Here's what we'll do: # # 1. Designing our experiment # 2. Collecting and preparing the data # 3. Visualising the results # 4. Testing the hypothesis # 5. Drawing conclusions # # To make it a bit more realistic, here's a potential **scenario** for our study: # # > Let's imagine you work on the product team at a medium-sized **online e-commerce business**. The UX designer worked really hard on a new version of the product page, with the hope that it will lead to a higher conversion rate. The product manager (PM) told you that the **current conversion rate** is about **13%** on average throughout the year, and that the team would be happy with an **increase of 2%**, meaning that the new design will be considered a success if it raises the conversion rate to 15%. # # Before rolling out the change, the team would be more comfortable testing it on a small number of users to see how it performs, so you suggest running an **A/B test** on a subset of your user base users. # + [markdown] id="mSR2XKnOxbZ5" # *** # ## 1. Designing our experiment # + [markdown] id="UddxvZVjxbZ6" # ### Formulating a hypothesis # # First things first, we want to make sure we formulate a hypothesis at the start of our project. This will make sure our interpretation of the results is correct as well as rigorous. # # Given we don't know if the new design will perform better or worse (or the same?) as our current design, we'll choose a <a href="https://en.wikipedia.org/wiki/One-_and_two-tailed_tests">**two-tailed test**</a>: # # $$H_0: p = p_0$$ # $$H_a: p \ne p_0$$ # # where $p$ and $p_0$ stand for the conversion rate of the new and old design, respectively. We'll also set a **confidence level of 95%**: # # $$\alpha = 0.05$$ # # The $\alpha$ value is a threshold we set, by which we say "if the probability of observing a result as extreme or more ($p$-value) is lower than $\alpha$, then we reject the null hypothesis". Since our $\alpha=0.05$ (indicating 5% probability), our confidence (1 - $\alpha$) is 95%. # # Don't worry if you are not familiar with the above, all this really means is that whatever conversion rate we observe for our new design in our test, we want to be 95% confident it is statistically different from the conversion rate of our old design, before we decide to reject the Null hypothesis $H_0$. # + [markdown] id="23b3NwD9xbZ7" # ### Choosing the variables # # For our test we'll need **two groups**: # * A `control` group - They'll be shown the old design # * A `treatment` (or experimental) group - They'll be shown the new design # # This will be our *Independent Variable*. The reason we have two groups even though we know the baseline conversion rate is that we want to control for other variables that could have an effect on our results, such as seasonality: by having a `control` group we can directly compare their results to the `treatment` group, because the only systematic difference between the groups is the design of the product page, and we can therefore attribute any differences in results to the designs. # # For our *Dependent Variable* (i.e. what we are trying to measure), we are interested in capturing the `conversion rate`. A way we can code this is by each user session with a binary variable: # * `0` - The user did not buy the product during this user session # * `1` - The user bought the product during this user session # # This way, we can easily calculate the mean for each group to get the conversion rate of each design. # + [markdown] id="yKqt1-cOxbZ-" # ### Choosing a sample size # # It is important to note that since we won't test the whole user base (our <a href="https://www.bmj.com/about-bmj/resources-readers/publications/statistics-square-one/3-populations-and-samples">population</a>), the conversion rates that we'll get will inevitably be only *estimates* of the true rates. # # The number of people (or user sessions) we decide to capture in each group will have an effect on the precision of our estimated conversion rates: **the larger the sample size**, the more precise our estimates (i.e. the smaller our confidence intervals), **the higher the chance to detect a difference** in the two groups, if present. # # On the other hand, the larger our sample gets, the more expensive (and impractical) our study becomes. # # *So how many people should we have in each group?* # # The sample size we need is estimated through something called <a href="https://research.usu.edu//irb/wp-content/uploads/sites/12/2015/08/A_Researchers_Guide_to_Power_Analysis_USU.pdf">*Power analysis*</a>, and it depends on a few factors: # * **Power of the test** ($1 - \beta$) - This represents the probability of finding a statistical difference between the groups in our test when a difference is actually present. This is usually set at 0.8 as a convention (here's more info on <a href="https://en.wikipedia.org/wiki/Power_of_a_test">statistical power</a>, if you are curious) # * **Alpha value** ($\alpha$) - The critical value we set earlier to 0.05 # * **Effect size** - How big of a difference we expect there to be between the conversion rates # # Since our team would be happy with a difference of 2%, we can use 13% and 15% to calculate the effect size we expect. # # Luckily, **Python takes care of all these calculations for us**: # + id="J0Bq-G8DxbaA" # Packages imports import numpy as np import pandas as pd import scipy.stats as stats import statsmodels.stats.api as sms import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns from math import ceil # %matplotlib inline import warnings warnings.filterwarnings("ignore") # Some plot styling preferences plt.style.use('seaborn-whitegrid') font = {'family' : 'Helvetica', 'weight' : 'bold', 'size' : 14} mpl.rc('font', **font) # + id="eiaZhk-vxbaC" colab={"base_uri": "https://localhost:8080/"} outputId="8c4fc745-a881-4d6d-f6f3-6e25308ff967" effect_size = sms.proportion_effectsize(0.13, 0.15) # Calculating effect size based on our expected rates required_n = sms.NormalIndPower().solve_power( effect_size, power=0.8, alpha=0.05, ratio=1 ) # Calculating sample size needed required_n = ceil(required_n) # Rounding up to next whole number print(required_n) # + [markdown] id="eZl2r4v7xbaF" # We'd need **at least 4720 observations for each group**. # # Having set the `power` parameter to 0.8 in practice means that if there exists an actual difference in conversion rate between our designs, assuming the difference is the one we estimated (13% vs. 15%), we have about 80% chance to detect it as statistically significant in our test with the sample size we calculated. # + [markdown] id="CURpYxEZxbaG" # *** # ## 2. Collecting and preparing the data # + [markdown] id="QnEwYEjhxbaH" # Great stuff! So now that we have our required sample size, we need to collect the data. Usually at this point you would work with your team to set up the experiment, likely with the help of the Engineering team, and make sure that you collect enough data based on the sample size needed. # # However, since we'll use a dataset that we found online, in order to simulate this situation we'll: # 1. Download the <a href='https://www.kaggle.com/zhangluyuan/ab-testing?select=ab_data.csv'>dataset from Kaggle</a> # 2. Read the data into a pandas DataFrame # 3. Check and clean the data as needed # 4. Randomly sample `n=4720` rows from the DataFrame for each group ***** # # ***Note**: Normally, we would not need to perform step 4, this is just for the sake of the exercise # # Since I already downloaded the dataset, I'll go straight to number 2. # + id="Z4s5ICJQxbaH" colab={"base_uri": "https://localhost:8080/", "height": 204} outputId="36350c16-000d-4124-f4be-38115ca5b396" df = pd.read_csv('https://github.com/sparsh-ai/reco-data/raw/master/ab-testing.zip') df.head() # + id="Z3RiYHMBxbaI" colab={"base_uri": "https://localhost:8080/"} outputId="d912411a-3e0c-4bbe-dba2-d67f074a1238" df.info() # + id="3jGYR9EJxbaI" colab={"base_uri": "https://localhost:8080/", "height": 142} outputId="dd8c7044-844f-4f04-a0bd-8a6b535e2117" # To make sure all the control group are seeing the old page and viceversa pd.crosstab(df['group'], df['landing_page']) # + [markdown] id="v4EyzPcPxbaJ" # There are **294478 rows** in the DataFrame, each representing a user session, as well as **5 columns** : # * `user_id` - The user ID of each session # * `timestamp` - Timestamp for the session # * `group` - Which group the user was assigned to for that session {`control`, `treatment`} # * `landing_page` - Which design each user saw on that session {`old_page`, `new_page`} # * `converted` - Whether the session ended in a conversion or not (binary, `0`=not converted, `1`=converted) # # We'll actually only use the `group` and `converted` columns for the analysis. # # Before we go ahead and sample the data to get our subset, let's make sure there are no users that have been sampled multiple times. # + id="32x1ywhYxbaJ" colab={"base_uri": "https://localhost:8080/"} outputId="cb57b90a-00eb-4144-ec79-c88774bd58c8" session_counts = df['user_id'].value_counts(ascending=False) multi_users = session_counts[session_counts > 1].count() print(f'There are {multi_users} users that appear multiple times in the dataset') # + [markdown] id="yI1v4QCrxbaK" # There are, in fact, users that appear more than once. Since the number is pretty low, we'll go ahead and remove them from the DataFrame to avoid sampling the same users twice. # + id="1VTCNR5SxbaK" colab={"base_uri": "https://localhost:8080/"} outputId="298a791b-4df8-4ea2-d2f1-293cae82b43b" users_to_drop = session_counts[session_counts > 1].index df = df[~df['user_id'].isin(users_to_drop)] print(f'The updated dataset now has {df.shape[0]} entries') # + [markdown] id="VYalyUeJxbaK" # ### Sampling # # Now that our DataFrame is nice and clean, we can proceed and sample `n=4720` entries for each of the groups. We can use pandas' `DataFrame.sample()` method to do this, which will perform Simple Random Sampling for us. # # **Note**: I've set `random_state=22` so that the results are reproducible if you feel like following on your own Notebook: just use `random_state=22` in your function and you should get the same sample as I did. # + id="6EXbtFaexbaL" control_sample = df[df['group'] == 'control'].sample(n=required_n, random_state=22) treatment_sample = df[df['group'] == 'treatment'].sample(n=required_n, random_state=22) ab_test = pd.concat([control_sample, treatment_sample], axis=0) ab_test.reset_index(drop=True, inplace=True) # + id="ORf0Hlv2xbaL" colab={"base_uri": "https://localhost:8080/", "height": 419} outputId="0edd346b-7612-4ef1-bb54-7578893a3326" ab_test # + id="fIFKXUmBxbaN" colab={"base_uri": "https://localhost:8080/"} outputId="cdecfb42-bbf6-4e21-ab13-778bb1b5af33" ab_test.info() # + id="5mGQRVnSxbaO" colab={"base_uri": "https://localhost:8080/"} outputId="9c440cdc-37ac-4233-eb7f-b824768b18b1" ab_test['group'].value_counts() # + [markdown] id="HPUc1bznxbaO" # Great, looks like everything went as planned, and we are now ready to analyse our results. # + [markdown] id="g1PoRb9KxbaP" # *** # ## 3. Visualising the results # + [markdown] id="fmwnE9rXxbaP" # The first thing we can do is to calculate some **basic statistics** to get an idea of what our samples look like. # + id="OrfD9yUyxbaQ" colab={"base_uri": "https://localhost:8080/", "height": 103} outputId="2e3fc958-aaf7-49c1-aed5-a8bd53ac2b68" conversion_rates = ab_test.groupby('group')['converted'] std_p = lambda x: np.std(x, ddof=0) # Std. deviation of the proportion se_p = lambda x: stats.sem(x, ddof=0) # Std. error of the proportion (std / sqrt(n)) conversion_rates = conversion_rates.agg([np.mean, std_p, se_p]) conversion_rates.columns = ['conversion_rate', 'std_deviation', 'std_error'] conversion_rates.style.format('{:.3f}') # + [markdown] id="MPADWAVexbaR" # Judging by the stats above, it does look like **our two designs performed very similarly**, with our new design performing slightly better, approx. **12.3% vs. 12.6% conversion rate**. # # Plotting the data will make these results easier to grasp: # + id="gcasaVmXxbaR" colab={"base_uri": "https://localhost:8080/", "height": 489} outputId="11dcf7af-5468-43f0-959e-a7e4577fb1bd" plt.figure(figsize=(8,6)) sns.barplot(x=ab_test['group'], y=ab_test['converted'], ci=False) plt.ylim(0, 0.17) plt.title('Conversion rate by group', pad=20) plt.xlabel('Group', labelpad=15) plt.ylabel('Converted (proportion)', labelpad=15); # + [markdown] id="9s8WH7MoxbaS" # The conversion rates for our groups are indeed very close. Also note that the conversion rate of the `control` group is lower than what we would have expected given what we knew about our avg. conversion rate (12.3% vs. 13%). This goes to show that there is some variation in results when sampling from a population. # # So... the `treatment` group's value is higher. **Is this difference *statistically significant***? # + [markdown] id="Cz0hF-gXxbaS" # *** # ## 4. Testing the hypothesis # + [markdown] id="np2wDTn4xbaS" # The last step of our analysis is testing our hypothesis. Since we have a very large sample, we can use the <a href="https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Normal_approximation_interval">normal approximation</a> for calculating our $p$-value (i.e. z-test). # # Again, Python makes all the calculations very easy. We can use the `statsmodels.stats.proportion` module to get the $p$-value and confidence intervals: # + id="WRFRW8NpxbaT" from statsmodels.stats.proportion import proportions_ztest, proportion_confint # + id="dbjM4L56xbaU" control_results = ab_test[ab_test['group'] == 'control']['converted'] treatment_results = ab_test[ab_test['group'] == 'treatment']['converted'] # + id="HUm9Alv-xbaV" colab={"base_uri": "https://localhost:8080/"} outputId="bd092939-cc8c-4401-97f0-73e4ac35d3c4" n_con = control_results.count() n_treat = treatment_results.count() successes = [control_results.sum(), treatment_results.sum()] nobs = [n_con, n_treat] z_stat, pval = proportions_ztest(successes, nobs=nobs) (lower_con, lower_treat), (upper_con, upper_treat) = proportion_confint(successes, nobs=nobs, alpha=0.05) print(f'z statistic: {z_stat:.2f}') print(f'p-value: {pval:.3f}') print(f'ci 95% for control group: [{lower_con:.3f}, {upper_con:.3f}]') print(f'ci 95% for treatment group: [{lower_treat:.3f}, {upper_treat:.3f}]') # + [markdown] id="wY-zEPrLxbaV" # *** # ## 5. Drawing conclusions # + [markdown] id="AqesRmhrxbaW" # Since our $p$-value=0.732 is way above our $\alpha$=0.05, we cannot reject the null hypothesis $H_0$, which means that our new design did not perform significantly different (let alone better) than our old one :( # # Additionally, if we look at the confidence interval for the `treatment` group ([0.116, 0.135], i.e. 11.6-13.5%) we notice that: # 1. It includes our baseline value of 13% conversion rate # 2. It does not include our target value of 15% (the 2% uplift we were aiming for) # # What this means is that it is more likely that the true conversion rate of the new design is similar to our baseline, rather than the 15% target we had hoped for. This is further proof that our new design is not likely to be an improvement on our old design, and that unfortunately we are back to the drawing board!
_notebooks/2021-06-28-step-by-step-ab-testing-guide.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab={} colab_type="code" id="bxDEhuxYaq84" import numpy as np # + [markdown] colab_type="text" id="akXzRXdfosVb" # # Exercise on finding number of points outside n-dimensional sphere # + colab={} colab_type="code" id="f1K1EBAznZ8i" ndim = 2 # + colab={} colab_type="code" id="0mmLapjkoygG" npoints = 1000000 # + colab={} colab_type="code" id="GvMDTwD4o29h" points = np.random.rand(npoints, ndim) # + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="7iaudHXNo_tE" outputId="ee48735b-608e-4755-fa47-84e4a1eb3b7b" points[0:2, :] # + colab={} colab_type="code" id="1iJ61u5GpHDH" dfo = np.zeros((npoints, 1)) outside_points = 0 # + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="iUPpQKVSpcMK" outputId="77b40503-d973-4f91-d895-b2231d8b0db9" # %%time for i in range(npoints): for j in range(ndim): dfo[i] += points[i, j] ** 2 dfo[i] = np.sqrt(dfo[i]) if dfo[i] > 1: outside_points += 1 # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="iuURBZKOqBHm" outputId="52bf9338-0a09-42aa-dc80-e79f7207db82" print('Fraction of points outside is ', outside_points/npoints) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="EF17iDHEqHlR" outputId="23dbf0ad-7d54-41f5-d4d3-e88a62dd8994" # 1 - (pi/4) 1 - 3.14/4 # + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="9QTyjo36qSrr" outputId="92135517-c569-441d-8e47-2d05316e96ad" # %%time sq_points = points * points dfo = np.sqrt(np.sum(sq_points, axis = 1)) outside_points = np.sum(dfo > 1) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="bMBepz8FrVkw" outputId="17acba9b-09f0-4ae4-fbff-9aa128e01d82" print('Fraction of points outside is ', outside_points/npoints) # + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="mgaZFO_NrXBy" outputId="a8364ef3-41c6-4738-b856-f933dbd34cdf" # %%time outside_points = np.sum(np.sqrt(np.sum(points * points, axis = 1)) > 1) # + colab={} colab_type="code" id="-4cLrXITrybE" def area_outside_square(npoints, ndim): points = np.random.rand(npoints, ndim) return np.sum(np.sqrt(np.sum(points * points, axis = 1)) > 1)/npoints # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="CUkwtIHIsIYK" outputId="452136a0-b737-45c5-8a51-ae5494b22567" area_outside_square(100000, 2) # + colab={"base_uri": "https://localhost:8080/", "height": 168} colab_type="code" id="L0kLrWi3sLlm" outputId="e7bb3ccf-f3f1-44ea-d256-889f47e92b0b" for i in range(2, 11): print(i, area_outside_square(100000, i)) # + [markdown] colab_type="text" id="3G61YH2z-UC5" # # Case study Cricket # + colab={"base_uri": "https://localhost:8080/", "height": 185} colab_type="code" id="JVsQ_9Xv9n2B" outputId="c0ee49e3-c140-40f7-cf8b-4f502054ef2e" # !head cric_data.tsv # + [markdown] colab_type="text" id="saNccFUJ-we0" # # # 1. Find mean, median, IQR for Sachin, Rahul, and India # 2. Find the histogram of Sachin's scores with 10 bins # 3. Find mean of Sachin's scores grouped by 25 matches # 4. Find mean of Sachin's scores where he has scored a century # 5. Find mean of Sachin's scores when Rahul has scored less than 10 # 6. Find mean for Sachin's scores based on which quartile India's score falls in # 7. For every match find out who has has scored more - Sachin or Rahul # 8. How many more runs does Sachin score on average after having scored x runs # 9. How many matches did Sachin take to score first 1000 runs, next 1000 runs, ... # # # + [markdown] colab_type="text" id="oRhgwxv6BT_u" # ### Problem 1 # + colab={"base_uri": "https://localhost:8080/", "height": 303} colab_type="code" id="IirauM-7-fP7" outputId="676c35ce-d2a3-4450-fd87-d2dbdb4df20e" cric_data = np.loadtxt("cric_data.tsv") # + colab={} colab_type="code" id="u9rXKkXFBXkD" cric_data = np.loadtxt("cric_data.tsv", skiprows=1) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="R1RFcBthBa3K" outputId="4be2686f-d9a3-4f8d-8d7b-e70fbd3e981c" cric_data.shape # + colab={} colab_type="code" id="dx6hPsFTBcFy" cric_data = cric_data[:, [1, 2, 3]] # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="q0vn54z6Bn8n" outputId="17fbb57b-f61f-47df-a5a1-e4aad070c0ec" cric_data.shape # + colab={} colab_type="code" id="CX19cgYRBpQj" sachin = cric_data[:, 0] # + colab={} colab_type="code" id="EBvn_H6UBt_4" rahul = cric_data[:, 1] # + colab={} colab_type="code" id="N_C4b0NvBvPL" india = cric_data[:, 2] # + colab={} colab_type="code" id="pTncsrxKBww3" def stats(col): print('Mean', np.mean(col)) print('Median', np.median(col)) print('IQR', np.percentile(col, 75) - np.percentile(col, 25)) # + colab={"base_uri": "https://localhost:8080/", "height": 67} colab_type="code" id="ZnlOG46HCAhE" outputId="d2bc2fd9-f3f5-42fd-aa1c-eb8f927732e1" stats(sachin) # + colab={"base_uri": "https://localhost:8080/", "height": 67} colab_type="code" id="qM9zPLH8CBgi" outputId="42e92428-b82f-4f09-ea32-51c637da94e6" stats(rahul) # + colab={"base_uri": "https://localhost:8080/", "height": 67} colab_type="code" id="zpUovg5qCEYu" outputId="f97a7a88-36ce-460a-8bcd-566498d70fb5" stats(india) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="ZYzes1hZCFbU" outputId="6b92c0f9-2395-45c0-8ab2-1cd93ebf3f01" np.mean(cric_data, axis = 0) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="YCzCNjxzCVIx" outputId="7400391b-5f51-4156-fbd6-8df0a623203d" np.median(cric_data, axis = 0) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="GDK19hacCX0f" outputId="1edeb3c9-3c3c-4859-9d6a-7ad66c391e93" np.percentile(cric_data, 75, axis = 0) - np.percentile(cric_data, 25, axis = 0) # + [markdown] colab_type="text" id="7uxW57KrCjYi" # ## Problem 2 # + colab={"base_uri": "https://localhost:8080/", "height": 67} colab_type="code" id="iSy4zL2qCbJ0" outputId="b65a743c-d7d5-4f23-eb1d-9a27b2e9dc52" np.histogram(sachin) # + [markdown] colab_type="text" id="JjPRAznlDvbv" # ## Problem 3 # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="fgEhV1c7Dj0G" outputId="a0341287-3a2e-46a6-aa5c-078c63af55af" sachin.shape # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="9qFUYDLDDxLr" outputId="c97141f9-e46d-429c-9920-242d09a7a557" sachin.reshape(9, 25).shape # + colab={} colab_type="code" id="kGrjI7DKD6gD" sachin_by_25s = sachin.reshape(9, 25) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="HJSeHYl_EIVO" outputId="7f589043-e387-48a6-aebb-c6133bc82f16" np.mean(sachin_by_25s, axis = 1) # + [markdown] colab_type="text" id="r0ytFoVUEzcq" # ## Problem 4, 5 # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="jBJBr0nPEQaD" outputId="77cf5bd6-783f-4efb-f95d-6116e32bef89" np.mean(sachin[sachin >= 100]) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="97ByMvboE1jp" outputId="a3d78163-6c44-4c89-97e3-8e1d9de36c89" np.mean(sachin[rahul <= 10]) # + [markdown] colab_type="text" id="S3S_w_syMctn" # ## Problem 6 # + colab={} colab_type="code" id="Fo79XPEuL6KR" qrs = np.percentile(india, [25, 50, 75, 100]) # + [markdown] colab_type="text" id="NRDXVgKGMoCj" # If India <= 175: Sachin's average is .... # # If India <= 216: Sachin's average is .... # # <= 273 # <= 499 # # # + colab={"base_uri": "https://localhost:8080/", "height": 162} colab_type="code" id="QWBZ0GMGMhZy" outputId="9d7c2ace-e365-4ecd-a73c-0e2a968da767" india < qrs # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="0YieLkm7NKf9" outputId="24abec64-3285-4aed-d0a6-80622c80c4ab" india.shape # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="zeCzxeOANQLc" outputId="3795ece9-345b-4b1a-98a5-8639e1ca9002" qrs.shape # + colab={} colab_type="code" id="HKW3xn3dNRC1" qrs = qrs.reshape(4, 1) # + colab={} colab_type="code" id="yfiKYkbqNU4Q" indices = india < qrs # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="xDPjUGOdNb0g" outputId="b0f06054-10a1-436f-9e5e-3b3cf5611848" indices.shape # + colab={"base_uri": "https://localhost:8080/", "height": 202} colab_type="code" id="HMMnAyoFNfY8" outputId="d306667e-fca3-4e29-db9f-bbb7ad01481d" sachin[indices[1, :]] # + colab={"base_uri": "https://localhost:8080/", "height": 84} colab_type="code" id="MjlIpKhNNmOv" outputId="b894abfb-d953-4021-995f-77f3e5b73866" for i in range(4): print(i, np.mean(sachin[indices[i]])) # + [markdown] colab_type="text" id="vjzVesqkOF6j" # ## Problem 7 # + colab={} colab_type="code" id="4L_y5LXoNy7A" snr = cric_data[:, 0:2] # + colab={"base_uri": "https://localhost:8080/", "height": 0} colab_type="code" id="4jNnpDuUOLr3" outputId="40a8a4e8-35b8-4d2b-b4b4-2f749bc69416" np.argmax([10, 3, 2, 5, 1]) # + colab={} colab_type="code" id="0tVmlcJxOUsT" is_rahul_higher = np.argmax(snr, axis=1) # + colab={"base_uri": "https://localhost:8080/", "height": 0} colab_type="code" id="KXID9LsEOkI3" outputId="e9a6860b-f202-40b5-caf9-8dc90faffa07" np.sum(is_rahul_higher) / 225 # + colab={"base_uri": "https://localhost:8080/", "height": 0} colab_type="code" id="WPei39PQOuB2" outputId="2145cc58-45e7-41a5-8220-cab021f3b41c" np.where(is_rahul_higher == 0, 'Sachin', 'Rahul') # + [markdown] colab_type="text" id="IdcY1mOsPbqG" # ## Problem 8 # + colab={} colab_type="code" id="HLJgvEgIO8gt" x_arr = np.arange(0, 101, 5) # + colab={"base_uri": "https://localhost:8080/", "height": 162} colab_type="code" id="fnzdXOjMPhia" outputId="0c600462-9793-4b7f-a3bf-fc13ab0225a9" sachin >= x_arr # + colab={} colab_type="code" id="wu7o937VPqPG" x_arr = x_arr.reshape(x_arr.shape[0], 1) # + colab={} colab_type="code" id="aj18oJ_yPv7g" indices = (sachin >= x_arr) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="y0MwJXf7PxDV" outputId="49267c56-573c-462c-b8dc-22f43af5a7ff" indices.shape # + colab={"base_uri": "https://localhost:8080/", "height": 286} colab_type="code" id="pNr7IhElP0Tg" outputId="30a731b8-0314-4250-b1b0-d3e47e411b9d" sachin[indices[1, :]] # + colab={"base_uri": "https://localhost:8080/", "height": 370} colab_type="code" id="iAr4OQPgP6tI" outputId="66d48e05-2ed8-4904-bf66-abd7f9b24b9c" for i in range(x_arr.shape[0]): print(x_arr[i, 0], np.mean(sachin[indices[i, :]]) - x_arr[i, 0]) # + [markdown] colab_type="text" id="ZMBcLnSEQlE3" # ## Problem 9 # + colab={"base_uri": "https://localhost:8080/", "height": 370} colab_type="code" id="KFx_Ywk_P_Pi" outputId="2e6e5260-a46c-4f79-be27-c52186f13017" sachin # + colab={} colab_type="code" id="NBf5OrDrQmOY" sachin_cumscores = np.cumsum(sachin) # + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="Beb_KP7fQvdR" outputId="fd68ebf9-6f6e-48b0-c749-aeb9f47e4112" np.histogram(sachin_cumscores, bins=np.arange(0, 10000, 1000))
Lab-Sessions/M03_Week08-Numpy/FDS_W08_Solutions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import tensorflow as tf from tensorflow import keras from tensorflow import feature_column from tensorflow.keras import layers import numpy as np # + import pandas as pd df = pd.read_csv('data/data.csv') df['response'] = df['ICE BofA US High Yield Index TR'].apply(lambda x: True if x < 0 else False) df = df.dropna() df_original = df.copy() dates = df.pop('Date') for col in df.columns: df = df.rename({col: col.replace(' ', '_').replace('&', '')}, axis=1) # + ### normalize features from sklearn.preprocessing import StandardScaler xHY = df.pop('response') def normalize_column(df): scaler = StandardScaler() df = pd.DataFrame(scaler.fit_transform(df.values), columns = df.columns, index= df.index) df = pd.DataFrame(np.clip(df, -5, 5), columns = df.columns, index= df.index) return df df = normalize_column(df) df['response'] = xHY.values df.describe() # - df def df_to_dataset(df_features, df_labels, batch_size=32, single_step=False): test_split = int(len(df_features) * 0.8) validation_split = int(test_split * 0.6) x_train, y_train = create_multivariate_data(df_features, df_labels, 0, validation_split, past_history, future_target, single_step) x_val, y_val = create_multivariate_data(df_features, df_labels, validation_split, test_split, past_history, future_target, single_step) x_test, y_test = create_multivariate_data(df_features, df_labels, test_split, None, past_history, future_target, single_step) print("Training data", x_train.shape) print("Validation data", x_val.shape) print("Test data", x_test.shape) train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train)) train_data = train_data.shuffle(len(df_features)).batch(batch_size) val_data = tf.data.Dataset.from_tensor_slices((x_val, y_val)) val_data = val_data.batch(batch_size) test_data = tf.data.Dataset.from_tensor_slices((x_test, y_test)) test_data = test_data.batch(1) return x_train.shape[-2:], train_data, val_data, test_data def create_multivariate_data(features, target, start_index, end_index, history_size, target_size, single_step=False): data = [] labels = [] start_index = start_index + history_size if end_index is None: end_index = len(features) - target_size for i in range(start_index, end_index): indices = range(i-history_size, i) data.append(features[indices]) if single_step: labels.append(target[i+target_size]) else: labels.append(target[i:i+target_size]) return np.asarray(data), np.asarray(labels) # + features = [ 'ICE_BofA_US_High_Yield_Index_TR', #'CAPE_index', #'SP_500_Real_TR_Index', 'SPXT', 'CAPE_change', 'PhilFed_US_Leading_Index_Change', #'PhilFed_US_Leading_Index', 'VIX_change', #'TenYr_Rate_Change', #'Inflation', 'delinquency_rates_modified', #'USD_Swap_Spread_Semi_5Yr', #'BuyWrite', #'CreditSpread', ] df_features = df[features] df_features.head() df_features = df_features.values #time window parameters for the model past_history = 12 future_target = 0 #note: smallest index is 0 if single step, 1 if multi step is_single_step = True shape, train_data, val_data, test_data = df_to_dataset(df_features, df["response"].values, batch_size=int((len(df_features)-past_history)), single_step=is_single_step) # + import matplotlib.pyplot as plt def create_time_steps(length): return list(range(-length, 0)) def multi_step_plot(history, true_future, prediction): plt.figure(figsize=(12, 6)) num_in = create_time_steps(len(history)) num_out = len(true_future) plt.plot(num_in, np.array(history[:, 1]), label='History') plt.plot(np.arange(num_out), np.array(true_future), 'bo', label='True Future') if prediction.any(): plt.plot(np.arange(num_out), np.array(prediction), 'ro', label='Predicted Future') plt.legend(loc='upper left') plt.show def plot_train_history(history, title, other_metric=None): loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(loss)) plt.figure() fig, ax1 = plt.subplots() ax1.plot(epochs, loss, 'b', label='Training loss') ax1.plot(epochs, val_loss, 'r', label='Validation loss') if other_metric: ax2 = ax1.twinx() ax2.plot(epochs, history.history[other_metric], 'g', label=other_metric) plt.title(title) ax1.legend(loc='upper left') ax2.legend(loc='upper right') plt.show() if not is_single_step: for x, y in train_data.take(1): multi_step_plot(x[0], y[0], np.array([0])) # + ### overweighing negative response y category ## note: cannot oversample categorical y to rebalance since will lose past history information weight_negative = (1/df['response'].value_counts()[True]) * len(df['response'])/2.0 weight_positive = (1/df['response'].value_counts()[False]) * len(df['response'])/2.0 class_weight = {False: weight_positive, True: weight_negative} print(class_weight) print(df['response'].value_counts()) df['response'].value_counts().plot(kind='bar') # - def make_model(bias, shape): if bias is not None: bias = keras.initializers.Constant(bias) model = tf.keras.Sequential() #add LSTM layer #model.add(layers.LSTM(1280, input_shape=shape)) model.add(layers.LSTM(1280, return_sequences=True, input_shape=shape)) model.add(layers.LSTM(480, return_sequences=True)) model.add(layers.Dropout(0.5)) model.add(layers.LSTM(240, return_sequences=True)) model.add(layers.LSTM(1280)) model.add(layers.Dense(10000, activation='relu')) model.add(layers.Dropout(0.5)) # Add the output layer: output_unit = 1 if not is_single_step else future_target + 1 model.add(layers.Dense(output_unit, activation='sigmoid', bias_initializer= bias)) model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=[keras.metrics.BinaryAccuracy(), keras.metrics.Precision(), keras.metrics.Recall(), keras.metrics.AUC(name='auc')]) return model earlystop_callback = tf.keras.callbacks.EarlyStopping(monitor="val_auc", min_delta=0.01, patience=5, mode="max") checkpoint_callback = tf.keras.callbacks.ModelCheckpoint("bestcheckpoint_RNN.h5", monitor="val_auc", save_best_only=True, mode="max") # + model = make_model(None, shape) history = model.fit(train_data, epochs=500, validation_data=val_data, class_weight=class_weight, callbacks=[earlystop_callback, checkpoint_callback]) if not is_single_step: for x, y in val_data.take(10): multi_step_plot(x[0], y[0], model.predict(x)[0]) # + plot_train_history(history, 'Final Model', 'val_auc') #model = tf.keras.models.load_model("bestcheckpoint_RNN.h5") model.summary() # + model.evaluate(test_data) predict_data = [] for x, y in test_data: real_x = [] for history_item in x[0].numpy(): real_x.append(df.loc[np.logical_and(df[features[0]] == history_item[0], df[features[1]] == history_item[1])]) predict_y = float(model.predict(x)[0]) #print(x[0].numpy(), y[0].numpy(), predict_y) values = real_x[len(real_x)-1][features].values[0].tolist() #note: this is only getting the last row in past_history values.extend([y[0].numpy(),predict_y]) predict_data.append(values) predict_columns = features.copy() predict_columns.extend(['response_negative','prob_negative']) predicted = pd.DataFrame(predict_data, columns= predict_columns ) predicted.to_csv("RNNresults.csv") predicted
.ipynb_checkpoints/RNN on imbalanced time-series data, categorical output-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/steve-keys/Assignment---1--Intro-to-Programming/blob/main/final_amazon_prices.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="UOzL6X-9pE-d" # ## Lab 8 # + id="sP0evzCj2O2d" # !pip install kora -q '''load packages''' from bs4 import BeautifulSoup from kora.selenium import wd import pandas as pd def get_url(): search_term = input("What do you want to search for? ") template = 'https://www.amazon.com.au/s?k={}&rh=n%3A4913312051&ref=nb_sb_noss' search_term = search_term.replace(' ','+') url = template.format(search_term) return url def extract_description(item): description = item.h2.a.text return description def extract_price(item): try: price_parent = item.find('span', 'a-price') price = price_parent.find('span', 'a-offscreen') price = price.text except AttributeError: price = '' return price def extract_record(item): return { 'description': extract_description(item), 'price': extract_price(item) } # + colab={"base_uri": "https://localhost:8080/", "height": 248} id="8g0sjRXfh1Rb" outputId="70ddefca-24cb-4fa7-c7fa-a411e6ad6720" # Establish Session url = 'https://www.amazon.com.au' wd.get(url) earch_term = input("What do you want to search for today? ") url = get_url(search_term) wd.get(url) soup = BeautifulSoup(wd.page_source, 'html.parser') records = [] results = soup.find_all('div',{'data-component-type': 's-search-result'}) for item in results: records.append(extract_record(item)) wd.close() df = pd.DataFrame.from_records(records) df.head()
final_amazon_prices.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab={} colab_type="code" id="5iOYEiU1pbcB" import numpy as np import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as st # %matplotlib inline sns.set(style='ticks', palette='Set2') # + [markdown] colab_type="text" id="beuY1nFFpbcF" # # Bayesian in Python # # In this tutorial, we are going to go over basic bayesian analysis in python. # # ## Review # # __Prior p(H):__ Our prior reflects what we know about the value of some parameter before seeing data. This could refer to previous trials and distributions. # # __Likelihood p(D|H)__: what is the plausibility that our data is observed, given our prior? # # __Posterior p(H|D):__ This is result of the Bayesian analysis and reflects all that we know about a problem (given our data and model). # # __Evidence p(D):__ Evidence is the probability of observing the data averaged over all the possible values the parameters can take. Also knowns as the noramlziing factor. The normalising constant makes sure that the resulting posterior distribution is a true probability distribution by ensuring that the sum of the distribution is equal to 1. # # Because p(D) is considered a normalizing constant we can say: $p(H|D) \propto p(D|H) * p(H)$ # # ## Coin - Flipping Problem # # Let's think of these terms in the context of a coin-flipping experiment. # # On a standard coin, we have two sides, heads or tails. Both of which are equally likely to show after a coin flip, or a 50% probability. # # In the case of a coin-flipping trials, we may want to consider this probability our prior. # # Let's go ahead and create our prior distribution: # + colab={} colab_type="code" id="3S88FE4CpbcG" coin_flips_prior = np.random.binomial(n = 1, p = 0.5, size = 1000) coin_flips_prior[:5] # + colab={} colab_type="code" id="27wlBPn8pbcM" params = np.linspace(0,1,100) params # + colab={} colab_type="code" id="bOeR37HcpbcQ" p_prior = np.array([np.product(st.bernoulli.pmf(coin_flips_prior, p)) for p in params]) # + colab={} colab_type="code" id="AuqlEVUQpbcT" p_prior = p_prior/np.sum(p_prior) plt.plot(params, p_prior) sns.despine() # + [markdown] colab_type="text" id="_69aywdZpbcW" # As you can see, our prior distribution peaks at 0.5 which is what our probability for our fair coin is. # # Now, let's introduce some observations from trials with an unfair coin. Let's say the probability is now weight 80-20, where the probability a head is shown is 0.8. # # Let's create this sampling distribution: # + colab={} colab_type="code" id="UURyMMb5pbcX" coin_flips_observed = np.random.binomial(n=1, p=0.8, size = 1000) p_observed = np.array([np.product(st.bernoulli.pmf(coin_flips_observed, p)) for p in params]) p_observed = p_observed/np.sum(p_observed) plt.plot(params, p_observed) sns.despine() # + [markdown] colab_type="text" id="Chie1Gg4pbcb" # The peak for our sampling distribution is around 0.8. # # While our observations from our sampling distribution indicate a probability around 0.8, because our prior is 0.5, we have to assess the likelihood that these values could be observed and find our posterior distribution. # # Remember, $p(H|D) \propto p(D|H) * p(H)\ OR\ Posterior\ \propto Likelihood\ * Prior$ # + colab={} colab_type="code" id="lAnyv5BApbcb" p_posterior = [p_prior[i] * p_observed[i] for i in range(len(p_prior))] p_posterior = p_posterior/np.sum(p_posterior) plt.plot(params, p_posterior) sns.despine() # + [markdown] colab_type="text" id="SA-eNhIfpbce" # ## University of Michigan Student IQs # # We'll do another example where we have some prior belief about the IQ of University of Michigan students. # # For our prior distribution, we'll have a normal distribution with a mean IQ of 100 and a standard deviation of 10. # + colab={} colab_type="code" id="O39Sb2WLpbcf" prior_distribution = np.random.normal(100, 10, 1000) plt.hist(prior_distribution) sns.despine() # + [markdown] colab_type="text" id="LwcQkHPApbck" # Now, let's say we are collecting some observations of student IQs which takes the shape of a normal distribution with mean 115 and standard deviation of 7.5 and want to construct our posterior distribution. # # In order to do this, we update our prior by calculating the mean and variance after each observation. # # The equations for our updated prior mean and variance are: # # $$Updated\ Prior\ Mean = \frac{\sigma^2\mu_{observed} + \sigma_{prior}^2x}{\sigma_{observed}^2 + \sigma_{prior}^2}$$ # # $$Updated\ Prior\ Variance = \frac{\sigma_{observed}^2\sigma_{prior}^2}{\sigma_{observed}^2 + \sigma_{prior}^2}$$ # + colab={} colab_type="code" id="8jnqJUX7pbck" np.random.seed(5) observed_distribution = np.random.normal(115, 10, 1000) mu = [100] * 1000 sigma = [10] * 1000 mu[0] = (10**2*observed_distribution[0] + (10**2)*100)/(10**2+10**2) sigma[0] = (10**2*10**2)/(10**2+10**2) for i in range(1000): if i == 999: break mu[i + 1] = (sigma[i]**2*observed_distribution[i+1] + (10**2)*mu[i] )/(sigma[i]**2+10**2) sigma[i + 1] = (sigma[i]*10**2)/(sigma[i]+10**2) posterior_distributions = [[]] * 20 for i in range(20): posterior_distributions[i] = np.random.normal(mu[i], sigma[i], 1000) plt.hist(prior_distribution) plt.hist(observed_distribution, alpha = 0.75) plt.hist(posterior_distributions[14], alpha = 0.5) sns.despine() # -
Fitting_Statistical_Models_to_Data_with_Python/week4/bayesian.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + deletable=false editable=false nbgrader={"checksum": "512b9d458893e474da69aa7e23a01e24", "grade": false, "grade_id": "cell-9e42398fb4955fba", "locked": true, "schema_version": 1, "solution": false} id="JXWSUWp5FFfp" # Execute this code block to install dependencies when running on colab try: import torch except: from os.path import exists from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) # cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\.\([0-9]*\)\.\([0-9]*\)$/cu\1\2/' accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu' # !pip install -q http://download.pytorch.org/whl/{accelerator}/torch-1.0.0-{platform}-linux_x86_64.whl torchvision # + [markdown] deletable=false editable=false nbgrader={"checksum": "57488d0734123ec82683f50de0d1496d", "grade": false, "grade_id": "cell-9daf9d2f6ba17cf3", "locked": true, "schema_version": 1, "solution": false} id="3pRwcZfSFFf4" # ## The Fashion-MNIST Dataset # # Fashion-MNIST is a dataset of Zalando’s article images consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28×28 grayscale image, associated with a label from 10 classes. Fashion-MNIST is intended to serve as a direct drop-in replacement of the original MNIST dataset for benchmarking machine learning algorithms as it is a more challenging dataset. # # For this lab, let's start by loading the Fashion-MNIST dataset using the Torchvision library. When loading, we can transform the images to be flattened vectors of dimension 784 (= 28 x 28). # # Once the data has been downloaded, we can plot some of the examples to see what the classes look like. # + [markdown] deletable=false editable=false nbgrader={"checksum": "a7eaa07fe30212adedb7388dbd85af8d", "grade": false, "grade_id": "cell-2122f281579eb211", "locked": true, "schema_version": 1, "solution": false} id="WFVrPq49FFf6" # ### Loading the Dataset using PyTorch and the Torchvision Library # + deletable=false editable=false nbgrader={"checksum": "2cf6a4b32ba0c3cfe5b2265f3bb9980f", "grade": false, "grade_id": "cell-71a9243a4d066e4b", "locked": true, "schema_version": 1, "solution": false} id="PASHpVskFFf6" colab={"base_uri": "https://localhost:8080/", "height": 568, "referenced_widgets": ["e4c278480c79424f9d2efd92541fa3e7", "32b9fc72cb42487d9c74dea3109bfd76", "71e6eaf6ae994a2d97360984bca15e10", "9fe65673591049da9f330151bcd663ad", "95e9f6437d7c467ea303d518958b0815", "<KEY>", "4b9a4005dfe14f4a8b5446898e9bd3ad", "<KEY>", "9e0320d9c0fc46b69ac8efa6a8ded2bb", "<KEY>", "871b8ca7fc8b467396b7e33040a50c99", "<KEY>", "1a6c5e0079a940eea1bbe2efec6a3634", "<KEY>", "f27d74145a5c48758567c5fb60483ed2", "<KEY>", "61c92d13e7a944edadf626a422b264ed", "<KEY>", "be364c4de3374097b35af3d915cbd537", "988d76e9b3174cf1acabd902529b55e7", "8090259d9cff4ab0869e4b40016021be", "d9e54360b38c43ce94d5b0b4ecdcfe09", "<KEY>", "<KEY>", "56d4309237344725bef63d26571e521a", "aa78509be9104caa9eee45dae6540f7c", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "783d53d07f6d49a89fa4aee8614ceaca", "<KEY>"]} outputId="b1dc13f5-8554-4b17-8fd3-33f60b4a6249" import torch import torchvision import torchvision.transforms as transforms batch_size = 256 # dataset construction transform = transforms.Compose([ transforms.ToTensor(), # convert to tensor transforms.Lambda(lambda x: x.view(image_dim)) # flatten into vector ]) train_set = torchvision.datasets.FashionMNIST( root='./data/FashionMNIST' ,train=True ,download=True ,transform=transform ) train_loader = torch.utils.data.DataLoader( train_set, batch_size=batch_size ) # + deletable=false editable=false nbgrader={"checksum": "c4f8d5982641adb7486fd2aa2ba27e53", "grade": false, "grade_id": "cell-f128ce750ee024be", "locked": true, "schema_version": 1, "solution": false} id="qDaLfLwAFFf8" colab={"base_uri": "https://localhost:8080/", "height": 276} outputId="7cb6c021-120e-4ac5-8206-6716b900ecec" # %matplotlib inline import matplotlib.pyplot as plt for i in range(8): plt.subplot(int(str(24)+str(i+1))) plt.imshow(train_set.train_data[i], cmap=plt.get_cmap('gray')) # show the plot plt.show() # + [markdown] deletable=false editable=false nbgrader={"checksum": "d28cdaefd305274758b338af6fe64f68", "grade": false, "grade_id": "cell-c4a66cd9fec76585", "locked": true, "schema_version": 1, "solution": false} id="ADVAaAPqFFf8" # # Implement an Autoencoder # # The next step is to implement a very simple autoencoder algorithm. # # Recall from the lecture, an autoencoder is an unsupervised algorithm that consists of an encoder and a decoder. The input passes through an encoder, which typically contains a bottleneck to reduce to the dimensionality of the input. This latent code, or reduced dimensionality representation of the input is then passed through the decoder to reconstruct the input. The reconstruction will be a lossy version of the input. The encoder and decoder are neural networks and learning is achieved in the same manner as with a neural network. # # For this implementation, assume the Encoder (defined below) only has an input and an output. There is no hidden layer in the encoder. Assume the dimensionality of the latent space is $64$. # # For the Decoder, again, assume it is a simple dense layer without a hidden layer (simply an input and output layer). For the decoder, the output layer should have a Sigmoid non-linearity as opposed to Relu (which may be used for the other layers). # # Start by defining the Encoder and Decoder classes. # + deletable=false nbgrader={"checksum": "9b480dd0c33e23b0b5dfd8c4a546393b", "grade": true, "grade_id": "cell-9c0efdfaad95aa4d", "locked": false, "points": 6, "schema_version": 1, "solution": true} id="SBo25TrfFFf9" import torch import torch.nn as nn import torch.nn.functional as F class Encoder(nn.Module): ''' simple encoder with no hidden dense layer ''' def __init__(self, input_dim, hidden_dim): super(Encoder, self).__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) def forward(self, x): out = self.fc1(x) return out class Decoder(nn.Module): ''' simple decoder: single dense hidden layer followed by output layer with a sigmoid to squish values ''' def __init__(self, input_dim, output_dim): super(Decoder, self).__init__() self.fc1 = nn.Linear(input_dim, output_dim) def forward(self, x): out = self.fc1(x) out = F.sigmoid(out) return out # + [markdown] deletable=false editable=false nbgrader={"checksum": "3db39fdb6caa610d5867f8d5cc543d03", "grade": false, "grade_id": "cell-5b3a0d1e71e6d5c6", "locked": true, "schema_version": 1, "solution": false} id="y2TJmTlMFFf-" # Next, let's test the autoencoder implementation to make sure it is functioning and see what the reconstructed images look like. # # The code to test your autoencoder is written below. You will simply need to write the code to display your reconstructed images. # + deletable=false nbgrader={"checksum": "5fd6a5d1b81d78fb6e25cbad5a6e4b56", "grade": true, "grade_id": "cell-33025b3e04e43ebb", "locked": false, "points": 2, "schema_version": 1, "solution": true} id="GpopHd8AFFf_" colab={"base_uri": "https://localhost:8080/", "height": 538, "referenced_widgets": ["780e8d90dd6c4b048d6031469b069f9b", "a09dde2726314c51bd11fc5d11a94248", "8d9d3c86c40243dd9cccb4590fc004d5", "5631bd0906624bb0a16ea72b3f3d7b32", "12f9e309e49b4d0cb942b1a6e71182eb", "5497774e137a4c1881fee937d4d84b04", "07390a4f250143c29a2f909f7490ddca", "a93502d33486420c9158db5f106280d0", "bd982b3c22844d1fb8df7e87ef04b0ae", "cdb0557b971f4e23be13a93935270118", "70833875e17e4e3d94d6c140669c89d5", "<KEY>", "<KEY>", "a4955510b5a34c428a96e3cd5ca860ff", "4ada807826f44c2aab30aea872444222", "57f685adbe75459b99b1317254e3e053", "80818ef9fc9d4a56932ea8e10c793a77", "<KEY>", "8ff831a9de974b17a482b3c3617c3c7d", "<KEY>", "12f33f6d8ca148dbb5ae79413a817688", "5b4f8eae31b04785b1bed2b149734aab", "c3b5819aef3d4ea2b56a366ca2958a73", "b74d3655a4284904b3ef27ccd28c89ad", "7fc11e699a5b4f9990c6e2953af0769a", "<KEY>", "<KEY>", "<KEY>", "381336eb1c424238ab15ce059b1ce4e7", "<KEY>", "<KEY>", "<KEY>", "e3228c4d661c4e9da7aa7677df5b7aa7", "<KEY>", "<KEY>", "<KEY>", "4d5a19d2a16849de9bd1eac38b1ba65d", "fb836d162bae4c639c9ef683e3198c83", "cc4f1285e9104df7bd8681f89a9d32dc", "<KEY>", "70ce9a7d87a94002a2eb7ba75ed88ffe", "22d9830377004ab59b932ad7f1d2b9ba", "<KEY>", "e5b179a39cc043c9a076b6b764d6644e", "ddc4e6855644496383d9390548de2d9a", "013f1320e7894de489132a100f42b46f", "3ec5853c18674c2e86f06f38e10165fb", "<KEY>", "26bc8b06e37b4485be9e76a9d7c233e0", "9ab66b0d7d114d019468685fe088ac82", "<KEY>", "02d759d57c7a41af959e853ebef3bb2a", "f4408e6a90334d68861a8fc2ed5f7038", "56215f305d644e7a93c305d450e01225", "35254c66bee34c888a1c16ae1da04dce", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "d38b295d3e9040458298f9800606ff52", "9fb96159ad2e44a08da28cda54ce5d4d", "<KEY>", "<KEY>", "3dd16053bac446139d197a166a8fac0c", "e2922c6a09ee4241b0d22e39b19ec670", "<KEY>", "<KEY>", "da05497dee40414ca7b00ee3cd000c01", "8b599e27240844f2b3375a891d32b6b2", "eed519e895144ccbabd7ddc75ac1f57a", "<KEY>", "d38550bd7afe4dbe9e78c4c0096d82ce", "7a4746224fae412fa151ff139cc24243", "<KEY>", "9534b42982ec464d8e2794ca288411ca", "4981080a64d5439e8214181ccd5210ac", "00a17c008c5147619e4cb3a62f5f39c8"]} outputId="e84d007a-7644-467d-cb74-37147d7f9102" import matplotlib.gridspec as gridspec import os import torch.optim as optim import numpy as np from tqdm.autonotebook import tqdm from itertools import chain enc_dim = 64 image_dim = 784 # [flattened] nEpoch = 10 # construct the encoder, decoder and optimiser enc = Encoder(image_dim, enc_dim) dec = Decoder(enc_dim, image_dim) optimizer = optim.Adam(chain(enc.parameters(), dec.parameters()), lr=1e-3) # training loop for epoch in range(nEpoch): losses = [] trainloader = tqdm(train_loader) for i, data in enumerate(trainloader, 0): inputs, _ = data optimizer.zero_grad() z = enc(inputs) outputs = dec(z) loss = F.binary_cross_entropy(outputs, inputs, reduction='sum') / inputs.shape[0] loss.backward() optimizer.step() # keep track of the loss and update the stats losses.append(loss.item()) trainloader.set_postfix(loss=np.mean(losses), epoch=epoch) # + id="fFiTRa7XFFgA" colab={"base_uri": "https://localhost:8080/", "height": 242} outputId="ae758530-0994-4d8f-d1cb-728a9223cd66" for i in range(8): plt.subplot(int(str(24)+str(i+1))) img = outputs[i].reshape(28,28) plt.imshow(img.detach().numpy(), cmap=plt.get_cmap('gray')) # show the plot plt.show()
Pytorch Practical Tasks/8_1_Autoencoder.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # link dataset: https://www.kaggle.com/muthuj7/weather-dataset import pandas as pd data = pd.read_csv('weatherHistory.csv') data.head() data.shape data["Summary"].value_counts() data["Wind Speed (m/s)"]=data.apply(lambda x: (x["Wind Speed (km/h)"]*1000)/3600, axis=1) data["Visibility (m)"]=data.apply(lambda x: (x["Visibility (km)"]*1000), axis=1) data= data[["Summary", "Temperature (C)", "Humidity", "Wind Speed (m/s)", "Pressure (millibars)"]] data.head() data["Summary"].value_counts() temp = [['sun', 25.21, 0.51, 0.45, 1018], ['sun', 25.79, 0.49, 2.68, 1013], ['sun', 30.09, 0.39, 3, 1008], ['sun', 22.3,0.52,1.24,1011], ['sun', 34.8, 0.18,3.18 ,1015], ["sun", 24.56,0.6, 0.89,1017],["sun",35.96,0.18,3.17,1012], ["sun",26.8, 0.53, 3.05,1015],["sun",30.9, 0.40, 3.69,1010],["sun",31.63,0.25,4.64,1010], ["sun",27.12,0.46,0.89,1013],["sun",33.03,0.31,2.61,1008],["sun",34.83,0.22,1.37,1007],["sun",20.48999, 0.51, 2.68, 1001]] df2 = pd.DataFrame(temp, columns=['Summary', 'Temperature (C)', 'Humidity', 'Wind Speed (m/s)', 'Pressure (millibars)']) df2 sun = data[(data["Summary"] == "Clear")].sample(n = 190) sun=sun.append(df2) sun = sun.append(data[(data["Summary"] == "Clear") & (data["Temperature (C)"] >25)].sample(n = 145)) sun["Summary"] = "sun" print(sun.shape) cloud = data[(data["Summary"] == "Mostly Cloudy")] cloud = cloud.sample(n = 700) cloud["Summary"] = "cloudy" cloud.shape rain = data[(data["Summary"] == "Light Rain") | (data["Summary"] == "Rain") | (data["Summary"] == "Drizzle")] df_copy = data[(data["Summary"] == "Rain")].copy() rain = rain.append(df_copy) rain["Summary"] = "rain" rain.shape final_df = (rain.append(sun)).append(cloud) final_df # + from imblearn.over_sampling import SMOTE oversample = SMOTE() X, y = oversample.fit_resample(final_df[["Temperature (C)","Humidity", "Wind Speed (m/s)", "Pressure (millibars)"]].values, final_df["Summary"].values) # + from collections import Counter counter = Counter(y) print(counter) # + from sklearn.model_selection import train_test_split # Split dataset into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,random_state=0) # 70% training and 30% test # - X_train.shape X_test.shape X_test, X_validation, y_test, y_validation = train_test_split(X_test, y_test, test_size=0.25,random_state=0) # 70% training and 30% test X_validation.shape X_test.shape # + from sklearn import svm #Create a svm Classifier clf = svm.SVC(C= 1000, gamma= 0.01, kernel= 'rbf') #Train the model using the training sets clf.fit(X_train, y_train) # - from sklearn import metrics #Predict the response for test dataset y_pred = clf.predict(X_test) # Model Accuracy: how often is the classifier correct? print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) clf.predict([[35.21, 0.71,0.45,1018]])# correct clf.predict([[17, 0.5, 5.68, 1011]])# wrong --> sun clf.predict([[21.73999, 0.94, 0.9, 1011]])# wrong --> rain # + from micromlgen import port print(port(clf, classmap={ 0: 'cloudy', 1: 'sun', 2: 'rain' })) # + from sklearn.model_selection import GridSearchCV # defining parameter range param_grid = {'C': [0.1, 1, 10, 100, 1000], 'gamma': [1, 0.1, 0.01, 0.001, 0.0001], 'kernel': ['linear', 'rbf', 'sigmoid']} grid = GridSearchCV(svm.SVC(), param_grid, refit = True, verbose = 3) # fitting the model for grid search grid.fit(X_validation, y_validation) # - print(grid.best_params_) print(grid.best_estimator_)
Machine_Learning.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import os import shutil # # 引数の取得 # dir_in='C:/Users/chekolart/Desktop/kabuto_dataset/rotated_data/all' dir_out='C:/Users/chekolart/Desktop/kabuto_dataset/classes' n_steps=8 # # 実行 # if not os.path.exists(dir_out): os.mkdir(dir_out) sub_dirs=[] for i in range(n_steps): str_step='step'+str(i+1).zfill(2) sub_dir=os.path.join(dir_out, str_step) if not os.path.exists(sub_dir): os.mkdir(sub_dir) sub_dirs.append(sub_dir) f_name_list=os.listdir(dir_in) for f_name in f_name_list: tokens = f_name.split('_') step = int(tokens[2]) f_path = os.path.join(dir_in, f_name) f_path_out = os.path.join(sub_dirs[step-1], f_name) shutil.copy2(f_path, f_path_out) # -
data_gen/scripts/seperate_to_sub_dirs.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] tags=[] # # TSG093 - Agent log tail for all containers in BDC # # ## Steps # # ### Parameters # + tags=["parameters"] tail_lines = 100 line_offset = 27 # Skip the date/time at start of line cmd = f'tail -n {tail_lines} /var/log/agent/agent.log' log_analyzer_rules = [ [ "Failed to get file names from controller with Error", "TSG040", 'TSG040 - Failed to get file names from controller with Error', "../repair/tsg040-failed-get-file-names-controller.ipynb"], [ "Please increase sysctl fs.aio-max-nr", "TSG041", 'TSG041 - Unable to create a new asynchronous I/O context (increase sysctl fs.aio-max-nr)', "../repair/tsg041-increase-fs-aio-max-nr.ipynb"] ] coalesce_duplicates = True # + [markdown] tags=[] # ### Analyze log in all pod containers # # ### Instantiate Kubernetes client # + tags=["hide_input"] # Instantiate the Python Kubernetes client into 'api' variable import os from IPython.display import Markdown try: from kubernetes import client, config from kubernetes.stream import stream except ImportError: # Install the Kubernetes module import sys # !{sys.executable} -m pip install kubernetes try: from kubernetes import client, config from kubernetes.stream import stream except ImportError: display(Markdown(f'HINT: Use [SOP059 - Install Kubernetes Python module](../install/sop059-install-kubernetes-module.ipynb) to resolve this issue.')) raise if "KUBERNETES_SERVICE_PORT" in os.environ and "KUBERNETES_SERVICE_HOST" in os.environ: config.load_incluster_config() else: try: config.load_kube_config() except: display(Markdown(f'HINT: Use [TSG118 - Configure Kubernetes config](../repair/tsg118-configure-kube-config.ipynb) to resolve this issue.')) raise api = client.CoreV1Api() print('Kubernetes client instantiated') # + [markdown] tags=[] # ### Get the namespace for the big data cluster # # Get the namespace of the Big Data Cluster from the Kuberenetes API. # # **NOTE:** # # If there is more than one Big Data Cluster in the target Kubernetes # cluster, then either: # # - set \[0\] to the correct value for the big data cluster. # - set the environment variable AZDATA_NAMESPACE, before starting Azure # Data Studio. # + tags=["hide_input"] # Place Kubernetes namespace name for BDC into 'namespace' variable if "AZDATA_NAMESPACE" in os.environ: namespace = os.environ["AZDATA_NAMESPACE"] else: try: namespace = api.list_namespace(label_selector='MSSQL_CLUSTER').items[0].metadata.name except IndexError: from IPython.display import Markdown display(Markdown(f'HINT: Use [TSG081 - Get namespaces (Kubernetes)](../monitor-k8s/tsg081-get-kubernetes-namespaces.ipynb) to resolve this issue.')) display(Markdown(f'HINT: Use [TSG010 - Get configuration contexts](../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb) to resolve this issue.')) display(Markdown(f'HINT: Use [SOP011 - Set kubernetes configuration context](../common/sop011-set-kubernetes-context.ipynb) to resolve this issue.')) raise print('The kubernetes namespace for your big data cluster is: ' + namespace) # + tags=[] from IPython.display import Markdown pod_list = api.list_namespaced_pod(namespace) pod_names = [pod.metadata.name for pod in pod_list.items] for pod in pod_list.items: container_names = [container.name for container in pod.spec.containers] for container in container_names: print (f"*** LOGS for CONTAINER: {container} in POD: {pod.metadata.name}") try: logs=stream(api.connect_get_namespaced_pod_exec, pod.metadata.name, namespace, command=['/bin/sh', '-c', cmd], container=container, stderr=True, stdout=True) if coalesce_duplicates: previous_line = "" duplicates = 1 for line in logs.split('\n'): if line[line_offset:] != previous_line[line_offset:]: if duplicates != 1: print(f"\t{previous_line} (x{duplicates})") print(f"\t{line}") for rule in rules: if line[line_offset:].find(rule[0]) != -1: display(Markdown(f'HINT: Use [{rule[2]}](rule[3]) to resolve this issue.')) duplicates = 1 else: duplicates = duplicates + 1 continue previous_line = line else: print(logs) except Exception: print (f"Failed to get LOGS for CONTAINER: {container} in POD: {pod.metadata.name}") # + tags=[] print("Notebook execution is complete.")
Big-Data-Clusters/CU9/public/content/log-analyzers/tsg093-get-all-agent-log-tails.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import tensorflow as tf from tensorflow.contrib.slim import fully_connected as fc # pylint: disable=E0611 import os import errno import scedar as sce import argparse import pandas as pd from timeit import default_timer as timer import utils data = pd.read_csv('/Users/dawnstear/desktop/chop_cellpred/data.csv') sclabels = data['Labels'] scdata = data.drop(['Labels','TYPE'],axis=1) DataObj = utils.Data(scdata,sclabels,drop_remainder=True) assert not np.any(np.isnan(scdata)) assert not np.any(np.isnan(sclabels)) maxval = np.amax(scdata) scdata = (scdata+1e-7)/maxval # + class VariantionalAutoencoder(object): '''VAE implementation from https://github.com/shaohua0116/VAE-Tensorflow ''' def __init__(self, input_dim, nelfirst, nelsecond, ndlfirst, ndlsecond, n_z=2, learning_rate=1e-3, batch_size=100): self.input_dim = input_dim self.nelfirst = nelfirst self.nelsecond = nelsecond self.ndlfirst = ndlfirst self.ndlsecond = ndlsecond self.learning_rate = learning_rate self.batch_size = batch_size self.n_z = n_z self.build() config = tf.ConfigProto() config.gpu_options.allow_growth=True # pylint: disable=E1101 self.sess = tf.InteractiveSession(config=config) self.sess.run(tf.global_variables_initializer()) # Build the netowrk and the loss functions def build(self): self.x = tf.placeholder(name='x', dtype=tf.float32, shape=[None, self.input_dim]) # Encode # x -> z_mean, z_sigma -> z f1 = fc(self.x, self.nelfirst, scope='enc_fc1', activation_fn=tf.nn.elu) f2 = fc(f1, self.nelsecond, scope='enc_fc2', activation_fn=tf.nn.elu) self.z_mu = fc(f2, self.n_z, scope='enc_fc3_mu', activation_fn=None) self.z_log_sigma_sq = fc(f2, self.n_z, scope='enc_fc3_sigma', activation_fn=None) eps = tf.random_normal(shape=tf.shape(self.z_log_sigma_sq), mean=0, stddev=1, dtype=tf.float32) self.z = self.z_mu + tf.sqrt(tf.exp(self.z_log_sigma_sq)) * eps # Decode # z -> x_hat g1 = fc(self.z, self.ndlfirst, scope='dec_fc1', activation_fn=tf.nn.elu) g2 = fc(g1, self.ndlsecond, scope='dec_fc2', activation_fn=tf.nn.elu) self.x_hat = fc(g2, self.input_dim, scope='dec_fc3', activation_fn=tf.sigmoid) # Loss # Reconstruction loss # Minimize the cross-entropy loss # H(x, x_hat) = -\Sigma x*log(x_hat) + (1-x)*log(1-x_hat) epsilon = 1e-6 recon_loss = -tf.reduce_sum( self.x * tf.log(epsilon+self.x_hat) + (1-self.x) * tf.log(epsilon+1-self.x_hat), axis=1 ) self.recon_loss = tf.reduce_mean(recon_loss) # Latent loss # Kullback Leibler divergence: measure the difference between # two distributions Here we measure the divergence between the latent # distribution and N(0, 1) latent_loss = -0.5 * tf.reduce_sum( 1 + self.z_log_sigma_sq - tf.square(self.z_mu) - tf.exp(self.z_log_sigma_sq), axis=1) self.latent_loss = tf.reduce_mean(latent_loss) self.total_loss = tf.reduce_mean(recon_loss + latent_loss) self.train_op = tf.train.AdamOptimizer( learning_rate=self.learning_rate).minimize(self.total_loss) return # Execute the forward and the backward pass def run_single_step(self, x): _, loss, recon_loss, latent_loss = self.sess.run( [self.train_op, self.total_loss, self.recon_loss, self.latent_loss], feed_dict={self.x: x} ) return loss, recon_loss, latent_loss # x -> x_hat def reconstruct(self, x): x_hat = self.sess.run(self.x_hat, feed_dict={self.x: x}) return x_hat # z -> x def generate(self, z): x_hat = self.sess.run(self.x_hat, feed_dict={self.z: z}) return x_hat # x -> z def transform(self, x): z = self.sess.run(self.z, feed_dict={self.x: x}) return z def train(train_data, nelfirst, nelsecond, ndlfirst, ndlsecond, learning_rate=1e-5, batch_size=100, num_epoch=75): input_dim = train_data.shape[1] n_samples = train_data.shape[0] model = VariantionalAutoencoder( input_dim, nelfirst, nelsecond, ndlfirst, ndlsecond, n_z=2, learning_rate=learning_rate, batch_size=batch_size) for epoch in range(num_epoch): for i in range(n_samples // batch_size): # Obtina a batch batch = train_data[i*batch_size:(i+1)*batch_size] # Execute the forward and the backward pass and report computed losses loss, recon_loss, latent_loss = model.run_single_step(batch) if epoch % 5 == 0: print('[Epoch {}] Loss: {}, Recon loss: {}, Latent loss: {}'.format( epoch, loss, recon_loss, latent_loss)) print('Done!') return model # + train_start = timer() vae = train(scdata, 20, 20, 20, 20, 1e-11, batch_size=100, num_epoch=11) train_end = timer() train_time = train_end - train_start trans_start = timer() z = vae.transform(scdata) print(np.shape(z)) trans_end = timer() trans_time = trans_end - trans_start fig = sce.eda.cluster_scatter(z, labels=labels, s=50, figsize=(15, 7), n_txt_per_cluster=0, alpha=0.6) # - z
autoencoder_models/vae-yuanchao.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # QCArchive Interface # # Here we show how to create OpenFF molecules safely from data in the QCArchive using the cmiles entries, specifically we want to use the canonical_isomeric_explicit_hydrogen_mapped_smiles data which is metadata stored at the entry-level of a collection. # # First load up the client you wish to connect to, in this case, we use the public instance. # + import qcportal as ptl from openff.toolkit.topology import Molecule client= ptl.FractalClient() # list the collections available client.list_collections() # - # Now let us grab a molecule from an optimization dataset ds = client.get_collection('OptimizationDataset', 'Kinase Inhibitors: WBO Distributions') # Take the first entry from the collection. entry = ds.get_entry(ds.df.index[0]) # We can view the entry in detail by looking at the dictionary representation. entry.dict() # Now we can make a molecule using a few different input options. # + # first make a molecule using this record object mol_record = Molecule.from_qcschema(entry) # we could have also used the dictionary representation of the object mol_dict = Molecule.from_qcschema(entry.dict(encoding='json')) # + # we check that the molecule has been ordered to match the ordering used in the data base # by printing out the atomic numbers of both objects in order # first lets get the initial molecule from the database initial_mol = client.query_molecules(id=entry.initial_molecule)[0] for atoms in zip(mol_record.atoms, initial_mol.atomic_numbers): print(atoms[0].atomic_number, atoms[1]) # we can also check that the molecules are the same regardless of how they are made assert mol_dict == mol_record # + # we can also compare the graph representations of the molecules to make sure they are in the same order import networkx as nx # make a graph of the initial molecule using newtorkx and the data in the record initial_network = nx.Graph() for i, atom_num in enumerate(initial_mol.atomic_numbers): initial_network.add_node(i, atomic_number=atom_num) for bond in initial_mol.connectivity: initial_network.add_edge(*bond[:2]) # now we can use the new isomorphic check to get the atom mapping isomorphic, atom_map = Molecule.are_isomorphic(mol_record, initial_network, return_atom_map=True, aromatic_matching=False, formal_charge_matching=False, bond_order_matching=False, bond_stereochemistry_matching=False, atom_stereochemistry_matching=False) # we can print if the graph was found to be isomorphic and then the atom mapping # the atoms are in the same order here as the idexes are the same in the mapping print(isomorphic) print(atom_map) # - # Now that we have seen how to make the molecule, lets look at also getting the geometry as currently we have none. # + # check there is no geometry for the molecule assert mol_record.n_conformers == 0 # if we also want the input geometry for the molecule, we just need to pass the relavent client instance mol_dict = Molecule.from_qcschema(entry.dict(encoding='json'), client=client) # check that there is a conformer mol_dict.n_conformers # - # Thanks to the qcschema method we also get visualisation for free, along with being able to compute # properties like energy, gradient and hessian with qcengine using QM, rdkit, openmm, or ANI1 mol_dict.to_qcschema() # Here we will try and compute the energy using RDKit (only run this cell if qcengine is installed.) # + # for example this molecules energy can be computed using qcengine and RDKit import qcengine from openff.toolkit.typing.engines.smirnoff import ForceField # set up the RDKit task rdkit_task = {"schema_name": "qcschema_input", "schema_version": 2, "molecule": mol_dict.to_qcschema(), "driver": "energy", "model": {"method": 'uff', "basis": None}, "keywords": {"scf_type": "df"}} # now lets compute the energy using qcengine and RDKit and print the result result = qcengine.compute(rdkit_task, 'rdkit') # - # note the result is in QC units of hartrees print(result.return_result)
examples/QCArchive_interface/QCarchive_interface.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.8.10 64-bit # name: python3 # --- from sklearn import tree import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.ensemble import RandomForestClassifier np.random.seed(0) rf = RandomForestClassifier(10, max_depth=5) heart = pd.read_csv('../data/heart.csv') heart.head() X = heart.drop(['target'], axis=1) y=heart.target rf.fit(X, y) imp = pd.DataFrame(rf.feature_importances_, index=X.columns, columns=['importance']) imp.sort_values('importance').plot(kind='barh', figsize=(12, 8))
2/heart.ipynb