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
HugeCTR Continuous Training and Inference Demo (Part I) OverviewIn HugeCTR version 3.3, we finished the whole pipeline of parameter server, including 1. The parameter dumping interface from training to kafka.2. CPU cache(Redis Cluster / Hash Map / Parallel Hash Map).3. RocksDB as a persistence storage.4. Embedding ca...
!mkdir criteo_data !mkdir criteo_script
_____no_output_____
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
1.2 Download Criteo Dataset
!wget http://azuremlsampleexperiments.blob.core.windows.net/criteo/day_1.gz
_____no_output_____
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
**NOTE**: Replace `1` with a value from [0, 23] to use a different day.During preprocessing, the amount of data, which is used to speed up the preprocessing, fill missing values, and remove the feature values that are considered rare, is further reduced. 1.3 Write the preprocessing the script.
%%writefile preprocess.sh #!/bin/bash if [[ $# -lt 3 ]]; then echo "Usage: preprocess.sh [DATASET_NO.] [DST_DATA_DIR] [SCRIPT_TYPE] [SCRIPT_TYPE_SPECIFIC_ARGS...]" exit 2 fi DST_DATA_DIR=$2 echo "Warning: existing $DST_DATA_DIR is erased" rm -rf $DST_DATA_DIR if [[ $3 == "nvt" ]]; then if [[ $# -ne 6 ]]; the...
Overwriting preprocess.sh
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
**NOTE**: Here we only read the first 500000 lines of the data to do the demo.
%%writefile criteo_script/preprocess.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import sys import tempfile from six.moves import urllib import urllib.request import sys import os import math...
Overwriting criteo_script/preprocess.py
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
1.4 Run the preprocess script
!bash preprocess.sh 0 criteo_data pandas 1 1 1
_____no_output_____
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
**IMPORTANT NOTES**: Arguments may vary depend on your setting:- The first argument represents the dataset postfix. For instance, if `day_1` is used, the postfix is `1`.- The second argument, `criteo_data`, is where the preprocessed data is stored. 1.5 Generate data sample for inference
import pandas as pd import numpy as np df = pd.read_table("criteo_data/train/train.txt", header = None, sep= ' ', \ names = ['label'] + ['I'+str(i) for i in range(1, 14)] + \ ['C1_C2', 'C3_C4'] + ['C'+str(i) for i in range(1, 27)])[:5] left = df.iloc[:,:14].astype(np.float32) right...
_____no_output_____
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
2. Start the Kafka Broker **Please refer to the README to start the Kafka Broker properly.** 3. Wide&Deep Model Demo
!rm -r *model %%writefile wdl_demo.py import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(model_name = "wdl", max_eval_batches = 5000, batchsize_eval = 1024, batchsize = 1024, lr = 0.0...
[HUGECTR][03:34:23][INFO][RANK0]: Empty embedding, trained table will be stored in ./wdl_0_sparse_model [HUGECTR][03:34:23][INFO][RANK0]: Empty embedding, trained table will be stored in ./wdl_1_sparse_model HugeCTR Version: 3.2 ====================================================Model Init=============================...
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
4. WDL Inference 4.1 Inference using HugeCTR python API
#Create a folder for RocksDB !mkdir /wdl_infer !mkdir /wdl_infer/rocksdb
mkdir: cannot create directory β€˜/wdl_infer’: File exists mkdir: cannot create directory β€˜/wdl_infer/rocksdb’: File exists
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
**Please make sure you have started Redis cluster following the README before you start doing inference.**
%%writefile 'wdl_predict.py' from hugectr.inference import InferenceParams, CreateInferenceSession import hugectr import pandas as pd import numpy as np import sys from mpi4py import MPI def wdl_inference(model_name='wdl', network_file='wdl.json', dense_file='wdl_dense_0.model', \ embedding_file_list=...
[HUGECTR][03:36:30][INFO][RANK0]: default_emb_vec_value is not specified using default: 0.000000 [HUGECTR][03:36:30][INFO][RANK0]: default_emb_vec_value is not specified using default: 0.000000 [HUGECTR][03:36:30][INFO][RANK0]: Creating RedisCluster backend... [HUGECTR][03:36:30][INFO][RANK0]: Connecting to Redis clust...
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
4.2 Inference using Triton **Please refer to the [Triton_Inference.ipynb](./Triton_Inference.ipynb) notebook to start Triton and do the inference.** 5. Continue Training WDL Model
%%writefile wdl_continue.py import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(model_name = "wdl", max_eval_batches = 5000, batchsize_eval = 1024, batchsize = 1024, lr = 0.001, ...
[HUGECTR][03:37:25][INFO][RANK0]: Use existing embedding: ./wdl_0_sparse_model [HUGECTR][03:37:25][INFO][RANK0]: Use existing embedding: ./wdl_1_sparse_model HugeCTR Version: 3.2 ====================================================Model Init===================================================== [HUGECTR][03:37:25][INFO]...
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
6. Inference with new model 6.1 Continuous inference using Python API
!python wdl_predict.py
[HUGECTR][03:38:09][INFO][RANK0]: default_emb_vec_value is not specified using default: 0.000000 [HUGECTR][03:38:09][INFO][RANK0]: default_emb_vec_value is not specified using default: 0.000000 [HUGECTR][03:38:09][INFO][RANK0]: Creating RedisCluster backend... [HUGECTR][03:38:09][INFO][RANK0]: Connecting to Redis clust...
BSD-3-Clause
samples/hierarchical_deployment/hps_e2e_demo/Continuous_Training.ipynb
miguelusque/hugectr_backend
Observations and Insights
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import scipy.stats as st # Study data files mouse_metadata_path = "data/Mouse_metadata.csv" study_results_path = "data/Study_results.csv" # Read the mouse data and the study results mouse_metadata = pd.read_csv(mouse_metadata_path) study_res...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Summary Statistics
# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen # This method is the most straightforward, creating multiple series and putting them all together at the end. drug_df = clean_df.groupby("Drug Regimen") # calculating the statistics mean_...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Bar Plots
# Generate a bar plot showing the number of mice per time point for each treatment throughout the course of the study using pandas. #creating count dataframe bar_df = clean_df.groupby("Drug Regimen").count() #creating bar chart dataframe bar_df = bar_df.sort_values("Timepoint", ascending=False) bars_df = bar_df["Time...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Pie Plots
# Generate a pie plot showing the distribution of female versus male mice using pandas pie_chart = mouse_metadata["Sex"].value_counts() pie_chart.plot(kind='pie', subplots=True, autopct="%0.1f%%") # Generate a pie plot showing the distribution of female versus male mice using pyplot f_vs_m = mouse_metadata["Sex"].value...
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Quartiles, Outliers and Boxplots
# Calculate the final tumor volume of each mouse across four of the most promising treatment regimens. Calculate the IQR and quantitatively determine if there are any potential outliers. # returning the max timepoints for Capomulin temp_df = clean_df.loc[clean_df["Drug Regimen"] == "Capomulin", :] max_capo = temp_df....
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Line and Scatter Plots
# Generate a line plot of time point versus tumor volume for a mouse treated with Capomulin # Generate a scatter plot of mouse weight versus average tumor volume for the Capomulin regimen
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Correlation and Regression
# Calculate the correlation coefficient and linear regression model # for mouse weight and average tumor volume for the Capomulin regimen
_____no_output_____
ADSL
Pymaceuticals/pymaceuticals_starter.ipynb
tomlip/Matplotlib-challenge
Create Dataset
def create_dataset(df, name, bonds): print(f"Creating Dataset and Saving to {drive_path}/data/{name}.pkl") data = df.sample(frac=1) data = data.reset_index(drop=True) data['mol'] = data['smiles'].apply(lambda x: create_dgl_features(x, bonds)) data.to_pickle(f"{drive_path}/data/{name}.pkl") retur...
time: 148 ms (started: 2021-11-30 11:59:08 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Create Episode
def create_episode(n_support_pos, n_support_neg, n_query, data, test=False, train_balanced=True): """ n_query = per class data points Xy = dataframe dataset in format [['y', 'mol']] """ support = [] query = [] n_query_pos = n_query n_query_neg = n_query support_neg = data[data['y'] == 0].sample(...
time: 2.25 ms (started: 2021-11-27 16:25:20 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Graph Embedding
class GCN(nn.Module): def __init__(self, in_channels, out_channels=128): super(GCN, self).__init__() self.conv1 = GraphConv(in_channels, 64) self.conv2 = GraphConv(64, 128) self.conv3 = GraphConv(128, 64) self.sum_pool = SumPooling() self.dense = nn.Linear(64, out_channels) ...
time: 9.12 ms (started: 2021-11-30 11:46:53 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Distance Function
def euclidean_dist(x, y): # x: N x D # y: M x D n = x.size(0) m = y.size(0) d = x.size(1) assert d == y.size(1) x = x.unsqueeze(1).expand(n, m, d) y = y.unsqueeze(0).expand(n, m, d) return torch.pow(x - y, 2).sum(2)
time: 4.05 ms (started: 2021-11-30 11:44:08 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
LSTM
def cos(x, y): transpose_shape = tuple(list(range(len(y.shape)))[::-1]) x = x.float() denom = ( torch.sqrt(torch.sum(torch.square(x)) * torch.sum(torch.square(y))) + torch.finfo(torch.float32).eps) return torch.matmul(x, torch.permute(y, transpose_shape)) / denom class ResiLSTMEmb...
time: 75.5 ms (started: 2021-11-30 11:44:11 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Protonet https://colab.research.google.com/drive/1QDYIwg2-iiUpVU8YyAh0lOgFgFPhVgvxscrollTo=BnLOgECOKG_y
class ProtoNet(nn.Module): def __init__(self, with_bonds=False): """ Prototypical Network """ super(ProtoNet, self).__init__() def forward(self, X_support, X_query, n_support_pos, n_support_neg): n_support = len(X_support) # prototypes z_dim = X_support.size(-1) # size of the embe...
time: 18.5 ms (started: 2021-11-30 11:44:14 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Training Loop
def train(train_tasks, train_dfs, balanced_queries, k_pos, k_neg, n_query, episodes, lr): writer = SummaryWriter() start_time = time.time() node_feat_size = 177 embedding_size = 128 encoder = Net() resi_lstm = ResiLSTMEmbedding(k_pos+k_neg) proto_net = ProtoNet() loss_fn = nn.NLLLoss() if torch.cuda...
time: 171 ms (started: 2021-11-30 11:57:42 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Testing Loop
def test(encoder, lstm, proto_net, test_tasks, test_dfs, k_pos, k_neg, rounds): encoder.eval() lstm.eval() proto_net.eval() test_info = {} with torch.no_grad(): for task in test_tasks: Xy = test_dfs[task] running_loss = [] running_acc = [] running_roc = [0] running_prc = ...
time: 161 ms (started: 2021-11-30 11:57:33 +00:00)
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Initiate Training and Testing
from google.colab import drive drive.mount('/content/drive') # PATHS drive_path = "/content/drive/MyDrive/Colab Notebooks/MSC_21" method_dir = "ProtoNets" log_path = f"{drive_path}/{method_dir}/logs/" # PARAMETERS dataset = 'tox21' with_bonds = False test_rounds = 20 n_query = 64 # per class episodes = 10000 lr = 0.0...
_____no_output_____
MIT
Prototypical Nets Tox21 ECFP.ipynb
danielvlla/Few-Shot-Learning-for-Low-Data-Drug-Discovery
Normalize text
herod_fp = '/Users/kyle/cltk_data/greek/text/tlg/plaintext/TLG0016.txt' with open(herod_fp) as fo: herod_raw = fo.read() print(herod_raw[2000:2500]) # What do we notice needs help? from cltk.corpus.utils.formatter import tlg_plaintext_cleanup herod_clean = tlg_plaintext_cleanup(herod_raw, rm_punctuation=True, rm_...
έρῃ Ξ΄α½² λέγουσι γΡνΡῇ μΡτὰ ταῦτα Ἀλέξανδρον Ο„α½ΈΞ½ Πριάμου ἀκηκοότα ταῦτα ἐθΡλῆσαί ΞΏαΌ± ἐκ Ο„αΏ†Ο‚ Ἑλλάδος δι ἁρπαγῆς γΡνέσθαι Ξ³Ο…Ξ½Ξ±αΏ–ΞΊΞ± ἐπιστάμΡνον πάντως ὅτι οὐ δώσΡι Ξ΄α½·ΞΊΞ±Ο‚ οὐδὲ γὰρ ἐκΡίνους διδόναι. ΞŸα½•Ο„Ο‰ δὴ ἁρπάσαντος αὐτοῦ αΌ™Ξ»α½³Ξ½Ξ·Ξ½ τοῖσι Ἕλλησι Ξ΄α½ΉΞΎΞ±ΞΉ πρῢτον Ο€α½³ΞΌΟˆΞ±Ξ½Ο„Ξ±Ο‚ ἀγγέλους ἀπαιτέΡιν τΡ αΌ™Ξ»α½³Ξ½Ξ·Ξ½ ΞΊΞ±α½Ά Ξ΄α½·ΞΊΞ±Ο‚ Ο„αΏ†Ο‚ ἁρπαγῆς αἰτέΡιν. ΀ο...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Tokenize sentences
from cltk.tokenize.sentence import TokenizeSentence tokenizer = TokenizeSentence('greek') herod_sents = tokenizer.tokenize_sentences(herod_clean) print(herod_sents[:5]) for sent in herod_sents: print(sent) print() input()
Ἡροδότου Ξ˜ΞΏΟ…Οα½·ΞΏΟ… ἱστορίης ἀπόδΡξις αΌ₯δΡ ὑς μὡτΡ Ο„α½° γΡνόμΡνα ἐξ ἀνθρώπων Ο„αΏ· χρόνῳ ἐξίτηλα γένηται μὡτΡ ἔργα μΡγάλα τΡ ΞΊΞ±α½Ά θωμαστά Ο„α½° ΞΌα½²Ξ½ Ἕλλησι Ο„α½° Ξ΄α½² βαρβάροισι ἀποδΡχθέντα αΌ€ΞΊΞ»α½³Ξ± γένηται Ο„α½± τΡ ἄλλα ΞΊΞ±α½Ά δι αΌ£Ξ½ Ξ±αΌ°Ο„α½·Ξ·Ξ½ ἐπολέμησαν ἀλλὡλοισι. ΠΡρσέων ΞΌα½³Ξ½ Ξ½Ο…Ξ½ ΞΏαΌ± Ξ»α½ΉΞ³ΞΉΞΏΞΉ Φοίνικας Ξ±αΌ°Ο„α½·ΞΏΟ…Ο‚ φασὢ γΡνέσθαι Ο„αΏ†Ο‚ διαφορῆς τούτους γάρ ...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Make word tokens
from cltk.tokenize.word import nltk_tokenize_words for sent in herod_sents: words = nltk_tokenize_words(sent) print(words) input()
['Ἡροδότου', 'Ξ˜ΞΏΟ…Οα½·ΞΏΟ…', 'ἱστορίης', 'ἀπόδΡξις', 'αΌ₯δΡ', 'ὑς', 'μὡτΡ', 'Ο„α½°', 'γΡνόμΡνα', 'ἐξ', 'ἀνθρώπων', 'Ο„αΏ·', 'χρόνῳ', 'ἐξίτηλα', 'γένηται', 'μὡτΡ', 'ἔργα', 'μΡγάλα', 'τΡ', 'ΞΊΞ±α½Ά', 'θωμαστά', 'Ο„α½°', 'ΞΌα½²Ξ½', 'Ἕλλησι', 'Ο„α½°', 'Ξ΄α½²', 'βαρβάροισι', 'ἀποδΡχθέντα', 'αΌ€ΞΊΞ»α½³Ξ±', 'γένηται', 'Ο„α½±', 'τΡ', 'ἄλλα', 'ΞΊΞ±α½Ά', 'δι', 'αΌ£Ξ½', 'Ξ±αΌ°Ο„α½·...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Tokenize Latin enclitics
from cltk.corpus.utils.formatter import phi5_plaintext_cleanup from cltk.tokenize.word import WordTokenizer # 'LAT0474': 'Marcus Tullius Cicero, Cicero, Tully', cicero_fp = '/Users/kyle/cltk_data/latin/text/phi5/plaintext/LAT0474.TXT' with open(cicero_fp) as fo: cicero_raw = fo.read() cicero_clean = phi5_plaintex...
['Quae', 'res', 'in', 'civitate', 'duae', 'plurimum', 'possunt', 'eae', 'contra', 'nos', 'ambae', 'faciunt', 'in', 'hoc', 'tempore', 'summa', 'gratia', 'et', 'eloquentia', 'quarum', 'alteram', 'C.', 'Aquili', 'vereor', 'alteram', 'metuo.'] ['Eloquentia', 'Q.', 'Hortensi', 'ne', 'me', 'in', 'dicendo', 'impediat', 'non'...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
POS Tagging
from cltk.tag.pos import POSTag tagger = POSTag('greek') # Heordotus again for sent in herod_sents: tagged_text = tagger.tag_unigram(sent) print(tagged_text) input()
[('Ἡροδότου', None), ('Ξ˜ΞΏΟ…Οα½·ΞΏΟ…', None), ('ἱστορίης', None), ('ἀπόδΡξις', None), ('αΌ₯δΡ', 'P-S---FN-'), ('ὑς', 'D--------'), ('μὡτΡ', None), ('Ο„α½°', 'L-P---NA-'), ('γΡνόμΡνα', None), ('ἐξ', 'R--------'), ('ἀνθρώπων', None), ('Ο„αΏ·', 'P-S---MD-'), ('χρόνῳ', None), ('ἐξίτηλα', None), ('γένηται', None), ('μὡτΡ', None), ('ἔργα'...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
NER
## Latin -- decent, but see M, P, etc from cltk.tag import ner # Heordotus again for sent in cicero_sents: ner_tags = ner.tag_ner('latin', input_text=sent, output_type=list) print(ner_tags) input() # Greek -- not as good! from cltk.tag import ner # Heordotus again for sent in herod_sents: ner_tags = n...
[('Ἡροδότου',), ('Ξ˜ΞΏΟ…Οα½·ΞΏΟ…',), ('ἱστορίης',), ('ἀπόδΡξις',), ('αΌ₯δΡ',), ('ὑς',), ('μὡτΡ',), ('Ο„α½°',), ('γΡνόμΡνα',), ('ἐξ',), ('ἀνθρώπων',), ('Ο„αΏ·',), ('χρόνῳ',), ('ἐξίτηλα',), ('γένηται',), ('μὡτΡ',), ('ἔργα',), ('μΡγάλα',), ('τΡ',), ('ΞΊΞ±α½Ά',), ('θωμαστά',), ('Ο„α½°',), ('ΞΌα½²Ξ½',), ('Ἕλλησι', 'Entity'), ('Ο„α½°',), ('Ξ΄α½²',), ('βαρβ...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Stopword filtering
from cltk.stop.greek.stops import STOPS_LIST #p = PunktLanguageVars() for sent in herod_sents: words = nltk_tokenize_words(sent) print('W/ STOPS', words) words = [w for w in words if not w in STOPS_LIST] print('W/O STOPS', words) input()
W/ STOPS ['Ἡροδότου', 'Ξ˜ΞΏΟ…Οα½·ΞΏΟ…', 'ἱστορίης', 'ἀπόδΡξις', 'αΌ₯δΡ', 'ὑς', 'μὡτΡ', 'Ο„α½°', 'γΡνόμΡνα', 'ἐξ', 'ἀνθρώπων', 'Ο„αΏ·', 'χρόνῳ', 'ἐξίτηλα', 'γένηται', 'μὡτΡ', 'ἔργα', 'μΡγάλα', 'τΡ', 'ΞΊΞ±α½Ά', 'θωμαστά', 'Ο„α½°', 'ΞΌα½²Ξ½', 'Ἕλλησι', 'Ο„α½°', 'Ξ΄α½²', 'βαρβάροισι', 'ἀποδΡχθέντα', 'αΌ€ΞΊΞ»α½³Ξ±', 'γένηται', 'Ο„α½±', 'τΡ', 'ἄλλα', 'ΞΊΞ±α½Ά', 'δι', 'αΌ£...
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Concordance
from cltk.utils.philology import Philology p = Philology() herod_fp = '/Users/kyle/cltk_data/greek/text/tlg/plaintext/TLG0016.txt' p.write_concordance_from_file(herod_fp, 'kyle_herod')
INFO:CLTK:Wrote concordance to '/Users/kyle/cltk_data/user_data/concordance_kyle_herod.txt'.
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Word count
from nltk.text import Text words = nltk_tokenize_words(herod_clean) print(words[:15]) t = Text(words) vocabulary_count = t.vocab() vocabulary_count['ἱστορίης'] vocabulary_count['μὡτΡ'] vocabulary_count['ἀνθρώπων']
_____no_output_____
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Word frequency
from cltk.utils.frequency import Frequency freq = Frequency() herod_frequencies = freq.counter_from_str(herod_clean) herod_frequencies.most_common()
_____no_output_____
MIT
public_talks/2015_11_17_nyu/3 Normalization, tokenization, tagging.ipynb
kylepjohnson/ipython_notebooks
Fuel type
# remove the 'Type de carburant:' string from the carburant_type feature df.fuel_type = df.fuel_type.map(lambda x: x.lstrip('Type de carburant:'))
_____no_output_____
MIT
cars-price-dataset.ipynb
jaselnik/Car-Price-Predictor-Django
Mark & Model
# remove the 'Marque:' string from the mark feature df['mark'] = df['mark'].map(lambda x: x.replace('Marque:', '')) df = df[df.mark != '-'] # remove the 'Modèle:' string from model feature df['model'] = df['model'].map(lambda x: x.replace('Modèle:', ''))
_____no_output_____
MIT
cars-price-dataset.ipynb
jaselnik/Car-Price-Predictor-Django
fiscal powerFor the fiscal power we can see that there is exactly 5728 rows not announced, so we will fill them by the mean of the other columns, since it is an important feature in cars price prediction so we can not drop it.
# remove the 'Puissance fiscale:' from the fiscal_power feature df.fiscal_power = df.fiscal_power.map(lambda x: x.lstrip('Puissance fiscale:Plus de').rstrip(' CV')) # replace the - with NaN values and convert them to integer values df.fiscal_power = df.fiscal_power.str.replace("-","0") # convert all fiscal_power values...
_____no_output_____
MIT
cars-price-dataset.ipynb
jaselnik/Car-Price-Predictor-Django
fuel type
# remove those lines having the fuel_type not set df = df[df.fuel_type != '-']
_____no_output_____
MIT
cars-price-dataset.ipynb
jaselnik/Car-Price-Predictor-Django
drop unwanted columns
df = df.drop(columns=['sector', 'type']) df = df[['price', 'year_model', 'mileage', 'fiscal_power', 'fuel_type', 'mark']] df.to_csv('data/car_dataset.csv') df.head() from car_price.wsgi import application from api.models import Car for x in df.values[5598:]: car = Car( price=x[0], year_model=x[1], ...
_____no_output_____
MIT
cars-price-dataset.ipynb
jaselnik/Car-Price-Predictor-Django
Credit Risk ClassificationCredit risk poses a classification problem that’s inherently imbalanced. This is because healthy loans easily outnumber risky loans. In this Challenge, you’ll use various techniques to train and evaluate models with imbalanced classes. You’ll use a dataset of historical lending activity from ...
# Import the modules import numpy as np import pandas as pd from pathlib import Path from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import confusion_matrix from imblearn.metrics import classification_report_imbalanced import warnings warnings.filterwarnings('ignore')
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
--- Split the Data into Training and Testing Sets Step 1: Read the `lending_data.csv` data from the `Resources` folder into a Pandas DataFrame.
# Read the CSV file from the Resources folder into a Pandas DataFrame lending_data_df = pd.read_csv(Path("../Starter_Code/Resources/lending_data.csv")) # Review the DataFrame display(lending_data_df.head())
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 2: Create the labels set (`y`) from the β€œloan_status” column, and then create the features (`X`) DataFrame from the remaining columns.
# Separate the data into labels and features # Separate the y variable, the labels y = lending_data_df["loan_status"] # Separate the X variable, the features X = lending_data_df.drop(columns=["loan_status"]) # Review the y variable Series y.head() # Review the X variable DataFrame X.head()
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 3: Check the balance of the labels variable (`y`) by using the `value_counts` function.
# Check the balance of our target values y.value_counts()
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 4: Split the data into training and testing datasets by using `train_test_split`.
# Import the train_test_learn module from sklearn.model_selection import train_test_split # Split the data using train_test_split # Assign a random_state of 1 to the function X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
--- Create a Logistic Regression Model with the Original Data Step 1: Fit a logistic regression model by using the training data (`X_train` and `y_train`).
# Import the LogisticRegression module from SKLearn from sklearn.linear_model import LogisticRegression # Instantiate the Logistic Regression model # Assign a random_state parameter of 1 to the model model = LogisticRegression(random_state=1) # Fit the model using training data model.fit(X_train, y_train)
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 2: Save the predictions on the testing data labels by using the testing feature data (`X_test`) and the fitted model.
# Make a prediction using the testing data y_pred = model.predict(X_test) y_pred
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 3: Evaluate the model’s performance by doing the following:* Calculate the accuracy score of the model.* Generate a confusion matrix.* Print the classification report.
# Print the balanced_accuracy score of the model BAS = balanced_accuracy_score(y_test, y_pred) print(BAS) # Generate a confusion matrix for the model print(confusion_matrix(y_test, y_pred)) # Print the classification report for the model print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup 0 1.00 0.99 0.91 1.00 0.95 0.91 18765 1 0.85 0.91 0.99 0.88 0.95 0.90 619 avg / total 0.99 0.99 0.91 0.99 0.95 0...
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 4: Answer the following question. **Question:** How well does the logistic regression model predict both the `0` (healthy loan) and `1` (high-risk loan) labels?**Answer:** The regression models predicts both healthy loans and high-risk loans, for the most part, accurately. We have an average 99% for our F1 score,...
# Import the RandomOverSampler module form imbalanced-learn from imblearn.over_sampling import RandomOverSampler # Instantiate the random oversampler model # # Assign a random_state parameter of 1 to the model random_oversampler = RandomOverSampler(random_state=1) # Fit the original training data to the random_oversa...
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 2: Use the `LogisticRegression` classifier and the resampled data to fit the model and make predictions.
# Instantiate the Logistic Regression model # Assign a random_state parameter of 1 to the model resampled_model = LogisticRegression(random_state=1) # Fit the model using the resampled training data resampled_model.fit(X_resampled, y_resampled) # Make a prediction using the testing data y_pred = resampled_model.predi...
_____no_output_____
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Step 3: Evaluate the model’s performance by doing the following:* Calculate the accuracy score of the model.* Generate a confusion matrix.* Print the classification report.
# Print the balanced_accuracy score of the model print(balanced_accuracy_score(y_test, y_pred)) # Generate a confusion matrix for the model confusion_matrix(y_test, y_pred) # Print the classification report for the model print(classification_report_imbalanced(y_test, y_pred))
pre rec spe f1 geo iba sup 0 1.00 0.99 0.99 1.00 0.99 0.99 18765 1 0.84 0.99 0.99 0.91 0.99 0.99 619 avg / total 0.99 0.99 0.99 0.99 0.99 0...
MIT
Starter_Code/credit_risk_resampling.ipynb
LeoHarada/Challenge_12
Average
from sklearn.metrics import accuracy_score, roc_auc_score from sklearn.preprocessing import StandardScaler oof_preds = np.mean(df_norm[all_feat_names].to_numpy(),1) oof_gts = df_norm['MGMT_value'] cv_preds = [np.mean(df_norm[df_norm.fold==fold][all_feat_names].to_numpy(),1) for fold in range(5)] cv_gts = [df_norm[df_n...
OOF acc 0.5944540727902946, OOF auc 0.6514516827964754, CV AUC 0.6504285580435163 (std 0.02232524533384981)
MIT
notebooks/7-Ensemble.ipynb
jpjuvo/RSNA-MICCAI-Brain-Tumor-Classification
2nd level models
import xgboost as xgb def get_data(fold, features): df = df_norm.dropna(inplace=False) scaler = StandardScaler() df_train = df[df.fold != fold] df_val = df[df.fold == fold] if len(df_val) == 0: df_val = df[df.fold == 0] # shuffle train df_train = df_train.sample(frac=1) ...
_____no_output_____
MIT
notebooks/7-Ensemble.ipynb
jpjuvo/RSNA-MICCAI-Brain-Tumor-Classification
Introduction to \LaTeX Math ModeJupyter notebooks integrate the MathJax Javascript library in order to render mathematical formulas and symbols in the same way as one would in \LaTeX (often used to typeset textbooks, research papers, or other technical documents).First, we will take a look at a couple of rendered expr...
| One | Two | Three | Four | | --- | --- | --- | --- | | 10% | Something | Else | 40% | | 90% | To | Do | 50% |
_____no_output_____
MIT
Introductions/LaTeX and Markdown Intro.ipynb
mtr3t/notebook-examples
Interacting with models November 2014, by Max Zwiessele with edits by James HensmanThe GPy model class has a set of features which are designed to make it simple to explore the parameter space of the model. By default, the scipy optimisers are used to fit GPy models (via model.optimize()), for which we provide mechani...
m = GPy.examples.regression.sparse_GP_regression_1D(plot=False, optimize=False)
_____no_output_____
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Examining the model using printTo see the current state of the model parameters, and the model’s (marginal) likelihood just print the model print mThe first thing displayed on the screen is the log-likelihood value of the model with its current parameters. Below the log-likelihood, a table with all the model’s para...
m
_____no_output_____
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
In this case the kernel parameters (`bf.variance`, `bf.lengthscale`) as well as the likelihood noise parameter (`Gaussian_noise.variance`), are constrained to be positive, while the inducing inputs have no constraints associated. Also there are no ties or prior defined.You can also print all subparts of the model, by p...
m.rbf
_____no_output_____
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
When you want to get a closer look into multivalue parameters, print them directly:
m.inducing_inputs m.inducing_inputs[0] = 1
_____no_output_____
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Interacting with Parameters:The preferred way of interacting with parameters is to act on the parameter handle itself. Interacting with parameter handles is simple. The names, printed by print m are accessible interactively and programatically. For example try to set the kernel's `lengthscale` to 0.2 and print the res...
m.rbf.lengthscale = 0.2 print m
Name : sparse_gp Objective : 563.178096129 Number of Parameters : 8 Number of Optimization Parameters : 8 Updates : True Parameters: sparse_gp.  | value | constraints | priors inducing_inputs  | (5, 1) | | rbf.variance  |...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
This will already have updated the model’s inner state: note how the log-likelihood has changed. YOu can immediately plot the model or see the changes in the posterior (`m.posterior`) of the model. Regular expressionsThe model’s parameters can also be accessed through regular expressions, by β€˜indexing’ the model with ...
print m['.*var'] #print "variances as a np.array:", m['.*var'].values() #print "np.array of rbf matches: ", m['.*rbf'].values()
index | sparse_gp.rbf.variance | constraints | priors [0]  | 1.00000000 | +ve | ----- | sparse_gp.Gaussian_noise.variance | ----------- | ------ [0]  | 1.00000000 | +ve ...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
There is access to setting parameters by regular expression, as well. Here are a few examples of how to set parameters by regular expression. Note that each time the values are set, computations are done internally to compute the log likeliood of the model.
m['.*var'] = 2. print m m['.*var'] = [2., 3.] print m
Name : sparse_gp Objective : 680.058219518 Number of Parameters : 8 Number of Optimization Parameters : 8 Updates : True Parameters: sparse_gp.  | value | constraints | priors inducing_inputs  | (5, 1) | | rbf.variance  |...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
A handy trick for seeing all of the parameters of the model at once is to regular-expression match every variable:
print m['']
index | sparse_gp.inducing_inputs | constraints | priors [0 0] | 1.00000000 | | [1 0] | -1.51676820 | | [2 0] | -2.23387110 | ...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Setting and fetching parameters parameter_arrayAnother way to interact with the model’s parameters is through the parameter_array. The Parameter array holds all the parameters of the model in one place and is editable. It can be accessed through indexing the model for example you can set all the parameters through thi...
new_params = np.r_[[-4,-2,0,2,4], [.1,2], [.7]] print new_params m[:] = new_params print m
[-4. -2. 0. 2. 4. 0.1 2. 0.7] Name : sparse_gp Objective : 322.428807303 Number of Parameters : 8 Number of Optimization Parameters : 8 Updates : True Parameters: sparse_gp.  | value | constraints | priors inducing_inputs  | (5, 1) | | ...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Parameters themselves (leafs of the hierarchy) can be indexed and used the same way as numpy arrays. First let us set a slice of the inducing_inputs:
m.inducing_inputs[2:, 0] = [1,3,5] print m.inducing_inputs
index | sparse_gp.inducing_inputs | constraints | priors [0 0] | -4.00000000 | | [1 0] | -2.00000000 | | [2 0] | 1.00000000 | | [3 0] |...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Or you use the parameters as normal numpy arrays for calculations:
precision = 1./m.Gaussian_noise.variance print precision
[ 1.42857143]
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Getting the model parameter’s gradientsThe gradients of a model can shed light on understanding the (possibly hard) optimization process. The gradients of each parameter handle can be accessed through their gradient field.:
print "all gradients of the model:\n", m.gradient print "\n gradients of the rbf kernel:\n", m.rbf.gradient
all gradients of the model: [ 2.1054468 3.67055686 1.28382016 -0.36934978 -0.34404866 99.49876932 -12.83697274 -268.02492615] gradients of the rbf kernel: [ 99.49876932 -12.83697274]
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
If we optimize the model, the gradients (should be close to) zero
m.optimize() print m.gradient
[ -4.62140715e-04 -2.13365576e-04 9.60255226e-05 4.82744982e-04 8.56445996e-05 -5.25465293e-06 -6.89058756e-06 -9.34850797e-02]
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Adjusting the model’s constraintsWhen we initially call the example, it was optimized and hence the log-likelihood gradients were close to zero. However, since we have been changing the parameters, the gradients are far from zero now. Next we are going to show how to optimize the model setting different restrictions o...
m.rbf.variance.unconstrain() print m m.unconstrain() print m
Name : sparse_gp Objective : -613.999681976 Number of Parameters : 8 Number of Optimization Parameters : 8 Updates : True Parameters: sparse_gp.  | value | constraints | priors inducing_inputs  | (5, 1) | | rbf.varianc...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
If you want to unconstrain only a specific constraint, you can call the respective method, such as `unconstrain_fixed()` (or `unfix()`) to only unfix fixed parameters:
m.inducing_inputs[0].fix() m.rbf.constrain_positive() print m m.unfix() print m
Name : sparse_gp Objective : -613.999681976 Number of Parameters : 8 Number of Optimization Parameters : 7 Updates : True Parameters: sparse_gp.  | value | constraints | priors inducing_inputs  | (5, 1) | {fixed} | rbf.varianc...
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Tying ParametersNot yet implemented for GPy version 0.8.0 Optimizing the modelOnce we have finished defining the constraints, we can now optimize the model with the function optimize.:
m.Gaussian_noise.constrain_positive() m.rbf.constrain_positive() m.optimize()
No handlers could be found for logger "rbf"
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
By deafult, GPy uses the lbfgsb optimizer.Some optional parameters may be discussed here. * `optimizer`: which optimizer to use, currently there are lbfgsb, fmin_tnc, scg, simplex or any unique identifier uniquely identifying an optimizer.Thus, you can say m.optimize('bfgs') for using the `lbfgsb` optimizer * `messages...
fig = m.plot()
/home/nbuser/anaconda2_501/lib/python2.7/site-packages/matplotlib/figure.py:1999: UserWarning:This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
We can even change the backend for plotting and plot the model using a different backend.
GPy.plotting.change_plotting_library('plotly') fig = m.plot(plot_density=True) GPy.plotting.show(fig, filename='gpy_sparse_gp_example')
This is the format of your plot grid: [ (1,1) x1,y1 ] Aw, snap! We don't have an account for ''. Want to try again? You can authenticate with your email address or username. Sign in is not case sensitive. Don't have an account? plot.ly Questions? support@plot.ly
MIT
tests/GPy/models_basic.ipynb
gopala-kr/ds-notebooks
Partial Dependence PlotsSigurd Carlsen Feb 2019Holger Nahrstaedt 2020.. currentmodule:: skoptPlot objective now supports optional use of partial dependence as well asdifferent methods of defining parameter values for dependency plots.
print(__doc__) import sys from skopt.plots import plot_objective from skopt import forest_minimize import numpy as np np.random.seed(123) import matplotlib.pyplot as plt
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Objective functionPlot objective now supports optional use of partial dependence as well asdifferent methods of defining parameter values for dependency plots
# Here we define a function that we evaluate. def funny_func(x): s = 0 for i in range(len(x)): s += (x[i] * i) ** 2 return s
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Optimisation using decision treesWe run forest_minimize on the function
bounds = [(-1, 1.), ] * 3 n_calls = 150 result = forest_minimize(funny_func, bounds, n_calls=n_calls, base_estimator="ET", random_state=4)
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Partial dependence plotHere we see an example of using partial dependence. Even when settingn_points all the way down to 10 from the default of 40, this method isstill very slow. This is because partial dependence calculates 250 extrapredictions for each point on the plots.
_ = plot_objective(result, n_points=10)
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
It is possible to change the location of the red dot, which normally showsthe position of the found minimum. We can set it 'expected_minimum',which is the minimum value of the surrogate function, obtained by aminimum search method.
_ = plot_objective(result, n_points=10, minimum='expected_minimum')
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Plot without partial dependenceHere we plot without partial dependence. We see that it is a lot faster.Also the values for the other parameters are set to the default "result"which is the parameter set of the best observed value so far. In the caseof funny_func this is close to 0 for all parameters.
_ = plot_objective(result, sample_source='result', n_points=10)
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Modify the shown minimumHere we try with setting the `minimum` parameters to something other than"result". First we try with "expected_minimum" which is the set ofparameters that gives the miniumum value of the surrogate function,using scipys minimum search method.
_ = plot_objective(result, n_points=10, sample_source='expected_minimum', minimum='expected_minimum')
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
"expected_minimum_random" is a naive way of finding the minimum of thesurrogate by only using random sampling:
_ = plot_objective(result, n_points=10, sample_source='expected_minimum_random', minimum='expected_minimum_random')
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
We can also specify how many initial samples are used for the two different"expected_minimum" methods. We set it to a low value in the next examplesto showcase how it affects the minimum for the two methods.
_ = plot_objective(result, n_points=10, sample_source='expected_minimum_random', minimum='expected_minimum_random', n_minimum_search=10) _ = plot_objective(result, n_points=10, sample_source="expected_minimum", minimum='expected_minimum', n_minimum_search=2)
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Set a minimum locationLastly we can also define these parameters ourself by parsing a listas the minimum argument:
_ = plot_objective(result, n_points=10, sample_source=[1, -0.5, 0.5], minimum=[1, -0.5, 0.5])
_____no_output_____
BSD-3-Clause
dev/notebooks/auto_examples/plots/partial-dependence-plot.ipynb
scikit-optimize/scikit-optimize.github.io
Training ModelsThe central goal of machine learning is to train predictive models that can be used by applications. In Azure Machine Learning, you can use scripts to train models leveraging common machine learning frameworks like Scikit-Learn, Tensorflow, PyTorch, SparkML, and others. You can run these training scrip...
import azureml.core from azureml.core import Workspace # Load the workspace from the saved config file ws = Workspace.from_config() print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
Ready to use Azure ML 1.17.0 to work with ml-sdk
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Create a Training ScriptYou're going to use a Python script to train a machine learning model based on the diabates data, so let's start by creating a folder for the script and data files.
import os, shutil # Create a folder for the experiment files training_folder = 'diabetes-training' os.makedirs(training_folder, exist_ok=True) # Copy the data file into the experiment folder shutil.copy('data/diabetes.csv', os.path.join(training_folder, "diabetes.csv"))
_____no_output_____
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Now you're ready to create the training script and save it in the folder.
%%writefile $training_folder/diabetes_training.py # Import libraries from azureml.core import Run import pandas as pd import numpy as np import joblib import os from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn...
Overwriting diabetes-training/diabetes_training.py
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Use an Estimator to Run the Script as an ExperimentYou can run experiment scripts using a **RunConfiguration** and a **ScriptRunConfig**, or you can use an **Estimator**, which abstracts both of these configurations in a single object.In this case, we'll use a generic **Estimator** object to run the training experimen...
from azureml.train.estimator import Estimator from azureml.core import Experiment # Create an estimator estimator = Estimator(source_directory=training_folder, entry_script='diabetes_training.py', compute_target='local', conda_packages=['scikit-learn'] ...
WARNING - If 'script' has been provided here and a script file name has been specified in 'run_config', 'script' provided in ScriptRunConfig initialization will take precedence.
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
As with any experiment run, you can use the **RunDetails** widget to view information about the run and get a link to it in Azure Machine Learning studio.
from azureml.widgets import RunDetails RunDetails(run).show()
_____no_output_____
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
You can also retrieve the metrics and outputs from the **Run** object.
# Get logged metrics metrics = run.get_metrics() for key in metrics.keys(): print(key, metrics.get(key)) print('\n') for file in run.get_file_names(): print(file)
Regularization Rate 0.01 Accuracy 0.774 AUC 0.8484929598487486 azureml-logs/60_control_log.txt azureml-logs/70_driver_log.txt logs/azureml/8_azureml.log outputs/diabetes_model.pkl
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Register the Trained ModelNote that the outputs of the experiment include the trained model file (**diabetes_model.pkl**). You can register this model in your Azure Machine Learning workspace, making it possible to track model versions and retrieve them later.
from azureml.core import Model # Register the model run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model', tags={'Training context':'Estimator'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Accuracy']}) # List regi...
diabetes_model version: 4 Training context : Estimator AUC : 0.8484929598487486 Accuracy : 0.774 diabetes_mitigated_20 version: 1 diabetes_mitigated_19 version: 1 diabetes_mitigated_18 version: 1 diabetes_mitigated_17 version: 1 diabetes_mitigated_16 version: 1 diabetes_mitigated_15 version: 1 diabe...
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Create a Parameterized Training ScriptYou can increase the flexibility of your training experiment by adding parameters to your script, enabling you to repeat the same training experiment with different settings. In this case, you'll add a parameter for the regularization rate used by the Logistic Regression algorithm...
import os, shutil # Create a folder for the experiment files training_folder = 'diabetes-training-params' os.makedirs(training_folder, exist_ok=True) # Copy the data file into the experiment folder shutil.copy('data/diabetes.csv', os.path.join(training_folder, "diabetes.csv"))
_____no_output_____
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Now let's create a script containing a parameter for the regularization rate hyperparameter.
%%writefile $training_folder/diabetes_training.py # Import libraries from azureml.core import Run import pandas as pd import numpy as np import joblib import os import argparse from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_sc...
Writing diabetes-training-params/diabetes_training.py
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Use a Framework-Specific EstimatorYou used a generic **Estimator** class to run the training script, but you can also take advantage of framework-specific estimators that include environment definitions for common machine learning frameworks. In this case, you're using Scikit-Learn, so you can use the **SKLearn** esti...
from azureml.train.sklearn import SKLearn from azureml.widgets import RunDetails # Create an estimator estimator = SKLearn(source_directory=training_folder, entry_script='diabetes_training.py', script_params = {'--reg_rate': 0.1}, compute_target='local' ...
WARNING - If 'script' has been provided here and a script file name has been specified in 'run_config', 'script' provided in ScriptRunConfig initialization will take precedence. WARNING - If 'arguments' has been provided here and arguments have been specified in 'run_config', 'arguments' provided in ScriptRunConfig ini...
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Once again, you can get the metrics and outputs from the run.
# Get logged metrics metrics = run.get_metrics() for key in metrics.keys(): print(key, metrics.get(key)) print('\n') for file in run.get_file_names(): print(file)
Regularization Rate 0.1 Accuracy 0.7736666666666666 AUC 0.8483904671874223 azureml-logs/60_control_log.txt azureml-logs/70_driver_log.txt logs/azureml/8_azureml.log outputs/diabetes_model.pkl
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
Register A New Version of the ModelNow that you've trained a new model, you can register it as a new version in the workspace.
from azureml.core import Model # Register the model run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model', tags={'Training context':'Parameterized SKLearn Estimator'}, properties={'AUC': run.get_metrics()['AUC'], 'Accuracy': run.get_metrics()['Acc...
diabetes_model version: 5 Training context : Parameterized SKLearn Estimator AUC : 0.8483904671874223 Accuracy : 0.7736666666666666 diabetes_model version: 4 Training context : Estimator AUC : 0.8484929598487486 Accuracy : 0.774 diabetes_mitigated_20 version: 1 diabetes_mitigated_19 version: 1 diabe...
MIT
02-Training_Models.ipynb
djanie1/mslearn-aml-labs
CHALLENGE TASKStats Challege notebook Fit multiple linear regression for the following data and check for the assumptions using pythonX1 22 22 25 26 24 28 29 27 24 33 39 42X2 15 14 18 13 12 11 11 10 5 9 7 3Y 55 56 55 59 66 65 69 70 75 75 78 79
import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt """ Convert the data values into DataFrames""" stats_chal={"X1":[22, 22, 25, 26, 24, 28, 29, 27, 24, 33, 39, 42], "X2":[15, 14, 18, 13, 12, 11, 11, 10, 5, 9, 7, 3], "Y":[55, 56, 55, 59, 66, 65, 6...
Intercept: 74.59582972285749 Coefficients: [ 0. 0.33138486 -1.61056402]
MIT
Stats_Live_MLR_challenge.ipynb
krishnavizster/Statistics
CHECKING FOR LINEAR REGRESSION ASSUMPTIONS 1.Linear Relationship Aims at finding linear relationship between the independent and dependent variables TESTA simple visual way of determining this is through the use of scatter plot2.Variables follow a normal DistributionThis assumption ensures that for each value of indepe...
#Multicollinearity test corr =df.corr() print(corr) #Linearity and Normality Test import seaborn as sns sns.set(style="ticks", color_codes=True, font_scale=2) g=sns.pairplot(df, height=3, diag_kind="hist",kind="reg") g.fig.suptitle("Scatter Plot",y=1.08) X_test = sm.add_constant(X_test) X_test y_pred=mlr_model.pr...
_____no_output_____
MIT
Stats_Live_MLR_challenge.ipynb
krishnavizster/Statistics
Prepare stimuli in stereo with sync tone in the L channelTo syncrhonize the recording systems, each stimulus file goes in stereo, the L channel has the stimulus, and the R channel has a pure tone (500-5Khz).This is done here, with the help of the rigmq.util.stimprep moduleIt uses (or creates) a dictionary of {stim_fil...
import socket import os import sys import logging import warnings import numpy as np import glob from rigmq.util import stimprep as sp # setup the logger logger = logging.getLogger() handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler...
2019-06-27 16:36:59,810 rigmq.util.stimprep INFO Processing /Users/zeke/experiment/birds/g3v3/SongData/acute_0/bos.wav 2019-06-27 16:36:59,813 rigmq.util.stimprep INFO tag_freq = 1000 2019-06-27 16:36:59,815 rigmq.util.stimprep INFO Will resample from 40414 to 60621 sampes 2019-06-27 16:36:59,831 rigmq.util...
MIT
rigmq/util/prepare_audio_stims_debug.ipynb
zekearneodo/rigmq
Scaling and Normalization
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler from scipy.cluster.vq import whiten
_____no_output_____
MIT
Scaling and Normalization.ipynb
dbl007/python-cheat-sheet