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 |
|---|---|---|---|---|---|
15. Of the houses with more than 300 square meters of living room, how many have more than 2 bathrooms? | # Estrategy:
# 1. Select only houses whit mor than 300m² of livingo room and mor than 2 bedrooms.
house_300m_2bat = data[(data['m2']>300) & (data['bathrooms']>2)].shape[0]
print('Of the houses whit 300 square meters of living room, {} houses have 2 bathrooms.'.format(house_300m_2bat)) | Of the houses whit 300 square meters of living room, 2201 houses have 2 bathrooms.
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
List of themes The list of available `matplotlib` themes is stored in a list called `plt.style.available`. There are 26 of them. | import matplotlib.pyplot as plt
plt.style.available | _____no_output_____ | 0BSD | src/notebooks/199-matplotlib-style-sheets.ipynb | s-lasch/The-Python-Graph-Gallery |
Scatterplot The [scatterplot section](https://python-graph-gallery.com/scatter-plot/) of the gallery explains in depth how to build a basic scatterplot with `matplotlib`. It is pretty straightforward thanks to the `plot()` function. | # Create a dataset:
import numpy as np
import pandas as pd
df=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })
# plot
plt.plot( 'x', 'y', data=df, linestyle='none', marker='o')
plt.show()
| _____no_output_____ | 0BSD | src/notebooks/199-matplotlib-style-sheets.ipynb | s-lasch/The-Python-Graph-Gallery |
Apply a theme Now, let's make this chart a bit prettier thanks to the style called `fivethirtyheight`. In case you don't know it already, [FiveThirtyHeight](https://fivethirtyeight.com) is an online newspaper that often displays some very nice dataviz articles. | plt.style.use('fivethirtyeight')
plt.plot( 'x', 'y', data=df, linestyle='none', marker='o')
plt.title('Scatterplot with the five38 theme', fontsize=12)
plt.show() | _____no_output_____ | 0BSD | src/notebooks/199-matplotlib-style-sheets.ipynb | s-lasch/The-Python-Graph-Gallery |
Apply the style on a barchart You can apply the same exact tip for any kind of chart to make it look better. Here is a barchart example coming from the barchart section of the gallery. It uses the `dark_background` theme to demo another type of customization. | # create dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
# Create horizontal bars
plt.barh(y_pos, height)
# Create names on the x-axis
plt.yticks(y_pos, bars)
# Show graphic
plt.style.use('dark_background')
plt.show() | _____no_output_____ | 0BSD | src/notebooks/199-matplotlib-style-sheets.ipynb | s-lasch/The-Python-Graph-Gallery |
Search from MQLThese are examples of[MQL](https://shebanq.ancient-data.org/static/docs/MQL-Query-Guide.pdf)queries on[SHEBANQ](https://shebanq.ancient-data.org/hebrew/queries), now expressedas Text-Fabric search templates.For more basic examples, see[searchTutorial](https://github.com/etcbc/text-fabric/blob/master/doc... | %load_ext autoreload
%autoreload 2
from tf.fabric import Fabric
ETCBC = 'hebrew/etcbc4c'
TF = Fabric( modules=ETCBC )
api = TF.load('''
rela function pdp
''')
api.makeAvailableIn(globals()) | 0.00s loading features ...
| 0.21s B rela from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
| 0.08s B function from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
| 0.13s B pdp from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
| ... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Oliver Glanz[Oliver Glanz: PP with adjective followed by noun](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=547)```select all objects where[phrase FOCUS typ = PP [word sp= prep] [word sp=adjv] [word sp=subs]]```64 results having 251 words. | query = '''
phrase typ=PP
word sp=prep
<: word sp=adjv
<: word sp=subs
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
for r in S.fetch(amount=10):
print(S.glean(r)) | 0.00s Checking search template ...
0.00s loading features ...
| 0.20s B sp from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
| 0.22s B typ from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
0.43s All additional features loaded - for details use loadLog()... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
The number of results is right. The number of words that SHEBANQ reportsis the number of words in the phrases of the result. Let us count them: | print(sum([len(L.d(r[0], otype='word')) for r in S.fetch()])) | 251
| MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Martijn Naaijer[Martijn Naaijer: Object clauses with >CR](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=997)```Select all objects where [clause rela = Objc [word focus first lex = '>CR']]```157 results | query = '''
verse
clause rela=Objc
=: word lex=>CR
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
for r in sorted(S.fetch(), key=lambda x: C.rank.data[x[0]-1])[0:10]:
print(S.glean(r)) | 0.00s Checking search template ...
0.00s loading features ...
| 0.19s B lex from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
0.20s All additional features loaded - for details use loadLog()
0.20s Setting up search space for 3 objects ...
0.94s Constraining search space with 3 re... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
We have fewer cases: 96 instead of 157.We are working on the ETCBC version 4c, and the query has been executed against 4b.There have been coding updates that are relevant to this query, e.g. in Genesis 43:27, which is in the resultson SHEBANQ, but not here. In 4c the `rela` is `Attr`, and not `Objc`. | query = '''
verse book=Genesis chapter=43 verse=27
clause
=: word lex=>CR
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
results = sorted(S.fetch(), key=lambda x: C.rank.data[x[0]-1])
for r in results:
print(r[1], F.rela.v(r[1]), S.glean(r)) | 0.00s Checking search template ...
0.00s loading features ...
0.00s All additional features loaded - for details use loadLog()
0.01s Setting up search space for 3 objects ...
0.75s Constraining search space with 3 relations ...
0.84s Setting up retrieval plan ...
0.84s Ready to deliver results from 3 node... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Cody Kingham[Cody Kingham: MI Hierarchies. p.18n49. First Person Verbs in Narrative](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=1050)```SELECT ALL OBJECTS WHERE[book [clause txt = 'N' [word FOCUS sp = verb [word ps = p1 ] ] ]]OR[book [clause txt = '?N' [word FOCU... | query = '''
book
clause txt=N|?N
word sp=verb ps=p1
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
for r in sorted(S.fetch(), key=lambda x: C.rank.data[x[0]-1])[0:10]:
print(S.glean(r)) | 0.00s Checking search template ...
0.00s loading features ...
| 0.21s B ps from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
| 0.04s B txt from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
0.26s All additional features loaded - for details use loadLog()... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Reinoud Oosting[Reinoud Oosting: to go + object marker](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=755)```Select all objectswhere [clause [phrase function = Pred OR function = PreC [word FOCUS sp = verb AND vs = qal AND lex = "HLK[" ] ] .. [phrase FOCUS [word First lex = ">T"... | query = '''
clause
p1:phrase function=Pred|PreC
word sp=verb vs=qal lex=HLK[
p2:phrase
=: word lex=>T
p1 # p2
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
for r in sorted(S.fetch(), key=lambda x: C.rank.data[x[0]-1])[0:10]:
print(S.glean(r)) | 0.00s Checking search template ...
0.00s loading features ...
| 0.21s B vs from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
0.21s All additional features loaded - for details use loadLog()
0.21s Setting up search space for 5 objects ...
1.84s Constraining search space with 6 re... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Reinoud Oosting (ii)[Reinoud Oosting: To establish covenant](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=1485)```select all objectswhere [clause [phrase function = Pred OR function = PreC [word FOCUS sp = verb AND vs = hif AND lex = "QWM[" ] ] .. [phrase function = Objc [word ... | query = '''
clause
phrase function=Pred|PreC
word sp=verb vs=hif lex=QWM[
phrase function=Objc
word lex=BRJT/
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
resultsx = sorted((L.u(r[0], otype='verse')+r for r in S.fetch()), key=lambda r: sortKey(r[0]))
for r in resultsx:
print(S.glean... | Genesis 6:18 clause[וַהֲקִמֹתִ֥י אֶת־בְּרִיתִ֖י אִתָּ֑ךְ ] phrase[הֲקִמֹתִ֥י ] הֲקִמֹתִ֥י phrase[אֶת־בְּרִיתִ֖י ] בְּרִיתִ֖י
Genesis 9:9 clause[הִנְנִ֥י מֵקִ֛ים אֶת־בְּרִיתִ֖י אִתְּכֶ֑ם ...] phrase[מֵקִ֛ים ] מֵקִ֛ים phrase[אֶת־בְּרִיתִ֖י ] בְּרִיתִ֖י
Genesis 9:11 clause[וַהֲקִמֹתִ֤י אֶת־בְּרִיתִי֙ אִתְּכֶ֔ם ] phras... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Reinoud Oosting (iii)[Reinoud Oosting: To find grace in sight of](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=1484)```select all objectswhere [clause [phrase FOCUS function = Pred OR function = PreC [word sp = verb AND vs = qal AND lex = "MY>[" ] ] .. [phrase function = Objc [... | query = '''
clause
p1:phrase function=Pred|PreC
word sp=verb vs=qal lex=MY>[
p2:phrase function=Objc
word lex=XN/
p3:phrase function=Cmpl
word lex=B
<: word lex=<JN/
p2 << p3
'''
S.study(query)
S.showPlan(details=True)
S.count(progress=1000, limit=-1) | 0.00s Checking search template ...
0.00s Setting up search space for 8 objects ...
3.44s Constraining search space with 9 relations ...
3.45s Setting up retrieval plan ...
3.46s Ready to deliver results from 16034 nodes
Iterate over S.fetch() to get the results
See S.showPlan() to interpret the results
Search... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
By Stephen Ku[Stephen Ku: Verbless Clauses](https://shebanq.ancient-data.org/hebrew/query?version=4&id=1314)```SELECT ALL OBJECTS WHERE [clause [phrase function IN (Subj) [phrase_atom NOT rela IN (Appo,Para,Spec) [word FOCUS pdp IN (subs,nmpr,prps,prde,prin,adjv) ] ] ] NOTEXIST [phrase function IN ... | excludedRela = {'Appo', 'Para', 'Spec'}
'|'.join(x[0] for x in F.rela.freqList() if x[0] not in excludedRela)
print(S.relationLegend)
query = '''
clause
p1:phrase function=Subj
phrase_atom rela=NA|rec|par|Adju|Attr|adj|Coor|atr|dem|Resu|Objc|Link|mod|Subj|RgRc|ReVo|Cmpl|PrAd|PreC|Sfxs
word pdp=subs|nmpr|prp... | 0.00s Checking search template ...
0.00s loading features ...
| 0.14s B ls from /Users/dirk/github/text-fabric-data/hebrew/etcbc4c
0.15s All additional features loaded - for details use loadLog()
0.15s Setting up search space for 6 objects ...
2.55s Constraining search space with 6 re... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
We have too many results, because we have not posed the restrictions by the `NOTEXIST` operator.Let's weed out the results that do not satisfy those criteria.That is, essentially, throwing away those clauses * that have a phrase with `function=Pred` after the phrase with `function=Pred`* where the second phrase has a p... | indent(reset=True)
properResults = []
resultWords = set()
for r in S.fetch():
clause = r[0]
phrase1 = r[1]
phrase2 = r[4]
word1 = r[3]
word2 = r[5]
phrases = [p for p in L.d(clause, otype='phrase') if sortKey(p) > sortKey(phrase1)]
words2 = L.d(phrase2, otype='word')
if any(F.f... | 0.17s Found 2307 proper results with 2133 words in it
| MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
We have still many more results than the MQL query on SHEBANQ.Let us have a look at some results words and compare them with the result words on SHEBANQ.It is handy to fetch from SHEBANQ the csv file with query results. | resultsx = sorted((L.u(r[0], otype='verse')+r for r in properResults), key=lambda r: sortKey(r[0]))
resultWordsx = [(L.u(w, otype='verse')[0], w) for w in sortNodes(resultWords)]
for r in resultWordsx[0:30]:
print(S.glean(r)) | Genesis 5:4 יְמֵי־
Genesis 5:4 אָדָ֗ם
Genesis 5:4 שְׁמֹנֶ֥ה
Genesis 5:4 מֵאֹ֖ת
Genesis 5:5 כָּל־
Genesis 5:5 יְמֵ֤י
Genesis 5:5 אָדָם֙
Genesis 5:5 תְּשַׁ֤ע
Genesis 5:5 מֵאֹות֙
Genesis 5:5 שְׁלֹשִׁ֖ים
Genesis 5:8 כָּל־
Genesis 5:8 יְמֵי־
Genesis 5:8 שֵׁ֔ת
Genesis 5:8 שְׁתֵּ֤ים
Genesis 5:8 עֶשְׂרֵה֙
Genesis 5:... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
In the list from SHEBANQ we see this: | Genesis,5,4,יְמֵי־,,JWM/,day,subs,2169,m,pl,NA,NA,451,1,326,9
Genesis,5,4,אָדָ֗ם ,,>DM===/,Adam,nmpr,2170,m,sg,NA,NA,451,1,326,9
Genesis,5,4,שְׁמֹנֶ֥ה ,,CMNH/,eight,subs,2175,unknown,sg,NA,NA,453,1,326,9
Genesis,5,4,מֵאֹ֖ת ,,M>H/,hundred,subs,2176,f,pl,NA,NA,453,1,326,9
Genesis,5,5,כָּל־,,KL/,whole,subs,2185,m,sg,NA,NA... | _____no_output_____ | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
The first thing we miss in the SHEBANQ output is```Genesis 5:14 עֶ֣שֶׂר```and in SHEBANQ we see that this word has not been marked with `ls=card|ordn`,while in the newer ETCBC4c it is!I have conducted a SHEBANQ query for numerals here[Dirk Roorda: numerals](https://shebanq.ancient-data.org/hebrew/query?id=1487),in vers... | S.study('''
word ls=card|ordn
''') | 0.00s Checking search template ...
0.00s Setting up search space for 1 objects ...
0.61s Constraining search space with 0 relations ...
0.61s Setting up retrieval plan ...
0.61s Ready to deliver results from 7013 nodes
Iterate over S.fetch() to get the results
See S.showPlan() to interpret the results
| MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
So we have for the amount of numerals in the ETCBC versions:4|4b|4c---|---|---6839|7014|7013On the basis of these numbers, this cannot be the sole cause of the discrepancy. By Dirk Roorda[Dirk Roorda: Yesh](https://shebanq.ancient-data.org/hebrew/query?version=4b&id=556)```select all objects where[book [chapter [verse... | query = '''
verse
clause
clause_atom
phrase
phrase_atom
word lex=JC/|>JN/
'''
S.study(query)
S.showPlan()
S.count(progress=1000, limit=-1)
for r in sorted(S.fetch(), key=lambda x: C.rank.data[x[0]-1])[0:10]:
print(S.glean(r)) | 0.00s Checking search template ...
0.00s Setting up search space for 6 objects ...
0.77s Constraining search space with 5 relations ...
0.81s Setting up retrieval plan ...
0.82s Ready to deliver results from 5415 nodes
Iterate over S.fetch() to get the results
See S.showPlan() to interpret the results
0.82s... | MIT | various/searchFromMQL.ipynb | dirkroorda/text-fabric-data |
Question and Answer Chatbot ---------- Loading the DataUsing the Babi Data Set from Facebook Research.https://research.fb.com/downloads/babi/ Paper Reference- Jason Weston, Antoine Bordes, Sumit Chopra, Tomas Mikolov, Alexander M. Rush, "Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks", http... | import pickle
import numpy as np
with open("train_qa.txt", "rb") as fp: # Unpickling
train_data = pickle.load(fp)
with open("test_qa.txt", "rb") as fp: # Unpickling
test_data = pickle.load(fp) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
---- Exploring the Format of the Data | type(test_data)
type(train_data)
len(test_data)
len(train_data)
train_data[0]
' '.join(train_data[0][0])
' '.join(train_data[0][1])
train_data[0][2] | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
----- Setting up Vocabulary of All Words | # Create a set that holds the vocab words
vocab = set()
all_data = test_data + train_data
for story, question , answer in all_data:
# In case you don't know what a union of sets is:
# https://www.programiz.com/python-programming/methods/set/union
vocab = vocab.union(set(story))
vocab = vocab.union(set(q... | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Vectorizing the Data | vocab
# Reserve 0 for pad_sequences
vocab_size = len(vocab) + 1 | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
----------- | from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
# integer encode sequences of words
tokenizer = Tokenizer(filters=[])
tokenizer.fit_on_texts(vocab)
tokenizer.word_index
train_story_text = []
train_question_text = []
train_answers = []
for story,question,answer in t... | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Functionalize Vectorization | def vectorize_stories(data, word_index=tokenizer.word_index, max_story_len=max_story_len,max_question_len=max_question_len):
'''
INPUT:
data: consisting of Stories,Queries,and Answers
word_index: word index dictionary from tokenizer
max_story_len: the length of the longest story (used for pad_... | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Creating the Model | from keras.models import Sequential, Model
from keras.layers.embeddings import Embedding
from keras.layers import Input, Activation, Dense, Permute, Dropout
from keras.layers import add, dot, concatenate
from keras.layers import LSTM | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Placeholders for InputsRecall we technically have two inputs, stories and questions. So we need to use placeholders. `Input()` is used to instantiate a Keras tensor. | input_sequence = Input((max_story_len,))
question = Input((max_question_len,)) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Building the NetworksTo understand why we chose this setup, make sure to read the paper we are using:* Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, Rob Fergus, "End-To-End Memory Networks", http://arxiv.org/abs/1503.08895 Encoders Input Encoder m | # Input gets embedded to a sequence of vectors
input_encoder_m = Sequential()
input_encoder_m.add(Embedding(input_dim=vocab_size,output_dim=64))
input_encoder_m.add(Dropout(0.3))
# This encoder will output:
# (samples, story_maxlen, embedding_dim) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Input Encoder c | # embed the input into a sequence of vectors of size query_maxlen
input_encoder_c = Sequential()
input_encoder_c.add(Embedding(input_dim=vocab_size,output_dim=max_question_len))
input_encoder_c.add(Dropout(0.3))
# output: (samples, story_maxlen, query_maxlen) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Question Encoder | # embed the question into a sequence of vectors
question_encoder = Sequential()
question_encoder.add(Embedding(input_dim=vocab_size,
output_dim=64,
input_length=max_question_len))
question_encoder.add(Dropout(0.3))
# output: (samples, query_maxlen, embedding... | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Encode the Sequences | # encode input sequence and questions (which are indices)
# to sequences of dense vectors
input_encoded_m = input_encoder_m(input_sequence)
input_encoded_c = input_encoder_c(input_sequence)
question_encoded = question_encoder(question) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Use dot product to compute the match between first input vector seq and the query | # shape: `(samples, story_maxlen, query_maxlen)`
match = dot([input_encoded_m, question_encoded], axes=(2, 2))
match = Activation('softmax')(match) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Add this match matrix with the second input vector sequence | # add the match matrix with the second input vector sequence
response = add([match, input_encoded_c]) # (samples, story_maxlen, query_maxlen)
response = Permute((2, 1))(response) # (samples, query_maxlen, story_maxlen) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Concatenate | # concatenate the match matrix with the question vector sequence
answer = concatenate([response, question_encoded])
answer
# Reduce with RNN (LSTM)
answer = LSTM(32)(answer) # (samples, 32)
# Regularization with Dropout
answer = Dropout(0.5)(answer)
answer = Dense(vocab_size)(answer) # (samples, vocab_size)
# we outp... | Train on 10000 samples, validate on 1000 samples
Epoch 1/120
10000/10000 [==============================] - 7s 701us/step - loss: 0.8846 - acc: 0.4966 - val_loss: 0.6938 - val_acc: 0.4970
Epoch 2/120
10000/10000 [==============================] - 4s 364us/step - loss: 0.7022 - acc: 0.4987 - val_loss: 0.6935 - val_acc: ... | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Saving the Model | filename = 'chatbot_120_epochs.h5'
model.save(filename) | _____no_output_____ | MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Evaluating the Model Plotting Out Training History | import matplotlib.pyplot as plt
%matplotlib inline
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show() | dict_keys(['val_loss', 'val_acc', 'loss', 'acc'])
| MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Evaluating on Given Test Set | model.load_weights(filename)
pred_results = model.predict(([inputs_test, queries_test]))
test_data[0][0]
story =' '.join(word for word in test_data[0][0])
print(story)
query = ' '.join(word for word in test_data[0][1])
print(query)
print("True Test Answer from Data is:",test_data[0][2])
#Generate prediction from model
... | Predicted answer is: no
Probability of certainty was: 0.9999999
| MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Writing Own Stories and QuestionsRemember you can only use words from the existing vocab | vocab
# Note the whitespace of the periods
my_story = "John left the kitchen . Sandra dropped the football in the garden ."
my_story.split()
my_question = "Is the football in the garden ?"
my_question.split()
mydata = [(my_story.split(),my_question.split(),'yes')]
my_story,my_ques,my_ans = vectorize_stories(mydata)
pre... | Predicted answer is: yes
Probability of certainty was: 0.97079676
| MIT | Chat-Bots.ipynb | SUSHRUTM/NLP-CHATBOT |
Monitoring Data DriftOver time, models can become less effective at predicting accurately due to changing trends in feature data. This phenomenon is known as *data drift*, and it's important to monitor your machine learning solution to detect it so you can retrain your models if necessary.In this lab, you'll configure... | !pip show azureml-datadrift | Name: azureml-datadrift
Version: 1.34.0
Summary: Contains functionality for data drift detection for various datasets used in machine learning.
Home-page: https://docs.microsoft.com/python/api/overview/azure/ml/?view=azure-ml-py
Author: Microsoft Corp
Author-email: None
License: https://aka.ms/azureml-sdk-lic... | MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
Connect to your workspaceWith the required SDK packages installed, now you're ready to connect to your workspace.> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into... | from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to work with', ws.name) | Ready to work with azml-ws
| MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
Create a *baseline* datasetTo monitor a dataset for data drift, you must register a *baseline* dataset (usually the dataset used to train your model) to use as a point of comparison with data collected in the future. | from azureml.core import Datastore, Dataset
# Upload the baseline data
default_ds = ws.get_default_datastore()
default_ds.upload_files(files=['./data/diabetes.csv', './data/diabetes2.csv'],
target_path='diabetes-baseline',
overwrite=True,
show_prog... | Uploading an estimated of 2 files
Uploading ./data/diabetes.csv
Uploaded ./data/diabetes.csv, 1 files out of an estimated total of 2
Uploading ./data/diabetes2.csv
Uploaded ./data/diabetes2.csv, 2 files out of an estimated total of 2
Uploaded 2 files
Registering baseline dataset...
Baseline dataset registered!
| MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
Create a *target* datasetOver time, you can collect new data with the same features as your baseline training data. To compare this new data to the baseline data, you must define a target dataset that includes the features you want to analyze for data drift as well as a timestamp field that indicates the point in time... | import datetime as dt
import pandas as pd
print('Generating simulated data...')
# Load the smaller of the two data files
data = pd.read_csv('data/diabetes2.csv')
# We'll generate data for the past 6 weeks
weeknos = reversed(range(6))
file_paths = []
for weekno in weeknos:
# Get the date X weeks ago
dat... | Generating simulated data...
Uploading an estimated of 6 files
Uploading data/diabetes_2021-09-29.csv
Uploaded data/diabetes_2021-09-29.csv, 1 files out of an estimated total of 6
Uploading data/diabetes_2021-10-06.csv
Uploaded data/diabetes_2021-10-06.csv, 2 files out of an estimated total of 6
Uploading data/diabetes... | MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
Create a data drift monitorNow you're ready to create a data drift monitor for the diabetes data. The data drift monitor will run periodicaly or on-demand to compare the baseline dataset with the target dataset, to which new data will be added over time. Create a compute targetTo run the data drift monitor, you'll nee... | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
cluster_name = "anhldt-compute2"
try:
# Check for existing compute target
training_cluster = ComputeTarget(workspace=ws, name=cluster_name)
print('Found existing cluster, use it.')
exc... | InProgress...
SucceededProvisioning operation finished, operation "Succeeded"
Succeeded
AmlCompute wait for completion finished
Minimum number of nodes requested have been provisioned
| MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
> **Note**: Compute instances and clusters are based on standard Azure virtual machine images. For this exercise, the *Standard_DS11_v2* image is recommended to achieve the optimal balance of cost and performance. If your subscription has a quota that does not include this image, choose an alternative image; but bear i... | from azureml.datadrift import DataDriftDetector
# set up feature list
features = ['Pregnancies', 'Age', 'BMI']
# set up data drift detector
monitor = DataDriftDetector.create_from_datasets(ws, 'mslearn-diabates-drift', baseline_data_set, target_data_set,
compute_t... | _____no_output_____ | MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
Backfill the data drift monitorYou have a baseline dataset and a target dataset that includes simulated weekly data collection for six weeks. You can use this to backfill the monitor so that it can analyze data drift between the original baseline and the target data.> **Note** This may take some time to run, as the co... | from azureml.widgets import RunDetails
backfill = monitor.backfill(dt.datetime.now() - dt.timedelta(weeks=6), dt.datetime.now())
RunDetails(backfill).show()
backfill.wait_for_completion() | _____no_output_____ | MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
Analyze data driftYou can use the following code to examine data drift for the points in time collected in the backfill run. | drift_metrics = backfill.get_metrics()
for metric in drift_metrics:
print(metric, drift_metrics[metric]) | start_date 2021-09-19
end_date 2021-11-07
frequency Week
Datadrift percentage {'days_from_start': [7, 14, 21, 28, 35, 42], 'drift_percentage': [74.19152901127207, 87.23985219136877, 91.74192122865539, 94.96492628559955, 97.58354951107833, 99.23199438682525]}
| MIT | 17 - Monitor Data Drift.ipynb | ldtanh/MS-Azure-DP-100 |
PySAL Change Log Statistics Approach- get date of last gh release of each package -> github_released- get date of last pypi release of each package -> pypi_released- get data of last meta-release -> start_date- for each package - get issues between start_date and package_released in master - get pulls between start... | from release_info import (issues_closed_since, packages,
is_pull_request,
sorted_by_field,
clone_masters
)
import datetime
clone_masters()
packages
#packages['pysal'] = '2.2.0'
release_date = '2020-07-27'
start_date =... | _____no_output_____ | BSD-3-Clause | tools/100-gitcount.ipynb | AndrewAnnex/pysal |
Scaling up ML using Cloud AI PlatformIn this notebook, we take a previously developed TensorFlow model to predict taxifare rides and package it up so that it can be run in Cloud AI Platform. For now, we'll run this on a small dataset. The model that was developed is rather simplistic, and therefore, the accuracy of th... | !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
import os
PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID
BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME
REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# For Python Code
# Model Info
MODEL_N... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Packaging up the codeTake your code and put into a standard Python package structure. model.py and task.py containing the Tensorflow code from earlier (explore the directory structure). | %%bash
find ${MODEL_NAME}
%%bash
cat ${MODEL_NAME}/trainer/model.py | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Find absolute paths to your data Note the absolute paths below. | %%bash
echo "Working Directory: ${PWD}"
echo "Head of taxi-train.csv"
head -1 $PWD/taxi-train.csv
echo "Head of taxi-valid.csv"
head -1 $PWD/taxi-valid.csv | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Running the Python module from the command-line Clean model training dir/output dir | %%bash
# This is so that the trained model is started fresh each time. However, this needs to be done before
rm -rf $PWD/${TRAINING_DIR}
%%bash
# Setup python so it sees the task module which controls the model.py
export PYTHONPATH=${PYTHONPATH}:${PWD}/${MODEL_NAME}
# Currently set for python 2. To run with python 3 ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Clean model training dir/output dir | %%bash
# This is so that the trained model is started fresh each time. However, this needs to be done before
rm -rf $PWD/${TRAINING_DIR} | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Running locally using gcloud | %%bash
# Use Cloud Machine Learning Engine to train the model in local file system
gcloud ai-platform local train \
--module-name=trainer.task \
--package-path=${PWD}/${MODEL_NAME}/trainer \
-- \
--train_data_paths=${PWD}/taxi-train.csv \
--eval_data_paths=${PWD}/taxi-valid.csv \
--train_steps=1000 \... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Submit training job using gcloudFirst copy the training data to the cloud. Then, launch a training job.After you submit the job, go to the cloud console (http://console.cloud.google.com) and select AI Platform | Jobs to monitor progress. Note: Don't be concerned if the notebook stalls (with a blue progress bar) or r... | %%bash
# Clear Cloud Storage bucket and copy the CSV files to Cloud Storage bucket
echo $BUCKET
gsutil -m rm -rf gs://${BUCKET}/${MODEL_NAME}/smallinput/
gsutil -m cp ${PWD}/*.csv gs://${BUCKET}/${MODEL_NAME}/smallinput/
%%bash
OUTDIR=gs://${BUCKET}/${MODEL_NAME}/smallinput/${TRAINING_DIR}
JOBNAME=${MODEL_NAME}_$(date ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Don't be concerned if the notebook appears stalled (with a blue progress bar) or returns with an error about being unable to refresh auth tokens. This is a long-lived Cloud job and work is going on in the cloud. Use the Cloud Console link to monitor the job and do NOT proceed until the job is done. | %%bash
gsutil ls gs://${BUCKET}/${MODEL_NAME}/smallinput | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Train on larger datasetI have already followed the steps below and the files are already available. You don't need to do the steps in this comment. In the next chapter (on feature engineering), we will avoid all this manual processing by using Cloud Dataflow.Go to http://bigquery.cloud.google.com/ and type the query... | %%bash
OUTDIR=gs://${BUCKET}/${MODEL_NAME}/${TRAINING_DIR}
JOBNAME=${MODEL_NAME}_$(date -u +%y%m%d_%H%M%S)
CRS_BUCKET=cloud-training-demos # use the already exported data
echo $OUTDIR $REGION $JOBNAME
gsutil -m rm -rf $OUTDIR
gcloud ai-platform jobs submit training $JOBNAME \
--region=$REGION \
--module-name=tra... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/e_ai_platform.ipynb | Glairly/introduction_to_tensorflow |
Nanodegree Engenheiro de Machine Learning Aprendizado Supervisionado Projeto: Encontrando doadores para a *CharityML* Seja bem-vindo ao segundo projeto do Nanodegree Engenheiro de Machine Learning! Neste notebook, você receberá alguns códigos de exemplo e será seu trabalho implementar as funcionalidades adicionais nec... | # Importe as bibliotecas necessárias para o projeto.
import numpy as np
import pandas as pd
from time import time
from IPython.display import display # Permite a utilização da função display() para DataFrames.
# Importação da biblioteca de visualização visuals.py
import visuals as vs
# Exibição amigável para notebook... | _____no_output_____ | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Implementação: Explorando os DadosUma investigação superficial da massa de dados determinará quantos indivíduos se enquadram em cada grupo e nos dirá sobre o percentual destes indivúdos com remuneração anual superior à \$50,000. No código abaixo, você precisará calcular o seguinte:- O número total de registros, `'n_re... | # Usado para a divisão retornar um float
from __future__ import division
# TODO: Número total de registros.
n_records = data['age'].count()
# TODO: Número de registros com remuneração anual superior à $50,000
n_greater_50k = data[data['income'] == '>50K']['age'].count()
# TODO: O número de registros com remuneração ... | Total number of records: 45222
Individuals making more than $50,000: 11208
Individuals making at most $50,000: 34014
Percentage of individuals making more than $50,000: 24.78%
| MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
** Explorando as colunas *** **age**: contínuo. * **workclass**: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked. * **education**: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-... | # Dividindo os dados entre features e coluna alvo
income_raw = data['income']
features_raw = data.drop('income', axis = 1)
# Visualizando os principais desvios das colunas contínuas entre os dados
vs.distribution(data) | _____no_output_____ | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Para atributos com distribuição muito distorcida, tais como `'capital-gain'` e `'capital-loss'`, é uma prática comum aplicar uma transformação logarítmica nos dados para que os valores muito grandes e muito pequenos não afetem a performance do algoritmo de aprendizado. Usar a transformação logarítmica reduz significati... | # Aplicando a transformação de log nos registros distorcidos.
skewed = ['capital-gain', 'capital-loss']
features_log_transformed = pd.DataFrame(data = features_raw)
features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))
# Visualizando as novas distribuições após a transformação.
vs.dist... | _____no_output_____ | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Normalizando atributos numéricosAlém das transformações em atributos distorcidos, é uma boa prática comum realizar algum tipo de adaptação de escala nos atributos numéricos. Ajustar a escala nos dados não modifica o formato da distribuição de cada coluna (tais como `'capital-gain'` ou `'capital-loss'` acima); no entan... | # Importando sklearn.preprocessing.StandardScaler
from sklearn.preprocessing import MinMaxScaler
# Inicializando um aplicador de escala e aplicando em seguida aos atributos
scaler = MinMaxScaler() # default=(0, 1)
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']
features_log_minm... | _____no_output_____ | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Implementação: Pré-processamento dos dadosA partir da tabela em **Explorando os dados** acima, nós podemos observar que existem diversos atributos não-numéricos para cada registro. Usualmente, algoritmos de aprendizado esperam que os inputs sejam numéricos, o que requer que os atributos não numéricos (chamados de *var... | # TODO: Utilize o one-hot encoding nos dados em 'features_log_minmax_transform' utilizando pandas.get_dummies()
features_final = pd.get_dummies(features_log_minmax_transform)
# TODO: Faça o encode da coluna 'income_raw' para valores numéricos
income = income_raw.apply(lambda d: 0 if d == '<=50K' else 1)
# Exiba o núm... | 103 total features after one-hot encoding.
| MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Embaralhar e dividir os dadosAgora todas as _variáveis de categoria_ foram convertidas em atributos numéricos e todos os atributos numéricos foram normalizados. Como sempre, nós agora dividiremos os dados entre conjuntos de treinamento e de teste. 80% dos dados serão utilizados para treinamento e 20% para teste.Execut... | # Importar train_test_split
from sklearn.cross_validation import train_test_split
# Dividir os 'atributos' e 'income' entre conjuntos de treinamento e de testes.
X_train, X_test, y_train, y_test = train_test_split(features_final,
income,
... | Training set has 36177 samples.
Testing set has 9045 samples.
| MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
---- Avaliando a performance do modeloNesta seção nós investigaremos quatro algoritmos diferentes e determinaremos qual deles é melhor para a modelagem dos dados. Três destes algoritmos serão algoritmos de aprendizado supervisionado de sua escolha e o quarto algoritmo é conhecido como *naive predictor*. Métricas e o N... | TP = np.sum(income) # Contando pois este é o caso "naive". Note que 'income' são os dados 'income_raw' convertido para valores numéricos durante o passo de pré-processamento de dados.
FP = income.count() - TP # Específico para o caso naive
TN = 0 # Sem predições negativas para o caso naive
FN = 0 # Sem predições negat... | Naive Predictor: [Accuracy score: 0.2478, F-score: 0.2917]
| MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Questão 1 - Performance do Naive Predictor* Se escolhessemos um modelo que sempre prediz que um indivíduo possui remuneração acima de $50,000, qual seria a accuracy e o F-score considerando este conjunto de dados? Você deverá utilizar o código da célula abaixo e atribuir os seus resultados para as variáveis `'accuracy... | # TODO: Import two metrics from sklearn - fbeta_score and accuracy_score
from sklearn.metrics import fbeta_score, accuracy_score
def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
'''
inputs:
- learner: the learning algorithm to be trained and predicted on
- sample_size: ... | _____no_output_____ | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Implementação: Validação inicial do modeloNo código da célular, você precisará implementar o seguinte:- Importar os três modelos de aprendizado supervisionado que você escolheu na seção anterior - Inicializar os três modelos e armazená-los em `'clf_A'`, `'clf_B'`, e `'clf_C'`. - Utilize um `'random_state'` para cada... | # TODO: Importe os três modelos de aprendizado supervisionado da sklearn
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
# TODO: Inicialize os três modelos
clf_A = GaussianNB()
clf_B = DecisionTreeClassifier(random_state=8)
... | GaussianNB trained on 361 samples.
GaussianNB trained on 3617 samples.
GaussianNB trained on 36177 samples.
DecisionTreeClassifier trained on 361 samples.
DecisionTreeClassifier trained on 3617 samples.
DecisionTreeClassifier trained on 36177 samples.
LogisticRegression trained on 361 samples.
LogisticRegression traine... | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
---- Melhorando os resultadosNesta seção final, você irá escolher o melhor entre os três modelos de aprendizado supervisionado para utilizar nos dados dos estudantes. Você irá então realizar uma busca grid para otimização em todo o conjunto de dados de treino (`X_train` e `y_train`) fazendo o tuning de pelo menos um pa... | # TODO: Importar 'GridSearchCV', 'make_scorer', e qualquer biblioteca necessária
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import fbeta_score, make_scorer
# TODO: Inicializar o classificador
clf = LogisticRegression(random_state=8)
# TODO: Criar a lista de parâmetros que você quer otimizar, ut... | /home/aron/.local/lib/python2.7/site-packages/sklearn/grid_search.py:42: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.
DeprecationWarning)
| MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Questão 5 - Validação final do modelo* Qual é a accuracy e o F-score do modelo otimizado utilizando os dados de testes?* Estes scores são melhores ou piores do que o modelo antes da otimização? * Como os resultados do modelo otimizado se comparam aos benchmarks do naive predictor que você encontrou na **Questão 1**?_*... | # TODO: Importar um modelo de aprendizado supervisionado que tenha 'feature_importances_'
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(random_state=8)
# TODO: Treinar o modelo utilizando o conjunto de treinamento com .fit(X_train, y_train)
model = model.fit(X_train, y_train)
# TODO:... | _____no_output_____ | MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Questão 7 - Extraindo importância dos atributosObserve a visualização criada acima que exibe os cinco atributos mais relevantes para predizer se um indivíduo possui remuneração igual ou superior à \$50,000 por ano.* Como estes cinco atributos se comparam com os 5 atributos que você discutiu na **Questão 6**? * Se você... | # Importar a funcionalidade para clonar um modelo
from sklearn.base import clone
# Reduzir a quantidade de atributos
X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]
X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]
# Treinar o melhor modelo enco... | [LibLinear]Final Model trained on full data
------
Accuracy on testing data: 0.8420
F-score on testing data: 0.6842
Final Model trained on reduced data
------
Accuracy on testing data: 0.8271
F-score on testing data: 0.6499
| MIT | finding_donors_PT.ipynb | aronkst/finding_donors |
Going deeper with TensorflowIn this seminar, we're going to play with [Tensorflow](https://www.tensorflow.org/) and see how it helps us build deep learning models.If you're running this notebook outside the course environment, you'll need to install tensorflow:* `pip install tensorflow` should install cpu-only TF on L... | import tensorflow as tf
gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.1)
s = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options)) | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Warming upFor starters, let's implement a python function that computes the sum of squares of numbers from 0 to N-1.* Use numpy or python* An array of numbers 0 to N - numpy.arange(N) | import numpy as np
def sum_squares(N):
return <student.Implement_me()>
%%time
sum_squares(10**8) | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Tensorflow teaserDoing the very same thing | #I gonna be your function parameter
N = tf.placeholder('int64', name="input_to_your_function")
#i am a recipe on how to produce sum of squares of arange of N given N
result = tf.reduce_sum((tf.range(N)**2))
%%time
#example of computing the same as sum_squares
print(result.eval({N:10**8})) | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
How does it work?1. define placeholders where you'll send inputs;2. make symbolic graph: a recipe for mathematical transformation of those placeholders;3. compute outputs of your graph with particular values for each placeholder * output.eval({placeholder:value}) * s.run(output, {placeholder:value})* So far there a... | #Default placeholder that can be arbitrary float32 scalar, vector, matrix, etc.
arbitrary_input = tf.placeholder('float32')
#Input vector of arbitrary length
input_vector = tf.placeholder('float32',shape=(None,))
#Input vector that _must_ have 10 elements and integer type
fixed_vector = tf.placeholder('int32',shape=(... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Visualizing graphsIt's often useful to visualize the computation graph when debugging or optimizing. Interactive visualization is where tensorflow really shines as compared to other frameworks. There's a special instrument for that, called Tensorboard. You can launch it from console:```tensorboard --logdir=/tmp/tboard... | # launch tensorflow the ugly way, uncomment if you need that
import os
port = 6000 + os.getuid()
print("Port: %d" % port)
#!killall tensorboard
os.system("tensorboard --logdir=./tboard --port=%d &" % port)
# show graph to tensorboard
writer = tf.summary.FileWriter("./tboard", graph=tf.get_default_graph())
writer.close... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
One basic functionality of tensorboard is drawing graphs. Once you've run the cell above, go to `localhost:7007` in your browser and switch to _graphs_ tab in the topbar. Here's what you should see:Tensorboard also allows you to draw graphs (e.g. learning curves), record images & audio ~~and play flash games~~. This is... | # Quest #1 - implement a function that computes a mean squared error of two input vectors
# Your function has to take 2 vectors and return a single number
<student.define_inputs_and_transformations()>
mse =<student.define_transformation()>
compute_mse = lambda vector1, vector2: <how to run you graph?>
# Tests
from s... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
variablesThe inputs and transformations have no value outside function call. This isn't too comfortable if you want your model to have parameters (e.g. network weights) that are always present, but can change their value over time.Tensorflow solves this with `tf.Variable` objects.* You can assign variable a value at a... | #creating shared variable
shared_vector_1 = tf.Variable(initial_value=np.ones(5))
#initialize variable(s) with initial values
s.run(tf.global_variables_initializer())
#evaluating shared variable (outside symbolic graph)
print("initial value", s.run(shared_vector_1))
# within symbolic graph you use them just as any ot... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
tf.gradients - why graphs matter* Tensorflow can compute derivatives and gradients automatically using the computation graph* Gradients are computed as a product of elementary derivatives via chain rule:$$ {\partial f(g(x)) \over \partial x} = {\partial f(g(x)) \over \partial g(x)}\cdot {\partial g(x) \over \partial x... | my_scalar = tf.placeholder('float32')
scalar_squared = my_scalar**2
#a derivative of scalar_squared by my_scalar
derivative = tf.gradients(scalar_squared, my_scalar)[0]
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(-3,3)
x_squared, x_squared_der = s.run([scalar_squared,derivative],
... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Why that rocks | my_vector = tf.placeholder('float32',[None])
#Compute the gradient of the next weird function over my_scalar and my_vector
#warning! Trying to understand the meaning of that function may result in permanent brain damage
weird_psychotic_function = tf.reduce_mean((my_vector+my_scalar)**(1+tf.nn.moments(my_vector,[0])[1... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Almost done - optimizersWhile you can perform gradient descent by hand with automatic grads from above, tensorflow also has some optimization methods implemented for you. Recall momentum & rmsprop? | y_guess = tf.Variable(np.zeros(2,dtype='float32'))
y_true = tf.range(1,3,dtype='float32')
loss = tf.reduce_mean((y_guess - y_true + tf.random_normal([2]))**2)
optimizer = tf.train.MomentumOptimizer(0.01,0.9).minimize(loss,var_list=y_guess)
#same, but more detailed:
#updates = [[tf.gradients(loss,y_guess)[0], y_gues... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Logistic regression exampleImplement the regular logistic regression training algorithmTips:* Use a shared variable for weights* X and y are potential inputs* Compile 2 functions: * `train_function(X, y)` - returns error and computes weights' new values __(through updates)__ * `predict_fun(X)` - just computes probabil... | from sklearn.datasets import load_digits
mnist = load_digits(2)
X,y = mnist.data, mnist.target
print("y [shape - %s]:" % (str(y.shape)), y[:10])
print("X [shape - %s]:" % (str(X.shape)))
print('X:\n',X[:3,:10])
print('y:\n',y[:10])
plt.imshow(X[0].reshape([8,8]))
# inputs and shareds
weights = <student.code_variable(... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Bonus: my1stNNYour ultimate task for this week is to build your first neural network [almost] from scratch and pure tensorflow.This time you will same digit recognition problem, but at a larger scale* images are now 28x28* 10 different digits* 50k samplesNote that you are not required to build 152-layer monsters here.... | from mnist import load_dataset
#[down]loading the original MNIST dataset.
#Please note that you should only train your NN on _train sample,
# _val can be used to evaluate out-of-sample error, compare models or perform early-stopping
# _test should be hidden under a rock untill final evaluation... But we both know it i... | _____no_output_____ | MIT | week1_intro/primer/recap_tensorflow.ipynb | minori111/Practical_RL |
Multi input perceptron | w = [.5, .8, .75]
b = 3
x = [3, 4, 4] | _____no_output_____ | MIT | nb/2. Perceptron (vector-input).ipynb | tivvit/nn-basics |
Python | %time
s = 0
for i, xi in enumerate(x):
s += (w[i] * xi)
r = s + b
r | CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 16 µs
| MIT | nb/2. Perceptron (vector-input).ipynb | tivvit/nn-basics |
Numpy | import numpy as np
%time
np.add(np.dot(w, x), b) | CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 14.3 µs
| MIT | nb/2. Perceptron (vector-input).ipynb | tivvit/nn-basics |
Tensorflow | import tensorflow as tf
%time
with tf.Session() as sess:
res = tf.add(tf.reduce_sum(tf.multiply(w, x)), b)
print(sess.run(res)) | CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 17.6 µs
10.7
| MIT | nb/2. Perceptron (vector-input).ipynb | tivvit/nn-basics |
VAE for MNIST clustering and generationThe goal of this notebook is to explore some recent works dealing with variational auto-encoder (VAE).We will use MNIST dataset and a basic VAE architecture. | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.metrics.cluster import normalized_mutual_info_score
def show(i... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
Variational AutoencodersConsider a latent variable model with a data variable $x\in \mathcal{X}$ and a latent variable $z\in \mathcal{Z}$, $p(z,x) = p(z)p_\theta(x|z)$. Given the data $x_1,\dots, x_n$, we want to train the model by maximizing the marginal log-likelihood:\begin{eqnarray*}\mathcal{L} = \mathbf{E}_{p_d(x... | # Hyper-parameters
image_size = 784
h_dim = 400
z_dim = 20
num_epochs = 15
learning_rate = 1e-3
# VAE model
class VAE(nn.Module):
def __init__(self, image_size=784, h_dim=400, z_dim=20):
super(VAE, self).__init__()
self.fc1 = nn.Linear(image_size, h_dim)
self.fc2 = nn.Linear(h_dim, z_dim)
... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
Here for the loss, instead of MSE for the reconstruction loss, we take BCE. The code below is still from the pytorch tutorial (with minor modifications to avoid warnings!). | # Start training
for epoch in range(num_epochs):
for i, (x, _) in enumerate(data_loader):
# Forward pass
x = x.to(device).view(-1, image_size)
x_reconst, mu, log_var = model(x)
# Compute reconstruction loss and kl divergence
# For KL divergence, see Appendix B in VAE... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
Let see how our network reconstructs our last batch. We display pairs of original digits and reconstructed version. | mu, _ = model.encode(x)
out = model.decode(mu)
x_concat = torch.cat([x.view(-1, 1, 28, 28), out.view(-1, 1, 28, 28)], dim=3)
out_grid = torchvision.utils.make_grid(x_concat).cpu().data
show(out_grid) | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
Let see now, how our network generates new samples. | with torch.no_grad():
z = torch.randn(16, z_dim).to(device)
out = model.decode(z).view(-1, 1, 28, 28)
out_grid = torchvision.utils.make_grid(out).cpu()
show(out_grid) | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
Not great, but we did not train our network for long... That being said, we have no control of the generated digits. In the rest of this jupyter, we explore ways to generates zeros, ones, twos and so on. As a by product, we show how our VAE will allow us to do clustering.The main idea is to build what we call a Gumbel ... | n_classes = 10
class VAE_Gumbel(nn.Module):
def __init__(self, image_size=784, h_dim=400, z_dim=20, n_classes = 10):
super(VAE_Gumbel, self).__init__()
#
# your code here
#
def encode(self, x):
#
# your code here / use F.log_softmax
#
... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
You need to modify the loss to take into account the categorical random variable with an uniform prior on $\{0,\dots 9\}$, see Appendix A.2 in the NIPS [paper](https://arxiv.org/abs/1804.00104) | def train_G(model, data_loader=data_loader,num_epochs=num_epochs, beta = 1., verbose=True):
nmi_scores = []
model.train(True)
for epoch in range(num_epochs):
all_labels = []
all_labels_est = []
for i, (x, labels) in enumerate(data_loader):
# Forward pass
x = x... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
This was for reconstruction, but we care more about generation. For each category, we are generating 8 samples thanks to the following matrix, so that in the end, we should have on each line only one digit represented. | matrix = np.zeros((8,n_classes))
matrix[:,0] = 1
final = matrix[:]
for i in range(1,n_classes):
final = np.vstack((final,np.roll(matrix,i)))
with torch.no_grad():
z = torch.randn(8*n_classes, z_dim).to(device)
y_onehot = torch.tensor(final).type(torch.FloatTensor).to(device)
out = model_G.de... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
It does not look like our original idea is working...To check that our network is not using the categorical variable, we can track the [normalized mutual information](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.normalized_mutual_info_score.html) between the true labels and the labels 'predicted' by... | model_G = VAE_Gumbel().to(device)
optimizer = torch.optim.Adam(model_G.parameters(), lr=learning_rate)
def train_G_modified_loss(model, data_loader=data_loader,num_epochs=num_epochs, beta , C_z_fin, C_c_fin, verbose=True):
#
# your code here
#
with torch.no_grad():
z = torch.randn(8*n_classes, z_dim... | _____no_output_____ | Apache-2.0 | Notebooks/VAE_clustering_empty.ipynb | lasofivec/dataflowr |
Embedded features example**Example illustrates embedding features directly in an IGV track configuration, as opposed to loading data from a file** | !pip install igv-notebook
import igv_notebook
igv_notebook.init()
b = igv_notebook.Browser({
"genome": "hg19",
"locus": "chr20:1,233,645-1,235,507"
})
b.load_track({
"name": "Copy number",
"type": "seg",
"displayMode": "EXPANDED",
"height": 50,
"isLog": True,
"features": [
{
... | _____no_output_____ | MIT | examples/EmbeddedFeatures.ipynb | igvteam/igv-notebook |
Upload to DataversePyEnzyme offers the upload to any Dataverse installation that supports the official [EnzymeML metadatablock](https://doi.org/10.18419/darus-2105) by utilizing the Dataverse API [PyDaRUS](https://github.com/JR-1991/pyDaRUS) to map all relevant fields and perform upload. The following steps will be do... | import pyenzyme as pe
# Load the EnzymeMLDocument
enzmldoc = pe.EnzymeMLDocument.fromTemplate("EnzymeML_Template_Example.xlsm")
# Upload it to Dataverse (Dataset is private)
enzmldoc.uploadToDataverse(dataverse_name="playground") | _____no_output_____ | BSD-2-Clause | examples/Dataverse/UploadToDataverse.ipynb | haeussma/PyEnzyme |
Table of ContentsMy ideia:121Train model- First normal xgb | import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', 50)
import sys
from utils import read_data, process_time, ... | pair_week 13
----- ---------
count 1431
mean 60.4913
std 235.209
min 1
25% 1
50% 3
75% 13
max 3022
----- ---------
pair_week 12
----- ---------
count 729
mean 63.4678
std 148.621
min 1
25% 1
50% 4
75% 64
max 2523
----- ---------
pair_week ... | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 |
Therefore, around 35% of a fortnight sales is NEW ITEMS.That is, items that never appeared in the dataset until now. Aproximately the same thing should happen for DMC (maybe a bit less)--- My ideia:- Divide into TWO seperate problems: - 1) Predict the amount of items already seen with tradional approach - 2) Pre... | def create_dataset(target_week, final_test=False):
if final_test:
train_items = df.query('(@target_week + 1) <= group_backwards <= 13')["itemID"].unique()
full = df.query('group_backwards >= (@target_week)').reset_index(drop = True)
else:
train_items = df.query('(@target_week + 2) <= gro... | _____no_output_____ | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 |
**OBS**: From now on, salesPrice and order in X_train means the SUM**OBS**: We remove it when defining x/y later on. | cols = ["order", "salesPrice"]
extra = full_sub.groupby(["group_backwards", "itemID"],
as_index=False)[cols].sum()
X_full_val = pd.merge(X_full_val, extra, on=["group_backwards", "itemID"], how="left",
validate="1:1")
# 0 so the features generated will make sense
X_full_val.fi... | _____no_output_____ | MIT | santana/EDA/new_featuresBruno.ipynb | joaopedromattos/DMC2020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.