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 |
|---|---|---|---|---|---|
CONTENTS* Text Models* Viterbi Text Segmentation* Information Retrieval* Information Extraction* Decoders TEXT MODELSBefore we start analyzing text processing algorithms, we will need to build some language models. Those models serve as a look-up table for character or word probabilities (depending on the type of mod... | psource(UnigramWordModel, NgramWordModel, UnigramCharModel, NgramCharModel) | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
Next we build our models. The text file we will use to build them is *Flatland*, by Edwin A. Abbott. We will load it from [here](https://github.com/aimacode/aima-data/blob/a21fc108f52ad551344e947b0eb97df82f8d2b2b/EN-text/flatland.txt). In that directory you can find other text files we might get to use here. Getting P... | flatland = open_data("EN-text/flatland.txt").read()
wordseq = words(flatland)
P1 = UnigramWordModel(wordseq)
P2 = NgramWordModel(2, wordseq)
print(P1.top(5))
print(P2.top(5))
print(P1['an'])
print(P2[('i', 'was')]) | [(2081, 'the'), (1479, 'of'), (1021, 'and'), (1008, 'to'), (850, 'a')]
[(368, ('of', 'the')), (152, ('to', 'the')), (152, ('in', 'the')), (86, ('of', 'a')), (80, ('it', 'is'))]
0.0036724740723330495
0.00114584557527324
| MIT | text.ipynb | Gerson1366/projeto_ia |
We see that the most used word in *Flatland* is 'the', with 2081 occurrences, while the most used sequence is 'of the' with 368 occurrences. Also, the probability of 'an' is approximately 0.003, while for 'i was' it is close to 0.001. Note that the strings used as keys are all lowercase. For the unigram model, the keys... | flatland = open_data("EN-text/flatland.txt").read()
wordseq = words(flatland)
P3 = NgramWordModel(3, wordseq)
print("Conditional Probabilities Table:", P3.cond_prob[('i', 'was')].dictionary, '\n')
print("Conditional Probability of 'once' give 'i was':", P3.cond_prob[('i', 'was')]['once'], '\n')
print("Next word after... | Conditional Probabilities Table: {'now': 2, 'glad': 1, 'keenly': 1, 'considered': 1, 'once': 2, 'not': 4, 'in': 2, 'by': 1, 'simulating': 1, 'intoxicated': 1, 'wearied': 1, 'quite': 1, 'certain': 2, 'sitting': 1, 'to': 2, 'rapidly': 1, 'will': 1, 'describing': 1, 'allowed': 1, 'at': 2, 'afraid': 1, 'covered': 1, 'appro... | MIT | text.ipynb | Gerson1366/projeto_ia |
First we print all the possible words that come after 'i was' and the times they have appeared in the model. Next we print the probability of 'once' appearing after 'i was', and finally we pick a word to proceed after 'i was'. Note that the word is picked according to its probability of appearing (high appearance count... | flatland = open_data("EN-text/flatland.txt").read()
wordseq = words(flatland)
P1 = UnigramCharModel(wordseq)
P2 = NgramCharModel(2, wordseq)
print(P1.top(5))
print(P2.top(5))
print(P1['z'])
print(P2[('g', 'h')]) | [(19208, 'e'), (13965, 't'), (12069, 'o'), (11702, 'a'), (11440, 'i')]
[(5364, (' ', 't')), (4573, ('t', 'h')), (4063, (' ', 'a')), (3654, ('h', 'e')), (2967, (' ', 'i'))]
0.0006028715031814578
0.0032371578540395666
| MIT | text.ipynb | Gerson1366/projeto_ia |
The most common letter is 'e', appearing more than 19000 times, and the most common sequence is "\_t". That is, a space followed by a 't'. Note that even though we do not count spaces for word models or unigram character models, we do count them for n-gram char models.Also, the probability of the letter 'z' appearing i... | flatland = open_data("EN-text/flatland.txt").read()
wordseq = words(flatland)
P1 = UnigramWordModel(wordseq)
P2 = NgramWordModel(2, wordseq)
P3 = NgramWordModel(3, wordseq)
print(P1.samples(10))
print(P2.samples(10))
print(P3.samples(10)) | hearing as inside is confined to conduct by the duties
all and of voice being in a day of the
party they are stirred to mutual warfare and perish by
| MIT | text.ipynb | Gerson1366/projeto_ia |
For the unigram model, we mostly get gibberish, since each word is picked according to its frequency of appearance in the text, without taking into consideration preceding words. As we increase *n* though, we start to get samples that do have some semblance of conherency and do remind a little bit of normal English. As... | data = open_data("EN-text/flatland.txt").read()
data += open_data("EN-text/sense.txt").read()
wordseq = words(data)
P3 = NgramWordModel(3, wordseq)
P4 = NgramWordModel(4, wordseq)
P5 = NgramWordModel(5, wordseq)
P7 = NgramWordModel(7, wordseq)
print(P3.samples(15))
print(P4.samples(15))
print(P5.samples(15))
print(P... | leave them at cleveland this christmas now pray do not ask you to relate or
meaning and both of us sprang forward in the direction and no sooner had they
palmer though very unwilling to go as well from real humanity and good nature as
time about what they should do and they agreed he should take orders directly and
| MIT | text.ipynb | Gerson1366/projeto_ia |
Notice how the samples start to become more and more reasonable as we add more data and increase the *n* parameter. We are still a long way to go though from realistic text generation, but at the same time we can see that with enough data even rudimentary algorithms can output something almost passable. VITERBI TEXT S... | psource(viterbi_segment) | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
The function takes as input a string and a text model, and returns the most probable sequence of words, together with the probability of that sequence.The "window" is `w` and it includes the characters from *j* to *i*. We use it to "build" the following sequence: from the start to *j* and then `w`. We have previously c... | flatland = open_data("EN-text/flatland.txt").read()
wordseq = words(flatland)
P = UnigramWordModel(wordseq)
text = "itiseasytoreadwordswithoutspaces"
s, p = viterbi_segment(text,P)
print("Sequence of words is:",s)
print("Probability of sequence is:",p) | Sequence of words is: ['it', 'is', 'easy', 'to', 'read', 'words', 'without', 'spaces']
Probability of sequence is: 2.273672843573388e-24
| MIT | text.ipynb | Gerson1366/projeto_ia |
The algorithm correctly retrieved the words from the string. It also gave us the probability of this sequence, which is small, but still the most probable segmentation of the string. INFORMATION RETRIEVAL OverviewWith **Information Retrieval (IR)** we find documents that are relevant to a user's needs for information.... | psource(IRSystem) | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
The `stopwords` argument signifies words in the queries that should not be accounted for in documents. Usually they are very common words that do not add any significant information for a document's relevancy.A quick guide for the functions in the `IRSystem` class:* `index_document`: Add document to the collection of d... | psource(UnixConsultant) | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
The class creates an IR System with the stopwords "how do i the a of". We could add more words to exclude, but the queries we will test will generally be in that format, so it is convenient. After the initialization of the system, we get the manual files and start indexing them.Let's build our Unix consultant and run a... | uc = UnixConsultant()
q = uc.query("how do I remove a file")
top_score, top_doc = q[0][0], q[0][1]
print(top_score, uc.documents[top_doc].url) | 0.7682667868462166 aima-data/MAN/rm.txt
| MIT | text.ipynb | Gerson1366/projeto_ia |
We asked how to remove a file and the top result was the `rm` (the Unix command for remove) manual. This is exactly what we wanted! Let's try another query: | q = uc.query("how do I delete a file")
top_score, top_doc = q[0][0], q[0][1]
print(top_score, uc.documents[top_doc].url) | 0.7546722691607105 aima-data/MAN/diff.txt
| MIT | text.ipynb | Gerson1366/projeto_ia |
Even though we are basically asking for the same thing, we got a different top result. The `diff` command shows the differences between two files. So the system failed us and presented us an irrelevant document. Why is that? Unfortunately our IR system considers each word independent. "Remove" and "delete" have similar... | plaintext = "ABCDWXYZ"
ciphertext = shift_encode(plaintext, 3)
print(ciphertext) | DEFGZABC
| MIT | text.ipynb | Gerson1366/projeto_ia |
Decoding a Caesar cipherTo decode a Caesar cipher we exploit the fact that not all letters in the alphabet are used equally. Some letters are used more than others and some pairs of letters are more probable to occur together. We call a pair of consecutive letters a bigram. | print(bigrams('this is a sentence')) | ['th', 'hi', 'is', 's ', ' i', 'is', 's ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce']
| MIT | text.ipynb | Gerson1366/projeto_ia |
We use `CountingProbDist` to get the probability distribution of bigrams. In the latin alphabet consists of only only `26` letters. This limits the total number of possible substitutions to `26`. We reverse the shift encoding for a given `n` and check how probable it is using the bigram distribution. We try all `26` va... | %psource ShiftDecoder | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
ExampleLet us encode a secret message using Caeasar cipher and then try decoding it using `ShiftDecoder`. We will again use `flatland.txt` to build the text model | plaintext = "This is a secret message"
ciphertext = shift_encode(plaintext, 13)
print('The code is', '"' + ciphertext + '"')
flatland = open_data("EN-text/flatland.txt").read()
decoder = ShiftDecoder(flatland)
decoded_message = decoder.decode(ciphertext)
print('The decoded message is', '"' + decoded_message + '"') | The decoded message is "This is a secret message"
| MIT | text.ipynb | Gerson1366/projeto_ia |
Permutation DecoderNow let us try to decode messages encrypted by a general mono-alphabetic substitution cipher. The letters in the alphabet can be replaced by any permutation of letters. For example, if the alphabet consisted of `{A B C}` then it can be replaced by `{A C B}`, `{B A C}`, `{B C A}`, `{C A B}`, `{C B A}... | psource(PermutationDecoder) | _____no_output_____ | MIT | text.ipynb | Gerson1366/projeto_ia |
Each state/node in the graph is represented as a letter-to-letter map. If there is no mapping for a letter, it means the letter is unchanged in the permutation. These maps are stored as dictionaries. Each dictionary is a 'potential' permutation. We use the word 'potential' because every dictionary doesn't necessarily ... | ciphertexts = ['ahed world', 'ahed woxld']
pd = PermutationDecoder(canonicalize(flatland))
for ctext in ciphertexts:
print('"{}" decodes to "{}"'.format(ctext, pd.decode(ctext))) | "ahed world" decodes to "shed could"
"ahed woxld" decodes to "shew atiow"
| MIT | text.ipynb | Gerson1366/projeto_ia |
VacationPy---- Note* Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps... | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import gmaps
import os
# Import API key
from api_keys import g_key
print(g_key)
csvfile = "../output_data/weather_data.csv"
heatmap_df = pd.read_csv(csvfile)
heatmap_df | _____no_output_____ | ADSL | VacationPy-Final.ipynb | JessicaKwon0121/Python-API-Challenge |
Humidity Heatmap* Configure gmaps.* Use the Lat and Lng as locations and Humidity as the weight.* Add Heatmap layer to map. | gmaps.configure(api_key=g_key)
locations = heatmap_df[["Lat", "Lng"]].astype(float)
humidity = heatmap_df["Humidity"].astype(float)
humidity.max()
fig = gmaps.figure()
heatmap_layer = gmaps.heatmap_layer(locations, weights=humidity,
dissipating=False, max_intensity=100,
... | _____no_output_____ | ADSL | VacationPy-Final.ipynb | JessicaKwon0121/Python-API-Challenge |
Create new DataFrame fitting weather criteria* Narrow down the cities to fit weather conditions.* Drop any rows will null values. | heatmap_data = heatmap_df.loc[(heatmap_df["Max Temp"] < 100) &
(heatmap_df["Max Temp"] >=70) &
(heatmap_df["Cloudiness"] == 0) &
(heatmap_df["Wind Speed"] < 10)].dropna()
heatmap_data | _____no_output_____ | ADSL | VacationPy-Final.ipynb | JessicaKwon0121/Python-API-Challenge |
Hotel Map* Store into variable named `hotel_df`.* Add a "Hotel Name" column to the DataFrame.* Set parameters to search for hotels with 5000 meters.* Hit the Google Places API for each city's coordinates.* Store the first Hotel result into the DataFrame.* Plot markers on top of the heatmap. | hotel_df = heatmap_data.loc[:,["City","Country","Lat","Lng"]]
hotel_df["Hotel Name"] = ""
hotel_df
import json
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
params = {
"radius": 5000,
"type": "hotel",
"keyword": "hotel",
"key": g_key}
for index, row in hotel_df.iterrows():
l... | _____no_output_____ | ADSL | VacationPy-Final.ipynb | JessicaKwon0121/Python-API-Challenge |
Cálculo de la factura eléctrica- Recuperación de datos de consumo eléctrico horario del medidor de consumo ([enerPI]()) vía JSON.Para otros casos, formar un `pandas.Series` de índice horario con datos de consumo en kWh.- Generación de factura eléctrica mediante `esiosdata.FacturaElec`- Simulación de cambio de tarifa e... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
from glob import glob
import matplotlib.pyplot as plt
import os
import pandas as pd
import requests
from esiosdata import FacturaElec
from esiosdata.prettyprinting import *
# enerPI JSON API
ip_enerpi = '192.168.1.44'
t0, tf = '2016-11-01', '2016-12-24... | [1m[32m517.615[0m
| MIT | notebooks/esiosdata - Factura electricidad con datos enerPI.ipynb | azogue/esiosdata |
Factura eléctrica con datos horarios | factura = FacturaElec(consumo=data_consumo.kWh)
print_info(factura)
factura.tipo_peaje = 2
print_cyan(factura)
factura.tipo_peaje = 3
print_magenta(factura) | [35mFACTURA ELÉCTRICA:
--------------------------------------------------------------------------------
* Fecha inicio 31/10/2016
* Fecha final 24/12/2016
* Peaje de acceso 2.0DHS (Vehículo eléctrico)
* Potencia contratada 3.45 kW
* Consumo periodo 517.61 kWh
* ¿Bon... | MIT | notebooks/esiosdata - Factura electricidad con datos enerPI.ipynb | azogue/esiosdata |
EXPORT TO CSV* Para importar en https://facturaluz2.cnmc.es/facturaluz2.html | path_csv = os.path.expanduser('~/Desktop/')
df_csv = factura.generacion_csv_oficial_consumo_horario(path_csv)
print_ok(df_csv.tail())
file_path = glob(path_csv + '*.csv')[0]
with open(file_path, 'r') as f:
print_magenta(f.read()[:500]) | [1m[32m CUPS Fecha Hora Consumo_kWh Metodo_obtencion
index
2016-12-24 19:00:00+01:00 ES00XXXXXXXXXXXXXXDB 24/12/2016 20 0.329 R
2016-12-24 20:00:00+01:... | MIT | notebooks/esiosdata - Factura electricidad con datos enerPI.ipynb | azogue/esiosdata |
Plots del periodo facturado | print_ok('Consumo diario')
factura.plot_consumo_diario()
plt.show()
print_ok('Patrón de consumo semanal')
factura.plot_patron_semanal_consumo()
plt.show() | [1m[32mPatrón de consumo semanal[0m
| MIT | notebooks/esiosdata - Factura electricidad con datos enerPI.ipynb | azogue/esiosdata |
Loops in PythonEstimated time needed: **20** minutes ObjectivesAfter completing this lab you will be able to:* work with the loop statements in Python, including for-loop and while-loop. Loops in Python Welcome! This notebook will teach you about the loops in the Python Programming Language. By the end of this l... | # Use the range
range(3) | _____no_output_____ | MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
***NOTE: While in Python 2.x it returned a list as seen in video lessons, in 3.x it returns a range object.*** What is for loop? The for loop enables you to execute a code block multiple times. For example, you would use this if you would like to print out every element in a list.\Let's try to use a for loop to print ... | # For loop example
dates = [1982,1980,1973]
N = len(dates)
for i in range(N):
print(dates[i]) | 1982
1980
1973
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
The code in the indent is executed N times, each time the value of i is increased by 1 for every execution. The statement executed is to print out the value in the list at index i as shown here: In this example we can print out a sequence of numbers from 0 to 7: | # Example of for loop
for i in range(0, 8):
print(i) | 0
1
2
3
4
5
6
7
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
In Python we can directly access the elements in the list as follows: | # Exmaple of for loop, loop through list
for year in dates:
print(year) | 1982
1980
1973
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
For each iteration, the value of the variable year behaves like the value of dates\[i] in the first example: We can change the elements in a list: | # Use for loop to change the elements in list
squares = ['red', 'yellow', 'green', 'purple', 'blue']
for i in range(0, 5):
print("Before square ", i, 'is', squares[i])
squares[i] = 'white'
print("After square ", i, 'is', squares[i]) | Before square 0 is red
After square 0 is white
Before square 1 is yellow
After square 1 is white
Before square 2 is green
After square 2 is white
Before square 3 is purple
After square 3 is white
Before square 4 is blue
After square 4 is white
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
We can access the index and the elements of a list as follows: | # Loop through the list and iterate on both index and element value
squares=['red', 'yellow', 'green', 'purple', 'blue']
for i, square in enumerate(squares):
print(i, square) | 0 red
1 yellow
2 green
3 purple
4 blue
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
What is while loop? As you can see, the for loop is used for a controlled flow of repetition. However, what if we don't know when we want to stop the loop? What if we want to keep executing a code block until a certain condition is met? The while loop exists as a tool for repeated execution based on a condition. The co... | # While Loop Example
dates = [1982, 1980, 1973, 2000]
i = 0
year = dates[0]
while(year != 1973):
print(year)
i = i + 1
year = dates[i]
print("It took ", i ,"repetitions to get out of loop.") | 1982
1980
It took 2 repetitions to get out of loop.
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
A while loop iterates merely until the condition in the argument is not met, as shown in the following figure: Quiz on Loops Write a for loop the prints out all the element between -5 and 5 using the range function. | # Write your code below and press Shift+Enter to execute
for i in range(-4, 5):
print(i) | -4
-3
-2
-1
0
1
2
3
4
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
Click here for the solution```pythonfor i in range(-4, 5): print(i) ``` Print the elements of the following list: Genres=\[ 'rock', 'R\&B', 'Soundtrack', 'R\&B', 'soul', 'pop']Make sure you follow Python conventions. | # Write your code below and press Shift+Enter to execute
Genres = ['rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop']
for Genre in Genres:
print(Genre) | rock
R&B
Soundtrack
R&B
soul
pop
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
Click here for the solution```pythonGenres = ['rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop']for Genre in Genres: print(Genre) ``` Write a for loop that prints out the following list: squares=\['red', 'yellow', 'green', 'purple', 'blue'] | # Write your code below and press Shift+Enter to execute
squares=['red', 'yellow', 'green', 'purple', 'blue']
for square in squares:
print(square) | red
yellow
green
purple
blue
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
Click here for the solution```pythonsquares=['red', 'yellow', 'green', 'purple', 'blue']for square in squares: print(square) ``` Write a while loop to display the values of the Rating of an album playlist stored in the list PlayListRatings. If the score is less than 6, exit the loop. The list PlayListRatings is ... | # Write your code below and press Shift+Enter to execute
PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
i = 0
Rating = PlayListRatings[0]
while(i < len(PlayListRatings) and Rating >= 6):
Rating = PlayListRatings[i]
print(Rating)
i = i + 1 | 10
9.5
10
8
7.5
5
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
Click here for the solution```pythonPlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]i = 0Rating = PlayListRatings[0]while(i = 6): Rating = PlayListRatings[i] print(Rating) i = i + 1 ``` Write a while loop to copy the strings 'orange' of the list squares to the list new_squares. Stop and exit the loop if ... | # Write your code below and press Shift+Enter to execute
squares = ['orange', 'orange', 'purple', 'blue ', 'orange']
new_squares = []
squares = ['orange', 'orange', 'purple', 'blue ', 'orange']
new_squares = []
i = 0
while(i < len(squares) and squares[i] == 'orange'):
new_squares.append(squares[i])
i = i + 1
p... | ['orange', 'orange']
| MIT | 1 - Python for Data Science/Module 3 - Python Programming Fundamentals/code/4-PY0101EN-3-2-Loops.ipynb | joaopaulo164/Data-Science-with-Python |
Line plot | x=[3,5,7,9,12,45,68,100]
y=[100,300,900,400,600,200,700,500]
y1=[1000,700,300,500,1200,100,600,900]
plt.style.use('dark_background')
#plt.xkcd()
plt.plot(x,y,color='b',marker='o')
plt.plot(x,y1,color='r',marker='.',linestyle='--')
plt.legend(['F','S'])
plt.grid()
plt.tight_layout()
plt.xlabel("x-point")
plt.ylabel("y-p... | _____no_output_____ | MIT | matplotlib.ipynb | AKSK16101999/technovative |
Amazon Comprehend Custom Classification - LabThis notebook will serve as a template for the overall process of taking a text dataset and integrating it into [Amazon Comprehend Custom Classification](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html) and perform NLP for custom classifica... | !mkdir nlp_data
| _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
With the data downloaded, now we will import the Pandas library as well as a few other data science tools in order to inspect the information. | import boto3
from time import sleep
import os
import subprocess
import pandas as pd
import json
import time
import pprint
import numpy as np
import seaborn as sn
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
import secrets
import string
import datetime
imp... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Please use the credentials that were part of initial login screen. Set the env variables. | import os
os.environ['AWS_DEFAULT_REGION'] = "us-east-1"
os.environ['AWS_ACCESS_KEY_ID'] = "<AWS_ACCESS_KEY_ID>"
os.environ['AWS_SECRET_ACCESS_KEY'] = "<AWS_SECRET_ACCESS_KEY>"
os.environ['AWS_SESSION_TOKEN'] = "<AWS_SESSION_TOKEN>" | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Test previous aws configure is set properly by running following command | !echo $AWS_SESSION_TOKEN | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Lets load the data in to dataframe and look at the data we uploaded. Examine the number of columns that are present. Look at few samples to see the content of the data. | raw_data = pd.read_csv('nlp_data/raw_data.csv')
raw_data.head()
raw_data['CATEGORY_NAME'] = raw_data['CATEGORY_NAME'].astype(str)
raw_data.groupby('CATEGORY_NAME')['CASE_SUBJECT_FULL'].count() | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
To convert data to the format that is required by Amazon Comprehend Custom Classifier,```CLASS,Text of document 1CLASS,Text of document 2CLASS,Text of document 3```We will identify the column which are class and which have the text content we would like to train on, we can create a new dataframe with selected columns. | selected_columns = ['CATEGORY_NAME', 'CASE_SUBJECT_FULL', 'CASE_DESCRIPTION_FULL']
# Select the columns we are interested in
selected_data = raw_data[selected_columns]
selected_data = selected_data[selected_data['CATEGORY_NAME']!='Not Known']
selected_data.shape
selected_data.groupby('CATEGORY_NAME')['CASE_SUBJECT_FULL... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
As we might be interested in finding outt he accuracy level of the model compared to known labels, we want to held out 10% dataset for later use to infer from the comdel, generate performanace matrix to asses the model. We want to stratify split data based on 'CATEGORY_NAME' | from sklearn.model_selection import train_test_split
train_data, test_data = train_test_split(selected_data, test_size=0.1, random_state=0,
stratify=selected_data[['CATEGORY_NAME']])
train_data_df = train_data.copy()
test_data_df = test_data.copy() | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Pre-processing data For training, the file format must conform with the [following](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification-training.html):- File must contain one label and one text per line – 2 columns- No header- Format UTF-8, carriage return “\n”.Labels “must be uppercase, can ... | labels_dict = {'Company':'COMPANY',
'EducationalInstitution':'EDUCATIONALINSTITUTION',
'Artist':'ARTIST',
'Athlete':'ATHLETE',
'OfficeHolder':'OFFICEHOLDER',
'MeanOfTransportation':'MEANOFTRANSPORTATION',
'Building':'BUILDING',
... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
At this point we have all the data the 2 needed files. Building The Target Train and Test FilesWith all of the above spelled out the next thing to do is to build 2 distinct files:1. `comprehend-train.csv` - A CSV file containing 2 columns without header, first column class, second column text.1. `comprehend-test.csv` ... | DSTTRAINFILE='nlp_data/comprehend-train.csv'
DSTVALIDATIONFILE='nlp_data/comprehend-test.csv'
train_data_df.to_csv(path_or_buf=DSTTRAINFILE,
header=False,
index=False,
escapechar='\\',
doublequote=False,
quotechar='"')
validatti... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Getting Started With Amazon ComprehendNow that all of the required data to get started exists, we can start working on Comprehend Custom Classfier. The custom classifier workload is built in two steps:1. Training the custom model – no particular machine learning or deep learning knowledge is necessary1. Classifying ne... | with open('/opt/ml/metadata/resource-metadata.json') as notebook_info:
data = json.load(notebook_info)
resource_arn = data['ResourceArn']
region = resource_arn.split(':')[3]
print(region) | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Configure your AWS APIs | session = boto3.Session(region_name=region)
comprehend = session.client(service_name='comprehend') | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Lets create a s3 bucket that will host training data and test data. | # Now perform the join
print(region)
s3 = boto3.client('s3')
prefix = 'ComprehendBYODPediaClassification'
account_id = boto3.client('sts').get_caller_identity().get('Account')
bucket_name = account_id + "-comprehend-byod-classification-{}".format(''.join(
secrets.choice(string.ascii_lowercase + string.digits) for i... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Uploading the data | boto3.Session().resource('s3').Bucket(bucket_name).Object(prefix+'/'+DSTTRAINFILE).upload_file(DSTTRAINFILE)
boto3.Session().resource('s3').Bucket(bucket_name).Object(prefix+'/'+DSTVALIDATIONFILE).upload_file(DSTVALIDATIONFILE) | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Configure an IAM roleIn order to authorize Amazon Comprehend to perform bucket reads and writes during the training or during the inference, we must grant Amazon Comprehend access to the Amazon S3 bucket that we created.We are going to create a data access role in our account to trust the Amazon Comprehend service pri... | iam = boto3.client("iam")
role_name = "ComprehendBucketAccessRole-{}".format(''.join(
secrets.choice(string.ascii_lowercase + string.digits) for i in range(8)))
assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Building Custom Classification model Launch the classifier training: | s3_train_data = 's3://{}/{}/{}'.format(bucket_name, prefix, DSTTRAINFILE)
s3_output_job = 's3://{}/{}/{}'.format(bucket_name, prefix, 'output/train_job')
print('training data location: ',s3_train_data, "output location:", s3_output_job)
id = str(datetime.datetime.now().strftime("%s"))
training_job = comprehend.create_d... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Trained model confusion matrixWhen a custom classifier model is trained, Amazon Comprehend creates a confusion matrix that provides metrics on how well the model performed in training. This enables you to assess how well the classifier will perform when run. This matrix shows a matrix of labels as predicted by the mod... | #Retrieve the S3URI from the model output and create jobkey variable.
job_output = describe_custom_classifier["DocumentClassifierProperties"]["OutputDataConfig"]["S3Uri"]
path_prefix = 's3://{}/'.format(bucket_name)
job_key = os.path.relpath(job_output, path_prefix)
#Download the model metrics
boto3.Session().resource(... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Evaluate Custom Classification model We will use custom classifier jobs to Evaluate on the test data we have. | model_arn = describe_custom_classifier["DocumentClassifierProperties"]["DocumentClassifierArn"]
print(model_arn)
s3_test_data = 's3://{}/{}/{}'.format(bucket_name, prefix, DSTVALIDATIONFILE)
print(s3_test_data)
id = str(datetime.datetime.now().strftime("%s"))
start_response = comprehend.start_document_classification_j... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Lets generate confusion metrix and other evaluation metrix for inferred results | import sklearn
print('The scikit-learn version is {}.'.format(sklearn.__version__))
from sklearn.metrics import confusion_matrix
y_true = test_data_df['class']
y_pred = test_data_df['predicted_class']
labels = comprehend_cm['labels']
cm_inference = confusion_matrix(y_true, y_pred,labels=labels)
plot_confusion_matrix(c... | _____no_output_____ | MIT | workshop/lab1/amazon-comprehend-custom-classification-byod-lab.ipynb | sriharshams/amazon-comprehend-workshop |
Set up google drive access | from google.colab import drive
drive.mount('/content/gdrive') | _____no_output_____ | MIT | master.ipynb | hfwittmann/colab-mlflow-papermill |
Goto directory Make sure this is the directory that corresponds to that on your local drive!!! | local_googledrive = '/Users/<username>/Google Drive/'
colab_googledrive_directory = "/content/gdrive/My Drive/"
project_directory = 'git/colab-mlflow-papermill/'
cd {colab_googledrive_directory}{project_directory} | _____no_output_____ | MIT | master.ipynb | hfwittmann/colab-mlflow-papermill |
Install missing packages | import importlib
if importlib.util.find_spec('mlflow') is None:
!pip install mlflow
if importlib.util.find_spec('papermill') is None:
!pip install papermill
# !pip install -r requirements.txt | _____no_output_____ | MIT | master.ipynb | hfwittmann/colab-mlflow-papermill |
Start | # import packages
import os
import pandas as pd
import papermill as pm
import mlflow | _____no_output_____ | MIT | master.ipynb | hfwittmann/colab-mlflow-papermill |
Load model names ... and make directories | # Create directory for temporary storage of artefacts and
# create mlflow experiment
artefacts_temp_dir = 'artefacts_temporary_depot'
if not os.path.exists(artefacts_temp_dir):
os.makedirs(artefacts_temp_dir)
pwd
2
# create mlflow experiment
mlflow.create_experiment('Iris Classification')
model_list = ['decision_... | _____no_output_____ | MIT | master.ipynb | hfwittmann/colab-mlflow-papermill |
Make metafiles local | from util import make_metafiles_local
make_metafiles_local(colab_googledrive_directory, local_googledrive) | _____no_output_____ | MIT | master.ipynb | hfwittmann/colab-mlflow-papermill |
Simple and elegant usage | with TM1640(clk_pin=24, din_pin=23) as d:
d.brightness = 0
d.write_text('HELLO')
for i in [1,1,1,1,1, -1,-1,-1,-1,-1]:
sleep(1)
d.brightness += i | _____no_output_____ | MIT | Trying my new module.ipynb | denilsonsa/rpi-led-display |
Global object for the purposes of this notebook | disp = TM1640(clk_pin=24, din_pin=23)
disp.brightness = 1 | _____no_output_____ | MIT | Trying my new module.ipynb | denilsonsa/rpi-led-display |
Showing some garbage | disp.write_bytes(b'0123456789abcdef')
disp.write_bytes([0xff, 0xef, 0b10000000, 0x63])
disp.write_bytes([0, 0x63, 0x5c, 0], 8)
import random
for i in range(64):
disp.write_bytes(bytes(random.randrange(256) for b in range(16)))
sleep(1 / (i+1)) | _____no_output_____ | MIT | Trying my new module.ipynb | denilsonsa/rpi-led-display |
Testing different characters | disp.write_text('.01.02..03')
disp.write_text('0123456789 yYzZ')
disp.write_text('aAbBcCdDeEfFgGhH')
disp.write_text('iIjJkKlLmMnNoOpP')
disp.write_text('qQrRsStTuUvVwWxX')
disp.write_text('~!@#$%^&*()[]{}')
disp.write_text('-_¯\'`"+=,./\\:;')
disp.write_text('🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹⁐ニ≡‾|‖')
disp.write_text('⌈⌉⌊⌋⎾⏋⎿⏌⌜⌝⌞⌟⌌... | _____no_output_____ | MIT | Trying my new module.ipynb | denilsonsa/rpi-led-display |
Some progress bar simulations | import textwrap
def animate(textarea):
for i in textwrap.dedent(textarea).strip().splitlines():
disp.write_text(i)
sleep(1)
animate('''
[ ]
[⁐ ]
[⁐⁐ ]
[⁐⁐⁐]
''')
animate('''
[ ]
[. ]
[.. ]
[... ]
[....]
''')
animate('''
⌈ ⌉
[ ⌉
[. ⌉
[... | _____no_output_____ | MIT | Trying my new module.ipynb | denilsonsa/rpi-led-display |
Homework: Decipherment | from collections import defaultdict, Counter
import collections
import pprint
import math
import bz2
pp = pprint.PrettyPrinter(width=45, compact=True) | _____no_output_____ | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
First let us read in the cipher text from the `data` directory: | def read_file(filename):
if filename[-4:] == ".bz2":
with bz2.open(filename, 'rt') as f:
content = f.read()
f.close()
else:
with open(filename, 'r') as f:
content = f.read()
f.close()
return content
cipher = read_file("data/cipher.txt")
print(... | º∫P/Z/uB∫ÀOR•–X•B
WV+≈GyF∞ºHPπKÇ—y≈
MJy^uIÀΩ—T‘NQyDµ£
S¢/º∑BPORAu∫∆R×E
À^LMZJƒ“\–FHVW≈æy
π+—GDºKI£∞—Xæµ§S¢
RN‘IyEÃOæ—GBTQS∑B
Lƒ/P∑BπX—EHMu^RRÀ
√ZK—–I£W—ÇæµLM“º∑
BPDR+j•∞\N¢≈EuHÀF
Z√–OVWIµ+‘L£Ã^R∞H
IºDR∏Ty“\ƒ≈/πXJQA
PµMæRu‘∫L£NVEKH•G
“IÇJÀµºæLMÃNA£Z¢P
§u–ÀAº∑BVW\+VT‘OP
^•S“Ã∆u≈∞ΩD§G∫∫IM
NÀ£S√E/º∫∫Z∆AP∑BV
–≈X—W—∏F∑æ√+πº... | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
Default Solution For the default solution we need to compute statistics like length, number of symbols/letters, unique occurences, frequencies and relative frequencies of a given file. This is done in the function `get_statistics` below.While using `get_statistics`, make sure that `cipher=True` is set when the input i... | def get_statistics(content, cipher=True):
stats = {}
content = list(content)
split_content = [x for x in content if x != '\n' and x!=' ']
length = len(split_content)
symbols = set(split_content)
uniq_sym = len(list(symbols))
freq = collections.Counter(split_content)
rel_freq = {}
for... | {'content': ['º', '∫', 'P', '/', 'Z', '/',
'u', 'B', '∫', 'À', 'O', 'R',
'•', '–', 'X', '•', 'B', 'W',
'V', '+', '≈', 'G', 'y', 'F',
'∞', 'º', 'H', 'P', 'π', 'K',
'Ç', '—', 'y', '≈', 'M', 'J',
'y', '^', 'u', 'I', 'À', 'Ω',
'—', '... | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
The default solution matches the frequency of symbols in the cipher text with frequency of letters in the plaintext language (in this case, English). Note that this is just some text in English used to compute letter frequencies. We do not have access to the real plaintext in this homework. In order to do compute plain... | # plaintext description
plaintxt = read_file("data/default.wiki.txt.bz2")
plaintxt_desc = get_statistics(plaintxt, cipher=False)
pp.pprint(plaintxt_desc) | {'frequencies': Counter({'e': 1001029,
't': 725515,
'a': 716871,
'i': 609790,
'n': 605384,
'o': 595295,
'r': 547660,
's': 544866,
... | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
We have all the tools we need to describe the default solution to this homework.We use a simple frequency matching heuristic to map cipher symbols to English letters.We match the frequencies using the function $f(\cdot)$ of each cipher symbol $c$ with each English letter $e$:$$h_{c,e} = | \log(\frac{f(c)}{f(e)})) | $$F... | """
default : frequency matching heuristic
Notice how the candidate mappings, a.k.a hypotheses, are first scored with a measure of quality and,
then, the best scoring hypothesis is chosen as the winner.
The plaintext letters from the winner are then mapped to the respective ciphertext symbols.
"""
def find_mapping... | _____no_output_____ | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
Using this scoring function we map the cipher symbol `∆` to `v` in English | mapping = find_mappings(cipher_desc, plaintxt_desc)
print("∆ maps to {}\n".format(mapping['∆']))
print(mapping) | ∆ maps to v
defaultdict(<class 'dict'>, {'∫': 'm', 'À': 'g', 'ƒ': 'b', 'N': 'b', 'W': 'g', '/': 'b', 'V': 'g', 'O': 'b', 'J': 'b', 'µ': 'g', '√': 'b', 'M': 'g', 'º': 'd', '“': 'b', 'π': 'b', '–': 'b', '\\': 'y', 'P': 'm', '∑': 'u', 'T': 'b', '§': 'k', 'L': 'g', '¢': 'k', '+': 'g', 'R': 'u', '£': 'g', 'Ç': 'y', 'u': 'u... | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
The default solution to this decipherment problem is to take each cipher symbol and map it to the most likely English letter as provided by the `find_mappings` function above. | english_text = []
for symbol in cipher_desc['content']:
english_text.append(mapping[symbol])
decipherment = ('').join(english_text)
print(decipherment) | dmmbgbuumgbubbgbugggububgdgmbyyluugbubumgvlbbbyubggbkbduumbugumvuylggbgggbbbybbgggugubglbbdymgglgggkbkubbmugybglbubybuugbbmuubglgggubuugbgylbmgglyggggbduumbugxbgybkuguggbgbbbggmggbggybuggmdbugbubybubbgbygmggguubmggbggygbbbmybggdgggybgggkmkubggduuggyggbbbmbbbbyvuugvbkbmmmgbggbbgbdmmgvgmuugbuglglgbugbgbdgdumbbguubggbulgb... | MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
Notice that the default solution provides a very bad decipherment. Your job is to make it better! Grading Ignore the following cells. They are for grading against the reference decipherment. Based on the clues provided in the decipherment homework description, you can easily find a reasonable reference text online for... | """
ATTENTION!
For grading purposes only. Don't bundle with the assignment.
Make sure '_ref.txt' is removed from the 'data' directory before publishing.
"""
def read_gold(gold_file):
with open(gold_file) as f:
gold = f.read()
f.close()
gold = list(gold.strip())
return gold
def symbol_error_ra... | Error: 97.30392156862744 Accuracy: 2.6960784313725505
| MIT | decipher/decipher.ipynb | anoopsarkar/nlp-class-hw-archive |
The first thing we need to do is to download the dataset from Kaggle. We use the [Enron dataset](https://www.kaggle.com/wcukierski/enron-email-dataset), which is the biggest public email dataset available.To do so we will use GDrive and download the dataset within a Drive folder to be used by Colab. | from google.colab import drive
drive.mount('/content/gdrive')
import os
os.environ['KAGGLE_CONFIG_DIR'] = "/content/gdrive/My Drive/Kaggle"
%cd /content/gdrive/My Drive/Kaggle | /content/gdrive/My Drive/Kaggle
| MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
We can download the dataset from Kaggle and save it in the GDrive folder. This needs to be done only the first time. | # !kaggle datasets download -d wcukierski/enron-email-dataset
# unzipping the zip files
# !unzip \*.zip | _____no_output_____ | MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
Now we are finally ready to start working with the dataset, accessible as a CSV file called `emails.csv`. | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import email
import re
if not 'emails_df' in locals():
emails_df = pd.read_csv('./emails.csv')
# Use only a subpart of the whole dataset to avoid exceeding RAM
# emails_df = emails_df[:10000]
print(emails_df.shape)
emails_df.head()
print(emails_d... | /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:1: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.
"""Entry point for launching an IPython kernel.
| MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
In the original paper, the dataset is built with 8billion emails where the context is provided by the email date, subject and previous message if the user is replying. Unfortunately, in the Enron dataset it's not possible to build the reply relationship between emails. In order thus to generate the context of a sentenc... | # Skip long sentences, which increase maximum length a lot when padding
# and make the number of parameters to train explode
SENTENCE_MAX_WORDS = 20
def generate_dataset (emails):
contents = emails['content']
output = []
vocabulary_sentences = []
for content in contents:
# Skip emails longer than one sent... | 509918
104151
('<start> here is <end>', '<start> our forecast <end>')
('<start> here is our <end>', '<start> forecast <end>')
('<start> way to <end>', '<start> go !!! <end>')
('<start> way to go <end>', '<start> !!! <end>')
("<start> let's shoot <end>", '<start> for tuesday at . <end>')
("<start> let's shoot for <end>"... | MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
This is where the fun begins. The dataset is finally available and we start working on the analysis by using [Keras](https://keras.io/) and [TensorFlow](https://www.tensorflow.org/). | import tensorflow as tf
from tensorflow import keras
np.random.seed(42) | _____no_output_____ | MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
We need to transform the text corpora into sequences of integers (each integer being the index of a token in a dictionary) by using keras `Tokenizer`. We also limit to the 10k most frequent words, deleting uncommon words from sentences.Normally we would use two tokenizers, one for the input strings and a different one ... | vocab_max_size = 10000
def tokenize(text):
tokenizer = keras.preprocessing.text.Tokenizer(filters='', num_words=vocab_max_size)
tokenizer.fit_on_texts(text)
return tokenizer
input = [pair[0] for pair in pairs]
output = [pair[1] for pair in pairs]
tokenizer = tokenize(vocabulary_sentences)
encoder_input = toke... | 10000 10
| MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
Here we define the RNN models. We start with the Encoder-Decoder model used in training which leverages the "teacher forcing technique". Therefore, it will receive as input `encoder_input` and `decoder_input` datasets.Then the second model is represented by the inference Decoder which will receive as input the encoded ... | # GRU Encoder
encoder_in_layer = keras.layers.Input(shape=(max_length_in,))
encoder_embedding = keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)
encoder_bi_gru = keras.layers.Bidirectional(keras.layers.GRU(units=latent_dim, return_sequences=True, return_state=True))
# Discard the encoder output a... | _____no_output_____ | MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
Let's test the inference model with some inputs. | texts = [
'here is',
'have a',
'please review',
'please call me',
'thanks for',
'let me',
'Let me know',
'Let me know if you',
'this sounds',
'is this call going to',
'can you get',
'is it okay',
'it should',
'call if there\'s',
'gave her a',
'i will let',... | _____no_output_____ | MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
The predicted outputs are actually quite good. The grammar is correct and have a logical sense. Some predictions also show that the predictions are personalized based on the Enron dataset, for instance in the case of `here is - the latest version of the presentation`.The `please review - the attached outage report` als... | import json
with open( 'word_dict-final.json' , 'w' ) as file:
json.dump( tokenizer.word_index , file)
encoder_model.save('./encoder-model-final.h5')
inf_model.save('./inf-model-final.h5') | _____no_output_____ | MIT | Google_Smart_Compose.ipynb | RavenColEvol/gmail-smart-compose |
Convolutional Wasserstein Barycenter exampleThis example is designed to illustrate how the Convolutional Wasserstein Barycenterfunction of POT works. | # Author: Nicolas Courty <ncourty@irisa.fr>
#
# License: MIT License
import numpy as np
import pylab as pl
import ot | _____no_output_____ | MIT | notebooks/plot_convolutional_barycenter.ipynb | vfdev-5/POT |
Data preparation----------------The four distributions are constructed from 4 simple images | f1 = 1 - pl.imread('../data/redcross.png')[:, :, 2]
f2 = 1 - pl.imread('../data/duck.png')[:, :, 2]
f3 = 1 - pl.imread('../data/heart.png')[:, :, 2]
f4 = 1 - pl.imread('../data/tooth.png')[:, :, 2]
A = []
f1 = f1 / np.sum(f1)
f2 = f2 / np.sum(f2)
f3 = f3 / np.sum(f3)
f4 = f4 / np.sum(f4)
A.append(f1)
A.append(f2)
A.ap... | _____no_output_____ | MIT | notebooks/plot_convolutional_barycenter.ipynb | vfdev-5/POT |
Barycenter computation and visualization---------------------------------------- | pl.figure(figsize=(10, 10))
pl.title('Convolutional Wasserstein Barycenters in POT')
cm = 'Blues'
# regularization parameter
reg = 0.004
for i in range(nb_images):
for j in range(nb_images):
pl.subplot(nb_images, nb_images, i * nb_images + j + 1)
tx = float(i) / (nb_images - 1)
ty = float(j)... | _____no_output_____ | MIT | notebooks/plot_convolutional_barycenter.ipynb | vfdev-5/POT |
1. The briefImagine working for a digital marketing agency, and the agency is approached by a massive online retailer of furniture. They want to test our skills at creating large campaigns for all of their website. We are tasked with creating a prototype set of keywords for search campaigns for their sofas section. Th... | # List of words to pair with products
words = ['buy', 'discount', 'promotion', 'cheap', 'offer', 'purchase', 'sale']
# Print list of words
print(words) | ['buy', 'discount', 'promotion', 'cheap', 'offer', 'purchase', 'sale']
| MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
2. Combine the words with the product namesImagining all the possible combinations of keywords can be stressful! But not for us, because we are keyword ninjas! We know how to translate campaign briefs into Python data structures and can imagine the resulting DataFrames that we need to create.Now that we have brainstor... | products = ['sofas', 'convertible sofas', 'love seats', 'recliners', 'sofa beds']
# Create an empty list
keywords_list = []
# Loop through products
for product in products:
# Loop through words
for word in words:
# Append combinations
keywords_list.append([product, product + ' ' + word])
... | [['sofas', 'sofas buy'], ['sofas', 'buy sofas'], ['sofas', 'sofas discount'], ['sofas', 'discount sofas'], ['sofas', 'sofas promotion'], ['sofas', 'promotion sofas'], ['sofas', 'sofas cheap'], ['sofas', 'cheap sofas'], ['sofas', 'sofas offer'], ['sofas', 'offer sofas'], ['sofas', 'sofas purchase'], ['sofas', 'purchase ... | MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
3. Convert the list of lists into a DataFrameNow we want to convert this list of lists into a DataFrame so we can easily manipulate it and manage the final output. | # Load library
# ... YOUR CODE FOR TASK 3 ...
import pandas as pd
# Create a DataFrame from list
keywords_df = pd.DataFrame.from_records(keywords_list)
# Print the keywords DataFrame to explore it
# ... YOUR CODE FOR TASK 3 ...
print(keywords_df.head()) | 0 1
0 sofas sofas buy
1 sofas buy sofas
2 sofas sofas discount
3 sofas discount sofas
4 sofas sofas promotion
| MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
4. Rename the columns of the DataFrameBefore we can upload this table of keywords, we will need to give the columns meaningful names. If we inspect the DataFrame we just created above, we can see that the columns are currently named 0 and 1. Ad Group (example: "sofas") and Keyword (example: "sofas buy") are much more ... | # Rename the columns of the DataFrame
keywords_df.columns = ['Ad Group', 'Keyword'] | _____no_output_____ | MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
5. Add a campaign columnNow we need to add some additional information to our DataFrame. We need a new column called Campaign for the campaign name. We want campaign names to be descriptive of our group of keywords and products, so let's call this campaign 'SEM_Sofas'. | # Add a campaign column
# ... YOUR CODE FOR TASK 5 ...
keywords_df['Campaign'] = 'SEM_Sofas' | _____no_output_____ | MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
6. Create the match type columnThere are different keyword match types. One is exact match, which is for matching the exact term or are close variations of that exact term. Another match type is broad match, which means ads may show on searches that include misspellings, synonyms, related searches, and other relevant ... | # Add a criterion type column
# ... YOUR CODE FOR TASK 6 ...
keywords_df['Criterion Type'] = 'Exact' | _____no_output_____ | MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
7. Duplicate all the keywords into 'phrase' matchThe great thing about exact match is that it is very specific, and we can control the process very well. The tradeoff, however, is that: The search volume for exact match is lower than other match typesWe can't possibly think of all the ways in which people search, and... | # Make a copy of the keywords DataFrame
keywords_phrase = keywords_df.copy()
# Change criterion type match to phrase
# ... YOUR CODE FOR TASK 7 ...
keywords_phrase['Criterion Type'] = 'Phrase'
# Append the DataFrames
keywords_df_final = keywords_df.append(keywords_phrase) | _____no_output_____ | MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
8. Save and summarize!To upload our campaign, we need to save it as a CSV file. Then we will be able to import it to AdWords editor or BingAds editor. There is also the option of pasting the data into the editor if we want, but having easy access to the saved data is great so let's save to a CSV file!To wrap up our ca... | # Save the final keywords to a CSV file
# ... YOUR CODE FOR TASK 8 ...
keywords_df_final.to_csv('keywords.csv', index=False)
# View a summary of our campaign work
summary = keywords_df_final.groupby(['Ad Group', 'Criterion Type'])['Keyword'].count()
print(summary) | Ad Group Criterion Type
convertible sofas Exact 14
Phrase 14
love seats Exact 14
Phrase 14
recliners Exact 14
Phrase 14
sofa beds Exact 14
... | MIT | projects_py/Generating Keywords for Google AdWords/notebook.ipynb | AndreasFerox/DataCamp |
Spectrogram and spectrum slice displaySelect an audio file from the dropdown list to display its waveform spectrogram. Click on a part of the waveform or spectrogram to select a spectrum slice to display. Mouse over the spectrum slice to explore the frequencies. The circle tracks the current frequency in the spectrum ... | import os
os.environ['BOKEH_RESOURCES'] = 'inline' # To ensure we load monkeypatched version of bokeh rather than from cdn
from spectrum_slice_app import spectrum_slice_app
from bokeh_phon.utils import remote_jupyter_proxy_url_callback, set_default_jupyter_url
from bokeh.io import show
# Set this value to the hostname ... | _____no_output_____ | BSD-3-Clause | spectrum_slice/spectrum_slice.ipynb | rsprouse/phonapps |
Solution for Big O Notation exercises **Question 1**Design an algorithm that calculates the factorial of a number , 1) By using for loop, 2) By using if-else statement. Then, calculate the time needed to run the program.for example, $4! = 4 \times 3 \times 2 \times 1 = 24 $Which algorithm is the fastest one? *Source:... | %%writefile fact1.py
#By using for-loop
from memory_profiler import profile
@profile
def fact(n):
product = 1
for i in range(n):
product = product * (i+1)
return product
print(fact(4))
# print(%timeit fact(4))
# print(%timeit fact(50))
#By using for-loop
def fact(n):
product = 1
for i i... | 24
505 ns ± 34.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
8.21 µs ± 1.38 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
| Apache-2.0 | Module-05/.ipynb_checkpoints/BigO_solution-checkpoint.ipynb | FairozaAmira/python-training |
import numpy as np
import tensorflow as tf
import gym
import tensorflow_probability as tfp
from multiprocessing import Process, Queue, Barrier, Lock
import tensorflow.keras.losses as kls
!pip3 install box2d-py
env= gym.make("CartPole-v0")
low = env.observation_space.low
high = env.observation_space.high
class critic(t... | WARNING:tensorflow:Layer actor is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because it's dtype defaults to floatx.
If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this wa... | MIT | algos/Multi_Worker_Actor_Critic.ipynb | olonok69/RL_Stable_baselines | |
Own PCA code | all_data_t=all_data.T
cov=np.cov(all_data_t)
cov
np.linalg.eig(cov)
eig_val,eig_vectors=np.linalg.eig(cov)
eig_val_vector_pair=[]
for i in range(len(eig_val)):
eig_vec=eig_vectors[:,i]
eig_val_vector_pair.append((eig_val[i],eig_vec))
eig_val_vector_pair.sort(reverse=True)
eig_val_vector_pair | _____no_output_____ | MIT | Lecture 19 PCA/Let-s Code our Own PCA/Own PCA code.ipynb | Paraskk/Data-Science-and-Machine-Leaning- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.