markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
The plot function The plot function creates a two-dimensional plot of one variable against another.
# Use the help function to see the documentation for plot
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Example Create a plot of $f(x) = x^2$ with $x$ between -2 and 2. * Set the linewidth to 3 points * Set the line transparency (alpha) to 0.6 * Set axis labels and title * Add a grid to the plot
# Create an array of x values from -6 to 6 # Create a variable y equal to the x squared # Use the plot function to plot the line # Add a title and axis labels # Add grid
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Example Create plots of the functions $f(x) = \log x$ (natural log) and $g(x) = 1/x$ between 0.01 and 5 * Set the limits for the $x$-axis to (0,5) * Set the limits for the $y$-axis to (-2,5) * Make the line for $log(x)$ solid blue * Make the line for $1/x$ dashd magenta * Set the linewidth of each line to 3 points * Se...
# Create an array of x values from -6 to 6 # Create y variables # Use the plot function to plot the lines # Add a title and axis labels # Set axis limits # legend # Add grid
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Example Consider the linear regression model: \begin{align} y_i = \beta_0 + \beta_1 x_i + \epsilon_i \end{align} where $x_i$ is the independent variable, $\epsilon_i$ is a random regression error term, $y_i$ is the dependent variable and $\beta_0$ and $\beta_1$ are constants. Let's simulate the model * Set values for $...
# Set betas # Create x values # create epsilon values from the standard normal distribution # create y # plot # Add a title and axis labels # Set axis limits # Add grid
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Example Create plots of the functions $f(x) = x$, $g(x) = x^2$, and $h(x) = x^3$ for $x$ between -2 and 2 * Use the optional string format argument to format the lines: - $x$: solid blue line - $x^2$: dashed green line - $x^3$: dash-dot magenta line * Set the linewidth of each line to 3 points * Set transparency ...
# Create an array of x values from -6 to 6 # Create y variables # Use the plot function to plot the lines # Add a title and axis labels # Add grid # legend
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Figures, axes, and subplots Often we want to create plots with multiple axes or we want to modify the size and shape of the plot areas. To be able to do these things, we need to explicity create a figure and then create the axes within the figure. The best way to see how this works is by example. Example: A single plot...
# Create data # Create a new figure # Create axis # Plot # Add grid
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
In the previous example the figure() function creates a new figure and add_subplot() puts a new axis on the figure. The command fig.add_subplot(1,1,1) means divide the figure fig into a 1 by 1 grid and assign the first component of that grid to the variable ax1. Example: Two plots side-by-side Create a new figure with ...
# Create data # Create a new figure # Create axis 1 and plot with title # Create axis 2 and plot with title
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Example: Block of four plots The default dimensions of a matplotlib figure are 6 inches by 4 inches. As we saw above, this leaves some whitespace on the right side of the figure. Suppose we want to remove that by making the plot area twice as wide. Create a new figure with four axes in a two-by-two grid. Plot the follo...
# Create data # Create a new figure # Create axis 1 and plot with title # Create axis 2 and plot with title # Create axis 3 and plot with title # Create axis 4 and plot with title # Adjust margins
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Exporting figures to image files Use the plt.savefig() function to save figures to images.
# Create data x = np.arange(-6,6,0.001) y = np.sin(x) # Create a new figure, axis, and plot fig = plt.figure() ax1 = fig.add_subplot(1,1,1) ax1.plot(x,y,lw=3,alpha = 0.6) ax1.grid() # Save plt.savefig('fig_econ129_class04_sine.png',dpi=120)
winter2017/econ129/python/Econ129_Class_04.ipynb
letsgoexploring/teaching
mit
Représentation Le module pandas manipule des tables et c'est la façon la plus commune de représenter les données. Lorsque les données sont multidimensionnelles, on distingue les coordonnées des valeurs :
NbImage("cube1.png")
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Dans cet exemple, il y a : 3 coordonnées : Age, Profession, Annéee 2 valeurs : Espérance de vie, Population On peut représenter les donnés également comme ceci :
NbImage("cube2.png")
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
C'est assez simple. Prenons un exemple : table de mortalité de 1960 à 2010 qu'on récupère à l'aide de la fonction table_mortalite_euro_stat. C'est assez long (4-5 minutes) sur l'ensemble des données car elles doivent être prétraitées (voir la documentation de la fonction). Pour écouter, il faut utiliser le paramètre st...
from actuariat_python.data import table_mortalite_euro_stat table_mortalite_euro_stat() import os os.stat("mortalite.txt") import pandas df = pandas.read_csv("mortalite.txt", sep="\t", encoding="utf8", low_memory=False) df.head()
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Les indicateurs pour deux âges différents :
df [ ((df.age=="Y60") | (df.age=="Y61")) & (df.annee == 2000) & (df.pays=="FR") & (df.genre=="F")]
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Exercice 1 : filtre On veut comparer les espérances de vie pour deux pays et deux années.
#
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Données trop grosses pour tenir en mémoire : SQLite
df.shape
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Les données sont trop grosses pour tenir dans une feuille Excel. Pour les consulter, il n'y a pas d'autres moyens que d'en regarder des extraits. Que passe quand même ceci n'est pas possible ? Quelques solutions : augmenter la mémoire de l'ordinateur, avec 20 Go, on peut faire beaucoup de choses stocker les données da...
import sqlite3 from pandas.io import sql cnx = sqlite3.connect('mortalite.db3') try: df.to_sql(name='mortalite', con=cnx) except ValueError as e: if "Table 'mortalite' already exists" not in str(e): # seulement si l'erreur ne vient pas du fait que cela # a déjà été fait raise e # on peu...
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
On peut maintenant récupérer un morceau avec la fonction read_sql.
import pandas example = pandas.read_sql('select * from mortalite where age_num==50 limit 5', cnx) example
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
L'ensemble des données restent sur le disque, seul le résultat de la requête est chargé en mémoire. Si on ne peut pas faire tenir les données en mémoire, il faut soit en obtenir une vue partielle (un échantillon aléatoire, un vue filtrée), soit une vue agrégrée. Pour finir, il faut fermer la connexion pour laisser d'au...
cnx.close()
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Sous Windows, on peut consulter la base avec le logiciel SQLiteSpy.
NbImage("sqlite.png")
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Sous Linux ou Max, on peut utiliser une extension Firefox SQLite Manager. Dans ce notebook, on utilisera la commande magique %%SQL du module pyensae :
%load_ext pyensae %SQL_connect mortalite.db3 %SQL_tables %SQL_schema mortalite %%SQL SELECT COUNT(*) FROM mortalite %SQL_close
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Exercice 2 : échantillon aléatoire Si on ne peut pas faire tenir les données en mémoire, on peut soit regarder les premières lignes soit prendre un échantillon aléatoire. Deux options : Dataframe.sample create_function La première fonction est simple :
sample = df.sample(frac=0.1) sample.shape, df.shape
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Je ne sais pas si cela peut être réalisé sans charger les données en mémoire. Si les données pèsent 20 Go, cette méthode n'aboutira pas. Pourtant, on veut juste un échantillon pour commencer à regarder les données. On utilise la seconde option avec create_function et la fonction suivante :
import random #loi uniforme def echantillon(proportion): return 1 if random.random() < proportion else 0 import sqlite3 from pandas.io import sql cnx = sqlite3.connect('mortalite.db3') cnx.create_function('echantillon', 1, echantillon)
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Que faut-il écrire ici pour récupérer 1% de la table ?
import pandas #example = pandas.read_sql(' ??? ', cnx) #example cnx.close()
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Pseudo Map/Reduce avec SQLite La liste des mots-clés du langage SQL utilisés par SQLite n'est pas aussi riche que d'autres solutions de serveurs SQL. La médiane ne semble pas en faire partie. Cependant, pour une année, un genre, un âge donné, on voudrait calculer la médiane de l'espérance de vie sur l'ensembles des pay...
import sqlite3, pandas from pandas.io import sql cnx = sqlite3.connect('mortalite.db3') pandas.read_sql('select pays,count(*) from mortalite group by pays', cnx)
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Il n'y a pas le même nombre de données selon les pays, il est probable que le nombre de pays pour lesquels il existe des données varie selon les âges et les années.
query = """SELECT nb_country, COUNT(*) AS nb_rows FROM ( SELECT annee,age,age_num, count(*) AS nb_country FROM mortalite WHERE indicateur=="LIFEXP" AND genre=="F" GROUP BY annee,age,age_num ) GROUP BY nb_country""" df = pandas.read_sql(query, cnx) df.sort_va...
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Soit un nombre inconstant de pays. Le fait qu'on est 100 pays suggère qu'on ait une erreur également.
query = """SELECT annee,age,age_num, count(*) AS nb_country FROM mortalite WHERE indicateur=="LIFEXP" AND genre=="F" GROUP BY annee,age,age_num HAVING nb_country >= 100""" df = pandas.read_sql(query, cnx) df.head()
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Ce sont des valeurs manquantes. Le problème pour calculer la médiane pour chaque observation est qu'il faut d'abord regrouper les lignes de la table par indicateur puis choisir la médiane dans chaque de ces petits groupes. On s'inspire pour cela de la logique Map/Reduce et de la fonction create_aggregate. Exercice 3 : ...
class ReducerMediane: def __init__(self): # ??? pass def step(self, value): # ??? # pass def finalize(self): # ??? # return ... //2 ] pass cnx.create_aggregate("ReducerMediane", 1, ReducerMediane) #query = """SELECT annee,age,age_num,...
_doc/notebooks/sessions/seance5_sql_multidimensionnelle_enonce.ipynb
sdpython/actuariat_python
mit
Convert A List To A Tuple You can change a list to a tuple in Python by using the tuple() function. Pass your list to this function and you will get a tuple back! NOTE: tuples are immutable thus can’t change them afterwards :( Convert Your List To A Set In Python a set is an unordered collection of unique items. That m...
helloWorld = ['hello','world','1','2'] # print(list(zip(helloWorld))) helloWorldDictionary = dict(zip(helloWorld[0::2], helloWorld[1::2])) # Print out the result print(helloWorldDictionary)
Section 1 - Core Python/Chapter 05 - Data Types/5.1 Uses of collection and datatype.ipynb
mayank-johri/LearnSeleniumUsingPython
gpl-3.0
Note that the second element that is passed to the zip() function makes use of the step value to make sure that only the world and 2 elements are selected. Likewise, the first element uses the step value to select hello and 1. If your list is large, you will probably want to do something like this:
a = [1, 2, 3, 4, 5] # Create a list iterator object i = iter(a) for k in i: print(k) # Zip and create a dictionary print(dict(zip(i, i))) ## Difference Between The Python append() and extend() Methods? # Append [4,5] to `shortList` # This is your list shortList = [1, 2, 3] longerList = [1, 2, 3] # Check whether...
Section 1 - Core Python/Chapter 05 - Data Types/5.1 Uses of collection and datatype.ipynb
mayank-johri/LearnSeleniumUsingPython
gpl-3.0
Clone Or Copy A List in Python here are a lot of ways of cloning or copying a list: You can slice your original list and store it into a new variable: newList = oldList[:] You can use the built-in list() function: newList = list(oldList) You can use the copy library: With the copy() method: newList = copy.copy(oldL...
# Copy the grocery list by slicing and store it in the `newGroceries` variable groceries = [1, 2, 3, 4, 5, 6] newGroceries = groceries[:] # Copy the grocery list with the `list()` function and store it in a `groceriesForFriends` variable groceriesForFriends = list(groceries) # Import the copy library import copy as c #...
Section 1 - Core Python/Chapter 05 - Data Types/5.1 Uses of collection and datatype.ipynb
mayank-johri/LearnSeleniumUsingPython
gpl-3.0
Run the following cell to print sentences from X_train and corresponding labels from Y_train. Change index to see different examples. Because of the font the iPython notebook uses, the heart emoji may be colored black rather than red.
index = 1 print(X_train[index], label_to_emoji(Y_train[index]))
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Let's see what convert_to_one_hot() did. Feel free to change index to print out different values.
index = 50 print(Y_train[index], "is converted into one hot", Y_oh_train[index])
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Exercise: Implement sentence_to_avg(). You will need to carry out two steps: 1. Convert every sentence to lower-case, then split the sentence into a list of words. X.lower() and X.split() might be useful. 2. For each word in the sentence, access its GloVe representation. Then, average all these values.
# GRADED FUNCTION: sentence_to_avg def sentence_to_avg(sentence, word_to_vec_map): """ Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence. Arguments: senten...
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Expected Output: <table> <tr> <td> **avg= ** </td> <td> [-0.008005 0.56370833 -0.50427333 0.258865 0.55131103 0.03104983 -0.21013718 0.16893933 -0.09590267 0.141784 -0.15708967 0.18525867 0.6495785 0.38371117 0.21102167 0.11301667 0.02613967 0.260...
# GRADED FUNCTION: model def model(X, Y, word_to_vec_map, learning_rate = 0.01, num_iterations = 400): """ Model to train word vector representations in numpy. Arguments: X -- input data, numpy array of sentences as strings, of shape (m, 1) Y -- labels, numpy array of integers between 0 and 7,...
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
2.1 - Overview of the model Here is the Emojifier-v2 you will implement: <img src="images/emojifier-v2.png" style="width:700px;height:400px;"> <br> <caption><center> Figure 3: Emojifier-V2. A 2-layer LSTM sequence classifier. </center></caption> 2.2 Keras and mini-batching In this exercise, we want to train Keras using...
# GRADED FUNCTION: sentences_to_indices def sentences_to_indices(X, word_to_index, max_len): """ Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4). ...
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Expected Output: <table> <tr> <td> **X1 =** </td> <td> ['funny lol' 'lets play football' 'food is ready for you'] </td> </tr> <tr> <td> **X1_indices =** </td> <td> [[ 155345. 225122. 0. 0. ...
# GRADED FUNCTION: pretrained_embedding_layer def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. ...
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Expected Output: <table> <tr> <td> **weights[0][1][3] =** </td> <td> -0.3403 </td> </tr> </table> 2.3 Building the Emojifier-V2 Lets now build the Emojifier-V2 model. You will do so using the embedding layer you have built, and feed its output to an LSTM n...
# GRADED FUNCTION: Emojify_V2 def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimension...
deeplearning.ai/C5.SequenceModel/Week2_NLP_WordEmbeddings/assignment/Emojify/Emojify - v2.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
1. Test Brown Corpus
from nltk.corpus import brown brown.words()[0:10] brown.tagged_words()[0:10] len(brown.words()) dir(brown)
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
2. Test NLTK Book Resources
from nltk.book import * dir(text1) len(text1)
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
3. Sent Tokenize(sentence boundary detection, sentence segmentation), Word Tokenize and Pos Tagging
from nltk import sent_tokenize, word_tokenize, pos_tag text = "Machine learning is the science of getting computers to act without being explicitly programmed. In the past decade, machine learning has given us self-driving cars, practical speech recognition, effective web search, and a vastly improved understanding of ...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
4. Sentence Tokenize and Word Tokenize Sentence boundary disambiguation (SBD), also known as sentence breaking, is the problem in natural language processing of deciding where sentences begin and end. Often natural language processing tools require their input to be divided into sentences for a number of reasons. Howev...
text = "this’s a sent tokenize test. this is sent two. is this sent three? sent 4 is cool! Now it’s your turn." from nltk.tokenize import sent_tokenize sent_tokenize_list = sent_tokenize(text) len(sent_tokenize_list) sent_tokenize_list import nltk.data tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
Tokenizing text into words
from nltk.tokenize import word_tokenize word_tokenize('Hello World.') word_tokenize("this's a test") from nltk.tokenize import TreebankWordTokenizer tokenizer = TreebankWordTokenizer() tokenizer.tokenize("this’s a test") # Standard word tokenizer. _word_tokenize = TreebankWordTokenizer().tokenize def word_tokenize(...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
5. Part-Of-Speech Tagging and POS Tagger In corpus linguistics, part-of-speech tagging (POS tagging or POST), also called grammatical tagging or word-category disambiguation, is the process of marking up a word in a text (corpus) as corresponding to a particular part of speech, based on both its definition, as well as ...
text = nltk.word_tokenize("Dive into NLTK: Part-of-speech tagging and POS Tagger") text nltk.pos_tag(text) nltk.help.upenn_tagset('NN.*') nltk.help.upenn_tagset('VB.*') nltk.help.upenn_tagset('JJ.*') nltk.help.upenn_tagset('CC.*') nltk.help.upenn_tagset('IN.*') nltk.help.upenn_tagset('PRP.*') nltk.help.upenn_tagset('...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
TnT POS Tagger Model
# Natural Language Toolkit: TnT Tagger # # Copyright (C) 2001-2013 NLTK Project # Author: Sam Huston <sjh900@gmail.com> # # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT ''' Implementation of 'TnT - A Statisical Part of Speech Tagger' by Thorsten Brants http://acl.ldc.upenn.edu/A/A00/A00-10...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
6. Stemming In linguistic morphology and information retrieval, stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form. The stem need not be identical to the morphological root of the word; it is usually sufficient that related words ma...
from nltk.stem.porter import PorterStemmer porter_stemmer = PorterStemmer() from nltk.stem.lancaster import LancasterStemmer lancaster_stemmer = LancasterStemmer() from nltk.stem import SnowballStemmer snowball_stemmer = SnowballStemmer("english") #from nltk.stem.api import StemmerI #api_stemmer = StemmerI() from nltk...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
7. Lemmatization Lemmatisation (or lemmatization) in linguistics, is the process of grouping together the different inflected forms of a word so they can be analysed as a single item. In computational linguistics, lemmatisation is the algorithmic process of determining the lemma for a given word. Since the process may ...
from nltk.stem import WordNetLemmatizer wordnet_lemmatizer = WordNetLemmatizer() words_lem = ['dogs','churches','aardwolves','abaci','hardrock','attractive','are','is'] #words_lem_pos = pos_tag(words_lem) wordnet_words = [] for word in words_lem: if word == 'is' or word == 'are': # for verbs ...
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
Some simple things you can do with NLTK http://www.nltk.org/
import nltk sentence = "At eight o'clock on Thursday morning Arthur didn't feel very good." tokens = nltk.word_tokenize(sentence) tokens tagged = nltk.pos_tag(tokens) tagged[0:6] entities = nltk.chunk.ne_chunk(tagged) entities from nltk.corpus import treebank t = treebank.parsed_sents('wsj_0001.mrg')[0] t.draw()
test/Learning/MN - text mining test.ipynb
datahac/jup
apache-2.0
Plotting 2 moons dataset Code taken directly from Chris Waites's jax-flows demo. This is the distribution we want to create a bijection to from a simple base distribution, such as a gaussian distribution.
n_samples = 10000 plot_range = [(-2, 2), (-2, 2)] n_bins = 100 scaler = preprocessing.StandardScaler() X, _ = datasets.make_moons(n_samples=n_samples, noise=0.05) X = scaler.fit_transform(X) plt.hist2d(X[:, 0], X[:, 1], bins=n_bins, range=plot_range)[-1] plt.savefig("two-moons-original.pdf") plt.savefig("two-moons-or...
notebooks/book2/22/two_moons_normalizingFlow.ipynb
probml/pyprobml
mit
Creating the normalizing flow in distrax+haiku Instead of a uniform distribution, we use a normal distribution as the base distribution. This makes more sense for a standardized two moons dataset that is scaled according to a normal distribution using sklearn's StandardScaler(). Using a uniform base distribution will r...
from typing import Any, Iterator, Mapping, Optional, Sequence, Tuple # Hyperparams - change these to experiment flow_num_layers = 8 mlp_num_layers = 4 hidden_size = 1000 num_bins = 8 batch_size = 512 learning_rate = 1e-4 eval_frequency = 100 Array = jnp.ndarray PRNGKey = Array Batch = Mapping[str, np.ndarray] OptStat...
notebooks/book2/22/two_moons_normalizingFlow.ipynb
probml/pyprobml
mit
Setting up the optimizer
optimizer = optax.adam(learning_rate) @jax.jit def update(params: hk.Params, prng_key: PRNGKey, opt_state: OptState, batch: Batch) -> Tuple[hk.Params, OptState]: """Single SGD update step.""" grads = jax.grad(loss_fn)(params, prng_key, batch) updates, new_opt_state = optimizer.update(grads, opt_state) ...
notebooks/book2/22/two_moons_normalizingFlow.ipynb
probml/pyprobml
mit
Training the flow
# Event shape TWO_MOONS_SHAPE = (2,) # Create tf dataset from sklearn dataset dataset = tf.data.Dataset.from_tensor_slices(X) # Splitting into train/validate ds train = dataset.skip(2000) val = dataset.take(2000) # load_dataset(split: tfds.Split, batch_size: int) train_ds = load_dataset(train, 512) valid_ds = load_d...
notebooks/book2/22/two_moons_normalizingFlow.ipynb
probml/pyprobml
mit
Overriding the __repr__ method:
class Ball(object): def __repr__(self): return 'TEST' b = Ball() print(b)
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
IPython expands on this idea and allows objects to declare other, rich representations including: HTML JSON PNG JPEG SVG LaTeX A single object can declare some or all of these representations; all of them are handled by IPython's display system. . Basic display imports The display function is a general purpose tool f...
from IPython.display import display
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
A few points: Calling display on an object will send all possible representations to the Notebook. These representations are stored in the Notebook document. In general the Notebook will use the richest available representation. If you want to display a particular representation, there are specific functions for that...
from IPython.display import ( display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg )
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Images To work with images (JPEG, PNG) use the Image class.
from IPython.display import Image i = Image(filename='./ipython-image.png') display(i)
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Returning an Image object from an expression will automatically display it:
i
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
An image can also be displayed from raw data or a URL.
Image(url='http://python.org/images/python-logo.gif')
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
HTML Python objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the HTML class.
from IPython.display import HTML s = """<table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table>""" h = HTML(s) display(h)
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
You can also use the %%html cell magic to accomplish the same thing.
%%html <table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> %%html <style> #notebook { background-color: skyblue; font-family: times new roman; } </style>
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
You can remove the abvove styling by using "Cell"$\rightarrow$"Current Output"$\rightarrow$"Clear" with that cell selected. JavaScript The Notebook also enables objects to declare a JavaScript representation. At first, this may seem odd as output is inherently visual and JavaScript is a programming language. However, ...
from IPython.display import Javascript
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Pass a string of JavaScript source code to the JavaScript object and then display it.
js = Javascript('alert("hi")'); display(js)
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
The same thing can be accomplished using the %%javascript cell magic:
%%javascript alert("hi");
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Here is a more complicated example that loads d3.js from a CDN, uses the %%html magic to load CSS styles onto the page and then runs ones of the d3.js examples.
Javascript( """$.getScript('https://cdnjs.cloudflare.com/ajax/libs/d3/3.2.2/d3.v3.min.js')""" ) %%html <style type="text/css"> circle { fill: rgb(31, 119, 180); fill-opacity: .25; stroke: rgb(31, 119, 180); stroke-width: 1px; } .leaf circle { fill: #ff7f0e; fill-opacity: 1; } text { font: 10px san...
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Audio IPython makes it easy to work with sounds interactively. The Audio display class allows you to create an audio control that is embedded in the Notebook. The interface is analogous to the interface of the Image display class. All audio formats supported by the browser can be used. Note that no single format is pre...
from IPython.display import Audio Audio("./scrubjay.mp3")
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
A NumPy array can be converted to audio. The Audio class normalizes and encodes the data and embeds the resulting audio in the Notebook. For instance, when two sine waves with almost the same frequency are superimposed a phenomena known as beats occur:
import numpy as np max_time = 3 f1 = 120.0 f2 = 124.0 rate = 8000.0 L = 3 times = np.linspace(0,L,rate*L) signal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times) Audio(data=signal, rate=rate)
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Video More exotic objects can also be displayed, as long as their representation supports the IPython display protocol. For example, videos hosted externally on YouTube are easy to load:
from IPython.display import YouTubeVideo YouTubeVideo('sjfsUzECqK0')
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
External sites You can even embed an entire page from another site in an iframe; for example this is IPython's home page:
from IPython.display import IFrame IFrame('https://ipython.org', width='100%', height=350)
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Links to local files IPython provides builtin display classes for generating links to local files. Create a link to a single file using the FileLink object:
from IPython.display import FileLink, FileLinks FileLink('../Visualization/Matplotlib.ipynb')
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
Alternatively, to generate links to all of the files in a directory, use the FileLinks object, passing '.' to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, FileLinks would work in a recursive manner creating links to files...
FileLinks('./')
days/day08/Display.ipynb
CalPolyPat/phys202-2015-work
mit
From the above code, we read the text file and saved the JSON data to the variable data to work with. We need to pull the time stamps, and their accompanying day of week. We want to convert a list of timestamps into a list of formatted timestamps. But first, we import datetime and parser.
from datetime import datetime from dateutil.parser import parse # limit to just march posts march_posts = list(filter(lambda x: parse(x['created_time'][:-5]) >= datetime(2017, 3, 1), data )) print(len(march_posts), "posts since", datetime(2017, 3, 1).date()) # get days to count occurrence march_days = list (map( lam...
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
Now let's write some utility functions to process the data for the chart. Scrub turns the raw string type into a datetime type. Then we can pass that into dow() and hod() to format the strings.
def scrub(raw_timestamp): timestamp = parser.parse(raw_timestamp) return dow(timestamp), hod(timestamp) # returns day of week def dow(date): return date.strftime("%A") # i.e. Monday # returns hour of day def hod(time): return time.strftime("%-I:%M%p") # i.e.
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
Now we want to try create nested lists. A month contains weeks, which in turn contains days. To express this in code, it would be something like so: M = [W, W, W, ...] W = ["Mon", "Tues, "Wed", "Thu", ... ] The lists are combined into a list of lists. The
yIndex = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] # Get a list of week numbers, 0-3. Note that March starts on week 9 of 2017 # but we subtract 9 to start at index 0 get_week = list (map( lambda x: parse(x['created_time']).isocalendar()[1]-9, march_posts )) # Get a list of day numbers...
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
Now let's step it up and count posts per day, so we can have more than 2 shades of colors on the heatmap.
# empty list of lists activity = [[0] * 7 for i in repeat(None, 5)] # the total number of posts limit = len(get_week) # fill in empty array with a fraction for i, (w, d) in enumerate(zip(get_week, get_day)): activity[w][d] += 1/limit print("activity per day: \n", activity)
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
Now our data is ready for plotting. Let's do the important config stuff.
%matplotlib inline import matplotlib.pyplot as plt import numpy as np
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
Here's how you create a chart of heatmap type, filled in with values from activity.
fig, ax = plt.subplots() heatmap = ax.pcolor(activity, cmap=plt.cm.Greens, alpha=0.8) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(0,7)+0.5, minor=False) ax.set_yticks(np.arange(0,5)+0.5, minor=False) # want a more natural, table-like display ax.invert_yaxis() ax.xaxis.tick_top() # labels...
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
I'm not liking how the borders look like. So I'm going to create another version with the seaborn library.
import seaborn as sns sns.set(font_scale=1.2) sns.set_style({"savefig.dpi": 100}) ax = sns.heatmap(activity, cmap=plt.cm.Greens, linewidths=.1) ax.xaxis.tick_top() ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(list(''), minor=False) fig = ax.get_figure()
facebook_posting_activity_part2.ipynb
katychuang/ipython-notebooks
gpl-2.0
<h3>Binary gaussian fit</h3> Now we fit two gaussians to the data to test the hypothesis that there are two stars in the data. To do this, we fit the data to the function \begin{eqnarray} f_B(x,y,\vec{z}) & = & F_1\exp\left[-\frac{(x-x_c-\frac{1}{2}r\cos\theta)^2 + (y-y_c-\frac{1}{2}r\sin\theta)^2}{2\sigma_0^2}\right]...
#Fit data to binary star model def binary_gaussian_f(z,sig,xc,yc,r,theta,F1,F2,B): f1 = F1*np.exp(-0.5*((z[0]-xc-0.5*r*np.cos(theta))**2 + (z[1]-yc-0.5*r*np.sin(theta))**2)/sig**2) f2 = F2*np.exp(-0.5*((z[0]-xc+0.5*r*np.cos(theta))**2 + (z[1]-yc+0.5*r*np.sin(...
stats/HW_4_PS.ipynb
mbuchove/notebook-wurk-b
mit
<h3>Model comparison</h3> To compare the binary and single star models, we compute the ratio of the posteriors for each model, given by $$\frac{P(B \mid {D_{x,y}})}{P(S \mid {D_{x,y}})} = \frac{P({D_{x,y}}\mid B)P(B)}{P({D_{x,y}}\mid S)P(S)}$$ We assume that the priors for each model are equal, so these terms cancel i...
F_max = 300. r_max = stardata.shape[0] det_cov_b = np.linalg.det(pcov_b) det_cov_s = np.linalg.det(pcov_s) sig_b, x0_b, y0_b, r_b, theta_b, F1_b, F2_b, B_b = popt_b chi2_b = 0. for xx in range(0,stardata.shape[0]): for yy in range(0,stardata.shape[1]): res_b = stardata[yy,xx] - binary_gaussian_f((xx,yy), *...
stats/HW_4_PS.ipynb
mbuchove/notebook-wurk-b
mit
<h3>Joint distribution for star fluxes in the binary model</h3> Assuming the joint distribution for the fluxes of star 1 and 2 is gaussian (this follows from the gaussian approximation of the distribution of the best-fit parameters and integrating out the unwanted parameters. The result is still a gaussian), we have $...
theta = np.linspace(0,2*np.pi,100) r = np.linspace(0,stardata.shape[0]-1,stardata.shape[0]) cov_r = pcov_b[3:5,3:5] det_covr = np.linalg.det(cov_r) inv_covr = np.linalg.inv(cov_r) joint_rt = np.array([[1/(2*np.pi*np.sqrt(det_covr))*np.exp(-0.5*float(np.dot(np.dot(np.transpose(np.array([[rr-r_b], ...
stats/HW_4_PS.ipynb
mbuchove/notebook-wurk-b
mit
Here are the RadarSat-2 quadpol coherency matrix image directories as created from the Sentinel-1 Toolbox:
ls /home/imagery
mohammed.ipynb
mortcanty/SARDocker
mit
To combine the matrix bands into a single GeoTiff image, we run the python script ingestrs2quad.py:
run /home/ingestrs2quad /home/imagery/RS2_OK82571_PK721079_DK650144_FQ17W_20160403_230258_HH_VV_HV_VH_SLC/ run /home/ingestrs2quad /home/imagery/RS2_OK82571_PK721080_DK650145_FQ17W_20160427_230257_HH_VV_HV_VH_SLC/ run /home/ingestrs2quad /home/imagery/RS2_OK82571_PK721081_DK650146_FQ17W_20160614_230256_HH_VV_HV_VH_SL...
mohammed.ipynb
mortcanty/SARDocker
mit
Here is an RGB display of the three diagonal matrix elements of the above image (bands 1,6 and 9):
run /home/dispms -f /home/imagery/RS2_OK82571_PK721081_DK650146_FQ17W_20160614_230256_HH_VV_HV_VH_SLC/polSAR.tif \ -p [1,6,9]
mohammed.ipynb
mortcanty/SARDocker
mit
To estimate the equivalent number of looks, run the python script enlml.py:
run /home/enlml /home/imagery/RS2_OK82571_PK721081_DK650146_FQ17W_20160614_230256_HH_VV_HV_VH_SLC/polSAR.tif
mohammed.ipynb
mortcanty/SARDocker
mit
So the ENL would appear to be about 5. To run the change sequential change detection on the three images, run the bash script sar_seq_rs2quad.sh. It gathers the three images together and calls the python script sar_seq.py which does the change detection. By choosing a spatial subset (in this case 400x400), the images a...
!/home/sar_seq_rs2quad.sh 20160403 20160427 20160614 [50,50,400,400] 5 0.01
mohammed.ipynb
mortcanty/SARDocker
mit
Here is the change map for the most recent changes:
run /home/dispms \ -f /home/imagery/RS2_OK82571_PK721079_DK650144_FQ17W_20160403_230258_HH_VV_HV_VH_SLC/sarseq(20160403-1-20160614)_cmap.tif -c
mohammed.ipynb
mortcanty/SARDocker
mit
Transliteration
from indicnlp.transliterate.unicode_transliterate import ItransTransliterator bangla_text = "ami apni tumi tomar tomader amar apnar apnader akash" text_trans = ItransTransliterator.from_itrans(bangla_text, "bn") print repr(text_trans).decode("unicode_escape")
stemming_and_transliteration/Bangla Stemming and Transliteration.ipynb
salman-jpg/maya
mit
Using Silpa https://github.com/libindic/Silpa-Flask Transliteration
from transliteration import getInstance trans = getInstance() text_trans = trans.transliterate(bangla_text, "bn_IN") print repr(text_trans).decode("unicode_escape")
stemming_and_transliteration/Bangla Stemming and Transliteration.ipynb
salman-jpg/maya
mit
Using BengaliStemmer https://github.com/gdebasis/BengaliStemmer Stemming
import rbs word_stem1 = [] for i in word_token: word_stem1.append(rbs.stemWord(i, True)) bs1 = pd.DataFrame({"1_Word": word_token, "2_Stem": word_stem1}) bs1
stemming_and_transliteration/Bangla Stemming and Transliteration.ipynb
salman-jpg/maya
mit
Using BanglaStemmer https://github.com/rafi-kamal/Bangla-Stemmer Stemming
import jnius_config jnius_config.set_classpath(".", "path to class") from jnius import autoclass cls = autoclass("RuleFileParser") stemmer = cls() word_stem2 = [] for i in word_token: word_stem2.append(stemmer.stemOfWord(i)) bs2 = pd.DataFrame({"1_Word": word_token, "2_Stem": word_stem2}) bs2
stemming_and_transliteration/Bangla Stemming and Transliteration.ipynb
salman-jpg/maya
mit
Using Avro https://github.com/kaustavdm/pyAvroPhonetic Transliteration
from pyavrophonetic import avro trans_text = avro.parse(bangla_text) print repr(trans_text).decode("unicode_escape")
stemming_and_transliteration/Bangla Stemming and Transliteration.ipynb
salman-jpg/maya
mit
In the following sections we will load the data, pre-process it, train the model, and explore the results using some of the implementation's functionality. Feel free to skip the loading and pre-processing for now, if you are familiar with the process. Loading the data In the cell below, we crawl the folders and files i...
import os, re # Folder containing all NIPS papers. data_dir = '/tmp/nipstxt/' # Set this path to the data on your machine. # Folders containin individual NIPS papers. yrs = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] dirs = ['nips' + yr for yr in yrs] # Get all document texts and ...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Construct a mapping from author names to document IDs.
filenames = [data_dir + 'idx/a' + yr + '.txt' for yr in yrs] # Using the years defined in previous cell. # Get all author names and their corresponding document IDs. author2doc = dict() i = 0 for yr in yrs: # The files "a00.txt" and so on contain the author-document mappings. filename = data_dir + 'idx/a' + y...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Pre-processing text The text will be pre-processed using the following steps: * Tokenize text. * Replace all whitespace by single spaces. * Remove all punctuation and numbers. * Remove stopwords. * Lemmatize words. * Add multi-word named entities. * Add frequent bigrams. * Remove frequent and rare words. A lot of the h...
import spacy nlp = spacy.load('en')
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
In the code below, Spacy takes care of tokenization, removing non-alphabetic characters, removal of stopwords, lemmatization and named entity recognition. Note that we only keep named entities that consist of more than one word, as single word named entities are already there.
%%time processed_docs = [] for doc in nlp.pipe(docs, n_threads=4, batch_size=100): # Process document using Spacy NLP pipeline. ents = doc.ents # Named entities. # Keep only words (no numbers, no punctuation). # Lemmatize tokens, remove punctuation and remove stopwords. doc = [token.lemma...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Below, we use a Gensim model to add bigrams. Note that this achieves the same goal as named entity recognition, that is, finding adjacent words that have some particular significance.
# Compute bigrams. from gensim.models import Phrases # Add bigrams and trigrams to docs (only ones that appear 20 times or more). bigram = Phrases(docs, min_count=20) for idx in range(len(docs)): for token in bigram[docs[idx]]: if '_' in token: # Token is a bigram, add to document. d...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Now we are ready to construct a dictionary, as our vocabulary is finalized. We then remove common words (occurring $> 50\%$ of the time), and rare words (occur $< 20$ times in total).
# Create a dictionary representation of the documents, and filter out frequent and rare words. from gensim.corpora import Dictionary dictionary = Dictionary(docs) # Remove rare and common tokens. # Filter out words that occur too frequently or too rarely. max_freq = 0.5 min_wordcount = 20 dictionary.filter_extremes(n...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
We produce the vectorized representation of the documents, to supply the author-topic model with, by computing the bag-of-words.
# Vectorize data. # Bag-of-words representation of the documents. corpus = [dictionary.doc2bow(doc) for doc in docs]
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Let's inspect the dimensionality of our data.
print('Number of authors: %d' % len(author2doc)) print('Number of unique tokens: %d' % len(dictionary)) print('Number of documents: %d' % len(corpus))
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
Train and use model We train the author-topic model on the data prepared in the previous sections. The interface to the author-topic model is very similar to that of LDA in Gensim. In addition to a corpus, ID to word mapping (id2word) and number of topics (num_topics), the author-topic model requires either an author ...
from gensim.models import AuthorTopicModel %time model = AuthorTopicModel(corpus=corpus, num_topics=10, id2word=dictionary.id2token, \ author2doc=author2doc, chunksize=2000, passes=1, eval_every=0, \ iterations=1, random_state=1)
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1
If you believe your model hasn't converged, you can continue training using model.update(). If you have additional documents and/or authors call model.update(corpus, author2doc). Before we explore the model, let's try to improve upon it. To do this, we will train several models with different random initializations, by...
%%time model_list = [] for i in range(5): model = AuthorTopicModel(corpus=corpus, num_topics=10, id2word=dictionary.id2token, \ author2doc=author2doc, chunksize=2000, passes=100, gamma_threshold=1e-10, \ eval_every=0, iterations=1, random_state=i) top_topics = model.top_t...
docs/notebooks/atmodel_tutorial.ipynb
markroxor/gensim
lgpl-2.1