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 |
|---|---|---|---|---|---|
Options | classTrainFeatures = basic_features
classModel = 'modelSwish'
varSet = "basic_features"
nSplits = 10
ensembleSize = 10
ensembleMode = 'loss'
maxEpochs = 200
compileArgs = {'loss':'binary_crossentropy', 'optimizer':'adam'}
trainParams = {'epochs' : 1, 'batch_size' : 256, 'verbose' : 0}
modelParams = {'version':classMo... |
Training on 30 features: ['DER_mass_MMC', 'DER_mass_transverse_met_lep', 'DER_mass_vis', 'PRI_tau_pt', 'DER_deltar_tau_lep', 'PRI_jet_leading_eta', 'PRI_lep_eta', 'PRI_tau_eta', 'DER_lep_eta_centrality', 'DER_mass_jet_jet', 'DER_deltaeta_jet_jet', 'DER_pt_tot', 'DER_met_phi_centrality', 'PRI_jet_num', 'PRI_met', 'DER_... | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Import data | trainData = h5py.File(dirLoc + 'train.hdf5', "r+")
valData = h5py.File(dirLoc + 'val.hdf5', "r+") | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Determine LR | lrFinder = batchLRFindClassifier(trainData, nSplits, getClassifier, modelParams, trainParams, lrBounds=[1e-5,0.1], trainOnWeights=False, verbose=0)
compileArgs['lr'] = 1e-2 | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Train classifier | results, histories = batchTrainClassifier(trainData, nSplits, getClassifier, modelParams, trainParams, cosAnnealMult=2, trainOnWeights=False, patience=200, maxEpochs=maxEpochs, verbose=1) | Using cosine annealing
Running fold 1 / 10
2 classes found, running in binary mode
1 New best found: 0.400561252252
3 New best found: 0.378149787368
6 New best found: 0.371132547385
7 New best found: 0.367546338621
13 New best found: 0.365329898119
14 New best found: 0.363622459261
15 New best found: 0.362778083891
27... | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Construct ensemble | with open('train_weights/resultsFile.pkl', 'r') as fin:
results = pickle.load(fin)
ensemble, weights = assembleEnsemble(results, ensembleSize, ensembleMode, compileArgs) | Choosing ensemble by loss
Model 0 is 5 with loss = 0.353122269688
Model 1 is 0 with loss = 0.359138851781
Model 2 is 4 with loss = 0.359199308138
Model 3 is 3 with loss = 0.359459306769
Model 4 is 1 with loss = 0.360221377798
Model 5 is 7 with loss = 0.361065514653
Model 6 is 6 with loss = 0.361383996214
Model 7 is 2 w... | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Response on development data | batchEnsemblePredict(ensemble, weights, trainData, ensembleSize=10, verbose=1)
print 'Training ROC AUC: unweighted {}, weighted {}'.format(roc_auc_score(getFeature('targets', trainData), getFeature('pred', trainData)),
roc_auc_score(getFeature('targets', train... | Training ROC AUC: unweighted 0.913288160645, weighted 0.934247941282
| MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Response on val data | batchEnsemblePredict(ensemble, weights, valData, ensembleSize=10, verbose=1)
print 'Testing ROC AUC: unweighted {}, weighted {}'.format(roc_auc_score(getFeature('targets', valData), getFeature('pred', valData)),
roc_auc_score(getFeature('targets', valData), get... | Testing ROC AUC: unweighted 0.908779216407, weighted 0.929871759305
| MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Evaluation Import in dataframe | def convertToDF(datafile, columns={'gen_target', 'gen_weight', 'pred_class'}, nLoad=-1):
data = pandas.DataFrame()
data['gen_target'] = getFeature('targets', datafile, nLoad)
data['gen_weight'] = getFeature('weights', datafile, nLoad)
data['pred_class'] = getFeature('pred', datafile, nLoad)
print le... | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
MVA distributions | getClassPredPlot([valData[bkgVal], valData[sigVal]], weightName='gen_weight')
def AMS(s, b):
""" Approximate Median Significance defined as:
AMS = sqrt(
2 { (s + b + b_r) log[1 + (s/(b+b_r))] - s}
)
where b_r = 10, b = background, s = signal, log is natural logarith... | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Save classified data | name = dirLoc + signal + "_" + channel + "_" + varSet + '_' + classModel + '_classifiedData.csv'
print "Saving data to", name
valData.to_csv(name, columns=['gen_target', 'gen_weight', 'gen_sample', 'pred_class']) | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Save/load | name = "weights/DNN_" + signal + "_" + channel + "_" + varSet + '_' + classModel
print name | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Save | saveEnsemble(name, ensemble, weights, compileArgs, overwrite=1) | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Load | ensemble, weights, compileArgs, inputPipe, outputPipe = loadEnsemble(name) | _____no_output_____ | MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Programming Assignment Готовим LDA по рецептам Как вы уже знаете, в тематическом моделировании делается предположение о том, что для определения тематики порядок слов в документе не важен; об этом гласит гипотеза >. Сегодня мы будем работать с несколько нестандартной для тематического моделирования коллекцией, которую... | import json
with open("recipes.json") as f:
recipes = json.load(f)
print recipes[1] | {u'cuisine': u'southern_us', u'id': 25693, u'ingredients': [u'plain flour', u'ground pepper', u'salt', u'tomatoes', u'ground black pepper', u'thyme', u'eggs', u'green tomatoes', u'yellow corn meal', u'milk', u'vegetable oil']}
| Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Составление корпуса | from gensim import corpora, models
import numpy as np | Couldn't import dot_parser, loading of dot files will not be possible.
| Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Наша коллекция небольшая и влезает в оперативную память. Gensim может работать с такими данными и не требует их сохранения на диск в специальном формате. Для этого коллекция должна быть представлена в виде списка списков, каждый внутренний список соответствует отдельному документу и состоит из его слов. Пример коллекци... | texts = [recipe["ingredients"] for recipe in recipes]
dictionary = corpora.Dictionary(texts) # составляем словарь
corpus = [dictionary.doc2bow(text) for text in texts] # составляем корпус документов
corpus[0]
print texts[0]
print corpus[0] | [u'romaine lettuce', u'black olives', u'grape tomatoes', u'garlic', u'pepper', u'purple onion', u'seasoning', u'garbanzo beans', u'feta cheese crumbles']
[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1)]
| Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
У объекта dictionary есть две полезных переменных: dictionary.id2token и dictionary.token2id; эти словари позволяют находить соответствие между ингредиентами и их индексами. Обучение моделиВам может понадобиться [документация](https://radimrehurek.com/gensim/models/ldamodel.html) LDA в gensim. __Задание 1.__ Обучите м... | np.random.seed(76543)
# здесь код для построения модели:
ldamodel = models.ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=40, passes=5)
topics = ldamodel.show_topics(num_topics=40, num_words=10, formatted=False)
c_salt, c_sugar, c_water, c_mushrooms, c_chicken, c_eggs = 0, 0, 0, 0, 0, 0
for topic in topics:
... | 20 7 8 1 1 1
| Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Фильтрация словаряВ топах тем гораздо чаще встречаются первые три рассмотренных ингредиента, чем последние три. При этом наличие в рецепте курицы, яиц и грибов яснее дает понять, что мы будем готовить, чем наличие соли, сахара и воды. Таким образом, даже в рецептах есть слова, часто встречающиеся в текстах и не несущи... | import copy
dictionary2 = copy.deepcopy(dictionary) | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
__Задание 2.__ У объекта dictionary2 есть переменная dfs - это словарь, ключами которого являются id токена, а элементами - число раз, сколько слово встретилось во всей коллекции. Сохраните в отдельный список ингредиенты, которые встретились в коллекции больше 4000 раз. Вызовите метод словаря filter_tokens, подав в кач... | more4000 = [w for w, count in dictionary2.dfs.iteritems() if count > 4000]
dict_size_before = len(dictionary2.items())
dictionary2.filter_tokens(bad_ids=more4000)
dict_size_after = len(dictionary2.items())
def get_corpus_size(corp):
res = 0
for doc in corp:
res += len(doc)
#for w in doc:
... | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Сравнение когерентностей__Задание 3.__ Постройте еще одну модель по корпусу corpus2 и словарю dictioanary2, остальные параметры оставьте такими же, как при первом построении модели. Сохраните новую модель в другую переменную (не перезаписывайте предыдущую модель). Не забудьте про фиксирование seed!Затем воспользуйтесь... | np.random.seed(76543)
# здесь код для построения модели:
ldamodel2 = models.ldamodel.LdaModel(corpus2, id2word=dictionary2, num_topics=40, passes=5)
coherences = ldamodel.top_topics(corpus)
coherences2 = ldamodel2.top_topics(corpus2)
import numpy as np
list1 = np.array([])
for coh in coherences:
list1 = np.append(l... | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Считается, что когерентность хорошо соотносится с человеческими оценками интерпретируемости тем. Поэтому на больших текстовых коллекциях когерентность обычно повышается, если убрать фоновую лексику. Однако в нашем случае этого не произошло. Изучение влияния гиперпараметра alpha В этом разделе мы будем работать со вто... | def save_answers4(count_model2, count_model3):
with open("cooking_LDA_pa_task4.txt", "w") as fout:
fout.write(" ".join([str(el) for el in [count_model2, count_model3]])) | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Таким образом, гиперпараметр alpha влияет на разреженность распределений тем в документах. Аналогично гиперпараметр eta влияет на разреженность распределений слов в темах. LDA как способ понижения размерностиИногда распределения над темами, найденные с помощью LDA, добавляют в матрицу объекты-признаки как дополнительн... | from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_score
def save_answers5(accuracy):
with open("cooking_LDA_pa_task5.txt", "w") as fout:
fout.write(str(accuracy)) | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Для такого большого количества классов это неплохая точность. Вы можете попроовать обучать RandomForest на исходной матрице частот слов, имеющей значительно большую размерность, и увидеть, что accuracy увеличивается на 10-15%. Таким образом, LDA собрал не всю, но достаточно большую часть информации из выборки, в матриц... | def generate_recipe(model, num_ingredients):
theta = np.random.dirichlet(model.alpha)
for i in range(num_ingredients):
t = np.random.choice(np.arange(model.num_topics), p=theta)
topic = model.show_topic(0, topn=model.num_terms)
topic_distr = [x[1] for x in topic]
terms = [x[0] fo... | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Интерпретация построенной моделиВы можете рассмотреть топы ингредиентов каждой темы. Большиснтво тем сами по себе похожи на рецепты; в некоторых собираются продукты одного вида, например, свежие фрукты или разные виды сыра.Попробуем эмпирически соотнести наши темы с национальными кухнями (cuisine). Построим матрицу A ... | import pandas
import seaborn
from matplotlib import pyplot as plt
%matplotlib inline
def compute_topic_cuisine_matrix(model, corpus, recipes):
# составляем вектор целевых признаков
targets = list(set([recipe["cuisine"] for recipe in recipes]))
# составляем матрицу
tc_matrix = pandas.DataFrame(data=np.ze... | _____no_output_____ | Apache-2.0 | course3/week4/CookingLDA_PA.ipynb | astarostin/MachineLearningSpecializationCoursera |
Reading Notebooks* https://nbformat.readthedocs.io/en/latest/api.html Read a .ipynb fileA notebook consists of metadata, format info, and a list of cells. Very simple. | import nbformat
from nbformat.v4.nbbase import new_code_cell, new_markdown_cell, new_notebook
# read notebook file
filename = "02.01-Tagging.ipynb"
with open(filename, "r") as fp:
nb = nbformat.read(fp, as_version=4)
# display file metadata
print(f"nbformat = {nb.nbformat}.{nb.nbformat_minor}")
display(nb.metadat... | nbformat = 4.4
| MIT | notebooks/nb_lite.ipynb | jckantor/nbcollection |
Loop over cellsThe heavy lifting is in the list of cells. Here's how to loop over cells. The cell metadata is editable in JupyterLab, and has a 'tags' key where you manage a list of your own tags. If you wanted to remove cells, this would be the place to tag them. | for n, cell in enumerate(nb.cells):
print(f"\nCell {n}")
print(" metadata:", cell.metadata)
print(" cell_type:", cell.cell_type)
print(" keys():", cell.keys()) |
Cell 0
metadata: {}
cell_type: markdown
keys(): dict_keys(['cell_type', 'metadata', 'source'])
Cell 1
metadata: {}
cell_type: markdown
keys(): dict_keys(['cell_type', 'metadata', 'source'])
Cell 2
metadata: {'tags': ['differential-equations', 'SIR-model', 'compartmental-model']}
cell... | MIT | notebooks/nb_lite.ipynb | jckantor/nbcollection |
Remove Code ElementsRemove code segments with specific tags. This uses regular expressions to identify code segments in code cells. This is actually a bit more general and would allow substitution as well. | import re
SOLUTION_CODE = "### BEGIN SOLUTION(.*)### END SOLUTION"
HIDDEN_TESTS = "### BEGIN HIDDEN TESTS(.*)### END HIDDEN TESTS"
def replace_code(pattern, replacement):
regex = re.compile(pattern, re.DOTALL)
for cell in nb.cells:
if cell.cell_type == "code" and regex.findall(cell.source):
... | - ### BEGIN SOLUTION(.*)### END SOLUTION removed
- ### BEGIN HIDDEN TESTS(.*)### END HIDDEN TESTS removed
| MIT | notebooks/nb_lite.ipynb | jckantor/nbcollection |
Remove cells with a specified tagNote the use of a generator. This keeps things fast, but does need an explicit `list` if you need a list of tagged cells. | # a example of an iterator that returns all cells satisfying certain conditions.
def get_cells(nb, tag):
for cell in nb.cells:
if cell.cell_type == "markdown":
if "tags" in cell.metadata.keys():
if tag in cell.metadata["tags"]:
yield cell
tagged_cells = list... | - removing cells with tag exercise
| MIT | notebooks/nb_lite.ipynb | jckantor/nbcollection |
Write file out | with open("out.ipynb", "w") as fp:
nbformat.write(nb, fp) | _____no_output_____ | MIT | notebooks/nb_lite.ipynb | jckantor/nbcollection |
Execute notebookshttps://nbconvert.readthedocs.io/en/latest/execute_api.html | import nbformat
from nbconvert.preprocessors import CellExecutionError, ExecutePreprocessor
nb_filename = "out.ipynb"
nb_filename_out = "executed_" + nb_filename
# read file
with open("out.ipynb", "r") as fp:
nb = nbformat.read(fp, as_version=4)
# instantiate an execution processor allowing errors
ep = ExecutePr... | _____no_output_____ | MIT | notebooks/nb_lite.ipynb | jckantor/nbcollection |
PaginaciónEl objetivo es crear una lista de páginas a mostrar. Se mostrará la página actual y las 3 siguientes y las 3 anteriores, y además la primera y la última. El algoritmo debe calcular qué numeros se muestran, y crear una lista con ellos. Además se pondrán espacios en blanco en el lugar donde irán los puntos sus... | def lista_paginas(paginas, actual):
if paginas < 10:
pagination = list(range(paginas))
else:
if actual <= 4:
pagination = (actual + 6)*['']
pagination[-1] = paginas - 1
pages = range(0, actual+4)
for i, p in enumerate(pages):
pagina... | 8 4 [0, 1, 2, 3, 4, 5, 6, 7]
9 4 [0, 1, 2, 3, 4, 5, 6, 7, 8]
10 2 [0, 1, 2, 3, 4, 5, '', 9]
10 3 [0, 1, 2, 3, 4, 5, 6, '', 9]
10 4 [0, 1, 2, 3, 4, 5, 6, 7, '', 9]
10 5 [0, '', 2, 3, 4, 5, 6, 7, 8, 9]
10 6 [0, '', 3, 4, 5, 6, 7, 8, 9]
10 7 [0, '', 4, 5, 6, 7, 8, 9]
10 8 [0, '', 5, 6, 7, 8, 9]
10 9 [0, '', 6, 7, 8, 9]
10... | MIT | analysis/pagination.ipynb | osso73/contabilidad |
Ahora personalizo, puedo escoger el número de páginas anteriores y posteriores a mostrar. | def lista_paginas_custom(paginas, actual, num=3):
"""Calcula la lista de páginas a mostrar. Las cadenas
nulas corresponden a puntos suspensivos.
Argumentos
----------
paginas: int
Total de páginas que hay.
actual: int
página actual.
num: int
número de paginas an... | pags=8 act=4 num=1: [0, 1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8]
pags=8 act=4 num=2: [0, 1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8]
pags=8 act=4 num=3: [0, 1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8]
pags=8 act=4 num=4: [0, 1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8]
pags=8 act=4 num=5: [0, 1, 2, 3, 4, 5, 6... | MIT | analysis/pagination.ipynb | osso73/contabilidad |
DF2 | df2 = df2.drop(columns = ["emotion_gold","emotion:confidence","_unit_id", "_golden","_unit_state","_trusted_judgments","_last_judgment_at","id","idiom_id"])
unique_emoniotns = df2.emotion.unique()
unique_emoniotns
reverse_dict = {"Anger":"anger", "Aggression":"anger","Disgust":"disgust","Contempt":"disgust","Sadness":"... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DF4 | import tweepy
auth = tweepy.OAuthHandler("wso6hl1mmqx5YlLuuiJ7apQci", "QQ1mGejEs70qBmpzODBGhMc2FLzVo30hctpaZjSVlBtlmsTiSZ")
auth.set_access_token("1055878812-fI40KKPy7zNOK8N18WROQ02AgnH820WFeOhTIDS", "q5WJXcqCWFRoU7KxR797fz4Ku3C6a876xdECJchupsnfY")
try:
redirect_url = auth.get_authorization_url()
except tweepy.Tw... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DF7 | None | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DF8 | df8[3] = "aslangiray"
df8
tweets8 = []
errorlist8 = []
code88errorlist = []
for i in range (len(df8)):
if i%100 == 0:
print(i)
if df8[3][i] == "aslangiray":
try:
x = (tweetminer(df8[0][i]))
df8[3][i] = x
except tweepy.TweepError as e:
e1 = "'code': 88"... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DF9 | None | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DF11 | for i in range (1431):
k = df11[0][i]
if "---" in k:
k = k.replace("---","")
if "\t" in k:
k = k.replace("\t", " ")
if "." in k:
k = k.replace(".","")
if "," in k:
k = k.replace(",","")
if "?" in k:
k = k.replace("?","")
if "!" in k:
k = k.repl... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DF13 | df13 = df13.drop(columns = ["Unnamed: 0"])
unique_emoniotns = df13.emotions.unique()
unique_emoniotns
reverse_dict = {"sadness":"sad", "joy":"happy","love":"happy","anger":"anger","fear":"fear","surprise":"surprise"}
df13["emotions"] = df13["emotions"].map(reverse_dict)
df13final = df13
df13final.to_csv("/Users/erenmac... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
DFJSON1 | dfjson1 = dfjson1.drop(columns = ["extras","metadata"])
labellist = []
for i in range (len(dfjson1)):
if dfjson1["annotation"][i]["label"] == ['1']:
labellist.append("negative")
else:
labellist.append("del")
for i in range (len(labellist)):
k = labellist[i]
dfjson1["annotation"][i] = k
d... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
Finalize DB | meryem1 = pd.read_json("/Users/erenmac/Downloads/df12f.json")
meryem2 = pd.read_json("/Users/erenmac/Downloads/result2.json")
meryem1
erenfin = pd.read_json("/Users/erenmac/Desktop/NEW_DATA/Cleaned_Data/final_multilabel.json")
erenfin2[0] = erenfin2.annotation
erenfin2[1] = erenfin2.content
erenfin2 = erenfin2.drop(co... | _____no_output_____ | MIT | Text_Emotion_Data_Exp/text_data_exp.ipynb | Erenaliaslangiray/ENGR497_Emotion_Recog |
Reverse a StringThis interview question requires you to reverse a string using recursion. Make sure to think of the base case here.Again, make sure you use recursion to accomplish this. Do not slice (e.g. string[::-1]) or use iteration, there muse be a recursive call for the function. SolutionIn order to reverse a st... | def rev(s):
if len(s)==1:
return s
else:
return rev(s[1:]) + rev(s[0])
rev("Hello my name is Shivam") | _____no_output_____ | CC0-1.0 | DS_Algo/Recursion/recursion_string.ipynb | ShivamBhosale/100DaysOfCode_V2 |
Extra NotesThe "trick" to this question was thinking about what a base case would look like when reversing a string recursively. It takes a lot of practice to be able to begin thinking like this, so don't worry if you're struggling! However it is important to fully understand the solution! String Permutation Problem... | def permute(s):
out = []
if len(s) == 1:
out = [s]
else:
# For every letter in string
for i, let in enumerate(s):
# For every permutation resulting from Step 2 and 3 described above
for perm in permute(s[:i] + s[i+1:]):
out += [let + perm]
... | _____no_output_____ | CC0-1.0 | DS_Algo/Recursion/recursion_string.ipynb | ShivamBhosale/100DaysOfCode_V2 |
Dependencies | import json, glob
from tweet_utility_scripts import *
from tweet_utility_preprocess_roberta_scripts_aux import *
from transformers import TFRobertaModel, RobertaConfig
from tokenizers import ByteLevelBPETokenizer
from tensorflow.keras import layers
from tensorflow.keras.models import Model | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Load data | test = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/test.csv')
print('Test samples: %s' % len(test))
display(test.head()) | Test samples: 3534
| MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Model parameters | input_base_path = '/kaggle/input/239-robertabase/'
with open(input_base_path + 'config.json') as json_file:
config = json.load(json_file)
config
# vocab_path = input_base_path + 'vocab.json'
# merges_path = input_base_path + 'merges.txt'
base_path = '/kaggle/input/qa-transformers/roberta/'
vocab_path = base_path ... | Models to predict:
/kaggle/input/239-robertabase/model_fold_1.h5
/kaggle/input/239-robertabase/model_fold_2.h5
/kaggle/input/239-robertabase/model_fold_3.h5
/kaggle/input/239-robertabase/model_fold_4.h5
/kaggle/input/239-robertabase/model_fold_5.h5
| MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Tokenizer | tokenizer = ByteLevelBPETokenizer(vocab_file=vocab_path, merges_file=merges_path,
lowercase=True, add_prefix_space=True) | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Pre process | test['text'].fillna('', inplace=True)
test['text'] = test['text'].apply(lambda x: x.lower())
test['text'] = test['text'].apply(lambda x: x.strip())
x_test, x_test_aux, x_test_aux_2 = get_data_test(test, tokenizer, config['MAX_LEN'], preprocess_fn=preprocess_roberta_test) | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Model | module_config = RobertaConfig.from_pretrained(config['config_path'], output_hidden_states=False)
def model_fn(MAX_LEN):
input_ids = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')
base_model = TFRob... | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Make predictions | NUM_TEST_IMAGES = len(test)
test_start_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN']))
test_end_preds = np.zeros((NUM_TEST_IMAGES, config['MAX_LEN']))
for model_path in model_path_list:
print(model_path)
model = model_fn(config['MAX_LEN'])
model.load_weights(model_path)
test_preds = model.p... | /kaggle/input/239-robertabase/model_fold_1.h5
/kaggle/input/239-robertabase/model_fold_2.h5
/kaggle/input/239-robertabase/model_fold_3.h5
/kaggle/input/239-robertabase/model_fold_4.h5
/kaggle/input/239-robertabase/model_fold_5.h5
| MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Post process | test['start'] = test_start_preds.argmax(axis=-1)
test['end'] = test_end_preds.argmax(axis=-1)
test['selected_text'] = test.apply(lambda x: decode(x['start'], x['end'], x['text'], config['question_size'], tokenizer), axis=1)
# Post-process
test["selected_text"] = test.apply(lambda x: ' '.join([word for word in x['sele... | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Visualize predictions | test['text_len'] = test['text'].apply(lambda x : len(x))
test['label_len'] = test['selected_text'].apply(lambda x : len(x))
test['text_wordCnt'] = test['text'].apply(lambda x : len(x.split(' ')))
test['label_wordCnt'] = test['selected_text'].apply(lambda x : len(x.split(' ')))
test['text_tokenCnt'] = test['text'].apply... | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Test set predictions | submission = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/sample_submission.csv')
submission['selected_text'] = test['selected_text']
submission.to_csv('submission.csv', index=False)
submission.head(10) | _____no_output_____ | MIT | Model backlog/Inference/239-tweet-inference-5fold-roberta-hf-cosine-wr.ipynb | dimitreOliveira/Tweet-Sentiment-Extraction |
Load Refer Dataset | data_root = '../../data' # contains refclef, refcoco, refcoco+, refcocog and images
dataset = 'refcoco'
splitBy = 'unc'
refer = REFER(data_root, dataset, splitBy) | loading dataset refcoco into memory...
creating index...
index created.
DONE (t=5.66s)
| MIT | tools/refer/pyReferDemo.ipynb | mikelmrtinez/ReferringExpression-COCO-VILBERT |
Stats about the Dataset | # print stats about the given dataset
print ('dataset [%s_%s] contains: ' % (dataset, splitBy))
ref_ids = refer.getRefIds()
image_ids = refer.getImgIds()
print ('%s expressions for %s refs in %s images.' % (len(refer.Sents), len(ref_ids), len(image_ids)))
print ('\nAmong them:')
if dataset == 'refclef':
if splitBy... | REF ID: , 25
{'sent_ids': [71, 72, 73], 'file_name': 'COCO_train2014_000000581563_3.jpg', 'ann_id': 1345868, 'ref_id': 25, 'image_id': 581563, 'split': 'testB', 'sentences': [{'tokens': ['lower', 'left', 'corner', 'darkness'], 'raw': 'lower left corner darkness', 'sent_id': 71, 'sent': 'lower left corner darkness'}, {... | MIT | tools/refer/pyReferDemo.ipynb | mikelmrtinez/ReferringExpression-COCO-VILBERT |
Show Refered Object and its Expressions | # randomly sample one ref
ref_ids = refer.getRefIds()
ref_id = ref_ids[np.random.randint(0, len(ref_ids))]
ref = refer.Refs[ref_id]
print ('ref_id [%s] (ann_id [%s])' % (ref_id, refer.refToAnn[ref_id]['id']))
# show the segmentation of the referred object
plt.figure()
refer.showRef(ref, seg_box='seg')
plt.show()
# or s... | sent_id[75185]: snowboarding buy in yellow
sent_id[75186]: man in yellow
sent_id[75187]: yellow guy
| MIT | tools/refer/pyReferDemo.ipynb | mikelmrtinez/ReferringExpression-COCO-VILBERT |
Binary trees | import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from dtreeviz.trees import *
from lolviz import *
import numpy as np
import pandas as pd
%config InlineBackend.figure_format = 'retina' | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Setup Make sure to install stuff:```pip install -U dtreevizpip install -U lolvizbrew install graphviz``` Binary tree class definitionA binary tree has a payload (a value) and references to left and right children. One or both of the children references can be `None`. A reference to a node is the same thing as a ref... | class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return str(self.value)
def __str__(self):
return str(self.value) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Manual tree construction Here's how to create and visualize a single node: | root = TreeNode(1)
treeviz(root) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
**Given `left` and `right` nodes, create node `root` with those nodes as children.** | left = TreeNode(2)
right = TreeNode(3)
root = ...
treeviz(root) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Solutionleft = TreeNode(2)right = TreeNode(3)root = TreeNode(1,left,right)treeviz(root) **Write code to create the following tree structure** | left = ...
right = ...
root = ...
treeviz(root) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Solutionleft = TreeNode(2,TreeNode(4))right = TreeNode(3,TreeNode(5),TreeNode(6))root = TreeNode(1,left,right)treeviz(root) Walking trees manuallyTo walk a tree, we simply follow the left and right children references, avoiding any `None` references. **Q.** Given tree `r` shown here, what Python expressions refer to t... | left = TreeNode(443,TreeNode(-34))
right = TreeNode(17,TreeNode(99))
r = TreeNode(10,left,right)
treeviz(r) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Solutionr.left, r.right **Q.** Given the same tree `r`, what Python expressions refer to the nodes with -34 and 99 in them? Solutionr.left.left, r.right.left Walking all nodesNow let's create a function to walk all nodes in a tree. Remember that our template for creating any recursive function looks like this:```def f... | def walk(p:TreeNode):
if p is None: return # step 1
print(p.value) # step 2
walk(p.left) # step 3
walk(p.right) # step 3 (there is no step 4 for this problem) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Let's create the simple 3-level tree we had before: | left = TreeNode(2,TreeNode(4))
right = TreeNode(3,TreeNode(5),TreeNode(6))
root = TreeNode(1,left,right)
treeviz(root) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
**Q.** What is the output of running `walk(root)`? Solution We walk the tree depth first, from left to right124356 Searching through nodesHere's how to search for an element as you walk, terminating as soon as the node with `x` is found: | def search(p:TreeNode, x:object):
print("enter ",p)
if p is None: return None
print(p)
if x==p.value:
return p
q = search(p.left, x)
if q is not None:
return q
q = search(p.right, x)
return q | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
**Q.** What is the output of running `search(root, 5)`? Solution We walk the tree depth first as before, but now we stop when we reach the node with 5:12435 To see the recursion entering and exiting (or discovering and finishing) nodes, here is a variation that prints out its progress through the tree: | def search(p:TreeNode, x:object):
if p is None: return None
print("enter ",p)
if x==p.value:
print("exit ",p)
return p
q = search(p.left, x)
if q is not None:
print("exit ",p)
return q
q = search(p.right, x)
print("exit ",p)
return q
search(root, 5) | enter 1
enter 2
enter 4
exit 4
exit 2
enter 3
enter 5
exit 5
exit 3
exit 1
| MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Creating (random) decision tree "stumps"A regression tree stump is a tree with a decision node at the root and two predictor leaves. These are used by gradient boosting machines as the "weak learners." | class TreeNode: # acts as decision node and leaf. it's a leaf if split is None
def __init__(self, split=None, prediction=None, left=None, right=None):
self.split = split
self.prediction = prediction
self.left = left
self.right = right
def __repr__(self):
return str(self.value)
def __str__(self... | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
The following code shows where sklearn would do a split with a normal decision tree. | X, y = df.sqfeet.values.reshape(-1,1), df.rent.values
t = DecisionTreeRegressor(max_depth=1)
t.fit(X,y)
fig, ax = plt.subplots(1, 1, figsize=(3,1.5))
t = rtreeviz_univar(t,
X, y,
feature_names='sqfeet',
target_name='rent',
fontsize=9,
... | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Instead of picking the optimal split point, we can choose a random value in between the minimum and maximum x value, like extremely random forests do: | def stumpfit(x, y):
if len(x)==1 or len(np.unique(x))==1: # if one x value, make leaf
return TreeNode(prediction=y[0])
split = np.round(np.random.uniform(min(x),max(x)))
t = TreeNode(split)
t.left = TreeNode(prediction=np.mean(y[x<split]))
t.right = TreeNode(prediction=np.mean(y[x>=split]))
... | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
**Run the following code multiple times to see how it creates different y lists in the nodes, according to the split value.** | root = stumpfit(X.reshape(-1),y)
treeviz(root) | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
Creating random decision trees (single variable)And now to demonstrate the magic of recursion. If we replace```t.left = TreeNode(prediction=np.mean(y[x<split]))```with```t.left = treefit(x[x<split], y[x<split])```(and same for `t.right`) then all of the sudden we get a full decision tree, rather than just a stump! | def treefit(x, y):
if len(x)==1 or len(np.unique(x))==1: # if one x value, make leaf
return TreeNode(prediction=y[0])
split = np.round(np.random.uniform(min(x),max(x)))
t = TreeNode(split)
t.left = treefit(x[x<split], y[x<split])
t.right = treefit(x[x>=split], y[x>=split])
return t
roo... | _____no_output_____ | MIT | labs/trees/binary-trees.ipynb | testinggg-art/msds621 |
 Split column by example DataPrep also offers you a way to easily split a column into multiple columns.The SplitColumnByExampleBuilder class lets... | import azureml.dataprep as dprep
dflow = dprep.read_lines(path='../data/crime.txt')
df = dflow.head(10)
df['Line'].iloc[0] | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
As you can see above, you can't split this particular file by space character as it will create too many columns.That's where split_column_by_example could be quite useful. | builder = dflow.builders.split_column_by_example('Line', keep_delimiters=True)
builder.preview() | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
Couple things to take note of here. No examples were given, and yet DataPrep was able to generate quite reasonable split program. We have passed keep_delimiters=True so we can see all the data split into columns. In practice, though, delimiters are rarely useful, so let's exclude them. | builder.keep_delimiters = False
builder.preview() | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
This looks pretty good already, except that one case number is split into 2 columns. Taking the first row as an example, we want to keep case number as "HY329907" instead of "HY" and "329907" seperately. If we request generation of suggested examples we will get a list of examples that require input. | suggestions = builder.generate_suggested_examples()
suggestions
suggestions.iloc[0]['Line'] | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
Having retrieved source value we can now provide an example of desired split.Notice that we chose not to split date and time but rather keep them together in one column. | builder.add_example(example=(suggestions['Line'].iloc[0], ['10140490','HY329907','7/5/2015 23:50','050XX N NEWLAND AVE','820','THEFT']))
builder.preview() | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
As we can see from the preview, some of the crime types (`Line_6`) do not show up as expected. Let's try to add one more example. | builder.add_example(example=(df['Line'].iloc[1],['10139776','HY329265','7/5/2015 23:30','011XX W MORSE AVE','460','BATTERY']))
builder.preview() | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
This looks just like what we need. Let's get a dataflow with splited columns and drop original column. | dflow = builder.to_dataflow()
dflow = dflow.drop_columns(['Line'])
dflow.head(5) | _____no_output_____ | MIT | how-to-guides/split-column-by-example.ipynb | Bhaskers-Blu-Org2/AMLDataPrepDocs |
Choose GPU (this may not be needed on your computer) | %env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES='' | env: CUDA_DEVICE_ORDER=PCI_BUS_ID
env: CUDA_VISIBLE_DEVICES=''
| MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
load packages | from tfumap.umap import tfUMAP
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tqdm.autonotebook import tqdm
import umap
import pandas as pd | _____no_output_____ | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
Load dataset | from sklearn.datasets import make_moons
X_train, Y_train = make_moons(1000, random_state=0, noise=0.1)
X_train_flat = X_train
X_test, Y_test = make_moons(1000, random_state=1, noise=0.1)
X_test_flat = X_test
X_valid, Y_valid = make_moons(1000, random_state=2, noise=0.1)
plt.scatter(X_test[:,0], X_test[:,1], c=Y_test) | _____no_output_____ | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
Create model and train | embedder = tfUMAP(direct_embedding=True, verbose=True, negative_sample_rate=5, training_epochs=100)
z = embedder.fit_transform(X_train_flat) | tfUMAP(direct_embedding=True, negative_sample_rate=5,
optimizer=<tensorflow.python.keras.optimizer_v2.adadelta.Adadelta object at 0x7f56a22fbcc0>,
tensorboard_logdir='/tmp/tensorboard/20200709-104443',
training_epochs=100)
Construct fuzzy simplicial set
Thu Jul 9 10:44:47 2020 Finding Nearest Neig... | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
Plot model output | fig, ax = plt.subplots( figsize=(8, 8))
sc = ax.scatter(
z[:, 0],
z[:, 1],
c=Y_train.astype(int)[:len(z)],
cmap="tab10",
s=0.1,
alpha=0.5,
rasterized=True,
)
ax.axis('equal')
ax.set_title("UMAP in Tensorflow embedding", fontsize=20)
plt.colorbar(sc, ax=ax); | _____no_output_____ | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
View loss | from tfumap.umap import retrieve_tensors
import seaborn as sns
loss_df = retrieve_tensors(embedder.tensorboard_logdir)
loss_df[:3]
ax = sns.lineplot(x="step", y="val", hue="group", data=loss_df[loss_df.variable=='umap_loss'])
ax.set_xscale('log') | _____no_output_____ | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
Save output | from tfumap.paths import ensure_dir, MODEL_DIR
output_dir = MODEL_DIR/'projections'/ 'moons' / 'direct'
ensure_dir(output_dir)
embedder.save(output_dir)
loss_df.to_pickle(output_dir / 'loss_df.pickle')
np.save(output_dir / 'z.npy', z) | _____no_output_____ | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
Compare to direct embedding with base UMAP | from umap import UMAP
z_umap = UMAP(verbose=True).fit_transform(X_train_flat)
### realign using procrustes
from scipy.spatial import procrustes
z_align, z_umap_align, disparity = procrustes(z, z_umap)
print(disparity)
fig, axs = plt.subplots(ncols=2, figsize=(20, 8))
ax = axs[0]
sc = ax.scatter(
z_align[:, 0],
... | _____no_output_____ | MIT | notebooks/dataset-projections/moons/moons-direct-embedding.ipynb | timsainb/ParametricUMAP_paper |
Train and hyperparameter tune with RAPIDS Prerequisites - Create an Azure ML Workspace and setup environmnet on local computer following the steps in [Azure README.md](https://gitlab-master.nvidia.com/drobison/aws-sagemaker-gtc-2020/tree/master/azure/README.md ) | # verify installation and check Azure ML SDK version
import azureml.core
print('SDK version:', azureml.core.VERSION) | SDK version: 1.2.0
| Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
- Install [AzCopy](https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-v10) to download dataset from [Azure Blob storage](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-overview) to your local computer (or another storage account). In this example, we will use 20 million rows (s... | !./azcopy cp 'https://airlinedataset.blob.core.windows.net/airline-20m/airline_20m.parquet' '/home/jzedlewski/code/drobinson/aws-sagemaker-gtc-2020/azure/notebooks
' | /bin/sh: 1: ./azcopy: not found
| Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Initialize workspace Load and initialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architectureworkspace) object from the existing workspace you created in the prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored i... | from azureml.core.workspace import Workspace
# if a locally-saved configuration file for the workspace is not available, use the following to load workspace
# ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, workspace_name=workspace_name)
ws = Workspace.from_config()
print('Workspace nam... | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Upload data Upload the dataset to the workspace's default datastore: | path_on_datastore = 'data_airline'
datastore.upload(src_dir='/add/local/path', target_path=path_on_datastore, overwrite=False, show_progress=True)
ds_data = datastore.path(path_on_datastore)
print(ds_data) | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Create AML compute You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecturecompute-target) for training your model. In this notebook, we will use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learn... | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# choose a name for your cluster
gpu_cluster_name = 'gpu-cluster'
if gpu_cluster_name in ws.compute_targets:
gpu_cluster = ws.compute_targets[gpu_cluster_name]
if gpu_cluster and type(gpu_... | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Prepare training script Create a project directory that will contain code from your local machine that you will need access to on the remote resource. This includes the training script and additional files your training script depends on. In this example, the training script is provided: `train_rapids_RF.py` - entry s... | import os
project_folder = './train_rapids'
os.makedirs(project_folder, exist_ok=True) | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
We will log some metrics by using the `Run` object within the training script:```pythonfrom azureml.core.run import Runrun = Run.get_context()``` We will also log the parameters and highest accuracy the model achieves:```pythonrun.log('Accuracy', np.float(accuracy))```These run metrics will become particularly importan... | import shutil
shutil.copy('../code/train_rapids_RF.py', project_folder) | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Train model on the remote compute Now that you have your data and training script prepared, you are ready to train on your remote compute. Create experiment Create an [Experiment](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architectureexperiment) to track all the runs in ... | from azureml.core import Experiment
experiment_name = 'train_rapids'
experiment = Experiment(ws, name=experiment_name) | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Create environment The [Environment class](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.environment.environment?view=azure-ml-py) allows you to build a Docker image and customize the system that you will use for training. We will build a container image using a RAPIDS container as base image a... | from azureml.core import Environment
# create the environment
rapids_env = Environment('rapids_env')
# create the environment inside a Docker container
rapids_env.docker.enabled = True
# specify docker steps as a string. Alternatively, load the string from a file
dockerfile = """
FROM rapidsai/rapidsai-nightly:0.13-... | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Create a RAPIDS Estimator The [Estimator](https://docs.microsoft.com/en-us/python/api/azureml-train-core/azureml.train.estimator.estimator?view=azure-ml-py) class can be used with machine learning frameworks that do not have a pre-configure estimator. `script_params` is a dictionary of command-line arguments to pass t... | from azureml.train.estimator import Estimator
script_params = {
'--data_dir': ds_data.as_mount(),
'--n_bins': 32,
}
estimator = Estimator(source_directory=project_folder,
script_params=script_params,
compute_target=gpu_cluster,
entry_script='t... | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Tune model hyperparameters We can optimize our model's hyperparameters and improve the accuracy using Azure Machine Learning's hyperparameter tuning capabilities. Start a hyperparameter sweep Let's define the hyperparameter space to sweep over. We will tune `n_estimators`, `max_depth` and `max_features` parameters. I... | from azureml.train.hyperdrive.runconfig import HyperDriveConfig
from azureml.train.hyperdrive.sampling import RandomParameterSampling
from azureml.train.hyperdrive.run import PrimaryMetricGoal
from azureml.train.hyperdrive.parameter_expressions import choice, loguniform, uniform
param_sampling = RandomParameterSamplin... | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
This will launch the RAPIDS training script with parameters that were specified in the cell above. | # start the HyperDrive run
hyperdrive_run = experiment.submit(hyperdrive_run_config) | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Monitor HyperDrive runs Monitor and view the progress of the machine learning training run with a [Jupyter widget](https://docs.microsoft.com/en-us/python/api/azureml-widgets/azureml.widgets?view=azure-ml-py).The widget is asynchronous and provides live updates every 10-15 seconds until the job completes. | from azureml.widgets import RunDetails
RunDetails(hyperdrive_run).show()
# hyperdrive_run.wait_for_completion(show_output=True)
# hyperdrive_run.cancel() | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Find and register best model | best_run = hyperdrive_run.get_best_run_by_primary_metric()
print(best_run.get_details()['runDefinition']['arguments']) | _____no_output_____ | Apache-2.0 | azure/notebooks/.ipynb_checkpoints/HPO-RAPIDS-checkpoint.ipynb | miguelusque/cloud-ml-examples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.