markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
(3) Internações por dia em cada município
from datetime import date datas = pd.date_range(date(2018,7,1), periods=365).tolist() lst_mun_ba = list(mun_ba['GEOCODIGO'].apply(lambda x: x[:-1]).values) datas[0] datas[-1] # Entraram em alguma data até 30/06/2019 e saíram entre 01/07/2018 até 30/06/2019 df2[(df2['DT_Inter'] <= datas[-1]) & (df2['DT_Saida'] >= datas[...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
* **Série temporal para todos os municípios:**
ba_int = pd.DataFrame(index=datas, columns=mun_ba['GEOCODIGO'].apply(lambda x: x[:-1]).values) list_mun = list(mun_ba['GEOCODIGO'].apply(lambda x: x[:-1]).values) for i, row in ba_int.iterrows(): for mun in list_mun: row[mun] = len(df2[(df2['DT_Inter'] <= i) & (df2['DT_Saida'] >= i) & (df2['Cod_Municipio'] ...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4) Padrão Origem-Destino das Internações
df.info() per = pd.date_range(date(2018,7,1), periods=365).tolist() per[0] per[-1] # Entraram em alguma data até 30/06/2019 e saíram entre 01/07/2018 até 30/06/2019 df_BA = df2[(df2['DT_Inter'] <= per[-1]) & (df2['DT_Saida'] >= per[0]) & (df2['DT_Saida'] <= per[-1]) & (df2['Cod_Municipio_Res'].str.startswith('29'))] #d...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4.1) Principais centros de internação hospitalar (origens mais demandadas)
tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascending = False)['Qtd'].sum() tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascending = False)[:20]
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
Proporção:
tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascending = False)[:50]['Qtd']/tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascending = False)['Qtd'].sum() (tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascending = False)[:50]['Qtd']/tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascen...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4.2) Municípios mais atendidos pelos principais centros de internação hospitalar
mun_ba.loc[mun_ba['GEOCODIGO'].isin(tab_OD['DES_GC'].astype(str))][['NOME','NOMEABREV','geometry']] idx = list(tab_OD.groupby(['DES_GC']).sum().sort_values(by='Qtd', ascending = False)[:10]['Qtd'].index)
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
20 municípios mais atendidos dos 10 maiores centros de atendimento
for k in np.arange(len(idx)): mun_ba[mun_ba['GEOCODIGO']==idx[k]]['NOME'].values[0] #Nome tab_OD[tab_OD['DES_GC']==idx[k]].sort_values(by='Qtd', ascending = False)['Qtd'].sum() #Quantidade de internações tab_OD[tab_OD['DES_GC']==idx[k]].sort_values(by='Qtd', ascending = False)['Qtd'][:20].sum() \ /tab_O...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4.3) Análise da Pandemia no NRS Sul: **Núcleos Regionais de Saúde:**
nrs = gpd.read_file('NT02 - Bahia/Oferta Hospitalar/SESAB - NUCLEO REG SAUDE - 20190514 - SIRGAS2000.shp') nrs = nrs.to_crs(CRS("WGS84")); nrs.crs mun_ba.crs == nrs.crs nrs mun_ba['NRS'] = 0 for i in list(nrs.index): mun_ba.loc[mun_ba['geometry'].apply(lambda x: x.centroid.within(nrs.loc[i,'geometry'])),'NRS'] = nr...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
População
for i in nrs['NM_NRS'].values: print(i,mun_ba[mun_ba['NRS']==i]['Pop'].sum()) mun_ba['Qtd_Tot'].sum() nrs.to_file('NT02 - Bahia/nrs.shp')
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Municípios com maior prevalência:**
fig, ax = plt.subplots(figsize=(10,10)); mun_ba.plot(ax = ax, column = 'prev'); plt.show(); # 20 maiores do Estado: mun_ba.sort_values(by='prev', ascending = False)[['GEOCODIGO','NOME','Pop','prev','NRS']][:20] # Quantidade de municípios no NRS Sul que já possuem casos confirmados até 24/04/2020 len(mun_ba[(mun_ba['NRS...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4.4) Oferta Hospitalar no NRS Sul **Leitos convencionais:**
leitos = pd.read_excel('NT02 - Bahia/Oferta Hospitalar/leitos.xlsx') leitos.info() leitos.head(2)
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Leitos complementares:**
leitos_c = pd.read_excel('NT02 - Bahia/Oferta Hospitalar/leitos_comp.xlsx') leitos_c.info() leitos_c.head(2)
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Leitos adicionados pós COVID:**
leitos_add = pd.read_excel('NT02 - Bahia/Oferta Hospitalar/leitos_add.xlsx') leitos_add.info() leitos_add.head(2)
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Respiradores:**
resp = pd.read_excel('NT02 - Bahia/Oferta Hospitalar/respiradores.xlsx') resp.info() resp.head(2)
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Profissionais:**
prof = pd.read_excel('NT02 - Bahia/Oferta Hospitalar/profissionais.xlsx') prof.info() prof.head(2)
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Adicionando à `mun_ba`:**
mun_ba['L_Clin'] = 0 mun_ba['L_UTI_Adu'] = 0 mun_ba['L_UTI_Ped'] = 0 mun_ba['L_CInt_Adu'] = 0 mun_ba['L_CInt_Ped'] = 0 mun_ba['LA_Clin'] = 0 mun_ba['LA_UTI_Adu'] = 0 mun_ba['Resp'] = 0 mun_ba['M_Pneumo'] = 0 mun_ba['M_Familia'] = 0 mun_ba['M_Intens'] = 0 mun_ba['Enferm'] = 0 mun_ba['Fisiot'] = 0 mun_ba['Nutric'] = 0 fo...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4.5) Dinâmica do Fluxo de Internaçõe no NRS Sul **(a) Recursos:**
#.isin(mun_ba[mun_ba['NRS']=='Sul']['NOME'].values) nrs_rec = mun_ba[['NRS','Pop','L_Clin','L_UTI_Adu','L_UTI_Ped','L_CInt_Adu','L_CInt_Ped','LA_Clin','LA_UTI_Adu','Resp','M_Pneumo','M_Familia','M_Intens','Enferm','Fisiot','Nutric']].groupby(['NRS']).sum() pd.DataFrame(zip(10000*nrs_rec['L_Clin']/nrs_rec['Pop'],10000*n...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**(b) Internações hospitalares:** **Interdependência entre NRS's (Matriz OD):**
nrs_names = list(nrs['NM_NRS'].values) nrs_OD = np.zeros([len(nrs_names),len(nrs_names)]) for i, nrs_o in enumerate(nrs_names): muns_o = list(mun_ba[mun_ba['NRS']==nrs_o]['GEOCODIGO'].values) for j, nrs_d in enumerate(nrs_names): muns_d = list(mun_ba[mun_ba['NRS']==nrs_d]['GEOCODIGO'].values) nr...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**P/ cada NRS:**
#Municípios de cada NRS for i in list(nrs['NM_NRS'].values): muns = list(mun_ba[mun_ba['NRS']==i]['NOME'].values) muns_gc = list(mun_ba[mun_ba['NRS']==i]['GEOCODIGO'].values) "NRS "+i+":" "Total de internações: {}".format(tab_OD[tab_OD['DES_GC'].isin(muns_gc)]['Qtd'].sum()) "Proporção de internações...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Dependência do NRS Leste:**
muns = [i for i in list(nrs['NM_NRS'].values) if i!='Leste'] for i in muns: muns_gc = list(mun_ba[mun_ba['NRS']==i]['GEOCODIGO'].values) muns_le = list(mun_ba[mun_ba['NRS']=='Leste']['GEOCODIGO'].values) "Internações de residentes do {} = {}".format(i,tab_OD[tab_OD['ORI_GC'].isin(muns_gc) ...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
**Análise do NRS Sul (maior qtd de casos acumulados):**
#Municípios do NRS Sul mun_sul = list(mun_ba[mun_ba['NRS']=='Sul']['NOME'].values) mun_sul_gc = list(mun_ba[mun_ba['NRS']=='Sul']['GEOCODIGO'].values) # Todas as internações demandadas pelos municípios do NRS Sul tab_OD[tab_OD['ORI_GC'].isin(mun_sul_gc)].sort_values(by='Qtd', ascending = False) # Todas as internações ...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
(4.6) Fluxo de Internações dos 10 municípios mais prevalentes do NRS Sul:
mun_sul = list(mun_ba[mun_ba['NRS']=='Sul'].sort_values(by='prev', ascending = False)['GEOCODIGO'].values) for i in mun_sul[:10]: orig = [] lst_orig = tab_OD[tab_OD['DES_GC']==i].sort_values(by = 'Qtd', ascending = False)['ORI_GC'].values if len(lst_orig) == 0: "{} não recebeu pacientes".format(mun_...
_____no_output_____
MIT
NT02-Bahia (NRS Sul).ipynb
pedreirajr/GeoCombatCOVID19
Assignment 2 Set 5Image CaptioningDeep Learning (S1-21_DSECLZG524) - DL Group 037 - SEC-3* Arindam Dey - 2020FC04251* Kaushik Dubey - 2020FC04245* Mohammad Attaullah - 2020FC04274 1. Import Libraries/Dataset (0 mark) 1. Import the required libraries 2. Check the GPU available (recommended- use free GPU provided by ...
import os #COLAB_GPU #print(os.environ ) isCollab = os.getenv('COLAB_GPU', False) and os.getenv('OS', True) print('Collab' if isCollab else 'Local') #libraries import numpy as np import pandas as pd import random # folder import os # Imports packages to view data #pip install opencv-python #pip install opencv-contr...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
2. Data Processing(1 mark) Read the pickle file
if isCollab: drivemasterpath = '/content/drive/My Drive/Colab Notebooks/AutoImageCaptioning' else: drivemasterpath = 'D:/OneDrive/Certification/Bits Pilani Data Science/3rd Sem/Deep Learning (S1-21_DSECLZG524)/Assignment 2' imgDatasetPath = drivemasterpath+"/Flicker8k_Dataset" pklFilePath = drivemasterpath+'/se...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
Plot at least two samples and their captions (use matplotlib/seaborn/any other library).
pics = os.listdir(imgDatasetPath)[25:30] # for 5 images we are showing pic_address = [imgDatasetPath + '/' + pic for pic in pics] pic_address for i in range(0,5): # Load the images norm_img = Image.open(pic_address[i]) #Let's plt these images ## plot normal picture f = plt.figure(figsize= (10,6)) ...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
3. Model Building (4 mark) 1. Use Pretrained VGG-16 model trained on ImageNet dataset (available publicly on google) for image feature extraction.2. Create 3 layered LSTM layer model and other relevant layers for image caption generation.3. Add L2 regularization to all the LSTM layers. 4. Add one layer of dropout at t...
image_model = VGG16(include_top=True, weights='imagenet') image_model.summary() transfer_layer = image_model.get_layer('fc2') image_model_transfer = Model(inputs=image_model.input, outputs=transfer_layer.output)
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
The model expects input images to be of this size:
img_size = K.int_shape(image_model.input)[1:3] img_size transfer_values_size = K.int_shape(transfer_layer.output)[1] transfer_values_size
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
Process All ImagesWe now make functions for processing all images in the data-set using the pre-trained image-model and saving the transfer-values in a cache-file so they can be reloaded quickly.We effectively create a new data-set of the transfer-values. This is because it takes a long time to process an image in the ...
import keras,os from keras.models import Sequential from keras.layers import Dense, Conv2D, MaxPool2D , Flatten from keras.preprocessing.image import ImageDataGenerator import numpy as np trdata = ImageDataGenerator() traindata = trdata.flow_from_directory(directory="data",target_size=(224,224)) tsdata = ImageDataGene...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
This is the function for processing the given files using the VGG16-model and returning their transfer-values.
def process_images(data_dir, filenames, batch_size=32): """ Process all the given files in the given data_dir using the pre-trained image-model and return their transfer-values. Note that we process the images in batches to save memory and improve efficiency on the GPU. """ # Numbe...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
Helper-function for processing all images in the training-set. This saves the transfer-values in a cache-file for fast reloading.
def process_images_train(): print("Processing {0} images in training-set ...".format(len(filenames_train))) # Path for the cache-file. cache_path = os.path.join(coco.data_dir, "transfer_values_train.pkl") # If the cache-file already exists then reload it, # otherwise ...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
Helper-function for processing all images in the validation-set.
def process_images_val(): print("Processing {0} images in validation-set ...".format(len(filenames_val))) # Path for the cache-file. cache_path = os.path.join(coco.data_dir, "transfer_values_val.pkl") # If the cache-file already exists then reload it, # otherwise process all images and save their ...
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
Process all images in the training-set and save the transfer-values to a cache-file. This took about 30 minutes to process on a GTX 1070 GPU.
%%time transfer_values_train = process_images_train() print("dtype:", transfer_values_train.dtype) print("shape:", transfer_values_train.shape)
_____no_output_____
Apache-2.0
Group_037_SEC_3_Assignment_2_Image_Captioning.ipynb
arindamdeyofficial/Amazon_Review_Sentiment_Analysys
Parameter extraction
# Stride length and stride duration print("len(disp_abs_all):", len(disp_abs_all)) print("disp_abs_all[0].shape:", disp_abs_all[0].shape) import copy from scipy import signal disp_abs_all_savgol = copy.deepcopy(disp_abs_all) file_id = 0 seg = 0 disp_abs_all_savgol[file_id][seg][:,1] = signal.savgol_filter(disp_abs_al...
_____no_output_____
Unlicense
Locomotion dynamcis/1_Kinemtaics_201102.ipynb
AlbertLordsun/Physical_measurement
Thematic ReportsThematic reports run historical analyses on the exposure of a portfolio to various Goldman Sachs Flagship Thematic baskets over a specified date range. PrerequisiteTo execute all the code in this tutorial, you will need the following application scopes:- **read_product_data**- **read_financial_data**- ...
import datetime as dt from time import sleep from gs_quant.markets.baskets import Basket from gs_quant.markets.report import ThematicReport from gs_quant.session import GsSession, Environment client = None secret = None scopes = None ## External users must fill in their client ID and secret below and comment out the...
_____no_output_____
Apache-2.0
gs_quant/documentation/10_one_delta/reports/Thematic Report.ipynb
daniel-schreier/gs-quant
Step 2: Create a New Thematic Report Already have a thematic report?If you want to skip creating a new report and continue this tutorial with an existing thematic report, run the following and skip to Step 3:
thematic_report_id = 'ENTER THEMATIC REPORT ID' thematic_report = ThematicReport.get(thematic_report_id)
_____no_output_____
Apache-2.0
gs_quant/documentation/10_one_delta/reports/Thematic Report.ipynb
daniel-schreier/gs-quant
The only parameter necessary in creating a new thematic report is the unique Marquee identifier of the portfolio on which you would like to run thematic analytics.
portfolio_id = 'ENTER PORTFOLIO ID' thematic_report = ThematicReport(position_source_id=portfolio_id) thematic_report.save() print(f'A new thematic report for portfolio "{portfolio_id}" has been made with ID "{thematic_report.id}".')
_____no_output_____
Apache-2.0
gs_quant/documentation/10_one_delta/reports/Thematic Report.ipynb
daniel-schreier/gs-quant
Step 3: Schedule the ReportWhen scheduling reports, you have two options:- Backcast the report: Take the earliest date with positions in the portfolio / basket and run the report on the positions held then with a start date before the earliest position date and an end date of the earliest position date- Do not backcas...
start_date = dt.date(2021, 1, 4) end_date = dt.date(2021, 8, 4) thematic_report.schedule( start_date=start_date, end_date=end_date, backcast=False ) print(f'Report "{thematic_report.id}" has been scheduled.')
_____no_output_____
Apache-2.0
gs_quant/documentation/10_one_delta/reports/Thematic Report.ipynb
daniel-schreier/gs-quant
Alternative Step 3: Run the ReportDepending on the size of your portfolio and the length of the schedule range, it usually takes anywhere from a couple seconds to half a minute for your report to finish executing.Only after that can you successfully pull the results from that report. If you would rather run the report...
start_date = dt.date(2021, 1, 4) end_date = dt.date(2021, 8, 4) report_result_future = thematic_report.run( start_date=start_date, end_date=end_date, backcast=False, is_async=True ) while not report_result_future.done(): print('Waiting for report results...') sleep(5) print('\nReport results ...
_____no_output_____
Apache-2.0
gs_quant/documentation/10_one_delta/reports/Thematic Report.ipynb
daniel-schreier/gs-quant
Step 3: Pull Report ResultsNow that we have our factor risk report, we can leverage the unique functionalities of the `ThematicReport` class to pull exposure and PnL data. Let's get the historical changes in thematic exposure and beta to the GS Asia Stay at Home basket:
basket = Basket.get('GSXASTAY') thematic_exposures = thematic_report.get_thematic_data( start_date=start_date, end_date=end_date, basket_ids=[basket.get_marquee_id()] ) print(f'Thematic Exposures: \n{thematic_exposures.__str__()}') thematic_exposures.plot(title='Thematic Data Breakdown')
_____no_output_____
Apache-2.0
gs_quant/documentation/10_one_delta/reports/Thematic Report.ipynb
daniel-schreier/gs-quant
The Generator The generator, G, is designed to map the latent space vector (z) to data-space. Since our data are images, converting z to data-space means ultimately creating a RGB image with the same size as the training images (i.e. 3x32x32). In practice, this is accomplished through a series of strided two dimension...
# Generator Code class Generator(nn.Module): def __init__(self, ngpu): super(Generator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2...
_____no_output_____
MIT
Deep-Fake-knu-2020/Part_2-Generative-Adversarial-Networks/dc-gan-tutorial.ipynb
kryvokhyzha/examples-and-courses
The DiscriminatorAs mentioned, the discriminator, D, is a binary classification network that takes an image as input and outputs a scalar probability that the input image is real (as opposed to fake). Here, D takes a 3x64x64 input image, processes it through a series of Conv2d, BatchNorm2d, and LeakyReLU layers, and o...
class Discriminator(nn.Module): def __init__(self, ngpu): super(Discriminator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is (nc) x 64 x 64 nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), # st...
_____no_output_____
MIT
Deep-Fake-knu-2020/Part_2-Generative-Adversarial-Networks/dc-gan-tutorial.ipynb
kryvokhyzha/examples-and-courses
Looking at the Pictures*Curtis Miller*In this notebook we see the images in our dataset and create some helper tools for managing the data. First, let's load in the needed libraries.
import numpy as np import pandas as pd import cv2 import matplotlib.pyplot as plt import matplotlib %matplotlib inline
_____no_output_____
MIT
LookingPictures.ipynb
PacktPublishing/Applications-of-Statistical-Learning-with-Python
The faces are stored in a CSV file `fer2013.csv`, loaded in next.
faces = pd.read_csv("fer2013.csv") faces faces.Usage.value_counts()
_____no_output_____
MIT
LookingPictures.ipynb
PacktPublishing/Applications-of-Statistical-Learning-with-Python
The faces themselves are in the `pixels` column of the `DataFrame`, in a string. We want to convert the faces to NumPy 48x48 arrays that can be plotted with matplotlib. The values themselves are the intensities of grayscale pixels. We split the strings on spaces and convert characters to their corresponding numbers, re...
def string_to_image(pixelstring): return np.array(pixelstring.split(' '), dtype=np.int16).reshape(48, 48) plt.imshow(string_to_image(faces.pixels[0])) plt.imshow(string_to_image(faces.pixels[8]))
_____no_output_____
MIT
LookingPictures.ipynb
PacktPublishing/Applications-of-Statistical-Learning-with-Python
As humans we would like to know what the codes in the `emotion` column represent. The following dictionary defines the mapping. We won't use it in training but it's useful when presenting.
emotion_code = {0: "angry", 1: "disgust", 2: "fear", 3: "happy", 4: "sad", 5: "surprise", 6: "neutral"}
_____no_output_____
MIT
LookingPictures.ipynb
PacktPublishing/Applications-of-Statistical-Learning-with-Python
Stochastic Block Model Experiment Before geting into the experiment details, let's review algorithm 1 and the primal and dual updates. Algorithm 1 ![title](../algorithm1.png)
# %load algorithm/main.py %time from sklearn.metrics import mean_squared_error from penalty import * def algorithm_1(K, D, weight_vec, datapoints, true_labels, samplingset, lambda_lasso, penalty_func_name='norm1', calculate_score=False): ''' :param K: the number of iterations :param D: the block incidenc...
CPU times: user 3 µs, sys: 1e+03 ns, total: 4 µs Wall time: 7.15 µs
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Primal Update As you see in the algorithm picture, the primal update needs a optimizer operator for the sampling set (line 6). We have implemented the optimizers discussed in the paper, both the logistic loss and squared error loss optimizers implementations with pytorch is available, also we have implemented the squ...
# %load algorithm/optimizer.py import torch import abc import numpy as np from abc import ABC # The linear model which is implemented by pytorch class TorchLinearModel(torch.nn.Module): def __init__(self, n): super(TorchLinearModel, self).__init__() self.linear = torch.nn.Linear(n, 1, bias=False...
_____no_output_____
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Dual Update As mentioned in the paper, the dual update has a penalty function(line 10) which is either norm1, norm2, or mocha.
# %load algorithm/penalty.py import abc import numpy as np from abc import ABC # The abstract penalty function which has a function update class Penalty(ABC): def __init__(self, lambda_lasso, weight_vec, Sigma, n): self.lambda_lasso = lambda_lasso self.weight_vec = weight_vec self.Sigma =...
_____no_output_____
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Create SBM Graph The stochastic block model is a generative model for random graphs with some clusters structure. Two nodes within the same cluster of the empirical graph are connected by an edge with probability pin, two nodes from different clusters are connected by an edge with probability pout. Each node $i \in V$...
from optimizer import * from torch.autograd import Variable #from graspy.simulations import sbm def get_sbm_data(cluster_sizes, G, W, m=5, n=2, noise_sd=0, is_torch_model=True): ''' :param cluster_sizes: a list containing the size of each cluster :param G: generated SBM graph with defined clusters using g...
_____no_output_____
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Compare Results As the result we compare the MSE of Algorithm 1 with plain linear regression and decision tree regression
# %load results/compare_results.py import numpy as np from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error def get_algorithm1_MSE(datapoints, predicted_w, samplingset): ''' :param datapoints: a dictionary containing th...
_____no_output_____
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
SBM with Two Clusters This SBM has two clusters $|C_1| = |C_2| = 100$.Two nodes within the same cluster are connected by an edge with probability `pin=0.5`, and two nodes from different clusters are connected by an edge with probability `pout=0.01`. Each node $i \in V$ represents a local dataset consisting of feature ...
#from graspy.simulations import sbm import networkx as nx def get_sbm_2blocks_data(m=5, n=2, pin=0.5, pout=0.01, noise_sd=0, is_torch_model=True): ''' :param m, n: shape of features vector for each node :param pin: the probability of edges inside each cluster :param pout: the probability of edges betw...
_____no_output_____
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Plot the MSE with respect to the different random sampling sets for each penalty function, the plots are in the log scale
%time import random import matplotlib.pyplot as plt from collections import defaultdict PENALTY_FUNCS = ['norm1', 'norm2', 'mocha'] LAMBDA_LASSO = {'norm1': 0.01, 'norm2': 0.01, 'mocha': 0.05} K = 1000 B, weight_vec, true_labels, datapoints = get_sbm_2blocks_data(pin=0.5, pout=0.01, is_torch_model=False) E, N = ...
CPU times: user 3 µs, sys: 1 µs, total: 4 µs Wall time: 26.9 µs algorithm 1, norm1: mean train MSE: 8.845062633626295e-06 mean test MSE: 8.411817666751793e-06 algorithm 1, norm2: mean train MSE: 8.937548539721603e-06 mean test MSE: 8.583071087032906e-06 algorithm 1, mocha: mean train MSE: 0.001154871491241519...
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Plot the MSE with respect to the different noise standard deviations (0.01, 0.1, 1.0) for each penalty function, as you can see algorithm 1 is somehow robust to the noise.
%time import random import matplotlib.pyplot as plt PENALTY_FUNCS = ['norm1', 'norm2', 'mocha'] lambda_lasso = 0.01 K = 20 sampling_ratio = 0.6 pouts = [0.01, 0.1, 0.2, 0.4, 0.6] colors = ['steelblue', 'darkorange', 'green'] for penalty_func in PENALTY_FUNCS: print('penalty_func:', penalty_func) for i, no...
CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 29.3 µs penalty_func: norm1 noise 0.01 MSEs: {0.01: 2.705315973442155, 0.1: 2.8803085633466834, 0.2: 3.123534394242319, 0.4: 3.118645741846799, 0.6: 3.2209511562160515} noise 0.1 MSEs: {0.01: 2.858618729737168, 0.1: 2.8760340056295552, 0.2: 3.0985472679149177, 0...
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
Plot the MSE with respect to the different sampling ratios (0.2, 0.4, 0.6) for each penalty function
import random import matplotlib.pyplot as plt PENALTY_FUNCS = ['norm1', 'norm2', 'mocha'] lambda_lasso = 0.01 K = 30 sampling_ratio = 0.6 pouts = [0.01, 0.1, 0.2, 0.4, 0.6] colors = ['steelblue', 'darkorange', 'green'] for penalty_func in PENALTY_FUNCS: print('penalty_func:', penalty_func) for i, samplin...
penalty_func: norm1 M: 0.2 MSE: {0.01: 6.011022085530584, 0.1: 5.854915785166783, 0.2: 6.136745451677013, 0.4: 6.165292827085321, 0.6: 6.495651188025879} M: 0.4 MSE: {0.01: 4.224003404596983, 0.1: 4.423759609325218, 0.2: 4.394123644502406, 0.4: 4.516906390091848, 0.6: 4.494963955858758} M: 0.6 MSE: {0.01: 2.70743745325...
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
SBM with Five Clusters The size of the clusters are {70, 10, 50, 100, 150} with random weight vectors $\in R^2$ selected uniformly from $[0,1)$. We run Algorithm 1 with a fixed `pin = 0.5` and `pout = 0.001`, and a fixed number of 1000 iterations. Each node $i \in V$ represents a local dataset consisting of feature ve...
from graspy.simulations import sbm def get_sbm_5blocks_data(m=5, n=2, pin=0.5, pout=0.01, noise_sd=0, is_torch_model=True): ''' :param m, n: shape of features vector for each node :param pin: the probability of edges inside each cluster :param pout: the probability of edges between the clusters :p...
_____no_output_____
MIT
SBM_experiment.ipynb
YuTian8328/flow-based-clustering
E2E ML on GCP: MLOps stage 3 : formalization: get started with custom training pipeline components View on GitHub Open in Google Cloud Notebooks OverviewThis tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : f...
ONCE_ONLY = False if ONCE_ONLY: ! pip3 install -U tensorflow==2.5 $USER_FLAG ! pip3 install -U tensorflow-data-validation==1.2 $USER_FLAG ! pip3 install -U tensorflow-transform==1.2 $USER_FLAG ! pip3 install -U tensorflow-io==0.18 $USER_FLAG ! pip3 install --upgrade google-cloud-aiplatform[tensorboa...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Restart the kernelOnce you've installed the additional packages, you need to restart the notebook kernel so it can find the packages.
import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True)
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Set your project ID**If you don't know your project ID**, you may be able to get your project ID using `gcloud`.
PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:"...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
RegionYou can also change the `REGION` variable, which is used for operationsthroughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.- Americas: `us-central1`- Europe: `europe-west4`- Asia Pacific: `asia-east1`You may not use a multi-regi...
REGION = "us-central1" # @param {type: "string"}
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
TimestampIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial.
from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Create a Cloud Storage bucket**The following steps are required, regardless of your notebook environment.**When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.Se...
BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.
! gsutil mb -l $REGION $BUCKET_NAME
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Finally, validate access to your Cloud Storage bucket by examining its contents:
! gsutil ls -al $BUCKET_NAME
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Service Account**If you don't know your service account**, try to get your service account using `gcloud` command by executing the second cell below.
SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"} if ( SERVICE_ACCOUNT == "" or SERVICE_ACCOUNT is None or SERVICE_ACCOUNT == "[your-service-account]" ): # Get your GCP project id from gcloud shell_output = !gcloud auth list 2>/dev/null SERVICE_ACCOUNT = shell_output[2].strip(...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Set service account access for Vertex AI PipelinesRun the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account.
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_NAME ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_NAME
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Set up variablesNext, set up some variables used throughout the tutorial. Import libraries and define constants
import google.cloud.aiplatform as aip import json from kfp import dsl from kfp.v2 import compiler from kfp.v2.dsl import component
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Initialize Vertex AI SDK for PythonInitialize the Vertex AI SDK for Python for your project and corresponding bucket.
aip.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_NAME)
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Set hardware acceleratorsYou can set hardware accelerators for training and prediction.Set the variables `TRAIN_GPU/TRAIN_NGPU` and `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 ...
if os.getenv("IS_TESTING_TRAIN_GPU"): TRAIN_GPU, TRAIN_NGPU = ( aip.gapic.AcceleratorType.NVIDIA_TESLA_K80, int(os.getenv("IS_TESTING_TRAIN_GPU")), ) else: TRAIN_GPU, TRAIN_NGPU = (aip.gapic.AcceleratorType.NVIDIA_TESLA_K80, 1) if os.getenv("IS_TESTING_DEPLOY_GPU"): DEPLOY_GPU, DEPLOY_N...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Set pre-built containersSet the pre-built Docker container image for training and prediction.For the latest list, see [Pre-built containers for training](https://cloud.google.com/ai-platform-unified/docs/training/pre-built-containers).For the latest list, see [Pre-built containers for prediction](https://cloud.google....
if os.getenv("IS_TESTING_TF"): TF = os.getenv("IS_TESTING_TF") else: TF = "2.5".replace(".", "-") if TF[0] == "2": if TRAIN_GPU: TRAIN_VERSION = "tf-gpu.{}".format(TF) else: TRAIN_VERSION = "tf-cpu.{}".format(TF) if DEPLOY_GPU: DEPLOY_VERSION = "tf2-gpu.{}".format(TF) el...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Set machine typeNext, set the machine type to use for training and prediction.- Set the variables `TRAIN_COMPUTE` and `DEPLOY_COMPUTE` to configure the compute resources for the VMs you will use for for training and prediction. - `machine type` - `n1-standard`: 3.75GB of memory per vCPU. - `n1-highmem`: 6.5GB...
if os.getenv("IS_TESTING_TRAIN_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_TRAIN_MACHINE") else: MACHINE_TYPE = "n1-standard" VCPU = "4" TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU print("Train machine type", TRAIN_COMPUTE) if os.getenv("IS_TESTING_DEPLOY_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Location of Cloud Storage training data.Now set the variable `IMPORT_FILE` to the location of the CSV index file in Cloud Storage.
IMPORT_FILE = ( "gs://cloud-samples-data/vision/automl_classification/flowers/all_data_v2.csv" )
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Examine the training package Package layoutBefore you start the training, you will look at how a Python package is assembled for a custom training job. When unarchived, the package contains the following directory/file layout.- PKG-INFO- README.md- setup.cfg- setup.py- trainer - \_\_init\_\_.py - task.pyThe files `s...
# Make folder for Python training script ! rm -rf custom ! mkdir custom # Add package information ! touch custom/README.md setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0" ! echo "$setup_cfg" > custom/setup.cfg setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'tensorflow...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Create the task script for the Python training packageNext, you create the `task.py` script for driving the training package. Some noteable steps include:- Command-line arguments: - `data-format` The format of the data. In this example, the data is exported from an `ImageDataSet` and will be in a JSONL format. -...
%%writefile custom/trainer/task.py import tensorflow as tf from tensorflow.python.client import device_lib import argparse import os import sys import json import logging import tqdm def parse_args(): parser = argparse.ArgumentParser(description="TF.Keras Image Classification") # data source parser.add_ar...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Store training script on your Cloud Storage bucketNext, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket.
! rm -f custom.tar custom.tar.gz ! tar cvf custom.tar custom ! gzip custom.tar ! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_flowers.tar.gz !gsutil ls gs://andy-1234-221921aip-20211201001323/pipeline_root/custom_icn_training/aiplatform-custom-training-2021-12-01-00:39:25.109/dataset-899163017009168384-image_classifica...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Construct custom training pipelineIn the example below, you construct a pipeline for training a custom model using pre-built Google Cloud Pipeline Components for Vertex AI Training, as follows:1. Pipeline arguments, specify the locations of: - `import_file`: The CSV index file for the dataset. - `python_package`...
from google_cloud_pipeline_components import aiplatform as gcc_aip PIPELINE_ROOT = "{}/pipeline_root/custom_icn_training".format(BUCKET_NAME) @dsl.pipeline( name="custom-icn-training", description="Custom image classification training" ) def pipeline( import_file: str, display_name: str, python_packa...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Compile and execute the pipelineNext, you compile the pipeline and then exeute it. The pipeline takes the following parameters, which are passed as the dictionary `parameter_values`:- `import_file`: The Cloud Storage path to the dataset index file.- `display_name`: The display name for the generated Vertex AI resource...
compiler.Compiler().compile( pipeline_func=pipeline, package_path="custom_icn_training.json" ) pipeline = aip.PipelineJob( display_name="custom_icn_training", template_path="custom_icn_training.json", pipeline_root=PIPELINE_ROOT, parameter_values={ "import_file": IMPORT_FILE, "displ...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Delete a pipeline jobAfter a pipeline job is completed, you can delete the pipeline job with the method `delete()`. Prior to completion, a pipeline job can be canceled with the method `cancel()`.
pipeline.delete()
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
Cleaning upTo clean up all Google Cloud resources used in this project, you can [delete the Google Cloudproject](https://cloud.google.com/resource-manager/docs/creating-managing-projectsshutting_down_projects) you used for the tutorial.Otherwise, you can delete the individual resources you created in this tutorial:- D...
delete_all = True if delete_all: # Delete the dataset using the Vertex dataset object try: if "dataset" in globals(): dataset.delete() except Exception as e: print(e) # Delete the model using the Vertex model object try: if "model" in globals(): mode...
_____no_output_____
Apache-2.0
notebooks/community/ml_ops/stage3/get_started_with_custom_training_pipeline_components.ipynb
changlan/vertex-ai-samples
SAMUR Emergency Frequencies This notebook explores how the frequency of different types of emergency changes with time in relation to different periods (hours of the day, days of the week, months of the year...) and locations in Madrid. This will be useful for constructing a realistic emergency generator in the city s...
import pandas as pd import datetime import matplotlib.pyplot as plt import yaml %matplotlib inline df = pd.read_csv("../data/emergency_data.csv") df.head()
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
The column for the time of the call is a string, so let's change that into a timestamp.
df["time_call"] = pd.to_datetime(df["Solicitud"])
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
We will also need to assign a numerical code to each district of the city in order to properly vectorize the distribution an make it easier to work along with other parts of the project.
district_codes = { 'Centro': 1, 'Arganzuela': 2, 'Retiro': 3, 'Salamanca': 4, 'Chamartín': 5, 'Tetuán': 6, 'Chamberí': 7, 'Fuencarral - El Pardo': 8, 'Moncloa - Aravaca': 9, 'Latina': 10, 'Carabanchel': 11, 'Usera': 12, 'Puente de Vallecas': 13, 'Mora...
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
Each emergency has already been assigned a severity level, depending on the nature of the reported emergency.
df["severity"] = df["Gravedad"]
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
We also need the hour, weekday and month of the event in order to assign it in the various distributions.
df["hour"] = df["time_call"].apply(lambda x: x.hour) # From 0 to 23 df["weekday"] = df["time_call"].apply(lambda x: x.weekday()+1) # From 1 (Mon) to 7 (Sun) df["month"] = df["time_call"].apply(lambda x: x.month)
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
Let's also strip down the dataset to just the columns we need right now.
df = df[["district_code", "severity", "time_call", "hour", "weekday", "month"]] df.head()
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
We are going to group the distributions by severity.
emergencies_per_grav = df.severity.value_counts().sort_index().rename("total_emergencies") emergencies_per_grav
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
We will also need the global frequency of the emergencies:
total_seconds = (df.time_call.max()-df.time_call.min()).total_seconds() frequencies_per_grav = (emergencies_per_grav / total_seconds).rename("emergency_frequencies") frequencies_per_grav
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
Each emergency will need to be assigne a district. Assuming independent distribution of emergencies by district and time, each will be assigned to a district according to a global probability based on this dataset, as follows.
prob_per_district = (df.district_code.value_counts().sort_index()/df.district_code.value_counts().sum()).rename("distric_weight") prob_per_district
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
In order to be able to simplify the generation of emergencies, we are going to assume that the distributions of emergencies per hour, per weekday and per month are independent, sharing no correlation. This is obiously not fully true, but it is a good approximation for the chosen time-frames.
hourly_dist = (df.hour.value_counts()/df.hour.value_counts().mean()).sort_index().rename("hourly_distribution") daily_dist = (df.weekday.value_counts()/df.weekday.value_counts().mean()).sort_index().rename("daily_distribution") monthly_dist = (df.month.value_counts()/df.month.value_counts().mean()).sort_index().rename(...
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
We will actually make one of these per severity level. This will allow us to modify the base emergency density of a given severity as follows:
def emergency_density(gravity, hour, weekday, month): base_density = frequencies_per_grav[gravity] density = base_density * hourly_dist[hour] * daily_dist[weekday] * monthly_dist[month] return density emergency_density(3, 12, 4, 5) # Emergency frequency for severity level 3, at 12 hours of a thursday in Ma...
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
In order for the model to read these distributions we will need to store them in a dict-like format, in this case YAML, which is easily readable by human or machine.
dists = {} for severity in range(1, 6): sub_df = df[df["severity"] == severity] frequency = float(frequencies_per_grav.round(8)[severity]) hourly_dist = (sub_df.hour. value_counts()/sub_df.hour. value_counts().mean()).sort_index().round(5).to_dict() daily_dist = (sub_df.weekday.value_co...
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
We can now check that the dictionary stored in the YAML file is the same one we have created.
with open("../data/distributions.yaml") as dist_file: yaml_dict = yaml.safe_load(dist_file) yaml_dict == dists
_____no_output_____
MIT
notebooks/emergency_frequencies.ipynb
samurai-madrid/reinforced-learning
S3Fs Notebook ExampleS3Fs is a Pythonic file interface to S3. It builds on top of botocore.The top-level class S3FileSystem holds connection information and allows typical file-system style operations like cp, mv, ls, du, glob, etc., as well as put/get of local files to/from S3.The connection can be anonymous - in whi...
import json import os import s3fs
_____no_output_____
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
Load the credentials file .json to make a connection to `S3FileSystem`
tenant="standard" with open(f'/vault/secrets/minio-{tenant}-tenant-1.json') as f: creds = json.load(f)
_____no_output_____
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
The connection can be anonymous- in which case only publicly-available, read-only buckets are accessible - or via credentials explicitly supplied or in configuration files. Calling open() on a S3FileSystem (typically using a context manager) provides an S3File for read or write access to a particular key. The object em...
HOST = creds['MINIO_URL'] SECURE = HOST.startswith('https') fs = s3fs.S3FileSystem( anon=False, use_ssl=SECURE, client_kwargs= { "region_name": "us-east-1", "endpoint_url": creds['MINIO_URL'], "aws_access_key_id": creds['AWS_ACCESS_KEY_ID'], "aws_secret_access_key": creds...
_____no_output_____
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
Upload a fileNow that your personal bucket exists you can upload your files! We can use`example.txt` from the same folder as this notebook.**Note:** Bucket storage doesn't actually have real directories, so you won'tfind any functions for creating them. But some software will show you adirectory structure by looking a...
# Desired location in the bucket #NB_NAMESPACE: namespace of user e.g. rohan-katkar LOCAL_FILE='example.txt' REMOTE_FILE= os.environ['NB_NAMESPACE']+'/s3fs-examples/Happy-DAaaS-Bird.txt' fs.put(LOCAL_FILE,REMOTE_FILE)
_____no_output_____
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
Check path exists in bucket
fs.exists(os.environ['NB_NAMESPACE']+'/s3fs-examples')
_____no_output_____
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
List objects in bucket
fs.ls(os.environ['NB_NAMESPACE'])
_____no_output_____
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
List objects in path
x = [] x= fs.ls(os.environ['NB_NAMESPACE'] +'/s3fs-examples') for obj in x: print(f'Name: {obj}')
Name: rohan-katkar/s3fs-examples/Happy-DAaaS-Bird.txt
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
Download a fileThere is another method `download(rpath, lpath[, recursive])`. S3Fs has issues with this method. Get is an equivalent method.
from shutil import copyfileobj DL_FILE='downloaded_s3fsexample.txt' fs.get(os.environ['NB_NAMESPACE']+'/s3fs-examples/Happy-DAaaS-Bird.txt', DL_FILE) with open(DL_FILE, 'r') as file: print(file.read())
________________ / \ | Go DAaaS!!!! | | _______________/ |/ ^____, /` `\ / ^ > / / , / «^` // /=/ % ««.~ «_/ % ««\,___% ``\ \ ^ ^
MIT
self-serve-storage/python/s3Fs Examples.ipynb
DennisH3/jupyter-notebooks
Imports and Functions
import numpy as np from scipy.stats import special_ortho_group from scipy.spatial.transform import Rotation from scipy.linalg import svd import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') FIGURE_SCALE = 1.0 FONT_SIZE = 20 plt.rcParams.update({ 'figure.figsize': np.array((8, 6)) * FIGURE_SCALE, ...
_____no_output_____
Apache-2.0
special_orthogonalization/svd_vs_gs_simulations.ipynb
wy-go/google-research