repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
scotthuang1989/Python-3-Module-of-the-Week
data_persistence_exchange/Parsing_xml_document.ipynb
apache-2.0
from xml.etree import ElementTree with open('podcasts.opml', 'rt') as f: tree = ElementTree.parse(f) print(tree) """ Explanation: Example xml file: ``` <?xml version="1.0" encoding="UTF-8"?> <opml version="1.0"> <head> <title>My Podcasts</title> <dateCreated>Sat, 06 Aug 2016 15:53:26 GMT</dateCreated> <dateModified>Sat, 06 Aug 2016 15:53:26 GMT</dateModified> </head> <body> <outline text="Non-tech"> <outline text="99% Invisible" type="rss" xmlUrl="http://feeds.99percentinvisible.org/99percentinvisible" htmlUrl="http://99percentinvisible.org" /> </outline> <outline text="Python"> <outline text="Talk Python to Me" type="rss" xmlUrl="https://talkpython.fm/episodes/rss" htmlUrl="https://talkpython.fm" /> <outline text="Podcast.__init__" type="rss" xmlUrl="http://podcastinit.podbean.com/feed/" htmlUrl="http://podcastinit.com" /> </outline> </body> </opml> ``` To parse the file, pass an open file handle to parse() End of explanation """ from xml.etree import ElementTree import pprint with open('podcasts.opml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.iter(): print(node.tag) """ Explanation: Traversing the parsed tree To visit all the children in order, user iter() to create a generator that iterates over the ElementTree instance. End of explanation """ from xml.etree import ElementTree with open('podcasts.opml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.iter('outline'): name = node.attrib.get('text') url = node.attrib.get('xmlUrl') if name and url: print(' %s' % name) print(' %s' % url) else: print(name) """ Explanation: To print only the groups of names and feed URL for the podcasts, leaving out all of the data in the header section by iterating over only the outline nodes and print the text and xmlURL attributes by looking up the values in the attrib dictionary End of explanation """ from xml.etree import ElementTree with open('podcasts.opml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//outline'): url = node.attrib.get('xmlUrl') if url: print(url) """ Explanation: Finding Nodes in a Documents Walking the entire tree like this, searching for relevant nodes, can be error prone. The previous example had to look at each outline node to determine if it was a group (nodes with only a text attribute) or podcast (with both text and xmlUrl). To produce a simple list of the podcast feed URLs, without names or groups, the logic could be simplified using findall() to look for nodes with more descriptive search characteristics. As a first pass at converting the first version, an XPath argument can be used to look for all outline nodes. End of explanation """ from xml.etree import ElementTree with open('podcasts.opml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//outline/outline'): url = node.attrib.get('xmlUrl') print(url) """ Explanation: It is possible to take advantage of the fact that the outline nodes are only nested two levels deep. Changing the search path to .//outline/outline means the loop will process only the second level of outline nodes. End of explanation """ from xml.etree import ElementTree with open('data.xml', 'rt') as f: tree = ElementTree.parse(f) node = tree.find('./with_attributes') print(node.tag) for name, value in sorted(node.attrib.items()): print(' %-4s = "%s"' % (name, value)) """ Explanation: Parsed Node Attributes The items returned by findall() and iter() are Element objects, each representing a node in the XML parse tree. Each Element has attributes for accessing data pulled out of the XML. This can be illustrated with a somewhat more contrived example input file, data.xml. ``` <?xml version="1.0" encoding="UTF-8"?> <top> <child>Regular text.</child> <child_with_tail>Regular text.</child_with_tail>"Tail" text. <with_attributes name="value" foo="bar" /> <entity_expansion attribute="This &#38; That"> That &#38; This </entity_expansion> </top> ``` End of explanation """ from xml.etree import ElementTree with open('data.xml', 'rt') as f: tree = ElementTree.parse(f) for path in ['./child', './child_with_tail']: node = tree.find(path) print(node.tag) print(' child node text:', node.text) print(' and tail text :', node.tail) """ Explanation: The text content of the nodes is available, along with the tail text, which comes after the end of a close tag. End of explanation """ from xml.etree import ElementTree with open('data.xml', 'rt') as f: tree = ElementTree.parse(f) node = tree.find('entity_expansion') print(node.tag) print(' in attribute:', node.attrib['attribute']) print(' in text :', node.text.strip()) """ Explanation: XML entity references embedded in the document are converted to the appropriate characters before values are returned. End of explanation """ from xml.etree.ElementTree import iterparse depth = 0 prefix_width = 8 prefix_dots = '.' * prefix_width line_template = ''.join([ '{prefix:<0.{prefix_len}}', '{event:<8}', '{suffix:<{suffix_len}} ', '{node.tag:<12} ', '{node_id}', ]) EVENT_NAMES = ['start', 'end', 'start-ns', 'end-ns'] for (event, node) in iterparse('podcasts.opml', EVENT_NAMES): if event == 'end': depth -= 1 prefix_len = depth * 2 print(line_template.format( prefix=prefix_dots, prefix_len=prefix_len, suffix='', suffix_len=(prefix_width - prefix_len), node=node, node_id=id(node), event=event, )) if event == 'start': depth += 1 """ Explanation: Watching Events While Parsing The other API for processing XML documents is event-based. The parser generates start events for opening tags and end events for closing tags. Data can be extracted from the document during the parsing phase by iterating over the event stream, which is convenient if it is not necessary to manipulate the entire document afterwards and there is no need to hold the entire parsed document in memory. Events can be one of: start A new tag has been encountered. The closing angle bracket of the tag was processed, but not the contents. end The closing angle bracket of a closing tag has been processed. All of the children were already processed. start-ns Start a namespace declaration. end-ns End a namespace declaration. End of explanation """ import csv from xml.etree.ElementTree import iterparse import sys writer = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC) group_name = '' parsing = iterparse('podcasts.opml', events=['start']) for (event, node) in parsing: if node.tag != 'outline': # Ignore anything not part of the outline continue if not node.attrib.get('xmlUrl'): # Remember the current group group_name = node.attrib['text'] else: # Output a podcast entry writer.writerow( (group_name, node.attrib['text'], node.attrib['xmlUrl'], node.attrib.get('htmlUrl', '')) ) """ Explanation: The event-style of processing is more natural for some operations, such as converting XML input to some other format. This technique can be used to convert list of podcasts from the earlier examples from an XML file to a CSV file, so they can be loaded into a spreadsheet or database application. End of explanation """ from xml.etree.ElementTree import XML def show_node(node): print(node.tag) if node.text is not None and node.text.strip(): print(' text: "%s"' % node.text) if node.tail is not None and node.tail.strip(): print(' tail: "%s"' % node.tail) for name, value in sorted(node.attrib.items()): print(' %-4s = "%s"' % (name, value)) for child in node: show_node(child) parsed = XML(''' <root> <group> <child id="a">This is child "a".</child> <child id="b">This is child "b".</child> </group> <group> <child id="c">This is child "c".</child> </group> </root> ''') print('parsed =', parsed) for elem in parsed: show_node(elem) """ Explanation: Parsing Strings To work with smaller bits of XML text, especially string literals that might be embedded in the source of a program, use XML() and the string containing the XML to be parsed as the only argument. End of explanation """ from xml.etree.ElementTree import XMLID tree, id_map = XMLID(''' <root> <group> <child id="a">This is child "a".</child> <child id="b">This is child "b".</child> </group> <group> <child id="c">This is child "c".</child> </group> </root> ''') for key, value in sorted(id_map.items()): print('%s = %s' % (key, value)) """ Explanation: For structured XML that uses the id attribute to identify unique nodes of interest, XMLID() is a convenient way to access the parse results. XMLID() returns the parsed tree as an Element object, along with a dictionary mapping the id attribute strings to the individual nodes in the tree. End of explanation """
dh7/ML-Tutorial-Notebooks
RNN.ipynb
bsd-2-clause
""" Minimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy) BSD License """ import numpy as np # data I/O data = open('methamorphosis.txt', 'r').read() # should be simple plain text file chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print 'data has %d characters, %d unique.' % (data_size, vocab_size) char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } # hyperparameters hidden_size = 100 # size of hidden layer of neurons seq_length = 25 # number of steps to unroll the RNN for learning_rate = 1e-1 # model parameters Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output bh = np.zeros((hidden_size, 1)) # hidden bias by = np.zeros((vocab_size, 1)) # output bias def lossFun(inputs, targets, hprev): """ inputs,targets are both list of integers. hprev is Hx1 array of initial hidden state returns the loss, gradients on model parameters, and last hidden state """ xs, hs, ys, ps = {}, {}, {}, {} hs[-1] = np.copy(hprev) loss = 0 # forward pass for t in xrange(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) # backward pass: compute gradients going backwards dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why) dbh, dby = np.zeros_like(bh), np.zeros_like(by) dhnext = np.zeros_like(hs[0]) for t in reversed(xrange(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y dWhy += np.dot(dy, hs[t].T) dby += dy dh = np.dot(Why.T, dy) + dhnext # backprop into h dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity dbh += dhraw dWxh += np.dot(dhraw, xs[t].T) dWhh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(Whh.T, dhraw) for dparam in [dWxh, dWhh, dWhy, dbh, dby]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients return loss, dWxh, dWhh, dWhy, dbh, dby, hs[len(inputs)-1] def sample(h, seed_ix, n): """ sample a sequence of integers from the model h is memory state, seed_ix is seed letter for first time step """ x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in xrange(n): h = np.tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh) y = np.dot(Why, h) + by p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes n, p = 0, 0 mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why) mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad smooth_loss = -np.log(1.0/vocab_size)*seq_length # loss at iteration 0 while n<=1000: # was while True: in original code # prepare inputs (we're sweeping from left to right in steps seq_length long) if p+seq_length+1 >= len(data) or n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p = 0 # go from start of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # sample from the model now and then if n % 100 == 0: sample_ix = sample(hprev, inputs[0], 200) txt = ''.join(ix_to_char[ix] for ix in sample_ix) print '----\n %s \n----' % (txt, ) # forward seq_length characters through the net and fetch gradient loss, dWxh, dWhh, dWhy, dbh, dby, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 + loss * 0.001 if n % 100 == 0: print 'iter %d, loss: %f' % (n, smooth_loss) # print progress # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update p += seq_length # move data pointer n += 1 # iteration counter """ Explanation: Minimal character-level Vanilla RNN model. RNN stand for "Recurent Neural Network". To understand why RNN are so hot you must read this! This notebook to explain the Minimal character-level Vanilla RNN model written by Andrej Karpathy This code create a RNN to generate a text, char after char, by learning char after char from a textfile. I love this character-level Vanilla RNN code because it doesn't use any library except numpy. All the NN magic in 112 lines of code, no need to understand any dependency. Everything is there! I'll try to explain in detail every line of it. Disclamer: I still need to use some external links for reference. This notebook is for real beginners who whant to understand RNN concept by reading code. Feedback welcome @dh7net Let's start! Let's see the original code and the results for the first 1000 iterations. End of explanation """ """ Minimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy) BSD License """ import numpy as np # data I/O data = open('methamorphosis.txt', 'r').read() # should be simple plain text file """ Explanation: If you are not a NN expert, the code is not easy to understand. If you look to the results you can see that the code iterate 1000 time, calculate a loss that decrease over time, and output some text each 100 iteration. The output from the first iteration looks random. After 1000 iterations, the NN is able to create words that have plausible size, don't use too much caps, and can create correct small words like "the", "they", "be", "to". If you let the code learn over a nigth the NN will be able to create almost correct sentences: "with home to get there was much hadinge everything and he could that ho women this tending applear space" This is just a simple exemple, and there is no doubt this code can do much better. Theorie This code build a neural network that is able to predict one char from the previous one. In this example, it learn from a text file, so he can learn words and sentence ; if you feed HTML or XML during the tranning it can produce valid HTML or XML sequences. At each step it can use some results from the previous step to keep in memory what is going on. For instance if the previous char are "hello worl" the model can guess that the next char is "d". This model contain parameters that are initialized randomly and the trainning phase try to find optimal values for each of them. During the trainning process we do a "gradient descent": * We give to the model a pair of char: the input char and the target char. The target char is the char the network should guess, it is the next char in our trainning text file. * We calculate the probability for every possible next char according to the state of the model, using the paramters (This is the forward pass). * We create a distance (the loss) between the previous probabilty and the target char. * We calculate gradients for each of our parameters to see witch impact they have on the loss. (A fast way to calculate all gradients is called the backward pass). * We update all parameters in the direction that help to minimise the loss * We iterate until their is no more progress and print a generated sentence from times to times. Let's dive in! The code contains 4 parts Load the trainning data encode char into vectors Define the Network Define a function to create sentences from the model Define a loss function Forward pass Loss Backward pass Train the network Feed the network Calculate gradiend and update the model parameters Output a text to see the progress of the training Let's have a closer look to every line of the code. Disclaimer: the following code is cut and pasted from the original ones, with some adaptation to make it clearer for this notebook, like adding some print. Load the training data The network need a big txt file as an input. The content of the file will be used to train the network. For this example, I used Methamorphosis from Kafka (Public Domain). End of explanation """ chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print 'data has %d characters, %d unique.' % (data_size, vocab_size) """ Explanation: Encode/Decode char/vector Neural networks can only works on vectors. (a vector is an array of float) So we need a way to encode and decode a char as a vector. For this we count the number of unique char (vocab_size). It will be the size of the vector. The vector contain only zero exept for the position of the char wherae the value is 1. First we calculate vocab_size: End of explanation """ char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } print char_to_ix print ix_to_char """ Explanation: Then we create 2 dictionary to encode and decode a char to an int End of explanation """ %matplotlib notebook import matplotlib import matplotlib.pyplot as plt vector_for_char_a = np.zeros((vocab_size, 1)) vector_for_char_a[char_to_ix['a']] = 1 #print vector_for_char_a print vector_for_char_a.ravel() x = range(0,len(chars)) plt.figure(figsize=(10,2)) plt.bar(x, vector_for_char_a.ravel(), 0.3) plt.xticks(x, chars) plt.show() """ Explanation: Finaly we create a vector from a char like this: The dictionary defined above allow us to create a vector of size 61 instead of 256. Here and exemple for char 'a' The vector contains only zero, except at position char_to_ix['a'] where we put a 1. End of explanation """ # hyperparameters hidden_size = 100 # size of hidden layer of neurons seq_length = 25 # number of steps to unroll the RNN for learning_rate = 1e-1 # model parameters Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden print 'Wxh contain', Wxh.size, 'parameters' Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden print 'Whh contain', Whh.size, 'parameters' Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output print 'Why contain', Why.size, 'parameters' bh = np.zeros((hidden_size, 1)) # hidden bias print 'bh contain', bh.size, 'parameters' by = np.zeros((vocab_size, 1)) # output bias print 'by contain', by.size, 'parameters' """ Explanation: Definition of the network The neural network is made of 3 layers: * an input layer * an hidden layer * an output layer All layers are fully connected to the next one: each node of a layer are conected to all nodes of the next layer. The hidden layer is connected to the output and to itself: the values from an iteration are used for the next one. To centralise values that matter for the training (hyper parameters) we also define the sequence lenght and the learning rate End of explanation """ def sample(h, seed_ix, n): """ sample a sequence of integers from the model h is memory state, seed_ix is seed letter for first time step """ x = np.zeros((vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in xrange(n): h = np.tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh) y = np.dot(Why, h) + by p = np.exp(y) / np.sum(np.exp(y)) ix = np.random.choice(range(vocab_size), p=p.ravel()) x = np.zeros((vocab_size, 1)) x[ix] = 1 ixes.append(ix) txt = ''.join(ix_to_char[ix] for ix in ixes) print '----\n %s \n----' % (txt, ) hprev = np.zeros((hidden_size,1)) # reset RNN memory sample(hprev,char_to_ix['a'],200) """ Explanation: The model parameters are adjusted during the trainning. * Wxh are parameters to connect a vector that contain one input to the hidden layer. * Whh are parameters to connect the hidden layer to itself. This is the Key of the Rnn: Recursion is done by injecting the previous values from the output of the hidden state, to itself at the next iteration. * Why are parameters to connect the hidden layer to the output * bh contains the hidden bias * by contains the output bias You'll see in the next section how theses parameters are used to create a sentence. Create a sentence from the model End of explanation """ def lossFun(inputs, targets, hprev): """ inputs,targets are both list of integers. hprev is Hx1 array of initial hidden state returns the loss, gradients on model parameters, and last hidden state """ xs, hs, ys, ps = {}, {}, {}, {} hs[-1] = np.copy(hprev) loss = 0 # forward pass for t in xrange(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) # backward pass: compute gradients going backwards dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why) dbh, dby = np.zeros_like(bh), np.zeros_like(by) dhnext = np.zeros_like(hs[0]) for t in reversed(xrange(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y dWhy += np.dot(dy, hs[t].T) dby += dy dh = np.dot(Why.T, dy) + dhnext # backprop into h dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity dbh += dhraw dWxh += np.dot(dhraw, xs[t].T) dWhh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(Whh.T, dhraw) for dparam in [dWxh, dWhh, dWhy, dbh, dby]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients return loss, dWxh, dWhh, dWhy, dbh, dby, hs[len(inputs)-1] """ Explanation: Define the loss function The loss is a key concept in all neural networks trainning. It is a value that describe how bag/good is our model. It is always positive, the closest to zero, the better is our model. (A good model is a model where the predicted output is close to the training output) During the trainning phase we want to minimize the loss. The loss function calculate the loss but also the gradients (see backward pass): * It perform a forward pass: calculate the next char given a char from the trainning set. * It calculate the loss by comparing the predicted char to the target char. (The target char is the input following char in the tranning set) * It calculate the backward pass to calculate the gradients (see the backword pass paragraph) This function take as input: * a list of input char * a list of target char * and the previous hidden state This function output: * the loss * the gradient for each parameters between layers * the last hidden state Here the code: End of explanation """ # uncomment the print to get some details xs, hs, ys, ps = {}, {}, {}, {} hs[-1] = np.copy(hprev) # forward pass t=0 # for t in xrange(len(inputs)): xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation xs[t][inputs[t]] = 1 # print xs[t] hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars # print ys[t] ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars # print ps[t].ravel() # Let's build a dict to see witch probablity is associated with witch char probability_per_char = { ch:ps[t].ravel()[i] for i,ch in enumerate(chars) } # uncoment the next line to see the raw result # print probability_per_char # To print the probability in a way that is more easy to read. for x in range(vocab_size): print 'p('+ ix_to_char[x] + ")=", "%.4f" % ps[t].ravel()[x], if (x%7==0): print "" else: print "", x = range(0,len(chars)) plt.figure(figsize=(10,5)) plt.bar(x, ps[t], 0.3) plt.xticks(x, chars) plt.show() # We can create the next char from the above distribution ix = np.random.choice(range(vocab_size), p=ps[t].ravel()) print print "Next char code is:", ix print "Next char is:", ix_to_char[ix] """ Explanation: Forward pass The forward pass use the parameters of the model (Wxh, Whh, Why, bh, by) to calculate the next char given a char from the trainning set. xs[t] is the vector that encode the char at position t ps[t] is the probabilities for next char python hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars or is dirty pseudo code for each char python hs = input*Wxh + last_value_of_hidden_state*Whh + bh ys = hs*Why + by ps = normalized(ys) To dive into the code, we'll work on one char only (we set t=0 ; instead of the "for each" loop). End of explanation """ print 'Next char from training (target) was number', targets[t], 'witch is "' + ix_to_char[targets[t]] + '"' print 'Probability for this letter was', ps[t][targets[t],0] loss = -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) print 'loss for this input&target pair is', loss """ Explanation: You can run the previous code several time. A char is generated for a given probability. Loss For each char in the input the forward pass calculate the probability of the next char The loss is the sum python loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss) The loss is calculate using Softmax. more info here and here. End of explanation """ x = 10 a = 3 b = 7 loss = a+x + b print 'initial loss =', loss # dx stand for d(loss)/dx dx = a #Calculate dx=d(loss)/dx analytically step_size = 0.1 # use dx and step size to calculate new x new_x = x - dx * step_size new_loss = a+new_x + b print 'new loss =',new_loss if (new_loss<loss): print 'New loss is smaller, Yeah!' """ Explanation: Backward pass The goal of the backward pass is to calculate all gradients. Gradients tell in witch direction you have to move your parameter to make a better model. The naive way to calculate all gradients would be to recalculate a loss for small variations for each parameters. This is possible but would be time consuming. We have more than 20k parameters. There is a technic to calculates all the gradients for all the parameters at once: the backdrop propagation. Gradients are calculated in the oposite order of the forward pass, using simple technics. For instance if we have: python loss = a.x + b If we want to minimize loss, we need to calculate d(loss)/dx and use it to calculate the new_x value. python new_x = x - d(loss)/dx * step_size If new_loss is smaller than loss, it is a win: we succeed to find a better x input. Lets do the math: d(loss)/dx = d(a.x)/dx +d(b)/dx d(loss)/dx = (d(a)/dx)1 + ad(x)/dx + 0 d(loss)/dx = 0 + a*1 d(loss)/dx = a End of explanation """ # backward pass: compute gradients going backwards dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why) dbh, dby = np.zeros_like(bh), np.zeros_like(by) dhnext = np.zeros_like(hs[0]) t=0 #for t in reversed(xrange(len(inputs))): dy = np.copy(ps[t]) dy[targets[t]] -= 1 # backprop into y #print dy.ravel() dWhy += np.dot(dy, hs[t].T) #print dWhy.ravel() dby += dy #print dby.ravel() dh = np.dot(Why.T, dy) + dhnext # backprop into h dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity dbh += dhraw dWxh += np.dot(dhraw, xs[t].T) dWhh += np.dot(dhraw, hs[t-1].T) dhnext = np.dot(Whh.T, dhraw) for dparam in [dWxh, dWhh, dWhy, dbh, dby]: np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients #print dparam """ Explanation: goal is to calculate gradients for the forward formula: python hs = input*Wxh + last_value_of_hidden_state*Whh + bh ys = hs*Why + by This part need more work to explain the code, but here a great source to understand this technic in detail. ```python Backdrop this: ys = hs*Why + by dy=-1 # because the smaller the loss, the better is the model. dWhy = np.dot(dy, hs.T) dby = dy dh = np.dot(Why.T, dy) + dhnext # backprop into h dhraw = (1 - hs * hs) * dh # backprop through tanh nonlinearity Backdrop this: hs = inputWxh + last_value_of_hidden_stateWhh + bh dbh += dhraw dWxh += np.dot(dhraw, xs.T) dWhh += np.dot(dhraw, hs.T) dhnext = np.dot(Whh.T, dhraw) ``` End of explanation """ p=0 inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] print "inputs", inputs targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] print "targets", targets """ Explanation: Training This last part of the code is the main trainning loop: * Feed the network with portion of the file. Size of cunck is seq_lengh * Use the loss function to: * Do forward pass to calculate all parameters for the model for a given input/output pairs * Do backward pass to calculate all gradiens * Print a sentence from a random seed using the parameters of the network * Update the model using the Adaptative Gradien technique Adagrad Feed the loss function with inputs and targets We create two array of char from the data file, the targets one is shifted compare to the inputs one. For each char in the input array, the target array give the char that follows. End of explanation """ n, p = 0, 0 mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why) mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad smooth_loss = -np.log(1.0/vocab_size)*seq_length # loss at iteration 0 while n<=1000*100: # prepare inputs (we're sweeping from left to right in steps seq_length long) # check "How to feed the loss function to see how this part works if p+seq_length+1 >= len(data) or n == 0: hprev = np.zeros((hidden_size,1)) # reset RNN memory p = 0 # go from start of data inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]] targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]] # forward seq_length characters through the net and fetch gradient loss, dWxh, dWhh, dWhy, dbh, dby, hprev = lossFun(inputs, targets, hprev) smooth_loss = smooth_loss * 0.999 + loss * 0.001 # sample from the model now and then if n % 1000 == 0: print 'iter %d, loss: %f' % (n, smooth_loss) # print progress sample(hprev, inputs[0], 200) # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update p += seq_length # move data pointer n += 1 # iteration counter """ Explanation: Adagrad to update the parameters The easiest technics to update the parmeters of the model is this: python param += dparam * step_size Adagrad is a more efficient technique where the step_size are getting smaller during the training. It use a memory variable that grow over time: python mem += dparam * dparam and use it to calculate the step_size: python step_size = 1./np.sqrt(mem + 1e-8) In short: python mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update Smooth_loss Smooth_loss doesn't play any role in the training. It is just a low pass filtered version of the loss: python smooth_loss = smooth_loss * 0.999 + loss * 0.001 It is a way to average the loss on over the last iterations to better track the progress So finally Here the code of the main loop that does both trainning and generating text from times to times: End of explanation """
paoloRais/lightfm
examples/movielens/learning_schedules.ipynb
apache-2.0
import numpy as np import data %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt from lightfm import LightFM from lightfm.datasets import fetch_movielens from lightfm.evaluation import auc_score movielens = fetch_movielens() train, test = movielens['train'], movielens['test'] """ Explanation: Using different learning schedules lightfm implements two learning schedules: adagrad and adadelta. Neither is clearly superior, and, like other hyperparameter choices, the best learning schedule will differ based on the problem at hand. This example tries both at the Movielens 100k dataset. Preliminaries Let's first get the data and define the evaluations functions. End of explanation """ alpha = 1e-3 epochs = 70 adagrad_model = LightFM(no_components=30, loss='warp', learning_schedule='adagrad', user_alpha=alpha, item_alpha=alpha) adadelta_model = LightFM(no_components=30, loss='warp', learning_schedule='adadelta', user_alpha=alpha, item_alpha=alpha) adagrad_auc = [] for epoch in range(epochs): adagrad_model.fit_partial(train, epochs=1) adagrad_auc.append(auc_score(adagrad_model, test).mean()) adadelta_auc = [] for epoch in range(epochs): adadelta_model.fit_partial(train, epochs=1) adadelta_auc.append(auc_score(adadelta_model, test).mean()) """ Explanation: Experiment To evaluate the performance of both learning schedules, let's create two models and run each for a number of epochs, measuring the ROC AUC on the test set at the end of each epoch. End of explanation """ x = np.arange(len(adagrad_auc)) plt.plot(x, np.array(adagrad_auc)) plt.plot(x, np.array(adadelta_auc)) plt.legend(['adagrad', 'adadelta'], loc='lower right') plt.show() """ Explanation: It looks like the adadelta gets to a better result at the beginning of training. However, as we keep running more epochs adagrad wins out, converging to a better final solution. End of explanation """ alpha = 1e-3 epochs = 70 adagrad_model = LightFM(no_components=30, loss='warp-kos', learning_schedule='adagrad', user_alpha=alpha, item_alpha=alpha) adadelta_model = LightFM(no_components=30, loss='warp-kos', learning_schedule='adadelta', user_alpha=alpha, item_alpha=alpha) adagrad_auc = [] for epoch in range(epochs): adagrad_model.fit_partial(train, epochs=1) adagrad_auc.append(auc_score(adagrad_model, test).mean()) adadelta_auc = [] for epoch in range(epochs): adadelta_model.fit_partial(train, epochs=1) adadelta_auc.append(auc_score(adadelta_model, test).mean()) x = np.arange(len(adagrad_auc)) plt.plot(x, np.array(adagrad_auc)) plt.plot(x, np.array(adadelta_auc)) plt.legend(['adagrad', 'adadelta'], loc='lower right') plt.show() """ Explanation: We can try the same for the k-OS loss. End of explanation """
feststelltaste/software-analytics
demos/20190404_Duesseldorf/DataScienceMeetsSoftwareData.ipynb
gpl-3.0
import pandas as pd log = pd.read_csv("../dataset/linux_blame_log.csv.gz") log.head() """ Explanation: Data Science meets Software Data <b>Markus Harrer</b>, Software Development Analyst @feststelltaste <small>INNOQcon 2019, Düsseldorf, 04.04.2019</small> <img src="../resources/innoq_logo.jpg" width=20% height="20%" align="right"/> Data Science Was ist Data Science? "Statistik auf nem <b><span class="green">Mac</span></b>." <br/> <br/> <div align="right"><small>Nach https://twitter.com/cdixon/status/428914681911070720</small></div> <div align="center"> <img src ="../resources/trollface.jpg" align="center"/> </div> Meine Definition Was bedeutet "data"? "Without data you‘re just another person with an opinion." <br/> <div align="right"><small>W. Edwards Deming</small></div> <b>=> Belastbare Erkenntnisse mittels <span class="green">Fakten</span> liefern</b> Was bedeutet "science"? "The aim of science is to seek the simplest explanations of complex facts." <br/> <div align="right"><small>Albert Einstein</small></div> <b>=> Neue Erkenntnisse <span class="green">verständlich</span> herausarbeiten</b> Was ist ein Data Scientist? "Jemand, der mehr Ahnung von Statistik<br/> &nbsp;&nbsp;hat als ein <b><span class="green">Softwareentwickler</span></b><br/> &nbsp;&nbsp;und mehr Ahnung von <b><span class="green">Softwareentwicklung</span></b><br/> &nbsp;&nbsp;als ein Statistiker." <br/> <br/> <div align="right"><small>Nach zu https://twitter.com/cdixon/status/428914681911070720</small></div> <b>Data Science & Software Data:</b> Perfect <b><span class="green">match</span></b>! Software Data Was ist Software Data? Statisch Laufzeit Chronologisch Community <b>=> Krass viel!</b> Beispiele für Analysen Performance-Bottlenecks Verborgene Teamkommunikation No-Go-Areas Architektur-/Design-/Code-Smells ... Vorgehen Fragestellung Datenbeschaffung Modellierung Interpretation Kommunikation <b>=> vom <strong>Problem</strong> über die <span class="green">Daten</span> zur <span class="blue" style="background-color: #FFFF00">Erkenntnis</span>!</b> Grundprinzip <code> (Data + Code + Ergebnis) * Automatisierung = Reproduzierbare Analysen</code> Schlüssel: Computational notebooks Der Notebook-Ansatz <br/> <div align="center"><img src="../resources/notebook_approach.jpg"></div> Technik Technologie (1/2) Klassischer Data-Science-Werkzeugkasten * Jupyter (mit RISE) * Python 3 * pandas * matplotlib Technologie (2/2) Jupyter funktioniert und integriert sich auch mit * Cypher / Neo4j / jQAssistant * JVM-Sprachen über beakerx / Tablesaw * bash * ... Praktischer Teil Erstes Hands-On Der Patient Linux Betriebsystem-Kernel Hat verschiedene Treiberkomponenten Fast ausschließlich in C geschrieben Entwickelt von über 800.000 Entwicklern I. Idee (1/2) <b>Fragestellung</b> * Gibt es besonders alte Komponenten (No-Go-Areas)? I. Idee (2/2) Umsetzung Werkzeuge: Jupyter, Python, pandas, matplotlib Datenquelle: Git Blame Log Meta-Ziel: Grundfunktionen anhand eines einfachen Show-Cases sehen. <b>Git Blame Log</b> <div align="center"> <img src ="../resources/linux_1.gif" align="center"/> </div> <b>Git Blame Log</b> <div align="center"> <img src ="../resources/linux_2.gif" align="center"/> </div> <b>Git Blame Log</b> <div align="center"> <img src ="../resources/linux_3.gif" align="center"/> </div> II. Datenbeschaffung Wir laden Git Blame Daten aus einer CSV-Datei End of explanation """ log.info() """ Explanation: Was haben wir hier eigentlich? End of explanation """ log['timestamp'] = pd.to_datetime(log['timestamp']) log.head() """ Explanation: <b>1</b> DataFrame (~ programmierbares Excel-Arbeitsblatt), <b>4</b> Series (= Spalten), <b>5665947</b> Rows (= Einträge) III. Bereinigen Daten sind oft nicht so, wie man sie braucht Datentypen passen teilweise noch nicht Wir wandeln die Zeitstempel um End of explanation """ log['age'] = pd.Timestamp('today') - log['timestamp'] log.head() """ Explanation: IV. Anreichern Vorhandenen Daten noch zusätzlich mit anderen Datenquellen verschneiden Aber auch: Teile aus vorhanden Daten extrahieren => Dadurch werden mehrere <b>Perspektiven</b> auf ein Problem möglich Wir berechnen uns das Alter jeder Codezeilenänderung End of explanation """ log['component'] = log['path'].str.split("/").str[:2].str.join(":") log.head() """ Explanation: Wir ordnen jeder Zeilenänderung einer Komponente zu End of explanation """ age_per_component = log.groupby("component")['age'].min().sort_values() age_per_component.head() """ Explanation: <br/> <small><i>String-Operationen...die dauern. Gibt aber diverse Optimierungsmöglichkeiten!</i></small> V. Aggregieren Vorhandene Daten sind oft zu viel für manuelle Sichtung Neue Einsichten über Problem aber oft auf hoher Flugbahn möglich Wir fassen nach Komponenten zusammen und arbeiten mit der jeweils jüngsten Zeilenänderung weiter End of explanation """ age_per_component.plot.bar(figsize=[15,5]); """ Explanation: IV. Visualisieren Grafische Darstellung geben Analysen den letzten Schliff Probleme können Außenstehenden visuell dargestellt besser kommuniziert werden Wir bauen ein Diagramm mit min. Alter pro Komponente End of explanation """
qingshuimonk/LolStats
getMatchList.ipynb
mit
from lolcrawler_util import read_key, get_summoner_info api_key = read_key() name = 'Doublelift' summoner = get_summoner_info(api_key, name) usr_id = summoner[name.lower()]['id'] print usr_id """ Explanation: Get Match list of a player, and analyze the information First we need to find the player's id, it would be fun to look for status of professional players (and they definitely have more data than other players). I get those usernames from OP.GG Let's use Doublelift as an example in this script! PS: full API documentation End of explanation """ from lolcrawler_util import get_matchlist_by_summoner matchlist = get_matchlist_by_summoner(usr_id, api_key, rankedQueues='TEAM_BUILDER_DRAFT_RANKED_5x5', seasons='SEASON2016') print len(matchlist['matches']) """ Explanation: Ok, we get his id now, now we have to get his match history. Let's find all his matches in 2016 season and team builder draft 5v5 rank queue. End of explanation """ %matplotlib inline from collections import Counter import numpy as np import matplotlib.pyplot as plt role_cnt = Counter() lane_cnt = Counter() for match in matchlist['matches']: role_cnt[match['role']] += 1 lane_cnt[match['lane']] += 1 fig = plt.figure() ax1 = fig.add_subplot(121) indexes = np.arange(len(role_cnt.keys())) width = 1 ax1.bar(indexes, role_cnt.values(), width) plt.xticks(indexes + width * 0.5, role_cnt.keys(), rotation=-30) plt.xlabel('Role Type') plt.ylabel('Counts') plt.title('Role Type of Doublelift in S6') plt.grid(True) ax2 = fig.add_subplot(122) indexes = np.arange(len(lane_cnt.keys())) width = 1 ax2.bar(indexes, lane_cnt.values(), width) plt.xticks(indexes + width * 0.5, lane_cnt.keys()) plt.xlabel('Lane Type') plt.title('Lane Type of Doublelift in S6') plt.grid(True) plt.show() """ Explanation: 381 games, that almost the total number of games I've played in NA server. Then let's try to analyze those matches. First take a look of what role he likes to play the most. End of explanation """ import os import pickle path = os.path.join(os.path.dirname('getMatchList.ipynb'), 'data') f = open(os.path.join(path, 'Doublelift_TEAM_BUILDER_DRAFT_RANKED_5x5_SEASON2016.pickle'), 'r') doublelift_history = pickle.load(f) f.close() path = os.path.join(os.path.dirname('getMatchList.ipynb'), 'data') f = open(os.path.join(path, 'PraY8D_TEAM_BUILDER_DRAFT_RANKED_5x5_SEASON2016.pickle'), 'r') pray_history = pickle.load(f) f.close() fig = plt.figure(figsize=(12, 15)) ax1 = fig.add_subplot(421) kda = np.divide(np.array(doublelift_history.kill, dtype=np.float32) + np.array(doublelift_history.assist, dtype=np.float32), (np.array(doublelift_history.death, dtype=np.float32)+1)) n, bins, patches = plt.hist(kda, 20, facecolor='green', alpha=0.75) plt.xlabel('KDA') plt.ylabel('Counts') plt.title('Stats of Doublelift in Season 2016') plt.axis([0, 25, 0, 80]) plt.grid(True) ax2 = fig.add_subplot(423) n, bins, patches = plt.hist(doublelift_history.gold, 20, facecolor='green', alpha=0.75) plt.xlabel('Gold') plt.ylabel('Counts') plt.axis([0, 35000, 0, 60]) plt.grid(True) ax3 = fig.add_subplot(425) n, bins, patches = plt.hist(doublelift_history.damage, 20, facecolor='green', alpha=0.75) plt.xlabel('Damage Dealt') plt.ylabel('Counts') plt.axis([0, 100000, 0, 60]) plt.grid(True) ax4 = fig.add_subplot(427) n, bins, patches = plt.hist(doublelift_history.damage_taken, 20, facecolor='green', alpha=0.75) plt.xlabel('Damage Taken') plt.ylabel('Counts') plt.axis([0, 60000, 0, 60]) plt.grid(True) ax1 = fig.add_subplot(422) kda = np.divide(np.array(pray_history.kill, dtype=np.float32)+ np.array(pray_history.assist, dtype=np.float32), (np.array(pray_history.death, dtype=np.float32)+1)) n, bins, patches = plt.hist(kda, 20, facecolor='blue', alpha=0.75) plt.xlabel('KDA') plt.ylabel('Counts') plt.title('Stats of Pray in Season 2016') plt.axis([0, 25, 0, 80]) plt.grid(True) ax2 = fig.add_subplot(424) n, bins, patches = plt.hist(pray_history.gold, 20, facecolor='blue', alpha=0.75) plt.xlabel('Gold') plt.ylabel('Counts') plt.axis([0, 35000, 0, 60]) plt.grid(True) ax3 = fig.add_subplot(426) n, bins, patches = plt.hist(pray_history.damage, 20, facecolor='blue', alpha=0.75) plt.xlabel('Damage Dealt') plt.ylabel('Counts') plt.axis([0, 100000, 0, 60]) plt.grid(True) ax4 = fig.add_subplot(428) n, bins, patches = plt.hist(pray_history.damage_taken, 20, facecolor='blue', alpha=0.75) plt.xlabel('Damage Taken') plt.ylabel('Counts') plt.axis([0, 60000, 0, 60]) plt.grid(True) plt.suptitle('Stats Comparison Between Doublelift and Pray in Season 2016') plt.show() """ Explanation: Ok, he likes to play ad carry in bottom lane. Just as expected. Now comes the analysis, because he is a ADC player, let's just focus on matches he played ADC. The matches and corresponding information were crawled and saved in \data folder by script GetPlayerMatchHistoryInfo.py. For comparison, I also crawled Pray's data in 2016 season (I know he is from another region, but he has a similarly amount of data) End of explanation """ fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111) sc1 = plt.scatter(doublelift_history.gold, doublelift_history.damage, alpha=0.5, color='green') sc2 = plt.scatter(pray_history.gold, pray_history.damage, alpha=0.5, color='blue') plt.xlabel('Gold') plt.ylabel('Damage') plt.title('Gold to Damage Comparison') plt.legend((sc1, sc2), ('Doublelift', 'Pray'), scatterpoints=1, loc='upper left') plt.grid(True) ax.set_xlim(xmin=0) ax.set_ylim(ymin=0) plt.show() """ Explanation: Hmm... Looks pretty! Doublelift have almost 100 more games played than pray so he seems to have a higher peak. But they both share similar shape of histogram. However, the only difference is Doublelift's gold histogram is more like a triangle while it is more uniform for Pray's. Now how about damage to gold? We all this is a critical criteria for ADC player. End of explanation """
Lstyle1/Deep_learning_projects
batch-norm/Batch_Normalization_Lesson.ipynb
mit
# Import necessary packages import tensorflow as tf import tqdm import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import MNIST data so we have something for our experiments from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) """ Explanation: Batch Normalization – Lesson What is it? What are it's benefits? How do we add it to a network? Let's see it work! What are you hiding? What is Batch Normalization?<a id='theory'></a> Batch normalization was introduced in Sergey Ioffe's and Christian Szegedy's 2015 paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. The idea is that, instead of just normalizing the inputs to the network, we normalize the inputs to layers within the network. It's called "batch" normalization because during training, we normalize each layer's inputs by using the mean and variance of the values in the current mini-batch. Why might this help? Well, we know that normalizing the inputs to a network helps the network learn. But a network is a series of layers, where the output of one layer becomes the input to another. That means we can think of any layer in a neural network as the first layer of a smaller network. For example, imagine a 3 layer network. Instead of just thinking of it as a single network with inputs, layers, and outputs, think of the output of layer 1 as the input to a two layer network. This two layer network would consist of layers 2 and 3 in our original network. Likewise, the output of layer 2 can be thought of as the input to a single layer network, consisting only of layer 3. When you think of it like that - as a series of neural networks feeding into each other - then it's easy to imagine how normalizing the inputs to each layer would help. It's just like normalizing the inputs to any other neural network, but you're doing it at every layer (sub-network). Beyond the intuitive reasons, there are good mathematical reasons why it helps the network learn better, too. It helps combat what the authors call internal covariate shift. This discussion is best handled in the paper and in Deep Learning a book you can read online written by Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Specifically, check out the batch normalization section of Chapter 8: Optimization for Training Deep Models. Benefits of Batch Normalization<a id="benefits"></a> Batch normalization optimizes network training. It has been shown to have several benefits: 1. Networks train faster – Each training iteration will actually be slower because of the extra calculations during the forward pass and the additional hyperparameters to train during back propagation. However, it should converge much more quickly, so training should be faster overall. 2. Allows higher learning rates – Gradient descent usually requires small learning rates for the network to converge. And as networks get deeper, their gradients get smaller during back propagation so they require even more iterations. Using batch normalization allows us to use much higher learning rates, which further increases the speed at which networks train. 3. Makes weights easier to initialize – Weight initialization can be difficult, and it's even more difficult when creating deeper networks. Batch normalization seems to allow us to be much less careful about choosing our initial starting weights. 4. Makes more activation functions viable – Some activation functions do not work well in some situations. Sigmoids lose their gradient pretty quickly, which means they can't be used in deep networks. And ReLUs often die out during training, where they stop learning completely, so we need to be careful about the range of values fed into them. Because batch normalization regulates the values going into each activation function, non-linearlities that don't seem to work well in deep networks actually become viable again. 5. Simplifies the creation of deeper networks – Because of the first 4 items listed above, it is easier to build and faster to train deeper neural networks when using batch normalization. And it's been shown that deeper networks generally produce better results, so that's great. 6. Provides a bit of regularlization – Batch normalization adds a little noise to your network. In some cases, such as in Inception modules, batch normalization has been shown to work as well as dropout. But in general, consider batch normalization as a bit of extra regularization, possibly allowing you to reduce some of the dropout you might add to a network. 7. May give better results overall – Some tests seem to show batch normalization actually improves the training results. However, it's really an optimization to help train faster, so you shouldn't think of it as a way to make your network better. But since it lets you train networks faster, that means you can iterate over more designs more quickly. It also lets you build deeper networks, which are usually better. So when you factor in everything, you're probably going to end up with better results if you build your networks with batch normalization. Batch Normalization in TensorFlow<a id="implementation_1"></a> This section of the notebook shows you one way to add batch normalization to a neural network built in TensorFlow. The following cell imports the packages we need in the notebook and loads the MNIST dataset to use in our experiments. However, the tensorflow package contains all the code you'll actually need for batch normalization. End of explanation """ class NeuralNet: def __init__(self, initial_weights, activation_fn, use_batch_norm): """ Initializes this object, creating a TensorFlow graph using the given parameters. :param initial_weights: list of NumPy arrays or Tensors Initial values for the weights for every layer in the network. We pass these in so we can create multiple networks with the same starting weights to eliminate training differences caused by random initialization differences. The number of items in the list defines the number of layers in the network, and the shapes of the items in the list define the number of nodes in each layer. e.g. Passing in 3 matrices of shape (784, 256), (256, 100), and (100, 10) would create a network with 784 inputs going into a hidden layer with 256 nodes, followed by a hidden layer with 100 nodes, followed by an output layer with 10 nodes. :param activation_fn: Callable The function used for the output of each hidden layer. The network will use the same activation function on every hidden layer and no activate function on the output layer. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. :param use_batch_norm: bool Pass True to create a network that uses batch normalization; False otherwise Note: this network will not use batch normalization on layers that do not have an activation function. """ # Keep track of whether or not this network uses batch normalization. self.use_batch_norm = use_batch_norm self.name = "With Batch Norm" if use_batch_norm else "Without Batch Norm" # Batch normalization needs to do different calculations during training and inference, # so we use this placeholder to tell the graph which behavior to use. self.is_training = tf.placeholder(tf.bool, name="is_training") # This list is just for keeping track of data we want to plot later. # It doesn't actually have anything to do with neural nets or batch normalization. self.training_accuracies = [] # Create the network graph, but it will not actually have any real values until after you # call train or test self.build_network(initial_weights, activation_fn) def build_network(self, initial_weights, activation_fn): """ Build the graph. The graph still needs to be trained via the `train` method. :param initial_weights: list of NumPy arrays or Tensors See __init__ for description. :param activation_fn: Callable See __init__ for description. """ self.input_layer = tf.placeholder(tf.float32, [None, initial_weights[0].shape[0]]) layer_in = self.input_layer for weights in initial_weights[:-1]: layer_in = self.fully_connected(layer_in, weights, activation_fn) self.output_layer = self.fully_connected(layer_in, initial_weights[-1]) def fully_connected(self, layer_in, initial_weights, activation_fn=None): """ Creates a standard, fully connected layer. Its number of inputs and outputs will be defined by the shape of `initial_weights`, and its starting weight values will be taken directly from that same parameter. If `self.use_batch_norm` is True, this layer will include batch normalization, otherwise it will not. :param layer_in: Tensor The Tensor that feeds into this layer. It's either the input to the network or the output of a previous layer. :param initial_weights: NumPy array or Tensor Initial values for this layer's weights. The shape defines the number of nodes in the layer. e.g. Passing in 3 matrix of shape (784, 256) would create a layer with 784 inputs and 256 outputs. :param activation_fn: Callable or None (default None) The non-linearity used for the output of the layer. If None, this layer will not include batch normalization, regardless of the value of `self.use_batch_norm`. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. """ # Since this class supports both options, only use batch normalization when # requested. However, do not use it on the final layer, which we identify # by its lack of an activation function. if self.use_batch_norm and activation_fn: # Batch normalization uses weights as usual, but does NOT add a bias term. This is because # its calculations include gamma and beta variables that make the bias term unnecessary. # (See later in the notebook for more details.) weights = tf.Variable(initial_weights) linear_output = tf.matmul(layer_in, weights) # Apply batch normalization to the linear combination of the inputs and weights batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training) # Now apply the activation function, *after* the normalization. return activation_fn(batch_normalized_output) else: # When not using batch normalization, create a standard layer that multiplies # the inputs and weights, adds a bias, and optionally passes the result # through an activation function. weights = tf.Variable(initial_weights) biases = tf.Variable(tf.zeros([initial_weights.shape[-1]])) linear_output = tf.add(tf.matmul(layer_in, weights), biases) return linear_output if not activation_fn else activation_fn(linear_output) def train(self, session, learning_rate, training_batches, batches_per_sample, save_model_as=None): """ Trains the model on the MNIST training dataset. :param session: Session Used to run training graph operations. :param learning_rate: float Learning rate used during gradient descent. :param training_batches: int Number of batches to train. :param batches_per_sample: int How many batches to train before sampling the validation accuracy. :param save_model_as: string or None (default None) Name to use if you want to save the trained model. """ # This placeholder will store the target labels for each mini batch labels = tf.placeholder(tf.float32, [None, 10]) # Define loss and optimizer cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=self.output_layer)) # Define operations for testing correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(labels, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) if self.use_batch_norm: # If we don't include the update ops as dependencies on the train step, the # tf.layers.batch_normalization layers won't update their population statistics, # which will cause the model to fail at inference time with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) else: train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # Train for the appropriate number of batches. (tqdm is only for a nice timing display) for i in tqdm.tqdm(range(training_batches)): # We use batches of 60 just because the original paper did. You can use any size batch you like. batch_xs, batch_ys = mnist.train.next_batch(60) session.run(train_step, feed_dict={self.input_layer: batch_xs, labels: batch_ys, self.is_training: True}) # Periodically test accuracy against the 5k validation images and store it for plotting later. if i % batches_per_sample == 0: test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.validation.images, labels: mnist.validation.labels, self.is_training: False}) self.training_accuracies.append(test_accuracy) # After training, report accuracy against test data test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.validation.images, labels: mnist.validation.labels, self.is_training: False}) print('{}: After training, final accuracy on validation set = {}'.format(self.name, test_accuracy)) # If you want to use this model later for inference instead of having to retrain it, # just construct it with the same parameters and then pass this file to the 'test' function if save_model_as: tf.train.Saver().save(session, save_model_as) def test(self, session, test_training_accuracy=False, include_individual_predictions=False, restore_from=None): """ Trains a trained model on the MNIST testing dataset. :param session: Session Used to run the testing graph operations. :param test_training_accuracy: bool (default False) If True, perform inference with batch normalization using batch mean and variance; if False, perform inference with batch normalization using estimated population mean and variance. Note: in real life, *always* perform inference using the population mean and variance. This parameter exists just to support demonstrating what happens if you don't. :param include_individual_predictions: bool (default True) This function always performs an accuracy test against the entire test set. But if this parameter is True, it performs an extra test, doing 200 predictions one at a time, and displays the results and accuracy. :param restore_from: string or None (default None) Name of a saved model if you want to test with previously saved weights. """ # This placeholder will store the true labels for each mini batch labels = tf.placeholder(tf.float32, [None, 10]) # Define operations for testing correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(labels, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # If provided, restore from a previously saved model if restore_from: tf.train.Saver().restore(session, restore_from) # Test against all of the MNIST test data test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.test.images, labels: mnist.test.labels, self.is_training: test_training_accuracy}) print('-'*75) print('{}: Accuracy on full test set = {}'.format(self.name, test_accuracy)) # If requested, perform tests predicting individual values rather than batches if include_individual_predictions: predictions = [] correct = 0 # Do 200 predictions, 1 at a time for i in range(200): # This is a normal prediction using an individual test case. However, notice # we pass `test_training_accuracy` to `feed_dict` as the value for `self.is_training`. # Remember that will tell it whether it should use the batch mean & variance or # the population estimates that were calucated while training the model. pred, corr = session.run([tf.arg_max(self.output_layer,1), accuracy], feed_dict={self.input_layer: [mnist.test.images[i]], labels: [mnist.test.labels[i]], self.is_training: test_training_accuracy}) correct += corr predictions.append(pred[0]) print("200 Predictions:", predictions) print("Accuracy on 200 samples:", correct/200) """ Explanation: Neural network classes for testing The following class, NeuralNet, allows us to create identical neural networks with and without batch normalization. The code is heavily documented, but there is also some additional discussion later. You do not need to read through it all before going through the rest of the notebook, but the comments within the code blocks may answer some of your questions. About the code: This class is not meant to represent TensorFlow best practices – the design choices made here are to support the discussion related to batch normalization. It's also important to note that we use the well-known MNIST data for these examples, but the networks we create are not meant to be good for performing handwritten character recognition. We chose this network architecture because it is similar to the one used in the original paper, which is complex enough to demonstrate some of the benefits of batch normalization while still being fast to train. End of explanation """ def plot_training_accuracies(*args, **kwargs): """ Displays a plot of the accuracies calculated during training to demonstrate how many iterations it took for the model(s) to converge. :param args: One or more NeuralNet objects You can supply any number of NeuralNet objects as unnamed arguments and this will display their training accuracies. Be sure to call `train` the NeuralNets before calling this function. :param kwargs: You can supply any named parameters here, but `batches_per_sample` is the only one we look for. It should match the `batches_per_sample` value you passed to the `train` function. """ fig, ax = plt.subplots() batches_per_sample = kwargs['batches_per_sample'] for nn in args: ax.plot(range(0,len(nn.training_accuracies)*batches_per_sample,batches_per_sample), nn.training_accuracies, label=nn.name) ax.set_xlabel('Training steps') ax.set_ylabel('Accuracy') ax.set_title('Validation Accuracy During Training') ax.legend(loc=4) ax.set_ylim([0,1]) plt.yticks(np.arange(0, 1.1, 0.1)) plt.grid(True) plt.show() def train_and_test(use_bad_weights, learning_rate, activation_fn, training_batches=50000, batches_per_sample=500): """ Creates two networks, one with and one without batch normalization, then trains them with identical starting weights, layers, batches, etc. Finally tests and plots their accuracies. :param use_bad_weights: bool If True, initialize the weights of both networks to wildly inappropriate weights; if False, use reasonable starting weights. :param learning_rate: float Learning rate used during gradient descent. :param activation_fn: Callable The function used for the output of each hidden layer. The network will use the same activation function on every hidden layer and no activate function on the output layer. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. :param training_batches: (default 50000) Number of batches to train. :param batches_per_sample: (default 500) How many batches to train before sampling the validation accuracy. """ # Use identical starting weights for each network to eliminate differences in # weight initialization as a cause for differences seen in training performance # # Note: The networks will use these weights to define the number of and shapes of # its layers. The original batch normalization paper used 3 hidden layers # with 100 nodes in each, followed by a 10 node output layer. These values # build such a network, but feel free to experiment with different choices. # However, the input size should always be 784 and the final output should be 10. if use_bad_weights: # These weights should be horrible because they have such a large standard deviation weights = [np.random.normal(size=(784,100), scale=5.0).astype(np.float32), np.random.normal(size=(100,100), scale=5.0).astype(np.float32), np.random.normal(size=(100,100), scale=5.0).astype(np.float32), np.random.normal(size=(100,10), scale=5.0).astype(np.float32) ] else: # These weights should be good because they have such a small standard deviation weights = [np.random.normal(size=(784,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,10), scale=0.05).astype(np.float32) ] # Just to make sure the TensorFlow's default graph is empty before we start another # test, because we don't bother using different graphs or scoping and naming # elements carefully in this sample code. tf.reset_default_graph() # build two versions of same network, 1 without and 1 with batch normalization nn = NeuralNet(weights, activation_fn, False) bn = NeuralNet(weights, activation_fn, True) # train and test the two models with tf.Session() as sess: tf.global_variables_initializer().run() nn.train(sess, learning_rate, training_batches, batches_per_sample) bn.train(sess, learning_rate, training_batches, batches_per_sample) nn.test(sess) bn.test(sess) # Display a graph of how validation accuracies changed during training # so we can compare how the models trained and when they converged plot_training_accuracies(nn, bn, batches_per_sample=batches_per_sample) """ Explanation: There are quite a few comments in the code, so those should answer most of your questions. However, let's take a look at the most important lines. We add batch normalization to layers inside the fully_connected function. Here are some important points about that code: 1. Layers with batch normalization do not include a bias term. 2. We use TensorFlow's tf.layers.batch_normalization function to handle the math. (We show lower-level ways to do this later in the notebook.) 3. We tell tf.layers.batch_normalization whether or not the network is training. This is an important step we'll talk about later. 4. We add the normalization before calling the activation function. In addition to that code, the training step is wrapped in the following with statement: python with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): This line actually works in conjunction with the training parameter we pass to tf.layers.batch_normalization. Without it, TensorFlow's batch normalization layer will not operate correctly during inference. Finally, whenever we train the network or perform inference, we use the feed_dict to set self.is_training to True or False, respectively, like in the following line: python session.run(train_step, feed_dict={self.input_layer: batch_xs, labels: batch_ys, self.is_training: True}) We'll go into more details later, but next we want to show some experiments that use this code and test networks with and without batch normalization. Batch Normalization Demos<a id='demos'></a> This section of the notebook trains various networks with and without batch normalization to demonstrate some of the benefits mentioned earlier. We'd like to thank the author of this blog post Implementing Batch Normalization in TensorFlow. That post provided the idea of - and some of the code for - plotting the differences in accuracy during training, along with the idea for comparing multiple networks using the same initial weights. Code to support testing The following two functions support the demos we run in the notebook. The first function, plot_training_accuracies, simply plots the values found in the training_accuracies lists of the NeuralNet objects passed to it. If you look at the train function in NeuralNet, you'll see it that while it's training the network, it periodically measures validation accuracy and stores the results in that list. It does that just to support these plots. The second function, train_and_test, creates two neural nets - one with and one without batch normalization. It then trains them both and tests them, calling plot_training_accuracies to plot how their accuracies changed over the course of training. The really imporant thing about this function is that it initializes the starting weights for the networks outside of the networks and then passes them in. This lets it train both networks from the exact same starting weights, which eliminates performance differences that might result from (un)lucky initial weights. End of explanation """ train_and_test(False, 0.01, tf.nn.relu) """ Explanation: Comparisons between identical networks, with and without batch normalization The next series of cells train networks with various settings to show the differences with and without batch normalization. They are meant to clearly demonstrate the effects of batch normalization. We include a deeper discussion of batch normalization later in the notebook. The following creates two networks using a ReLU activation function, a learning rate of 0.01, and reasonable starting weights. End of explanation """ train_and_test(False, 0.01, tf.nn.relu, 2000, 50) """ Explanation: As expected, both networks train well and eventually reach similar test accuracies. However, notice that the model with batch normalization converges slightly faster than the other network, reaching accuracies over 90% almost immediately and nearing its max acuracy in 10 or 15 thousand iterations. The other network takes about 3 thousand iterations to reach 90% and doesn't near its best accuracy until 30 thousand or more iterations. If you look at the raw speed, you can see that without batch normalization we were computing over 1100 batches per second, whereas with batch normalization that goes down to just over 500. However, batch normalization allows us to perform fewer iterations and converge in less time over all. (We only trained for 50 thousand batches here so we could plot the comparison.) The following creates two networks with the same hyperparameters used in the previous example, but only trains for 2000 iterations. End of explanation """ train_and_test(False, 0.01, tf.nn.sigmoid) """ Explanation: As you can see, using batch normalization produces a model with over 95% accuracy in only 2000 batches, and it was above 90% at somewhere around 500 batches. Without batch normalization, the model takes 1750 iterations just to hit 80% – the network with batch normalization hits that mark after around 200 iterations! (Note: if you run the code yourself, you'll see slightly different results each time because the starting weights - while the same for each model - are different for each run.) In the above example, you should also notice that the networks trained fewer batches per second then what you saw in the previous example. That's because much of the time we're tracking is actually spent periodically performing inference to collect data for the plots. In this example we perform that inference every 50 batches instead of every 500, so generating the plot for this example requires 10 times the overhead for the same 2000 iterations. The following creates two networks using a sigmoid activation function, a learning rate of 0.01, and reasonable starting weights. End of explanation """ train_and_test(False, 1, tf.nn.relu) """ Explanation: With the number of layers we're using and this small learning rate, using a sigmoid activation function takes a long time to start learning. It eventually starts making progress, but it took over 45 thousand batches just to get over 80% accuracy. Using batch normalization gets to 90% in around one thousand batches. The following creates two networks using a ReLU activation function, a learning rate of 1, and reasonable starting weights. End of explanation """ train_and_test(False, 1, tf.nn.relu) """ Explanation: Now we're using ReLUs again, but with a larger learning rate. The plot shows how training started out pretty normally, with the network with batch normalization starting out faster than the other. But the higher learning rate bounces the accuracy around a bit more, and at some point the accuracy in the network without batch normalization just completely crashes. It's likely that too many ReLUs died off at this point because of the high learning rate. The next cell shows the same test again. The network with batch normalization performs the same way, and the other suffers from the same problem again, but it manages to train longer before it happens. End of explanation """ train_and_test(False, 1, tf.nn.sigmoid) """ Explanation: In both of the previous examples, the network with batch normalization manages to gets over 98% accuracy, and get near that result almost immediately. The higher learning rate allows the network to train extremely fast. The following creates two networks using a sigmoid activation function, a learning rate of 1, and reasonable starting weights. End of explanation """ train_and_test(False, 1, tf.nn.sigmoid, 2000, 50) """ Explanation: In this example, we switched to a sigmoid activation function. It appears to hande the higher learning rate well, with both networks achieving high accuracy. The cell below shows a similar pair of networks trained for only 2000 iterations. End of explanation """ train_and_test(False, 2, tf.nn.relu) """ Explanation: As you can see, even though these parameters work well for both networks, the one with batch normalization gets over 90% in 400 or so batches, whereas the other takes over 1700. When training larger networks, these sorts of differences become more pronounced. The following creates two networks using a ReLU activation function, a learning rate of 2, and reasonable starting weights. End of explanation """ train_and_test(False, 2, tf.nn.sigmoid) """ Explanation: With this very large learning rate, the network with batch normalization trains fine and almost immediately manages 98% accuracy. However, the network without normalization doesn't learn at all. The following creates two networks using a sigmoid activation function, a learning rate of 2, and reasonable starting weights. End of explanation """ train_and_test(False, 2, tf.nn.sigmoid, 2000, 50) """ Explanation: Once again, using a sigmoid activation function with the larger learning rate works well both with and without batch normalization. However, look at the plot below where we train models with the same parameters but only 2000 iterations. As usual, batch normalization lets it train faster. End of explanation """ train_and_test(True, 0.01, tf.nn.relu) """ Explanation: In the rest of the examples, we use really bad starting weights. That is, normally we would use very small values close to zero. However, in these examples we choose random values with a standard deviation of 5. If you were really training a neural network, you would not want to do this. But these examples demonstrate how batch normalization makes your network much more resilient. The following creates two networks using a ReLU activation function, a learning rate of 0.01, and bad starting weights. End of explanation """ train_and_test(True, 0.01, tf.nn.sigmoid) """ Explanation: As the plot shows, without batch normalization the network never learns anything at all. But with batch normalization, it actually learns pretty well and gets to almost 80% accuracy. The starting weights obviously hurt the network, but you can see how well batch normalization does in overcoming them. The following creates two networks using a sigmoid activation function, a learning rate of 0.01, and bad starting weights. End of explanation """ train_and_test(True, 1, tf.nn.relu) """ Explanation: Using a sigmoid activation function works better than the ReLU in the previous example, but without batch normalization it would take a tremendously long time to train the network, if it ever trained at all. The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting weights.<a id="successful_example_lr_1"></a> End of explanation """ train_and_test(True, 1, tf.nn.sigmoid) """ Explanation: The higher learning rate used here allows the network with batch normalization to surpass 90% in about 30 thousand batches. The network without it never gets anywhere. The following creates two networks using a sigmoid activation function, a learning rate of 1, and bad starting weights. End of explanation """ train_and_test(True, 2, tf.nn.relu) """ Explanation: Using sigmoid works better than ReLUs for this higher learning rate. However, you can see that without batch normalization, the network takes a long time tro train, bounces around a lot, and spends a long time stuck at 90%. The network with batch normalization trains much more quickly, seems to be more stable, and achieves a higher accuracy. The following creates two networks using a ReLU activation function, a learning rate of 2, and bad starting weights.<a id="successful_example_lr_2"></a> End of explanation """ train_and_test(True, 2, tf.nn.sigmoid) """ Explanation: We've already seen that ReLUs do not do as well as sigmoids with higher learning rates, and here we are using an extremely high rate. As expected, without batch normalization the network doesn't learn at all. But with batch normalization, it eventually achieves 90% accuracy. Notice, though, how its accuracy bounces around wildly during training - that's because the learning rate is really much too high, so the fact that this worked at all is a bit of luck. The following creates two networks using a sigmoid activation function, a learning rate of 2, and bad starting weights. End of explanation """ train_and_test(True, 1, tf.nn.relu) """ Explanation: In this case, the network with batch normalization trained faster and reached a higher accuracy. Meanwhile, the high learning rate makes the network without normalization bounce around erratically and have trouble getting past 90%. Full Disclosure: Batch Normalization Doesn't Fix Everything Batch normalization isn't magic and it doesn't work every time. Weights are still randomly initialized and batches are chosen at random during training, so you never know exactly how training will go. Even for these tests, where we use the same initial weights for both networks, we still get different weights each time we run. This section includes two examples that show runs when batch normalization did not help at all. The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting weights. End of explanation """ train_and_test(True, 2, tf.nn.relu) """ Explanation: When we used these same parameters earlier, we saw the network with batch normalization reach 92% validation accuracy. This time we used different starting weights, initialized using the same standard deviation as before, and the network doesn't learn at all. (Remember, an accuracy around 10% is what the network gets if it just guesses the same value all the time.) The following creates two networks using a ReLU activation function, a learning rate of 2, and bad starting weights. End of explanation """ def fully_connected(self, layer_in, initial_weights, activation_fn=None): """ Creates a standard, fully connected layer. Its number of inputs and outputs will be defined by the shape of `initial_weights`, and its starting weight values will be taken directly from that same parameter. If `self.use_batch_norm` is True, this layer will include batch normalization, otherwise it will not. :param layer_in: Tensor The Tensor that feeds into this layer. It's either the input to the network or the output of a previous layer. :param initial_weights: NumPy array or Tensor Initial values for this layer's weights. The shape defines the number of nodes in the layer. e.g. Passing in 3 matrix of shape (784, 256) would create a layer with 784 inputs and 256 outputs. :param activation_fn: Callable or None (default None) The non-linearity used for the output of the layer. If None, this layer will not include batch normalization, regardless of the value of `self.use_batch_norm`. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. """ if self.use_batch_norm and activation_fn: # Batch normalization uses weights as usual, but does NOT add a bias term. This is because # its calculations include gamma and beta variables that make the bias term unnecessary. weights = tf.Variable(initial_weights) linear_output = tf.matmul(layer_in, weights) num_out_nodes = initial_weights.shape[-1] # Batch normalization adds additional trainable variables: # gamma (for scaling) and beta (for shifting). gamma = tf.Variable(tf.ones([num_out_nodes])) beta = tf.Variable(tf.zeros([num_out_nodes])) # These variables will store the mean and variance for this layer over the entire training set, # which we assume represents the general population distribution. # By setting `trainable=False`, we tell TensorFlow not to modify these variables during # back propagation. Instead, we will assign values to these variables ourselves. pop_mean = tf.Variable(tf.zeros([num_out_nodes]), trainable=False) pop_variance = tf.Variable(tf.ones([num_out_nodes]), trainable=False) # Batch normalization requires a small constant epsilon, used to ensure we don't divide by zero. # This is the default value TensorFlow uses. epsilon = 1e-3 def batch_norm_training(): # Calculate the mean and variance for the data coming out of this layer's linear-combination step. # The [0] defines an array of axes to calculate over. batch_mean, batch_variance = tf.nn.moments(linear_output, [0]) # Calculate a moving average of the training data's mean and variance while training. # These will be used during inference. # Decay should be some number less than 1. tf.layers.batch_normalization uses the parameter # "momentum" to accomplish this and defaults it to 0.99 decay = 0.99 train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1 - decay)) train_variance = tf.assign(pop_variance, pop_variance * decay + batch_variance * (1 - decay)) # The 'tf.control_dependencies' context tells TensorFlow it must calculate 'train_mean' # and 'train_variance' before it calculates the 'tf.nn.batch_normalization' layer. # This is necessary because the those two operations are not actually in the graph # connecting the linear_output and batch_normalization layers, # so TensorFlow would otherwise just skip them. with tf.control_dependencies([train_mean, train_variance]): return tf.nn.batch_normalization(linear_output, batch_mean, batch_variance, beta, gamma, epsilon) def batch_norm_inference(): # During inference, use the our estimated population mean and variance to normalize the layer return tf.nn.batch_normalization(linear_output, pop_mean, pop_variance, beta, gamma, epsilon) # Use `tf.cond` as a sort of if-check. When self.is_training is True, TensorFlow will execute # the operation returned from `batch_norm_training`; otherwise it will execute the graph # operation returned from `batch_norm_inference`. batch_normalized_output = tf.cond(self.is_training, batch_norm_training, batch_norm_inference) # Pass the batch-normalized layer output through the activation function. # The literature states there may be cases where you want to perform the batch normalization *after* # the activation function, but it is difficult to find any uses of that in practice. return activation_fn(batch_normalized_output) else: # When not using batch normalization, create a standard layer that multiplies # the inputs and weights, adds a bias, and optionally passes the result # through an activation function. weights = tf.Variable(initial_weights) biases = tf.Variable(tf.zeros([initial_weights.shape[-1]])) linear_output = tf.add(tf.matmul(layer_in, weights), biases) return linear_output if not activation_fn else activation_fn(linear_output) """ Explanation: When we trained with these parameters and batch normalization earlier, we reached 90% validation accuracy. However, this time the network almost starts to make some progress in the beginning, but it quickly breaks down and stops learning. Note: Both of the above examples use extremely bad starting weights, along with learning rates that are too high. While we've shown batch normalization can overcome bad values, we don't mean to encourage actually using them. The examples in this notebook are meant to show that batch normalization can help your networks train better. But these last two examples should remind you that you still want to try to use good network design choices and reasonable starting weights. It should also remind you that the results of each attempt to train a network are a bit random, even when using otherwise identical architectures. Batch Normalization: A Detailed Look<a id='implementation_2'></a> The layer created by tf.layers.batch_normalization handles all the details of implementing batch normalization. Many students will be fine just using that and won't care about what's happening at the lower levels. However, some students may want to explore the details, so here is a short explanation of what's really happening, starting with the equations you're likely to come across if you ever read about batch normalization. In order to normalize the values, we first need to find the average value for the batch. If you look at the code, you can see that this is not the average value of the batch inputs, but the average value coming out of any particular layer before we pass it through its non-linear activation function and then feed it as an input to the next layer. We represent the average as $\mu_B$, which is simply the sum of all of the values $x_i$ divided by the number of values, $m$ $$ \mu_B \leftarrow \frac{1}{m}\sum_{i=1}^m x_i $$ We then need to calculate the variance, or mean squared deviation, represented as $\sigma_{B}^{2}$. If you aren't familiar with statistics, that simply means for each value $x_i$, we subtract the average value (calculated earlier as $\mu_B$), which gives us what's called the "deviation" for that value. We square the result to get the squared deviation. Sum up the results of doing that for each of the values, then divide by the number of values, again $m$, to get the average, or mean, squared deviation. $$ \sigma_{B}^{2} \leftarrow \frac{1}{m}\sum_{i=1}^m (x_i - \mu_B)^2 $$ Once we have the mean and variance, we can use them to normalize the values with the following equation. For each value, it subtracts the mean and divides by the (almost) standard deviation. (You've probably heard of standard deviation many times, but if you have not studied statistics you might not know that the standard deviation is actually the square root of the mean squared deviation.) $$ \hat{x_i} \leftarrow \frac{x_i - \mu_B}{\sqrt{\sigma_{B}^{2} + \epsilon}} $$ Above, we said "(almost) standard deviation". That's because the real standard deviation for the batch is calculated by $\sqrt{\sigma_{B}^{2}}$, but the above formula adds the term epsilon, $\epsilon$, before taking the square root. The epsilon can be any small, positive constant - in our code we use the value 0.001. It is there partially to make sure we don't try to divide by zero, but it also acts to increase the variance slightly for each batch. Why increase the variance? Statistically, this makes sense because even though we are normalizing one batch at a time, we are also trying to estimate the population distribution – the total training set, which itself an estimate of the larger population of inputs your network wants to handle. The variance of a population is higher than the variance for any sample taken from that population, so increasing the variance a little bit for each batch helps take that into account. At this point, we have a normalized value, represented as $\hat{x_i}$. But rather than use it directly, we multiply it by a gamma value, $\gamma$, and then add a beta value, $\beta$. Both $\gamma$ and $\beta$ are learnable parameters of the network and serve to scale and shift the normalized value, respectively. Because they are learnable just like weights, they give your network some extra knobs to tweak during training to help it learn the function it is trying to approximate. $$ y_i \leftarrow \gamma \hat{x_i} + \beta $$ We now have the final batch-normalized output of our layer, which we would then pass to a non-linear activation function like sigmoid, tanh, ReLU, Leaky ReLU, etc. In the original batch normalization paper (linked in the beginning of this notebook), they mention that there might be cases when you'd want to perform the batch normalization after the non-linearity instead of before, but it is difficult to find any uses like that in practice. In NeuralNet's implementation of fully_connected, all of this math is hidden inside the following line, where linear_output serves as the $x_i$ from the equations: python batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training) The next section shows you how to implement the math directly. Batch normalization without the tf.layers package Our implementation of batch normalization in NeuralNet uses the high-level abstraction tf.layers.batch_normalization, found in TensorFlow's tf.layers package. However, if you would like to implement batch normalization at a lower level, the following code shows you how. It uses tf.nn.batch_normalization from TensorFlow's neural net (nn) package. 1) You can replace the fully_connected function in the NeuralNet class with the below code and everything in NeuralNet will still work like it did before. End of explanation """ def batch_norm_test(test_training_accuracy): """ :param test_training_accuracy: bool If True, perform inference with batch normalization using batch mean and variance; if False, perform inference with batch normalization using estimated population mean and variance. """ weights = [np.random.normal(size=(784,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,10), scale=0.05).astype(np.float32) ] tf.reset_default_graph() # Train the model bn = NeuralNet(weights, tf.nn.relu, True) # First train the network with tf.Session() as sess: tf.global_variables_initializer().run() bn.train(sess, 0.01, 2000, 2000) bn.test(sess, test_training_accuracy=test_training_accuracy, include_individual_predictions=True) """ Explanation: This version of fully_connected is much longer than the original, but once again has extensive comments to help you understand it. Here are some important points: It explicitly creates variables to store gamma, beta, and the population mean and variance. These were all handled for us in the previous version of the function. It initializes gamma to one and beta to zero, so they start out having no effect in this calculation: $y_i \leftarrow \gamma \hat{x_i} + \beta$. However, during training the network learns the best values for these variables using back propagation, just like networks normally do with weights. Unlike gamma and beta, the variables for population mean and variance are marked as untrainable. That tells TensorFlow not to modify them during back propagation. Instead, the lines that call tf.assign are used to update these variables directly. TensorFlow won't automatically run the tf.assign operations during training because it only evaluates operations that are required based on the connections it finds in the graph. To get around that, we add this line: with tf.control_dependencies([train_mean, train_variance]): before we run the normalization operation. This tells TensorFlow it needs to run those operations before running anything inside the with block. The actual normalization math is still mostly hidden from us, this time using tf.nn.batch_normalization. tf.nn.batch_normalization does not have a training parameter like tf.layers.batch_normalization did. However, we still need to handle training and inference differently, so we run different code in each case using the tf.cond operation. We use the tf.nn.moments function to calculate the batch mean and variance. 2) The current version of the train function in NeuralNet will work fine with this new version of fully_connected. However, it uses these lines to ensure population statistics are updated when using batch normalization: python if self.use_batch_norm: with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) else: train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) Our new version of fully_connected handles updating the population statistics directly. That means you can also simplify your code by replacing the above if/else condition with just this line: python train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) 3) And just in case you want to implement every detail from scratch, you can replace this line in batch_norm_training: python return tf.nn.batch_normalization(linear_output, batch_mean, batch_variance, beta, gamma, epsilon) with these lines: python normalized_linear_output = (linear_output - batch_mean) / tf.sqrt(batch_variance + epsilon) return gamma * normalized_linear_output + beta And replace this line in batch_norm_inference: python return tf.nn.batch_normalization(linear_output, pop_mean, pop_variance, beta, gamma, epsilon) with these lines: python normalized_linear_output = (linear_output - pop_mean) / tf.sqrt(pop_variance + epsilon) return gamma * normalized_linear_output + beta As you can see in each of the above substitutions, the two lines of replacement code simply implement the following two equations directly. The first line calculates the following equation, with linear_output representing $x_i$ and normalized_linear_output representing $\hat{x_i}$: $$ \hat{x_i} \leftarrow \frac{x_i - \mu_B}{\sqrt{\sigma_{B}^{2} + \epsilon}} $$ And the second line is a direct translation of the following equation: $$ y_i \leftarrow \gamma \hat{x_i} + \beta $$ We still use the tf.nn.moments operation to implement the other two equations from earlier – the ones that calculate the batch mean and variance used in the normalization step. If you really wanted to do everything from scratch, you could replace that line, too, but we'll leave that to you. Why the difference between training and inference? In the original function that uses tf.layers.batch_normalization, we tell the layer whether or not the network is training by passing a value for its training parameter, like so: python batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training) And that forces us to provide a value for self.is_training in our feed_dict, like we do in this example from NeuralNet's train function: python session.run(train_step, feed_dict={self.input_layer: batch_xs, labels: batch_ys, self.is_training: True}) If you looked at the low level implementation, you probably noticed that, just like with tf.layers.batch_normalization, we need to do slightly different things during training and inference. But why is that? First, let's look at what happens when we don't. The following function is similar to train_and_test from earlier, but this time we are only testing one network and instead of plotting its accuracy, we perform 200 predictions on test inputs, 1 input at at time. We can use the test_training_accuracy parameter to test the network in training or inference modes (the equivalent of passing True or False to the feed_dict for is_training). End of explanation """ batch_norm_test(True) """ Explanation: In the following cell, we pass True for test_training_accuracy, which performs the same batch normalization that we normally perform during training. End of explanation """ batch_norm_test(False) """ Explanation: As you can see, the network guessed the same value every time! But why? Because during training, a network with batch normalization adjusts the values at each layer based on the mean and variance of that batch. The "batches" we are using for these predictions have a single input each time, so their values are the means, and their variances will always be 0. That means the network will normalize the values at any layer to zero. (Review the equations from before to see why a value that is equal to the mean would always normalize to zero.) So we end up with the same result for every input we give the network, because its the value the network produces when it applies its learned weights to zeros at every layer. Note: If you re-run that cell, you might get a different value from what we showed. That's because the specific weights the network learns will be different every time. But whatever value it is, it should be the same for all 200 predictions. To overcome this problem, the network does not just normalize the batch at each layer. It also maintains an estimate of the mean and variance for the entire population. So when we perform inference, instead of letting it "normalize" all the values using their own means and variance, it uses the estimates of the population mean and variance that it calculated while training. So in the following example, we pass False for test_training_accuracy, which tells the network that we it want to perform inference with the population statistics it calculates during training. End of explanation """
JavascriptMick/deeplearning
language-translation/dlnd_language_translation.ipynb
mit
import helper import problem_unittests as tests """ DON'T MODIFY ANYTHING IN THIS CELL """ import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) """ Explanation: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French. Get the Data Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus. End of explanation """ view_sentence_range = (0, 10) """ DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()}))) sentences = source_text.split('\n') word_counts = [len(sentence.split()) for sentence in sentences] print('Number of sentences: {}'.format(len(sentences))) print('Average number of words in a sentence: {}'.format(np.average(word_counts))) print() print('English sentences {} to {}:'.format(*view_sentence_range)) print('\n'.join(source_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]])) print() print('French sentences {} to {}:'.format(*view_sentence_range)) print('\n'.join(target_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]])) """ Explanation: Explore the Data Play around with view_sentence_range to view different parts of the data. End of explanation """ def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int): """ Convert source and target text to proper word ids :param source_text: String that contains all the source text. :param target_text: String that contains all the target text. :param source_vocab_to_int: Dictionary to go from the source words to an id :param target_vocab_to_int: Dictionary to go from the target words to an id :return: A tuple of lists (source_id_text, target_id_text) """ source_words = [line.split(' ') for line in source_text.split('\n')] source_id_text = [[source_vocab_to_int[word] for word in line if word] for line in source_words ] target_words = [line.split(' ') for line in target_text.split('\n')] target_id_text = [[target_vocab_to_int[word] for word in line if word] + [target_vocab_to_int['<EOS>']] for line in target_words ] return source_id_text, target_id_text """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_text_to_ids(text_to_ids) """ Explanation: Implement Preprocessing Function Text to Word Ids As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the &lt;EOS&gt; word id at the end of target_text. This will help the neural network predict when the sentence should end. You can get the &lt;EOS&gt; word id by doing: python target_vocab_to_int['&lt;EOS&gt;'] You can get other word ids using source_vocab_to_int and target_vocab_to_int. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ helper.preprocess_and_save_data(source_path, target_path, text_to_ids) """ Explanation: Preprocess all the data and save it Running the code cell below will preprocess all the data and save it to file. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np import helper import problem_unittests as tests (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess() """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ from distutils.version import LooseVersion import warnings import tensorflow as tf from tensorflow.python.layers.core import Dense # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.1'), 'Please use TensorFlow version 1.1 or newer' print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) """ Explanation: Check the Version of TensorFlow and Access to GPU This will check to make sure you have the correct version of TensorFlow and access to a GPU End of explanation """ def model_inputs(): """ Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences. :return: Tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length) """ # TODO: Implement Function input = tf.placeholder(tf.int32, [None, None], name='input') targets = tf.placeholder(tf.int32, [None, None], name='targets') learning_rate = tf.placeholder(tf.float32, name='learning_rate') keep_prob = tf.placeholder(tf.float32, name='keep_prob') target_sequence_length = tf.placeholder(tf.int32, (None,), name='target_sequence_length') max_target_sequence_length = tf.reduce_max(target_sequence_length, name='max_target_len') source_sequence_length = tf.placeholder(tf.int32, (None,), name='source_sequence_length') return input, targets, learning_rate, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_model_inputs(model_inputs) """ Explanation: Build the Neural Network You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below: - model_inputs - process_decoder_input - encoding_layer - decoding_layer_train - decoding_layer_infer - decoding_layer - seq2seq_model Input Implement the model_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders: Input text placeholder named "input" using the TF Placeholder name parameter with rank 2. Targets placeholder with rank 2. Learning rate placeholder with rank 0. Keep probability placeholder named "keep_prob" using the TF Placeholder name parameter with rank 0. Target sequence length placeholder named "target_sequence_length" with rank 1 Max target sequence length tensor named "max_target_len" getting its value from applying tf.reduce_max on the target_sequence_length placeholder. Rank 0. Source sequence length placeholder named "source_sequence_length" with rank 1 Return the placeholders in the following the tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length) End of explanation """ def process_decoder_input(target_data, target_vocab_to_int, batch_size): """ Preprocess target data for encoding :param target_data: Target Placehoder :param target_vocab_to_int: Dictionary to go from the target words to an id :param batch_size: Batch Size :return: Preprocessed target data """ # ending = target_data[:,:-1] # you can also use strided_slice but I can't figure out why you would.. the above syntax is more terse ending = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1]) dec_input = tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), ending], 1) return dec_input """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_process_encoding_input(process_decoder_input) """ Explanation: Process Decoder Input Implement process_decoder_input by removing the last word id from each batch in target_data and concat the GO ID to the begining of each batch. End of explanation """ from imp import reload reload(tests) def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size :param num_layers: Number of layers :param keep_prob: Dropout keep probability :param source_sequence_length: a list of the lengths of each sequence in the batch :param source_vocab_size: vocabulary size of source data :param encoding_embedding_size: embedding size of source data :return: tuple (RNN output, RNN state) """ # Encoder embedding enc_embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size) # RNN cell def make_cell(rnn_size): enc_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2)) enc_cell = tf.contrib.rnn.DropoutWrapper(enc_cell, output_keep_prob = keep_prob) return enc_cell enc_cell = tf.contrib.rnn.MultiRNNCell([make_cell(rnn_size) for _ in range(num_layers)]) enc_output, enc_state = tf.nn.dynamic_rnn(enc_cell, enc_embed_input, sequence_length=source_sequence_length, dtype=tf.float32) return enc_output, enc_state """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_encoding_layer(encoding_layer) """ Explanation: Encoding Implement encoding_layer() to create a Encoder RNN layer: * Embed the encoder input using tf.contrib.layers.embed_sequence * Construct a stacked tf.contrib.rnn.LSTMCell wrapped in a tf.contrib.rnn.DropoutWrapper * Pass cell and embedded input to tf.nn.dynamic_rnn() End of explanation """ def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_summary_length, output_layer, keep_prob): """ Create a decoding layer for training :param encoder_state: Encoder State :param dec_cell: Decoder RNN Cell :param dec_embed_input: Decoder embedded input :param target_sequence_length: The lengths of each sequence in the target batch :param max_summary_length: The length of the longest sequence in the batch :param output_layer: Function to apply the output layer :param keep_prob: Dropout keep probability :return: BasicDecoderOutput containing training logits and sample_id """ # Helper for the training process. Used by BasicDecoder to read inputs. training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input, sequence_length=target_sequence_length, time_major=False) # Basic decoder training_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, training_helper, encoder_state, output_layer) # Perform dynamic decoding using the decoder training_decoder_output = tf.contrib.seq2seq.dynamic_decode(training_decoder, impute_finished=True, maximum_iterations=max_summary_length)[0] return training_decoder_output """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_decoding_layer_train(decoding_layer_train) """ Explanation: Decoding - Training Create a training decoding layer: * Create a tf.contrib.seq2seq.TrainingHelper * Create a tf.contrib.seq2seq.BasicDecoder * Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode End of explanation """ def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob): """ Create a decoding layer for inference :param encoder_state: Encoder state :param dec_cell: Decoder RNN Cell :param dec_embeddings: Decoder embeddings :param start_of_sequence_id: GO ID :param end_of_sequence_id: EOS Id :param max_target_sequence_length: Maximum length of target sequences :param vocab_size: Size of decoder/target vocabulary :param decoding_scope: TenorFlow Variable Scope for decoding :param output_layer: Function to apply the output layer :param batch_size: Batch size :param keep_prob: Dropout keep probability :return: BasicDecoderOutput containing inference logits and sample_id """ start_tokens = tf.tile(tf.constant([start_of_sequence_id], dtype=tf.int32), [batch_size], name='start_tokens') # Helper for the inference process. inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings, start_tokens, end_of_sequence_id) # Basic decoder inference_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, inference_helper, encoder_state, output_layer) # Perform dynamic decoding using the decoder inference_decoder_output = tf.contrib.seq2seq.dynamic_decode(inference_decoder, impute_finished=True, maximum_iterations=max_target_sequence_length)[0] return inference_decoder_output """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_decoding_layer_infer(decoding_layer_infer) """ Explanation: Decoding - Inference Create inference decoder: * Create a tf.contrib.seq2seq.GreedyEmbeddingHelper * Create a tf.contrib.seq2seq.BasicDecoder * Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode End of explanation """ def decoding_layer(dec_input, encoder_state, target_sequence_length, max_target_sequence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, decoding_embedding_size): """ Create decoding layer :param dec_input: Decoder input :param encoder_state: Encoder state :param target_sequence_length: The lengths of each sequence in the target batch :param max_target_sequence_length: Maximum length of target sequences :param rnn_size: RNN Size :param num_layers: Number of layers :param target_vocab_to_int: Dictionary to go from the target words to an id :param target_vocab_size: Size of target vocabulary :param batch_size: The size of the batch :param keep_prob: Dropout keep probability :param decoding_embedding_size: Decoding embedding size :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput) """ # 1. Decoder Embedding dec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size])) dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input) # 2. Construct the decoder cell def make_cell(rnn_size): dec_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2)) return dec_cell dec_cell = tf.contrib.rnn.MultiRNNCell([make_cell(rnn_size) for _ in range(num_layers)]) # 3. Dense layer to translate the decoder's output at each time # step into a choice from the target vocabulary output_layer = Dense(target_vocab_size, kernel_initializer = tf.truncated_normal_initializer(mean = 0.0, stddev=0.1)) # 4. Set up a training decoder and an inference decoder # Training Decoder with tf.variable_scope("decode"): training_decoder_output = decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob) # 5. Inference Decoder # Reuses the same parameters trained by the training process with tf.variable_scope("decode", reuse=True): inference_decoder_output = decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, target_vocab_to_int['<GO>'], target_vocab_to_int['<EOS>'], max_target_sequence_length, target_vocab_size, output_layer, batch_size, keep_prob) return training_decoder_output, inference_decoder_output """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_decoding_layer(decoding_layer) """ Explanation: Build the Decoding Layer Implement decoding_layer() to create a Decoder RNN layer. Embed the target sequences Construct the decoder LSTM cell (just like you constructed the encoder cell above) Create an output layer to map the outputs of the decoder to the elements of our vocabulary Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob) function to get the training logits. Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob) function to get the inference logits. Note: You'll need to use tf.variable_scope to share variables between training and inference. End of explanation """ def seq2seq_model(input_data, target_data, keep_prob, batch_size, source_sequence_length, target_sequence_length, max_target_sentence_length, source_vocab_size, target_vocab_size, enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int): """ Build the Sequence-to-Sequence part of the neural network :param input_data: Input placeholder :param target_data: Target placeholder :param keep_prob: Dropout keep probability placeholder :param batch_size: Batch Size :param source_sequence_length: Sequence Lengths of source sequences in the batch :param target_sequence_length: Sequence Lengths of target sequences in the batch :param source_vocab_size: Source vocabulary size :param target_vocab_size: Target vocabulary size :param enc_embedding_size: Decoder embedding size :param dec_embedding_size: Encoder embedding size :param rnn_size: RNN Size :param num_layers: Number of layers :param target_vocab_to_int: Dictionary to go from the target words to an id :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput) """ # Pass the input data through the encoder. We'll ignore the encoder output, but use the state _, enc_state = encoding_layer(input_data, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, enc_embedding_size) # Prepare the target sequences we'll feed to the decoder in training mode dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size) # Pass encoder state and decoder inputs to the decoders training_decoder_output, inference_decoder_output = decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size) return training_decoder_output, inference_decoder_output """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_seq2seq_model(seq2seq_model) """ Explanation: Build the Neural Network Apply the functions you implemented above to: Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size). Process target data using your process_decoder_input(target_data, target_vocab_to_int, batch_size) function. Decode the encoded input using your decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size) function. End of explanation """ # Number of Epochs epochs = 12 # Batch Size batch_size = 512 # RNN Size rnn_size = 128 # Number of Layers num_layers = 2 # Embedding Size encoding_embedding_size = 256 decoding_embedding_size = 256 # Learning Rate learning_rate = 0.001 # Dropout Keep Probability keep_probability = 0.8 display_step = 100 """ Explanation: Neural Network Training Hyperparameters Tune the following parameters: Set epochs to the number of epochs. Set batch_size to the batch size. Set rnn_size to the size of the RNNs. Set num_layers to the number of layers. Set encoding_embedding_size to the size of the embedding for the encoder. Set decoding_embedding_size to the size of the embedding for the decoder. Set learning_rate to the learning rate. Set keep_probability to the Dropout keep probability Set display_step to state how many steps between each debug output statement End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_path = 'checkpoints/dev' (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess() max_target_sentence_length = max([len(sentence) for sentence in source_int_text]) train_graph = tf.Graph() with train_graph.as_default(): input_data, targets, lr, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length = model_inputs() #sequence_length = tf.placeholder_with_default(max_target_sentence_length, None, name='sequence_length') input_shape = tf.shape(input_data) train_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]), targets, keep_prob, batch_size, source_sequence_length, target_sequence_length, max_target_sequence_length, len(source_vocab_to_int), len(target_vocab_to_int), encoding_embedding_size, decoding_embedding_size, rnn_size, num_layers, target_vocab_to_int) training_logits = tf.identity(train_logits.rnn_output, name='logits') inference_logits = tf.identity(inference_logits.sample_id, name='predictions') masks = tf.sequence_mask(target_sequence_length, max_target_sequence_length, dtype=tf.float32, name='masks') with tf.name_scope("optimization"): # Loss function cost = tf.contrib.seq2seq.sequence_loss( training_logits, targets, masks) # Optimizer optimizer = tf.train.AdamOptimizer(lr) # Gradient Clipping gradients = optimizer.compute_gradients(cost) capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None] train_op = optimizer.apply_gradients(capped_gradients) """ Explanation: Build the Graph Build the graph using the neural network you implemented. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ def pad_sentence_batch(sentence_batch, pad_int): """Pad sentences with <PAD> so that each sentence of a batch has the same length""" max_sentence = max([len(sentence) for sentence in sentence_batch]) return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch] def get_batches(sources, targets, batch_size, source_pad_int, target_pad_int): """Batch targets, sources, and the lengths of their sentences together""" for batch_i in range(0, len(sources)//batch_size): start_i = batch_i * batch_size # Slice the right amount for the batch sources_batch = sources[start_i:start_i + batch_size] targets_batch = targets[start_i:start_i + batch_size] # Pad pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int)) pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int)) # Need the lengths for the _lengths parameters pad_targets_lengths = [] for target in pad_targets_batch: pad_targets_lengths.append(len(target)) pad_source_lengths = [] for source in pad_sources_batch: pad_source_lengths.append(len(source)) yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths """ Explanation: Batch and pad the source and target sequences End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ def get_accuracy(target, logits): """ Calculate accuracy """ max_seq = max(target.shape[1], logits.shape[1]) if max_seq - target.shape[1]: target = np.pad( target, [(0,0),(0,max_seq - target.shape[1])], 'constant') if max_seq - logits.shape[1]: logits = np.pad( logits, [(0,0),(0,max_seq - logits.shape[1])], 'constant') return np.mean(np.equal(target, logits)) # Split data to training and validation sets train_source = source_int_text[batch_size:] train_target = target_int_text[batch_size:] valid_source = source_int_text[:batch_size] valid_target = target_int_text[:batch_size] (valid_sources_batch, valid_targets_batch, valid_sources_lengths, valid_targets_lengths ) = next(get_batches(valid_source, valid_target, batch_size, source_vocab_to_int['<PAD>'], target_vocab_to_int['<PAD>'])) with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(epochs): for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumerate( get_batches(train_source, train_target, batch_size, source_vocab_to_int['<PAD>'], target_vocab_to_int['<PAD>'])): _, loss = sess.run( [train_op, cost], {input_data: source_batch, targets: target_batch, lr: learning_rate, target_sequence_length: targets_lengths, source_sequence_length: sources_lengths, keep_prob: keep_probability}) if batch_i % display_step == 0 and batch_i > 0: batch_train_logits = sess.run( inference_logits, {input_data: source_batch, source_sequence_length: sources_lengths, target_sequence_length: targets_lengths, keep_prob: 1.0}) batch_valid_logits = sess.run( inference_logits, {input_data: valid_sources_batch, source_sequence_length: valid_sources_lengths, target_sequence_length: valid_targets_lengths, keep_prob: 1.0}) train_acc = get_accuracy(target_batch, batch_train_logits) valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits) print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.4f}, Validation Accuracy: {:>6.4f}, Loss: {:>6.4f}' .format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss)) # Save Model saver = tf.train.Saver() saver.save(sess, save_path) print('Model Trained and Saved') """ Explanation: Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Save parameters for checkpoint helper.save_params(save_path) """ Explanation: Save Parameters Save the batch_size and save_path parameters for inference. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import tensorflow as tf import numpy as np import helper import problem_unittests as tests _, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess() load_path = helper.load_params() """ Explanation: Checkpoint End of explanation """ def sentence_to_seq(sentence, vocab_to_int): """ Convert a sentence to a sequence of ids :param sentence: String :param vocab_to_int: Dictionary to go from the words to an id :return: List of word ids """ return [vocab_to_int.get(word, vocab_to_int['<UNK>']) for word in sentence.lower().split()] """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_sentence_to_seq(sentence_to_seq) """ Explanation: Sentence to Sequence To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences. Convert the sentence to lowercase Convert words into ids using vocab_to_int Convert words not in the vocabulary, to the &lt;UNK&gt; word id. End of explanation """ translate_sentence = 'he saw a old yellow truck .' """ DON'T MODIFY ANYTHING IN THIS CELL """ translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_path + '.meta') loader.restore(sess, load_path) input_data = loaded_graph.get_tensor_by_name('input:0') logits = loaded_graph.get_tensor_by_name('predictions:0') target_sequence_length = loaded_graph.get_tensor_by_name('target_sequence_length:0') source_sequence_length = loaded_graph.get_tensor_by_name('source_sequence_length:0') keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') translate_logits = sess.run(logits, {input_data: [translate_sentence]*batch_size, target_sequence_length: [len(translate_sentence)*2]*batch_size, source_sequence_length: [len(translate_sentence)]*batch_size, keep_prob: 1.0})[0] print('Input') print(' Word Ids: {}'.format([i for i in translate_sentence])) print(' English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence])) print('\nPrediction') print(' Word Ids: {}'.format([i for i in translate_logits])) print(' French Words: {}'.format(" ".join([target_int_to_vocab[i] for i in translate_logits]))) """ Explanation: Translate This will translate translate_sentence from English to French. End of explanation """
smorton2/think-stats
code/chap03ex.ipynb
gpl-3.0
from __future__ import print_function, division %matplotlib inline import numpy as np import nsfg import first import thinkstats2 import thinkplot """ Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/MIT End of explanation """ preg = nsfg.ReadFemPreg() live = preg[preg.outcome == 1] """ Explanation: Again, I'll load the NSFG pregnancy file and select live births: End of explanation """ hist = thinkstats2.Hist(live.birthwgt_lb, label='birthwgt_lb') thinkplot.Hist(hist) thinkplot.Config(xlabel='Birth weight (pounds)', ylabel='Count') """ Explanation: Here's the histogram of birth weights: End of explanation """ n = hist.Total() pmf = hist.Copy() for x, freq in hist.Items(): pmf[x] = freq / n """ Explanation: To normalize the disrtibution, we could divide through by the total count: End of explanation """ thinkplot.Hist(pmf) thinkplot.Config(xlabel='Birth weight (pounds)', ylabel='PMF') """ Explanation: The result is a Probability Mass Function (PMF). End of explanation """ pmf = thinkstats2.Pmf([1, 2, 2, 3, 5]) pmf """ Explanation: More directly, we can create a Pmf object. End of explanation """ pmf.Prob(2) """ Explanation: Pmf provides Prob, which looks up a value and returns its probability: End of explanation """ pmf[2] """ Explanation: The bracket operator does the same thing. End of explanation """ pmf.Incr(2, 0.2) pmf[2] """ Explanation: The Incr method adds to the probability associated with a given values. End of explanation """ pmf.Mult(2, 0.5) pmf[2] """ Explanation: The Mult method multiplies the probability associated with a value. End of explanation """ pmf.Total() """ Explanation: Total returns the total probability (which is no longer 1, because we changed one of the probabilities). End of explanation """ pmf.Normalize() pmf.Total() """ Explanation: Normalize divides through by the total probability, making it 1 again. End of explanation """ pmf = thinkstats2.Pmf(live.prglngth, label='prglngth') """ Explanation: Here's the PMF of pregnancy length for live births. End of explanation """ thinkplot.Hist(pmf) thinkplot.Config(xlabel='Pregnancy length (weeks)', ylabel='Pmf') """ Explanation: Here's what it looks like plotted with Hist, which makes a bar graph. End of explanation """ thinkplot.Pmf(pmf) thinkplot.Config(xlabel='Pregnancy length (weeks)', ylabel='Pmf') """ Explanation: Here's what it looks like plotted with Pmf, which makes a step function. End of explanation """ live, firsts, others = first.MakeFrames() """ Explanation: We can use MakeFrames to return DataFrames for all live births, first babies, and others. End of explanation """ first_pmf = thinkstats2.Pmf(firsts.prglngth, label='firsts') other_pmf = thinkstats2.Pmf(others.prglngth, label='others') """ Explanation: Here are the distributions of pregnancy length. End of explanation """ width=0.45 axis = [27, 46, 0, 0.6] thinkplot.PrePlot(2, cols=2) thinkplot.Hist(first_pmf, align='right', width=width) thinkplot.Hist(other_pmf, align='left', width=width) thinkplot.Config(xlabel='Pregnancy length(weeks)', ylabel='PMF', axis=axis) thinkplot.PrePlot(2) thinkplot.SubPlot(2) thinkplot.Pmfs([first_pmf, other_pmf]) thinkplot.Config(xlabel='Pregnancy length(weeks)', axis=axis) """ Explanation: And here's the code that replicates one of the figures in the chapter. End of explanation """ weeks = range(35, 46) diffs = [] for week in weeks: p1 = first_pmf.Prob(week) p2 = other_pmf.Prob(week) diff = 100 * (p1 - p2) diffs.append(diff) thinkplot.Bar(weeks, diffs) thinkplot.Config(xlabel='Pregnancy length(weeks)', ylabel='Difference (percentage points)') """ Explanation: Here's the code that generates a plot of the difference in probability (in percentage points) between first babies and others, for each week of pregnancy (showing only pregnancies considered "full term"). End of explanation """ d = { 7: 8, 12: 8, 17: 14, 22: 4, 27: 6, 32: 12, 37: 8, 42: 3, 47: 2 } pmf = thinkstats2.Pmf(d, label='actual') """ Explanation: Biasing and unbiasing PMFs Here's the example in the book showing operations we can perform with Pmf objects. Suppose we have the following distribution of class sizes. End of explanation """ def BiasPmf(pmf, label): new_pmf = pmf.Copy(label=label) for x, p in pmf.Items(): new_pmf.Mult(x, x) new_pmf.Normalize() return new_pmf """ Explanation: This function computes the biased PMF we would get if we surveyed students and asked about the size of the classes they are in. End of explanation """ biased_pmf = BiasPmf(pmf, label='observed') thinkplot.PrePlot(2) thinkplot.Pmfs([pmf, biased_pmf]) thinkplot.Config(xlabel='Class size', ylabel='PMF') """ Explanation: The following graph shows the difference between the actual and observed distributions. End of explanation """ print('Actual mean', pmf.Mean()) print('Observed mean', biased_pmf.Mean()) """ Explanation: The observed mean is substantially higher than the actual. End of explanation """ def UnbiasPmf(pmf, label=None): new_pmf = pmf.Copy(label=label) for x, p in pmf.Items(): new_pmf[x] *= 1/x new_pmf.Normalize() return new_pmf """ Explanation: If we were only able to collect the biased sample, we could "unbias" it by applying the inverse operation. End of explanation """ unbiased = UnbiasPmf(biased_pmf, label='unbiased') print('Unbiased mean', unbiased.Mean()) """ Explanation: We can unbias the biased PMF: End of explanation """ thinkplot.PrePlot(2) thinkplot.Pmfs([pmf, unbiased]) thinkplot.Config(xlabel='Class size', ylabel='PMF') """ Explanation: And plot the two distributions to confirm they are the same. End of explanation """ import numpy as np import pandas array = np.random.randn(4, 2) df = pandas.DataFrame(array) df """ Explanation: Pandas indexing Here's an example of a small DataFrame. End of explanation """ columns = ['A', 'B'] df = pandas.DataFrame(array, columns=columns) df """ Explanation: We can specify column names when we create the DataFrame: End of explanation """ index = ['a', 'b', 'c', 'd'] df = pandas.DataFrame(array, columns=columns, index=index) df """ Explanation: We can also specify an index that contains labels for the rows. End of explanation """ df['A'] """ Explanation: Normal indexing selects columns. End of explanation """ df.loc['a'] """ Explanation: We can use the loc attribute to select rows. End of explanation """ df.iloc[0] """ Explanation: If you don't want to use the row labels and prefer to access the rows using integer indices, you can use the iloc attribute: End of explanation """ indices = ['a', 'c'] df.loc[indices] """ Explanation: loc can also take a list of labels. End of explanation """ df['a':'c'] """ Explanation: If you provide a slice of labels, DataFrame uses it to select rows. End of explanation """ df[0:2] """ Explanation: If you provide a slice of integers, DataFrame selects rows by integer index. End of explanation """ # Create original PMF resp = nsfg.ReadFemResp() numkdhh_pmf = thinkstats2.Pmf(resp['numkdhh'], label='actual') numkdhh_pmf # Create copy and confirm values pmf = numkdhh_pmf.Copy() print(pmf) print(pmf.Total()) print('mean', pmf.Mean()) # Weight PMF by number of children that would respond with each value def BiasPmf(pmf, label): child_pmf = pmf.Copy(label=label) for x, p in pmf.Items(): child_pmf.Mult(x, x) child_pmf.Normalize() return child_pmf child_pmf = BiasPmf(pmf, 'childs_view') print(child_pmf) print(child_pmf.Total()) print('mean', child_pmf.Mean()) # Plot thinkplot.PrePlot(2) thinkplot.Pmfs([pmf, child_pmf]) thinkplot.Show(xlabel='Children In Family', ylabel='PMF') # True mean print('True mean', pmf.Mean()) # Mean based on the children's responses print('Child view mean', child_pmf.Mean()) """ Explanation: But notice that one method includes the last elements of the slice and one does not. In general, I recommend giving labels to the rows and names to the columns, and using them consistently. Exercises Exercise: Something like the class size paradox appears if you survey children and ask how many children are in their family. Families with many children are more likely to appear in your sample, and families with no children have no chance to be in the sample. Use the NSFG respondent variable numkdhh to construct the actual distribution for the number of children under 18 in the respondents' households. Now compute the biased distribution we would see if we surveyed the children and asked them how many children under 18 (including themselves) are in their household. Plot the actual and biased distributions, and compute their means. End of explanation """ def PmfMean(pmf): mean=0 for x, p in pmf.Items(): mean += x*p return mean PmfMean(child_pmf) def PmfVar(pmf): variance=0 pmf_mean=PmfMean(pmf) for x, p in pmf.Items(): variance += p * np.power(x-pmf_mean, 2) return variance PmfVar(child_pmf) print('Check Mean =', PmfMean(child_pmf) == thinkstats2.Pmf.Mean(child_pmf)) print('Check Variance = ', PmfVar(child_pmf) == thinkstats2.Pmf.Var(child_pmf)) """ Explanation: Exercise: Write functions called PmfMean and PmfVar that take a Pmf object and compute the mean and variance. To test these methods, check that they are consistent with the methods Mean and Var provided by Pmf. End of explanation """ live, firsts, others = first.MakeFrames() preg.iloc[0:2].prglngth preg_map = nsfg.MakePregMap(live) hist = thinkstats2.Hist() for case, births in preg_map.items(): if len(births) >= 2: pair = preg.loc[births[0:2]].prglngth diff = pair.iloc[1] - pair.iloc[0] hist[diff] += 1 thinkplot.Hist(hist) pmf = thinkstats2.Pmf(hist) PmfMean(pmf) """ Explanation: Exercise: I started this book with the question, "Are first babies more likely to be late?" To address it, I computed the difference in means between groups of babies, but I ignored the possibility that there might be a difference between first babies and others for the same woman. To address this version of the question, select respondents who have at least two live births and compute pairwise differences. Does this formulation of the question yield a different result? Hint: use nsfg.MakePregMap: End of explanation """ import relay results = relay.ReadResults() speeds = relay.GetSpeeds(results) speeds = relay.BinData(speeds, 3, 12, 100) pmf = thinkstats2.Pmf(speeds, 'actual speeds') thinkplot.Pmf(pmf) thinkplot.Config(xlabel='Speed (mph)', ylabel='PMF') def ObservedPmf(pmf, speed, label): observed_pmf = pmf.Copy(label=label) for value in observed_pmf.Values(): diff = abs(speed - value) observed_pmf[value] *= diff observed_pmf.Normalize() return observed_pmf observed = ObservedPmf(pmf, 7, 'observed speeds') thinkplot.Hist(observed) """ Explanation: Exercise: In most foot races, everyone starts at the same time. If you are a fast runner, you usually pass a lot of people at the beginning of the race, but after a few miles everyone around you is going at the same speed. When I ran a long-distance (209 miles) relay race for the first time, I noticed an odd phenomenon: when I overtook another runner, I was usually much faster, and when another runner overtook me, he was usually much faster. At first I thought that the distribution of speeds might be bimodal; that is, there were many slow runners and many fast runners, but few at my speed. Then I realized that I was the victim of a bias similar to the effect of class size. The race was unusual in two ways: it used a staggered start, so teams started at different times; also, many teams included runners at different levels of ability. As a result, runners were spread out along the course with little relationship between speed and location. When I joined the race, the runners near me were (pretty much) a random sample of the runners in the race. So where does the bias come from? During my time on the course, the chance of overtaking a runner, or being overtaken, is proportional to the difference in our speeds. I am more likely to catch a slow runner, and more likely to be caught by a fast runner. But runners at the same speed are unlikely to see each other. Write a function called ObservedPmf that takes a Pmf representing the actual distribution of runners’ speeds, and the speed of a running observer, and returns a new Pmf representing the distribution of runners’ speeds as seen by the observer. To test your function, you can use relay.py, which reads the results from the James Joyce Ramble 10K in Dedham MA and converts the pace of each runner to mph. Compute the distribution of speeds you would observe if you ran a relay race at 7 mph with this group of runners. End of explanation """
maartenbreddels/ipyvolume
docs/source/examples/volshow.ipynb
mit
import numpy as np import ipyvolume as ipv V = np.zeros((128,128,128)) # our 3d array # outer box V[30:-30,30:-30,30:-30] = 0.75 V[35:-35,35:-35,35:-35] = 0.0 # inner box V[50:-50,50:-50,50:-50] = 0.25 V[55:-55,55:-55,55:-55] = 0.0 ipv.figure() ipv.volshow(V, level=[0.25, 0.75], opacity=0.03, level_width=0.1, data_min=0, data_max=1) ipv.view(-30, 40) ipv.show() """ Explanation: Volshow A simple volume rendering example Using the pylab API End of explanation """ import ipyvolume as ipv fig = ipv.figure() vol_head = ipv.examples.head(max_shape=128); vol_head.ray_steps = 400 ipv.view(90, 0) """ Explanation: Visualizating a scan of a male head Included in ipyvolume, is a visualuzation of a scan of a human head, see the sourcecode for more details. End of explanation """
mne-tools/mne-tools.github.io
0.20/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb
bsd-3-clause
import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(tmax=60).load_data() """ Explanation: Built-in plotting methods for Raw objects This tutorial shows how to plot continuous data as a time series, how to plot the spectral density of continuous data, and how to plot the sensor locations and projectors stored in :class:~mne.io.Raw objects. :depth: 2 As usual we'll start by importing the modules we need, loading some example data &lt;sample-dataset&gt;, and cropping the :class:~mne.io.Raw object to just 60 seconds before loading it into RAM to save memory: End of explanation """ raw.plot() """ Explanation: We've seen in a previous tutorial &lt;tut-raw-class&gt; how to plot data from a :class:~mne.io.Raw object using :doc:matplotlib &lt;matplotlib:index&gt;, but :class:~mne.io.Raw objects also have several built-in plotting methods: :meth:~mne.io.Raw.plot :meth:~mne.io.Raw.plot_psd :meth:~mne.io.Raw.plot_psd_topo :meth:~mne.io.Raw.plot_sensors :meth:~mne.io.Raw.plot_projs_topomap The first three are discussed here in detail; the last two are shown briefly and covered in-depth in other tutorials. Interactive data browsing with Raw.plot() The :meth:~mne.io.Raw.plot method of :class:~mne.io.Raw objects provides a versatile interface for exploring continuous data. For interactive viewing and data quality checking, it can be called with no additional parameters: End of explanation """ raw.plot_psd(average=True) """ Explanation: It may not be obvious when viewing this tutorial online, but by default, the :meth:~mne.io.Raw.plot method generates an interactive plot window with several useful features: It spaces the channels equally along the y-axis. 20 channels are shown by default; you can scroll through the channels using the :kbd:↑ and :kbd:↓ arrow keys, or by clicking on the colored scroll bar on the right edge of the plot. The number of visible channels can be adjusted by the n_channels parameter, or changed interactively using :kbd:page up and :kbd:page down keys. You can toggle the display to "butterfly" mode (superimposing all channels of the same type on top of one another) by pressing :kbd:b, or start in butterfly mode by passing the butterfly=True parameter. It shows the first 10 seconds of the :class:~mne.io.Raw object. You can shorten or lengthen the window length using :kbd:home and :kbd:end keys, or start with a specific window duration by passing the duration parameter. You can scroll in the time domain using the :kbd:← and :kbd:→ arrow keys, or start at a specific point by passing the start parameter. Scrolling using :kbd:shift:kbd:→ or :kbd:shift:kbd:← scrolls a full window width at a time. It allows clicking on channels to mark/unmark as "bad". When the plot window is closed, the :class:~mne.io.Raw object's info attribute will be updated, adding or removing the newly (un)marked channels to/from the :class:~mne.Info object's bads field (A.K.A. raw.info['bads']). .. TODO: discuss annotation snapping in the below bullets It allows interactive :term:annotation &lt;annotations&gt; of the raw data. This allows you to mark time spans that should be excluded from future computations due to large movement artifacts, line noise, or other distortions of the signal. Annotation mode is entered by pressing :kbd:a. See annotations-tutorial for details. It automatically applies any :term:projectors &lt;projector&gt; before plotting the data. These can be enabled/disabled interactively by clicking the Proj button at the lower right corner of the plot window, or disabled by default by passing the proj=False parameter. See tut-projectors-background for more info on projectors. These and other keyboard shortcuts are listed in the Help window, accessed through the Help button at the lower left corner of the plot window. Other plot properties (such as color of the channel traces, channel order and grouping, simultaneous plotting of :term:events, scaling, clipping, filtering, etc.) can also be adjusted through parameters passed to the :meth:~mne.io.Raw.plot method; see the docstring for details. Plotting spectral density of continuous data To visualize the frequency content of continuous data, the :class:~mne.io.Raw object provides a :meth:~mne.io.Raw.plot_psd to plot the spectral density_ of the data. End of explanation """ midline = ['EEG 002', 'EEG 012', 'EEG 030', 'EEG 048', 'EEG 058', 'EEG 060'] raw.plot_psd(picks=midline) """ Explanation: If the data have been filtered, vertical dashed lines will automatically indicate filter boundaries. The spectrum for each channel type is drawn in its own subplot; here we've passed the average=True parameter to get a summary for each channel type, but it is also possible to plot each channel individually, with options for how the spectrum should be computed, color-coding the channels by location, and more. For example, here is a plot of just a few sensors (specified with the picks parameter), color-coded by spatial location (via the spatial_colors parameter, see the documentation of :meth:~mne.io.Raw.plot_psd for full details): End of explanation """ raw.plot_psd_topo() """ Explanation: Alternatively, you can plot the PSD for every sensor on its own axes, with the axes arranged spatially to correspond to sensor locations in space, using :meth:~mne.io.Raw.plot_psd_topo: End of explanation """ raw.copy().pick_types(meg=False, eeg=True).plot_psd_topo() """ Explanation: This plot is also interactive; hovering over each "thumbnail" plot will display the channel name in the bottom left of the plot window, and clicking on a thumbnail plot will create a second figure showing a larger version of the selected channel's spectral density (as if you had called :meth:~mne.io.Raw.plot_psd on that channel). By default, :meth:~mne.io.Raw.plot_psd_topo will show only the MEG channels if MEG channels are present; if only EEG channels are found, they will be plotted instead: End of explanation """ raw.plot_sensors(ch_type='eeg') """ Explanation: Plotting sensor locations from Raw objects The channel locations in a :class:~mne.io.Raw object can be easily plotted with the :meth:~mne.io.Raw.plot_sensors method. A brief example is shown here; notice that channels in raw.info['bads'] are plotted in red. More details and additional examples are given in the tutorial tut-sensor-locations. End of explanation """ raw.plot_projs_topomap(colorbar=True) """ Explanation: Plotting projectors from Raw objects As seen in the output of :meth:mne.io.read_raw_fif above, there are :term:projectors &lt;projector&gt; included in the example :class:~mne.io.Raw file (representing environmental noise in the signal, so it can later be "projected out" during preprocessing). You can visualize these projectors using the :meth:~mne.io.Raw.plot_projs_topomap method. By default it will show one figure per channel type for which projectors are present, and each figure will have one subplot per projector. The three projectors in this file were only computed for magnetometers, so one figure with three subplots is generated. More details on working with and plotting projectors are given in tut-projectors-background and tut-artifact-ssp. End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/nims-kma/cmip6/models/sandbox-3/atmoschem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-3', 'atmoschem') """ Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-3 Topic: Atmoschem Sub-Topics: Transport, Emissions Concentrations, Gas Phase Chemistry, Stratospheric Heterogeneous Chemistry, Tropospheric Heterogeneous Chemistry, Photo Chemistry. Properties: 84 (39 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:29 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Key Properties --&gt; Timestep Framework 4. Key Properties --&gt; Timestep Framework --&gt; Split Operator Order 5. Key Properties --&gt; Tuning Applied 6. Grid 7. Grid --&gt; Resolution 8. Transport 9. Emissions Concentrations 10. Emissions Concentrations --&gt; Surface Emissions 11. Emissions Concentrations --&gt; Atmospheric Emissions 12. Emissions Concentrations --&gt; Concentrations 13. Gas Phase Chemistry 14. Stratospheric Heterogeneous Chemistry 15. Tropospheric Heterogeneous Chemistry 16. Photo Chemistry 17. Photo Chemistry --&gt; Photolysis 1. Key Properties Key properties of the atmospheric chemistry 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmospheric chemistry model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of atmospheric chemistry model code. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.chemistry_scheme_scope') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "troposhere" # "stratosphere" # "mesosphere" # "mesosphere" # "whole atmosphere" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Chemistry Scheme Scope Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Atmospheric domains covered by the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.basic_approximations') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basic approximations made in the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.prognostic_variables_form') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "3D mass/mixing ratio for gas" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.5. Prognostic Variables Form Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Form of prognostic variables in the atmospheric chemistry component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.number_of_tracers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 1.6. Number Of Tracers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of advected tracers in the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.family_approach') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.7. Family Approach Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry calculations (not advection) generalized into families of species? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.coupling_with_chemical_reactivity') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.8. Coupling With Chemical Reactivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry transport scheme turbulence is couple with chemical reactivity? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Software Properties Software properties of aerosol code 2.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Operator splitting" # "Integrated" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestep Framework Timestepping in the atmospheric chemistry model 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Mathematical method deployed to solve the evolution of a given variable End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_advection_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.2. Split Operator Advection Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemical species advection (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_physical_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.3. Split Operator Physical Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for physics (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_chemistry_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.4. Split Operator Chemistry Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemistry (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_alternate_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3.5. Split Operator Alternate Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.6. Integrated Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the atmospheric chemistry model (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Explicit" # "Implicit" # "Semi-implicit" # "Semi-analytic" # "Impact solver" # "Back Euler" # "Newton Raphson" # "Rosenbrock" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3.7. Integrated Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the type of timestep scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.turbulence') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Timestep Framework --&gt; Split Operator Order ** 4.1. Turbulence Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for turbulence scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.convection') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.2. Convection Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for convection scheme This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.precipitation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.3. Precipitation Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for precipitation scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.emissions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.4. Emissions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for emissions scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.5. Deposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for deposition scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.gas_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.6. Gas Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for gas phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.tropospheric_heterogeneous_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.7. Tropospheric Heterogeneous Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for tropospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.stratospheric_heterogeneous_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.8. Stratospheric Heterogeneous Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for stratospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.photo_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.9. Photo Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for photo chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.aerosols') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.10. Aerosols Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for aerosols scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Tuning Applied Tuning methodology for atmospheric chemistry component 5.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview description of tuning: explain and motivate the main targets and metrics retained. &amp;Document the relative weight given to climate performance metrics versus process oriented metrics, &amp;and on the possible conflicts with parameterization level tuning. In particular describe any struggle &amp;with a parameter value that required pushing it to its limits to solve a particular model deficiency. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics of the global mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics of mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Grid Atmospheric chemistry grid 6.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the atmopsheric chemistry grid End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.matches_atmosphere_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.2. Matches Atmosphere Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 * Does the atmospheric chemistry grid match the atmosphere grid?* End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Grid --&gt; Resolution Resolution in the atmospheric chemistry grid 7.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Canonical Horizontal Resolution Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.number_of_horizontal_gridpoints') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.3. Number Of Horizontal Gridpoints Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Total number of horizontal (XY) points (or degrees of freedom) on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.4. Number Of Vertical Levels Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Number of vertical levels resolved on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.is_adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 7.5. Is Adaptive Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Default is False. Set true if grid resolution changes during execution. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Transport Atmospheric chemistry transport 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview of transport implementation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.use_atmospheric_transport') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 8.2. Use Atmospheric Transport Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is transport handled by the atmosphere, rather than within atmospheric cehmistry? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.transport_details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.3. Transport Details Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If transport is handled within the atmospheric chemistry scheme, describe it. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Emissions Concentrations Atmospheric chemistry emissions 9.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview atmospheric chemistry emissions End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Vegetation" # "Soil" # "Sea surface" # "Anthropogenic" # "Biomass burning" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10. Emissions Concentrations --&gt; Surface Emissions ** 10.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of the chemical species emitted at the surface that are taken into account in the emissions scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Climatology" # "Spatially uniform mixing ratio" # "Spatially uniform concentration" # "Interactive" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.2. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Methods used to define chemical species emitted directly into model layers above the surface (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed via a climatology, and the nature of the climatology (E.g. CO (monthly), C2H6 (constant)) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.4. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.6. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via any other method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Aircraft" # "Biomass burning" # "Lightning" # "Volcanos" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11. Emissions Concentrations --&gt; Atmospheric Emissions TO DO 11.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of chemical species emitted in the atmosphere that are taken into account in the emissions scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Climatology" # "Spatially uniform mixing ratio" # "Spatially uniform concentration" # "Interactive" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Methods used to define the chemical species emitted in the atmosphere (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed via a climatology (E.g. CO (monthly), C2H6 (constant)) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.4. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.6. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and specified via an &quot;other method&quot; End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_lower_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12. Emissions Concentrations --&gt; Concentrations TO DO 12.1. Prescribed Lower Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the lower boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_upper_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.2. Prescribed Upper Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the upper boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 13. Gas Phase Chemistry Atmospheric chemistry transport 13.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview gas phase atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HOx" # "NOy" # "Ox" # "Cly" # "HSOx" # "Bry" # "VOCs" # "isoprene" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Species included in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_bimolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.3. Number Of Bimolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of bi-molecular reactions in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_termolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.4. Number Of Termolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of ter-molecular reactions in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_tropospheric_heterogenous_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.5. Number Of Tropospheric Heterogenous Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_stratospheric_heterogenous_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.6. Number Of Stratospheric Heterogenous Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_advected_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.7. Number Of Advected Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of advected species in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.8. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of gas phase species for which the concentration is updated in the chemical solver assuming photochemical steady state End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.interactive_dry_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.9. Interactive Dry Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.10. Wet Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet deposition included? Wet deposition describes the moist processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_oxidation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.11. Wet Oxidation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet oxidation included? Oxidation describes the loss of electrons or an increase in oxidation state by a molecule End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14. Stratospheric Heterogeneous Chemistry Atmospheric chemistry startospheric heterogeneous chemistry 14.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview stratospheric heterogenous atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Cly" # "Bry" # "NOy" # TODO - please enter value(s) """ Explanation: 14.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Gas phase species included in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Polar stratospheric ice" # "NAT (Nitric acid trihydrate)" # "NAD (Nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particule))" # TODO - please enter value(s) """ Explanation: 14.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.sedimentation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.5. Sedimentation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sedimentation is included in the stratospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the stratospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Tropospheric Heterogeneous Chemistry Atmospheric chemistry tropospheric heterogeneous chemistry 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview tropospheric heterogenous atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of gas phase species included in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Nitrate" # "Sea salt" # "Dust" # "Ice" # "Organic" # "Black carbon/soot" # "Polar stratospheric ice" # "Secondary organic aerosols" # "Particulate organic matter" # TODO - please enter value(s) """ Explanation: 15.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.interactive_dry_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.5. Interactive Dry Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the tropospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 16. Photo Chemistry Atmospheric chemistry photo chemistry 16.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview atmospheric photo chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.number_of_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 16.2. Number Of Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the photo-chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline (clear sky)" # "Offline (with clouds)" # "Online" # TODO - please enter value(s) """ Explanation: 17. Photo Chemistry --&gt; Photolysis Photolysis scheme 17.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Photolysis scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.environmental_conditions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.2. Environmental Conditions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any environmental conditions taken into account by the photolysis scheme (e.g. whether pressure- and temperature-sensitive cross-sections and quantum yields in the photolysis calculations are modified to reflect the modelled conditions.) End of explanation """
joshnsolomon/phys202-2015-work
assignments/assignment03/NumpyEx03.ipynb
mit
import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va """ Explanation: Numpy Exercise 3 Imports End of explanation """ def brownian(maxt, n): """Return one realization of a Brownian (Wiener) process with n steps and a max time of t.""" t = np.linspace(0.0,maxt,n) h = t[1]-t[0] Z = np.random.normal(0.0,1.0,n-1) dW = np.sqrt(h)*Z W = np.zeros(n) W[1:] = dW.cumsum() return t, W """ Explanation: Geometric Brownian motion Here is a function that produces standard Brownian motion using NumPy. This is also known as a Wiener Process. End of explanation """ # YOUR CODE HERE t, W = brownian(1.0,1000) assert isinstance(t, np.ndarray) assert isinstance(W, np.ndarray) assert t.dtype==np.dtype(float) assert W.dtype==np.dtype(float) assert len(t)==len(W)==1000 """ Explanation: Call the brownian function to simulate a Wiener process with 1000 steps and max time of 1.0. Save the results as two arrays t and W. End of explanation """ # YOUR CODE HERE plt.plot(t,W) plt.xlabel('time') plt.ylabel('Wiener Process') assert True # this is for grading """ Explanation: Visualize the process using plt.plot with t on the x-axis and W(t) on the y-axis. Label your x and y axes. End of explanation """ # YOUR CODE HERE dW = np.diff(W) mean = dW.mean() standard_deviation = dW.std() mean, standard_deviation assert len(dW)==len(W)-1 assert dW.dtype==np.dtype(float) """ Explanation: Use np.diff to compute the changes at each step of the motion, dW, and then compute the mean and standard deviation of those differences. End of explanation """ def geo_brownian(t, W, X0, mu, sigma): "Return X(t) for geometric brownian motion with drift mu, volatility sigma.""" Xt = X0*np.exp((((mu-(sigma**2))/2)*t)+(sigma*W)) return Xt assert True # leave this for grading """ Explanation: Write a function that takes $W(t)$ and converts it to geometric Brownian motion using the equation: $$ X(t) = X_0 e^{((\mu - \sigma^2/2)t + \sigma W(t))} $$ Use Numpy ufuncs and no loops in your function. End of explanation """ # YOUR CODE HERE Xt = geo_brownian(t, W, 1.0, .5, .3) plt.plot(t,Xt) plt.xlabel('time') plt.ylabel('position') assert True # leave this for grading """ Explanation: Use your function to simulate geometric brownian motion, $X(t)$ for $X_0=1.0$, $\mu=0.5$ and $\sigma=0.3$ with the Wiener process you computed above. Visualize the process using plt.plot with t on the x-axis and X(t) on the y-axis. Label your x and y axes. End of explanation """
xmunoz/sodapy
examples/basic_queries.ipynb
mit
import os import pandas as pd import numpy as np from sodapy import Socrata """ Explanation: Example 01: Basic Queries Retrieving data from Socrata databases using sodapy Setup End of explanation """ # Enter the information from those sections here socrata_domain = 'opendata.socrata.com' socrata_dataset_identifier = 'f92i-ik66' # App Tokens can be generated by creating an account at https://opendata.socrata.com/signup # Tokens are optional (`None` can be used instead), though requests will be rate limited. # # If you choose to use a token, run the following command on the terminal (or add it to your .bashrc) # $ export SODAPY_APPTOKEN=<token> socrata_token = os.environ.get("SODAPY_APPTOKEN") """ Explanation: Find some data Though any organization can host their own data with Socrata's tools, Socrata also hosts several open datasets themselves: https://opendata.socrata.com/browse The following search options can help you find some great datasets for getting started: * Limit to data sets (pre-analyzed stuff is great, but if you're using sodapy you probably want the raw numbers!) * Sort by "Most Accessed" Here's a link that applies those filters automatically. Click on a few listings until you find one that looks interesting. Then click API and extract the following bits of data from the displayed url. https://<opendata.socrata.com>/dataset/Santa-Fe-Contributors/<f92i-ik66>.json End of explanation """ client = Socrata(socrata_domain, socrata_token) print("Domain: {domain:}\nSession: {session:}\nURI Prefix: {uri_prefix:}".format(**client.__dict__)) results = client.get(socrata_dataset_identifier) df = pd.DataFrame.from_dict(results) df.head() """ Explanation: Get all the data End of explanation """ df['amount'] = df['amount'].astype(float) by_candidate = df.groupby('recipient').amount.aggregate([np.sum, np.mean, np.size]).round(0) by_candidate.sort_values('sum', ascending=False).head() """ Explanation: Success! Let's do some minimal cleaning and analysis just to justify the bandwidth used. End of explanation """ nyc_domain = 'data.cityofnewyork.us' nyc_dataset_identifier = 'fhrw-4uyv' nyc_client = Socrata(nyc_domain, socrata_token) nyc_results = nyc_client.get(nyc_dataset_identifier) nyc_df = pd.DataFrame.from_dict(nyc_results) print(nyc_df.shape) chatt_domain = 'data.chattlibrary.org' chatt_dataset_identifier = 'sf89-4qcw' chatt_client = Socrata(chatt_domain, socrata_token) chatt_results = chatt_client.get(chatt_dataset_identifier) chatt_df = pd.DataFrame.from_dict(chatt_results) print(chatt_df.shape) # extract tree-related complaints tree_related = pd.concat([ nyc_df.complaint_type.str.contains(r'[T|t]ree').value_counts(), chatt_df.description.str.contains(r'[T|t]ree').value_counts() ], axis=1, keys=['nyc', 'chatt']) tree_related.div(tree_related.sum()).round(2) """ Explanation: Multiple Data Sources That was much less annoying than downloading a CSV, though you can always save the dataframe to a CSV if you'd like. Where sodapy really shines though is in grabbing different data sources and mashing them together. For example, let's compare 311 calls between New York City and Chattanooga, TN. Socrata makes it so easy, you'd be crazy not to do it! End of explanation """
wuafeing/Python3-Tutorial
02 strings and text/02.08 regexp for multiline partterns.ipynb
gpl-3.0
import re comment = re.compile(r"/\*(.*?)\*/") text1 = '/* this is a comment */' text2 = '''/* this is a multiline comment */ ''' comment.findall(text1) comment.findall(text2) """ Explanation: Previous 2.8 多行匹配模式 问题 你正在试着使用正则表达式去匹配一大块的文本,而你需要跨越多行去匹配。 解决方案 这个问题很典型的出现在当你用点 (.) 去匹配任意字符的时候,忘记了点 (.) 不能匹配换行符的事实。 比如,假设你想试着去匹配 C 语言分割的注释: End of explanation """ comment = re.compile(r'/\*((?:.|\n)*?)\*/') comment.findall(text2) """ Explanation: 为了修正这个问题,你可以修改模式字符串,增加对换行的支持。比如: End of explanation """ comment = re.compile(r'/\*(.*?)\*/', re.DOTALL) comment.findall(text2) """ Explanation: 在这个模式中, (?:.|\n) 指定了一个非捕获组 (也就是它定义了一个仅仅用来做匹配,而不能通过单独捕获或者编号的组)。 讨论 re.compile() 函数接受一个标志参数叫 re.DOTALL ,在这里非常有用。 它可以让正则表达式中的点 (.) 匹配包括换行符在内的任意字符。比如: End of explanation """
gaufung/Data_Analytics_Learning_Note
Probability-Theory/Chapter_02.ipynb
mit
import numpy as np import matplotlib.pyplot as plt plt.plot([1,2], [1,1], linewidth=2,c='k') plt.plot([1,1], [0,1],'k--', linewidth=2) plt.plot([2,2], [0,1],'k--', linewidth=2) plt.plot([0,1], [1,1],'k--') plt.xticks([1,2],[r'$a$',r'$b$']) plt.yticks([1],[r'$\frac{1}{b-a}$']) plt.xlabel('x') plt.ylabel(r'$f(x)$') plt.axis([0, 2.5, 0, 2]) gca = plt.gca() gca.spines['right'].set_color('none') gca.spines['top'].set_color('none') gca.xaxis.set_ticks_position('bottom') gca.yaxis.set_ticks_position('left') plt.show() """ Explanation: Chapter02 1 Discrete random variable 1.1 (0-1) distribution $P(X=k)=p^k(1-p)^{1-k}, k=0,1 \space (0<p<1)$ 1.2 binomial distribution $P(X=k)=C_n^kp^k(1-p)^{n-k}, \space k=0,1,\ldots,n \space (0<p<1)$ Marked as $X \sim B(n,p)$ 1.3 possion Distribution $P(X=k)=\frac{\lambda^k e^{-\lambda}}{k!} \space \lambda > 0,\space k=0,1,2,\ldots$. Marked as $X\sim \pi(\lambda)$ If $X \sim B(n,p)$ and $n$ is big enough and $p$ is small enough, then: $$P(X=k)=C_n^kp^k(1-p)^{n-k} \approx \frac{\lambda^k e^{-\lambda}}{k!} $$ where: $\lambda=np$ 1.4 geometric distribution $P(X=k)=(1-p)^{k-1}p, \space k=1,2,3,\dots$ 2 Continues random variables 2.1 uniform distribution $$f(x)=\begin{cases} \frac{1}{b-a}, a<x<b \ 0, others \end{cases}$$ End of explanation """ import numpy as np import matplotlib.pyplot as plt lam = 5 x = np.linspace(0.01, 1, 1000) f_x = lam * np.power(np.e, -1.0*lam*x) plt.plot(x, f_x) plt.xlabel('x') plt.ylabel(r'$f(x)$') plt.axis([0, 1.1, 0, 2]) plt.xticks(()) plt.yticks(()) gca = plt.gca() gca.spines['right'].set_color('none') gca.spines['top'].set_color('none') gca.xaxis.set_ticks_position('bottom') gca.yaxis.set_ticks_position('left') plt.show() """ Explanation: 2.2 exponential distribution $$f(x)= \begin{cases} \lambda e^{-\lambda x}, x >0 \ 0, x \le 0 \end{cases}$$ End of explanation """ import math import numpy as np import matplotlib.pyplot as plt def gauss(x, mu, sigma): return 1.0 / (np.sqrt(2*np.pi) * sigma) * np.power(np.e, -1.0 * np.power(x-1, 2)/ (2)) mu = 1.0 sigma = 1.0 x = np.linspace(-2.0, 4.0, 1000) y = gauss(x, mu, sigma) plt.plot(x, y) plt.xticks([1.0], [r'$\mu$']) plt.yticks(()) plt.xlabel('x') plt.plot([1.0, 1.0],[0.0, gauss(1.0, mu, sigma)], 'k--') plt.plot([0,1.0],[gauss(1.0, mu, sigma),gauss(1.0, mu, sigma)],'k--') plt.text(0-.2, gauss(1.0, mu, sigma), r'$\frac{1}{\sqrt{2\pi}}$',ha='right', va='center') plt.axis([-3,5,0,0.5]) #plt.(r'$\frac{1}{\sqrt{2\pi}}e^{-\frac{(x-1)^{2}}{2\sigma^2}}$') gca = plt.gca() gca.spines['right'].set_color('none') gca.spines['top'].set_color('none') gca.xaxis.set_ticks_position('bottom') gca.spines['bottom'].set_position(('data',0)) gca.yaxis.set_ticks_position('left') gca.spines['left'].set_position(('data',0)) plt.show() """ Explanation: 2.3 normal distribution $$f(x)= \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^{2}}{2\sigma^2}} $$ where: $-\infty < x < \infty$ End of explanation """
samgoodgame/sf_crime
supporting_notebook.ipynb
mit
# Import relevant libraries: import time import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn import preprocessing from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import GaussianNB from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn.metrics import log_loss from sklearn.linear_model import LogisticRegression from sklearn import svm from sklearn.neural_network import MLPClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import GradientBoostingClassifier # Import Meta-estimators from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import BaggingClassifier # Import Calibration tools from sklearn.calibration import CalibratedClassifierCV # Set random seed and format print output: np.random.seed(0) np.set_printoptions(precision=3) """ Explanation: Kaggle San Francisco Crime Classification: Supporting Notebook UCB MIDS W207 Final Project: Sam Goodgame, Sarah Cha, Kalvin Kao, Bryan Moore Purpose This notebook will supoort the final, refined notebook submitted for the Berkeley MIDS W207 Final Project. This notebook contains code and markdown that contirbuted to our final notebook, graphs, and formal presentation. It serves as a reference for the final notebook. Throughout this notebook, there are local dependencies that will require data pathways to local files. These will be supressed for viewing comfort, as to not overwhelm the notebook with errors. Environment Engineering End of explanation """ #data_path = "./data/train_transformed.csv" #df = pd.read_csv(data_path, header=0) #x_data = df.drop('category', 1) #y = df.category.as_matrix() ########## Adding the date back into the data #import csv #import time #import calendar #data_path = "./data/train.csv" #dataCSV = open(data_path, 'rt') #csvData = list(csv.reader(dataCSV)) #csvFields = csvData[0] #['Dates', 'Category', 'Descript', 'DayOfWeek', 'PdDistrict', 'Resolution', 'Address', 'X', 'Y'] #allData = csvData[1:] #dataCSV.close() #df2 = pd.DataFrame(allData) #df2.columns = csvFields #dates = df2['Dates'] #dates = dates.apply(time.strptime, args=("%Y-%m-%d %H:%M:%S",)) #dates = dates.apply(calendar.timegm) #print(dates.head()) #x_data['secondsFromEpoch'] = dates #colnames = x_data.columns.tolist() #colnames = colnames[-1:] + colnames[:-1] #x_data = x_data[colnames] ########## ########## Adding the weather data into the original crime data #weatherData1 = "./data/1027175.csv" #weatherData2 = "./data/1027176.csv" #dataCSV = open(weatherData1, 'rt') #csvData = list(csv.reader(dataCSV)) #csvFields = csvData[0] #['Dates', 'Category', 'Descript', 'DayOfWeek', 'PdDistrict', 'Resolution', 'Address', 'X', 'Y'] #allWeatherData1 = csvData[1:] #dataCSV.close() #dataCSV = open(weatherData2, 'rt') #csvData = list(csv.reader(dataCSV)) #csvFields = csvData[0] #['Dates', 'Category', 'Descript', 'DayOfWeek', 'PdDistrict', 'Resolution', 'Address', 'X', 'Y'] #allWeatherData2 = csvData[1:] #dataCSV.close() #weatherDF1 = pd.DataFrame(allWeatherData1) #weatherDF1.columns = csvFields #dates1 = weatherDF1['DATE'] #sunrise1 = weatherDF1['DAILYSunrise'] #sunset1 = weatherDF1['DAILYSunset'] #weatherDF2 = pd.DataFrame(allWeatherData2) #weatherDF2.columns = csvFields #dates2 = weatherDF2['DATE'] #sunrise2 = weatherDF2['DAILYSunrise'] #sunset2 = weatherDF2['DAILYSunset'] #functions for processing the sunrise and sunset times of each day #def get_hour_and_minute(milTime): # hour = int(milTime[:-2]) # minute = int(milTime[-2:]) # return [hour, minute] #def get_date_only(date): # return time.struct_time(tuple([date[0], date[1], date[2], 0, 0, 0, date[6], date[7], date[8]])) #def structure_sun_time(timeSeries, dateSeries): # sunTimes = timeSeries.copy() # for index in range(len(dateSeries)): # sunTimes[index] = time.struct_time(tuple([dateSeries[index][0], dateSeries[index][1], dateSeries[index][2], timeSeries[index][0], timeSeries[index][1], dateSeries[index][5], dateSeries[index][6], dateSeries[index][7], dateSeries[index][8]])) # return sunTimes #dates1 = dates1.apply(time.strptime, args=("%Y-%m-%d %H:%M",)) #sunrise1 = sunrise1.apply(get_hour_and_minute) #sunrise1 = structure_sun_time(sunrise1, dates1) #sunrise1 = sunrise1.apply(calendar.timegm) #sunset1 = sunset1.apply(get_hour_and_minute) #sunset1 = structure_sun_time(sunset1, dates1) #sunset1 = sunset1.apply(calendar.timegm) #dates1 = dates1.apply(calendar.timegm) #dates2 = dates2.apply(time.strptime, args=("%Y-%m-%d %H:%M",)) #sunrise2 = sunrise2.apply(get_hour_and_minute) #sunrise2 = structure_sun_time(sunrise2, dates2) #sunrise2 = sunrise2.apply(calendar.timegm) #sunset2 = sunset2.apply(get_hour_and_minute) #sunset2 = structure_sun_time(sunset2, dates2) #sunset2 = sunset2.apply(calendar.timegm) #dates2 = dates2.apply(calendar.timegm) #weatherDF1['DATE'] = dates1 #weatherDF1['DAILYSunrise'] = sunrise1 #weatherDF1['DAILYSunset'] = sunset1 #weatherDF2['DATE'] = dates2 #weatherDF2['DAILYSunrise'] = sunrise2 #weatherDF2['DAILYSunset'] = sunset2 #weatherDF = pd.concat([weatherDF1,weatherDF2[32:]],ignore_index=True) # Starting off with some of the easier features to work with-- more to come here . . . still in beta #weatherMetrics = weatherDF[['DATE','HOURLYDRYBULBTEMPF','HOURLYRelativeHumidity', 'HOURLYWindSpeed', \ # 'HOURLYSeaLevelPressure', 'HOURLYVISIBILITY', 'DAILYSunrise', 'DAILYSunset']] #weatherMetrics = weatherMetrics.convert_objects(convert_numeric=True) #weatherDates = weatherMetrics['DATE'] #'DATE','HOURLYDRYBULBTEMPF','HOURLYRelativeHumidity', 'HOURLYWindSpeed', #'HOURLYSeaLevelPressure', 'HOURLYVISIBILITY' #timeWindow = 10800 #3 hours #hourlyDryBulbTemp = [] #hourlyRelativeHumidity = [] #hourlyWindSpeed = [] #hourlySeaLevelPressure = [] #hourlyVisibility = [] #dailySunrise = [] #dailySunset = [] #daylight = [] #test = 0 #for timePoint in dates:#dates is the epoch time from the kaggle data # relevantWeather = weatherMetrics[(weatherDates <= timePoint) & (weatherDates > timePoint - timeWindow)] # hourlyDryBulbTemp.append(relevantWeather['HOURLYDRYBULBTEMPF'].mean()) # hourlyRelativeHumidity.append(relevantWeather['HOURLYRelativeHumidity'].mean()) # hourlyWindSpeed.append(relevantWeather['HOURLYWindSpeed'].mean()) # hourlySeaLevelPressure.append(relevantWeather['HOURLYSeaLevelPressure'].mean()) # hourlyVisibility.append(relevantWeather['HOURLYVISIBILITY'].mean()) # dailySunrise.append(relevantWeather['DAILYSunrise'].iloc[-1]) # dailySunset.append(relevantWeather['DAILYSunset'].iloc[-1]) # daylight.append(1.0*((timePoint >= relevantWeather['DAILYSunrise'].iloc[-1]) and (timePoint < relevantWeather['DAILYSunset'].iloc[-1]))) #if timePoint < relevantWeather['DAILYSunset'][-1]: #daylight.append(1) #else: #daylight.append(0) # if test%100000 == 0: # print(relevantWeather) # test += 1 #hourlyDryBulbTemp = pd.Series.from_array(np.array(hourlyDryBulbTemp)) #hourlyRelativeHumidity = pd.Series.from_array(np.array(hourlyRelativeHumidity)) #hourlyWindSpeed = pd.Series.from_array(np.array(hourlyWindSpeed)) #hourlySeaLevelPressure = pd.Series.from_array(np.array(hourlySeaLevelPressure)) #hourlyVisibility = pd.Series.from_array(np.array(hourlyVisibility)) #dailySunrise = pd.Series.from_array(np.array(dailySunrise)) #dailySunset = pd.Series.from_array(np.array(dailySunset)) #daylight = pd.Series.from_array(np.array(daylight)) #x_data['HOURLYDRYBULBTEMPF'] = hourlyDryBulbTemp #x_data['HOURLYRelativeHumidity'] = hourlyRelativeHumidity #x_data['HOURLYWindSpeed'] = hourlyWindSpeed #x_data['HOURLYSeaLevelPressure'] = hourlySeaLevelPressure #x_data['HOURLYVISIBILITY'] = hourlyVisibility #x_data['DAILYSunrise'] = dailySunrise #x_data['DAILYSunset'] = dailySunset #x_data['Daylight'] = daylight #x_data.to_csv(path_or_buf="C:/MIDS/W207 final project/x_data.csv") ########## # Impute missing values with mean values: #x_complete = x_data.fillna(x_data.mean()) #X_raw = x_complete.as_matrix() # Scale the data between 0 and 1: #X = MinMaxScaler().fit_transform(X_raw) # Shuffle data to remove any underlying pattern that may exist: #shuffle = np.random.permutation(np.arange(X.shape[0])) #X, y = X[shuffle], y[shuffle] # Separate training, dev, and test data: #test_data, test_labels = X[800000:], y[800000:] #dev_data, dev_labels = X[700000:800000], y[700000:800000] #train_data, train_labels = X[:700000], y[:700000] #mini_train_data, mini_train_labels = X[:75000], y[:75000] #mini_dev_data, mini_dev_labels = X[75000:100000], y[75000:100000] #labels_set = set(mini_dev_labels) #print(labels_set) #print(len(labels_set)) #print(train_data[:10]) """ Explanation: Data Cleaning Here we include the data definition language that we wrote to bring our csv data into formatted tables: sql CREATE TABLE kaggle_sf_crime ( dates TIMESTAMP, category VARCHAR, descript VARCHAR, dayofweek VARCHAR, pd_district VARCHAR, resolution VARCHAR, addr VARCHAR, X FLOAT, Y FLOAT); Getting training data into a locally hosted PostgreSQL database: sql \copy kaggle_sf_crime FROM '/Users/Goodgame/Desktop/MIDS/207/final/sf_crime_train.csv' DELIMITER ',' CSV HEADER; SQL Query used to perform out transformations: sql SELECT category, date_part('hour', dates) AS hour_of_day, CASE WHEN dayofweek = 'Monday' then 1 WHEN dayofweek = 'Tuesday' THEN 2 WHEN dayofweek = 'Wednesday' THEN 3 WHEN dayofweek = 'Thursday' THEN 4 WHEN dayofweek = 'Friday' THEN 5 WHEN dayofweek = 'Saturday' THEN 6 WHEN dayofweek = 'Sunday' THEN 7 END AS dayofweek_numeric, X, Y, CASE WHEN pd_district = 'BAYVIEW' THEN 1 ELSE 0 END AS bayview_binary, CASE WHEN pd_district = 'INGLESIDE' THEN 1 ELSE 0 END AS ingleside_binary, CASE WHEN pd_district = 'NORTHERN' THEN 1 ELSE 0 END AS northern_binary, CASE WHEN pd_district = 'CENTRAL' THEN 1 ELSE 0 END AS central_binary, CASE WHEN pd_district = 'BAYVIEW' THEN 1 ELSE 0 END AS pd_bayview_binary, CASE WHEN pd_district = 'MISSION' THEN 1 ELSE 0 END AS mission_binary, CASE WHEN pd_district = 'SOUTHERN' THEN 1 ELSE 0 END AS southern_binary, CASE WHEN pd_district = 'TENDERLOIN' THEN 1 ELSE 0 END AS tenderloin_binary, CASE WHEN pd_district = 'PARK' THEN 1 ELSE 0 END AS park_binary, CASE WHEN pd_district = 'RICHMOND' THEN 1 ELSE 0 END AS richmond_binary, CASE WHEN pd_district = 'TARAVAL' THEN 1 ELSE 0 END AS taraval_binary FROM kaggle_sf_crime; The initial source of our data was at https://www.kaggle.com/c/sf-crime. We loaded the original training data, train.csv, then extracted the dates column and added it to the transformed data. Dates were converted to number of seconds from the Unix epoch (defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus the number of leap seconds that have taken place since then). We then moved the dates to the first column. Next, we one-hot encoded the location data. Location information tends to be extremely high-dimensional, which presents difficulties for modeling. The original dataset's location information came in three major formats: X and Y coordinates Street address information Police department districts After visualizing the data and conducting basic exploratory data analysis, we decided to use one-hot encoding to transform the police department location information into features. In other words, each police department becomes a feature, and a given observation receives a value of '1' if it occurred in the police department jurisdiction described by the feature. Otherwise, it received a value of '0'. Approaching location in this way allowed us to preserve the parsimony of our model; it retains the majority of the important variance in the data without overfitting. Feature Engineering: Weather Data, School Data, and Zipcode Data We sought to add features to our models that would improve performance with respect to our desired performance metric of Multi-class Log Loss. There is evidence that there is a correlation between weather patterns and crime, with some experts even arguing for a causal relationship between weather and crime [1]. More specifically, a 2013 paper published in Science showed that higher temperatures and extreme rainfall led to large increases in conflict. In the setting of strong evidence that weather influences crime, we saw it as a candidate for additional features to improve the performance of our classifiers. Weather data was gathered from the National Centers for Environmental Information (specifically, the National Oceanic and Atmospheric Administration). Certain features from this data set were incorporated into the original crime data set in order to add features that were hypothesizzed to improve performance. These features included: Hourly Dry Bulb Temperature Hourly Relative Humidity Hourly Wind Speed Hourly Seal Level Pressure Hourly Visibility Daylight: a daylight indicator (1 if time of sunrise < timestamp < time of sunset, and 0 otherwise) Details on School data and Zipcode data are below. Loading The Data With Additional Features There are local file dependencies here. For viewing comfort, we will suppress the code in order to not generate error messages. The code that follows was written by us to incorporate the weather data features into the original data from Kaggle, and to load and then subset the data into train, development, calibrate, and test subsets. A separate portion of code follows that was used to load the data from the CSV file that is generated from the code here. Further details on data cleaning will be provided there. Weather Data End of explanation """ ### Read in school data #data_path_schools = "./data/pubschls.csv" #schools = pd.read_csv(data_path_schools,header=0, sep ='\t', usecols = ["CDSCode","StatusType", "School", "EILCode", "EILName", "Zip", "Latitude", "Longitude"], dtype ={'CDSCode': str, 'StatusType': str, 'School': str, 'EILCode': str,'EILName': str,'Zip': str, 'Latitude': float, 'Longitude': float}) #schools = schools[(schools["StatusType"] == 'Active')] ### Find the closest school #def dist(lat1, long1, lat2, long2): # return np.sqrt((lat1-lat2)**2+(long1-long2)**2) #def find_closest_school(lat, long): # distances = schools.apply(lambda row: dist(lat, long, row["Latitude"], row["Longitude"]), axis=1) # return min(distances) #x_data['closest_school'] = x_data_sub.apply(lambda row: find_closest_school(row['y'], row['x']), axis=1) """ Explanation: School Data We hypothesized that incorporating data on school location as well as other details on schools as features would increase the performance of our classifiers. We found a data set offered by California Department of Education (cde.ca.gov) with a list of all schools (K-12) in California and accompanying characteristics of those schools including activity status, grades taught (elementary vs middle vs high school), and address, including location coordinates. We created a distance function to match the longitude, latitude coordinates of each of the crimes to the closest school and pulled other potentially interesting features including: ‘Closest_school’ - Name of closest school ‘School_distance’ - Euclidean distance between latitude/longitude coordinates of crime and latitude/longitude coordinates of school ‘School_type’ - Elementary school vs Middle school vs High school Ultimately, we were not able to get these features incorporated into our data, although the attempt was educational. End of explanation """ ### Read in zip code data #data_path_zip = "./data/2016_zips.csv" #zips = pd.read_csv(data_path_zip, header=0, sep ='\t', usecols = [0,5,6], names = ["GEOID", "INTPTLAT", "INTPTLONG"], dtype ={'GEOID': int, 'INTPTLAT': float, 'INTPTLONG': float}) #sf_zips = zips[(zips['GEOID'] > 94000) & (zips['GEOID'] < 94189)] ### Mapping longitude/latitude to zipcodes #def dist(lat1, long1, lat2, long2): # return np.sqrt((lat1-lat2)**2+(long1-long2)**2) # return abs(lat1-lat2)+abs(long1-long2) #def find_zipcode(lat, long): # distances = sf_zips.apply(lambda row: dist(lat, long, row["INTPTLAT"], row["INTPTLONG"]), axis=1) # return sf_zips.loc[distances.idxmin(), "GEOID"] #x_data['zipcode'] = 0 #for i in range(0, 1): # x_data['zipcode'][i] = x_data.apply(lambda row: find_zipcode(row['x'], row['y']), axis=1) #x_data['zipcode']= x_data.apply(lambda row: find_zipcode(row['x'], row['y']), axis=1) """ Explanation: Zipcode Data We found government data from data.gov that links each zip code in the country to longitude and latitude coordinates in an effort to reduce location dimensions from 2 to 1. We used a custom distance function to map each set of longitude, latitude coordinates associated with each crime incident to find the closest 5-digit zip code using the data.gov file. Unfortunately even after we narrowed the data California zip codes (> 94000 and < 95000) we were unable to run the data in time to add the feature to the data set. End of explanation """ #data_path = "/Users/Bryan/Desktop/UC_Berkeley_MIDS_files/Courses/W207_Intro_To_Machine_Learning/Final_Project/x_data_3.csv" #df = pd.read_csv(data_path, header=0) #x_data = df.drop('category', 1) #y = df.category.as_matrix() # Impute missing values with mean values: #x_complete = x_data.fillna(x_data.mean()) #X_raw = x_complete.as_matrix() # Scale the data between 0 and 1: #X = MinMaxScaler().fit_transform(X_raw) # Shuffle data to remove any underlying pattern that may exist. Must re-run random seed step each time: #np.random.seed(0) #shuffle = np.random.permutation(np.arange(X.shape[0])) #X, y = X[shuffle], y[shuffle] # Due to difficulties with log loss and set(y_pred) needing to match set(labels), we will remove the extremely rare # crimes from the data for quality issues. #X_minus_trea = X[np.where(y != 'TREA')] #y_minus_trea = y[np.where(y != 'TREA')] #X_final = X_minus_trea[np.where(y_minus_trea != 'PORNOGRAPHY/OBSCENE MAT')] #y_final = y_minus_trea[np.where(y_minus_trea != 'PORNOGRAPHY/OBSCENE MAT')] # Separate training, dev, and test data: #test_data, test_labels = X_final[800000:], y_final[800000:] #dev_data, dev_labels = X_final[700000:800000], y_final[700000:800000] #train_data, train_labels = X_final[100000:700000], y_final[100000:700000] #calibrate_data, calibrate_labels = X_final[:100000], y_final[:100000] # Create mini versions of the above sets #mini_train_data, mini_train_labels = X_final[:20000], y_final[:20000] #mini_calibrate_data, mini_calibrate_labels = X_final[19000:28000], y_final[19000:28000] #mini_dev_data, mini_dev_labels = X_final[49000:60000], y_final[49000:60000] # Create list of the crime type labels. This will act as the "labels" parameter for the log loss functions that follow #crime_labels = list(set(y_final)) #crime_labels_mini_train = list(set(mini_train_labels)) #crime_labels_mini_dev = list(set(mini_dev_labels)) #crime_labels_mini_calibrate = list(set(mini_calibrate_labels)) #print(len(crime_labels), len(crime_labels_mini_train), len(crime_labels_mini_dev),len(crime_labels_mini_calibrate)) #print(len(train_data),len(train_labels)) #print(len(dev_data),len(dev_labels)) #print(len(mini_train_data),len(mini_train_labels)) #print(len(mini_dev_data),len(mini_dev_labels)) #print(len(test_data),len(test_labels)) #print(len(mini_calibrate_data),len(mini_calibrate_labels)) #print(len(calibrate_data),len(calibrate_labels)) """ Explanation: Local, individual clean and load of the updated data set (with weather data integrated) generated by the previous cells. Our final set of features was: hour_of_day dayofweek_numeric x: is this the longitude of the crime? y: is this the latitude of the crime? bayview_binary ingleside_binary northern_binary central_binary mission_binary southern_binary tenderloin_binary park_binary richmond_binary taraval_binary HOURLYDRYBULBTEMPF HOURLYRelativeHumidity HOURLYWindSpeed HOURLYSeaLevelPressure HOURLYVISIBILITIY Daylight: = 1 if ‘DAILYSunset’ > ‘DATE’ and 0 otherwise As you can see below, the data required further cleaning and tranformation. We imputed missing values with the feature's mean value. We then scaled features between 0 and 1. The data was shuffled to remove any underlying pattern that may exist. Kaggle dictated that our performance metric was log loss. This was not directly submitted by us, but computed from a submitted csv file with a matrix of the probability estimates of each class of crime for each data point. In our work, we sought to directly optimize the log loss by hyperparameter tuning, calibrating, and applying meta-estimation to our models. This meant that we would not be submitting our probability estimates each time we attempted to improve the performance of a model. This posed operational difficulty though, as the log loss function in sklearn.metrics requires that the set of correct labels for the data must exactly match the set of labels as generated by the max values within the predicted probabilities. Two of the crimes in our data set were extremely rare: trespassing on an industrial property (TREA) and possessing obscene material (PORNOGRAPHY/OBSC) at 4 and 8 in approximately 1 million crimes, respectively. At such rare rates, those crimes were not showing up in our data when randomly suhhfling and then subsetting into necessary train, development, calibration, and test subsets. This caused errors in generating log loss Therefore, we decided to sacrifice our performance on these rare 12 out of 1 million data points to be able to more quickly determine our performance metric. To ensure that all the data subsets contained all of the remaining crimes as labels (all 37 of them), the data load sometimes required repeated iterations in order to secure a crime set of 37 across the board. This was due to the inability to set a seed when using the permutation method in numpy. The data subsets were sized such that it would not require more than a few attempts to get all 37 crime labels into each subset. There are local file dependencies here. For viewing comfort, we will suppress the code in order to not generate error messages. The code that follows was written by us to incorporate the weather data features into the original data from Kaggle, and to load and then subset the data into train, development, calibrate, and test subsets. End of explanation """ yFrame = pd.DataFrame(y, columns=['category']) yCounts = yFrame['category'].value_counts() f = plt.figure(figsize=(15,8)) yCounts.plot(kind='bar') plt.title('Distribution of Classes in the Training Data') plt.ylabel('Frequency') """ Explanation: Exploratory Analysis Of The Train Data Plot distribution of classes of the training data End of explanation """ pca1 = PCA(n_components=20) pca1.fit(train_data) explainedVariances = pca1.explained_variance_ratio_ totalExplained = [] for index in range(len(explainedVariances)): totalExplained.append(sum(explainedVariances[:index+1])) pd.DataFrame(totalExplained) """ Explanation: Generate table showing the fraction of the total variance explained by the first k components End of explanation """ plt.figure(figsize=(15,8)) plt.plot(np.linspace(1,20,20),totalExplained,".") plt.title("Fraction of Total Variance Explained by First k Principal Components") plt.xlabel("Number of Components") plt.ylabel("Fraction of Total Variance Explained") plt.show """ Explanation: Plot the fraction of the total variance explained by the first k components End of explanation """ # The Kaggle submission format requires listing the ID of each example. # This is to remember the order of the IDs after shuffling #allIDs = np.array(list(df.axes[0])) #allIDs = allIDs[shuffle] #testIDs = allIDs[800000:] #devIDs = allIDs[700000:800000] #trainIDs = allIDs[:700000] # Extract the column names for the required submission format #sampleSubmission_path = "./data/sampleSubmission.csv" #sampleDF = pd.read_csv(sampleSubmission_path) #allColumns = list(sampleDF.columns) #featureColumns = allColumns[1:] # Extracting the test data for a baseline submission #real_test_path = "./data/test_transformed.csv" #testDF = pd.read_csv(real_test_path, header=0) #real_test_data = testDF #test_complete = real_test_data.fillna(real_test_data.mean()) #Test_raw = test_complete.as_matrix() #TestData = MinMaxScaler().fit_transform(Test_raw) # Here we remember the ID of each test data point, in case we ever decide to shuffle the test data for some reason #testIDs = list(testDF.axes[0]) """ Explanation: Formatting Output for Kaggle Kaggle required a very specific format for submitting our results. Submissions are evaluated using the multi-class logarithmic loss. Each incident must be labeled with one true class. For each incident, one must submit a set of predicted probabilities (one for every class). A CSV file with the incident id, all candidate class names, and a probability for each class is required for the final submission document. End of explanation """ # Generate a baseline MNB classifier and make it return prediction probabilities for the actual test data #def MNB(): # mnb = MultinomialNB(alpha = 0.0000001) # mnb.fit(train_data, train_labels) # print("\n\nMultinomialNB accuracy on dev data:", mnb.score(dev_data, dev_labels)) # return mnb.predict_proba(dev_data) #MNB() #baselinePredictionProbabilities = MNB() # Place the resulting prediction probabilities in a .csv file in the required format # First, turn the prediction probabilties into a data frame #resultDF = pd.DataFrame(baselinePredictionProbabilities,columns=featureColumns) # Add the IDs as a final column #resultDF.loc[:,'Id'] = pd.Series(testIDs,index=resultDF.index) # Make the 'Id' column the first column #colnames = resultDF.columns.tolist() #colnames = colnames[-1:] + colnames[:-1] #resultDF = resultDF[colnames] # Output to a .csv file # resultDF.to_csv('result.csv',index=False) """ Explanation: Generating Baseline Prediction Probabilities from MNB classifier and store in a .csv file This step was completed as a test-run to ensure that everything up to this point was functioning properly and that we could generate a proper submission CSV file. We also provided an example of the model accuacy being generated, although this was not our formal metric for evaluation. End of explanation """ # -*- coding: utf-8 -*- """ Created on Sat Aug 19 19:49:47 2017 @author: kalvi """ #required imports import pandas as pd import numpy as np def make_kaggle_format(sample_submission_path, test_transformed_path, prediction_probabilities): """this function requires: sample_submission_path=(filepath for 'sampleSubmission.csv') test_transformed_path=(filepath for 'test_transformed.csv') prediction_probabilities=(output from clf.predict_proba(test_data))""" #this is for extracting the column names for the required submission format sampleDF = pd.read_csv(sample_submission_path) allColumns = list(sampleDF.columns) featureColumns = allColumns[1:] #this is for extracting the test data IDs for our baseline submission testDF = pd.read_csv(test_transformed_path, header=0) testIDs = list(testDF.axes[0]) #first we turn the prediction probabilties into a data frame resultDF = pd.DataFrame(prediction_probabilities,columns=featureColumns) #this adds the IDs as a final column resultDF.loc[:,'Id'] = pd.Series(testIDs,index=resultDF.index) #the next few lines make the 'Id' column the first column colnames = resultDF.columns.tolist() colnames = colnames[-1:] + colnames[:-1] resultDF = resultDF[colnames] #output to .csv file resultDF.to_csv('result.csv',index=False) ## Data sub-setting quality check-point print(train_data[:1]) print(train_labels[:1]) # Modeling quality check-point with MNB--fast model def MNB(): mnb = MultinomialNB(alpha = 0.0000001) mnb.fit(train_data, train_labels) print("\n\nMultinomialNB accuracy on dev data:", mnb.score(dev_data, dev_labels)) MNB() """ Explanation: Note: the code above will shuffle data differently every time it's run, so model accuracies will vary accordingly. We later wrote a python script to automatically generate a Kaggle-formatted CSV document for our results End of explanation """ def model_prototype(train_data, train_labels, eval_data, eval_labels): knn = KNeighborsClassifier(n_neighbors=5).fit(train_data, train_labels) bnb = BernoulliNB(alpha=1, binarize = 0.5).fit(train_data, train_labels) mnb = MultinomialNB().fit(train_data, train_labels) log_reg = LogisticRegression().fit(train_data, train_labels) neural_net = MLPClassifier().fit(train_data, train_labels) random_forest = RandomForestClassifier().fit(train_data, train_labels) decision_tree = DecisionTreeClassifier().fit(train_data, train_labels) support_vm_step_one = svm.SVC(probability = True) support_vm = support_vm_step_one.fit(train_data, train_labels) models = [knn, bnb, mnb, log_reg, neural_net, random_forest, decision_tree, support_vm] for model in models: eval_prediction_probabilities = model.predict_proba(eval_data) eval_predictions = model.predict(eval_data) print(model, "Multi-class Log Loss:", log_loss(y_true = eval_labels, y_pred = eval_prediction_probabilities, labels = crime_labels_mini_dev), "\n\n") model_prototype(mini_train_data, mini_train_labels, mini_dev_data, mini_dev_labels) """ Explanation: Defining Performance Criteria As determined by the Kaggle submission guidelines, the performance criteria metric for the San Francisco Crime Classification competition is Multi-class Logarithmic Loss (also known as cross-entropy). There are various other performance metrics that are appropriate for different domains: accuracy, F-score, Lift, ROC Area, average precision, precision/recall break-even point, and squared error. Multi-class Log Loss Accuracy F-score Lift ROC Area Average precision Precision/Recall break-even point Squared-error Model Prototyping With Default Hyperparameters We started our classifier engineering process by looking at the performance of various classifiers with default parameter settings in predicting labels on the mini_dev_data: End of explanation """ list_for_ks = [] list_for_ws = [] list_for_ps = [] list_for_log_loss = [] def k_neighbors_tuned(k,w,p): tuned_KNN = KNeighborsClassifier(n_neighbors=k, weights=w, p=p).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = tuned_KNN.predict_proba(mini_dev_data) list_for_ks.append(this_k) list_for_ws.append(this_w) list_for_ps.append(this_p) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with KNN and k,w,p =", k,",",w,",", p, "is:", working_log_loss) k_value_tuning = [i for i in range(1,5002,500)] weight_tuning = ['uniform', 'distance'] power_parameter_tuning = [1,2] start = time.clock() for this_k in k_value_tuning: for this_w in weight_tuning: for this_p in power_parameter_tuning: k_neighbors_tuned(this_k, this_w, this_p) index_best_logloss = np.argmin(list_for_log_loss) print('For KNN the best log loss with hyperparameter tuning is',list_for_log_loss[index_best_logloss], 'with k =', list_for_ks[index_best_logloss], 'w =', list_for_ws[index_best_logloss], 'p =', list_for_ps[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Hyperparameter Tuning and Model Calibration To Improve Prediction For Each Classifier Here we sought to optimize the performance of our classifiers in a three-step, dynamnic engineering process. 1) Feature addition We previously added components from the weather data into the original SF crime data as new features. We will not repeat work done in our initial submission, where our training dataset did not include these features. For comparision with respoect to how the added features improved our performance with respect to log loss, please refer back to our initial submission. 2) Hyperparameter tuning Each classifier has hyperparameters that we can engineer to further optimize performance, as opposed to using the default parameter values as we did above in the model prototyping cell. This will be specific to each classifier as detailed below. 3) Model calibration We can calibrate the models via Platt Scaling or Isotonic Regression to attempt to improve their performance. Platt Scaling: ((brief explanation of how it works)) Isotonic Regression: ((brief explanation of how it works)) For each classifier, we can use CalibratedClassifierCV to perform probability calibration with isotonic regression or sigmoid (Platt Scaling). The parameters within CalibratedClassifierCV that we can adjust are the method ('sigmoid' or 'isotonic') and cv (cross-validation generator). As we will already be training our models before calibration, we will only use cv = 'prefit'. Thus, in practice the cross-validation generator will not be a modifiable parameter for us. 4) Parallelizing GridSearchCV with Spark-sklearn To optimize the parameters, we used GridSearchCV -- with a slight wrinkle. Because we needed GridSearchCV to sort through an incredible number of model specifications with a very large amount of data, we decided to parallelize the process using Spark. Fortunately, there is a PyPI library for doing just that: spark-sklearn. Check out the package here. In order to run spark-sklearn, we took the following steps: Create an AWS EC2 instance (in our case, a c3.8xlarge instance with an Ubuntu Linux operating system, with 32 vCPUs and 60GiB of memory) Install: Java, Scala, Anaconda, pip, and relevant dependencies (key library: spark_sklearn) Run GridSearchCV within a SparkContext All of the code is the exact same as a normal GridSearchCV with scikit-learn, except for two lines: "from spark_sklearn import GridSearchCV" "gs = GridSearchCV(sc, clf, param_grid)" In other words, the grid search takes SparkContext as an extra parameter. Because of that, the process can be parallelized across multiple cores, which saves a lot of time. For more information on parallelizing GridSearchCV using Spark, see this DataBricks tutorial and this AWS EC2 PySpark tutorial. Note: we ran the PySpark code in the PySpark REPL, rather than in a script. We hit issues with dependencies using Python scripts. We appear not to be alone in this issue; other data scientists have also hit a wall using scikit-learn with Spark. K-Nearest Neighbors Hyperparameter tuning: For the KNN classifier, we can seek to optimize the following classifier parameters: n-neighbors, weights, and the power parameter ('p'). End of explanation """ list_for_ks = [] list_for_ws = [] list_for_ps = [] list_for_ms = [] list_for_log_loss = [] def knn_calibrated(k,w,p,m): tuned_KNN = KNeighborsClassifier(n_neighbors=k, weights=w, p=p).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = tuned_KNN.predict_proba(mini_dev_data) ccv = CalibratedClassifierCV(tuned_KNN, method = m, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilities = ccv.predict_proba(mini_dev_data) list_for_ks.append(this_k) list_for_ws.append(this_w) list_for_ps.append(this_p) list_for_ms.append(this_m) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = ccv_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) print("Multi-class Log Loss with KNN and k,w,p =", k,",",w,",",p,",",m,"is:", working_log_loss) k_value_tuning = ([i for i in range(1,21,1)] + [j for j in range(25,51,5)] + [k for k in range(55,22000,1000)]) weight_tuning = ['uniform', 'distance'] power_parameter_tuning = [1,2] methods = ['sigmoid', 'isotonic'] start = time.clock() for this_k in k_value_tuning: for this_w in weight_tuning: for this_p in power_parameter_tuning: for this_m in methods: knn_calibrated(this_k, this_w, this_p, this_m) index_best_logloss = np.argmin(list_for_log_loss) print('For KNN the best log loss with hyperparameter tuning and calibration is',list_for_log_loss[index_best_logloss], 'with k =', list_for_ks[index_best_logloss], 'w =', list_for_ws[index_best_logloss], 'p =', list_for_ps[index_best_logloss], 'm =', list_for_ms[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Model calibration: Here we will calibrate the KNN classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respectively. End of explanation """ list_for_as = [] list_for_bs = [] list_for_log_loss = [] def BNB_tuned(a,b): bnb_tuned = BernoulliNB(alpha = a, binarize = b).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = bnb_tuned.predict_proba(mini_dev_data) list_for_as.append(this_a) list_for_bs.append(this_b) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with BNB and a,b =", a,",",b,"is:", working_log_loss) alpha_tuning = [0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 10.0] binarize_thresholds_tuning = [1e-20, 1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 0.999, 0.9999] start = time.clock() for this_a in alpha_tuning: for this_b in binarize_thresholds_tuning: BNB_tuned(this_a, this_b) index_best_logloss = np.argmin(list_for_log_loss) print('For BNB the best log loss with hyperparameter tuning is',list_for_log_loss[index_best_logloss], 'with alpha =', list_for_as[index_best_logloss], 'binarization threshold =', list_for_bs[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Multinomial, Bernoulli, and Gaussian Naive Bayes Hyperparameter tuning: Bernoulli Naive Bayes For the Bernoulli Naive Bayes classifier, we seek to optimize the alpha parameter (Laplace smoothing parameter) and the binarize parameter (threshold for binarizing of the sample features). For the binarize parameter, we will create arbitrary thresholds over which our features, which are not binary/boolean features, will be binarized. End of explanation """ list_for_as = [] list_for_bs = [] list_for_ms = [] list_for_log_loss = [] def BNB_calibrated(a,b,m): bnb_tuned = BernoulliNB(alpha = a, binarize = b).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = bnb_tuned.predict_proba(mini_dev_data) ccv = CalibratedClassifierCV(bnb_tuned, method = m, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilities = ccv.predict_proba(mini_dev_data) list_for_as.append(this_a) list_for_bs.append(this_b) list_for_ms.append(this_m) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = ccv_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with BNB and a,b,m =", a,",", b,",", m, "is:", working_log_loss) alpha_tuning = [0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 10.0] binarize_thresholds_tuning = [1e-20, 1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 0.999, 0.9999] methods = ['sigmoid', 'isotonic'] start = time.clock() for this_a in alpha_tuning: for this_b in binarize_thresholds_tuning: for this_m in methods: BNB_calibrated(this_a, this_b, this_m) index_best_logloss = np.argmin(list_for_log_loss) print('For BNB the best log loss with hyperparameter tuning and calibration is',list_for_log_loss[index_best_logloss], 'with alpha =', list_for_as[index_best_logloss], 'binarization threshold =', list_for_bs[index_best_logloss], 'method = ', list_for_ms[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Model calibration: BernoulliNB Here we will calibrate the BNB classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respectively. End of explanation """ list_for_as = [] list_for_log_loss = [] def MNB_tuned(a): mnb_tuned = MultinomialNB(alpha = a).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities =mnb_tuned.predict_proba(mini_dev_data) list_for_as.append(this_a) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with BNB and a =", a, "is:", working_log_loss) alpha_tuning = [0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 10.0] start = time.clock() for this_a in alpha_tuning: MNB_tuned(this_a) index_best_logloss = np.argmin(list_for_log_loss) print('For MNB the best log loss with hyperparameter tuning is',list_for_log_loss[index_best_logloss], 'with alpha =', list_for_as[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Hyperparameter tuning: Multinomial Naive Bayes For the Multinomial Naive Bayes classifer, we seek to optimize the alpha parameter (Laplace smoothing parameter). End of explanation """ list_for_as = [] list_for_ms = [] list_for_log_loss = [] def MNB_calibrated(a,m): mnb_tuned = MultinomialNB(alpha = a).fit(mini_train_data, mini_train_labels) ccv = CalibratedClassifierCV(mnb_tuned, method = m, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilities = ccv.predict_proba(mini_dev_data) list_for_as.append(this_a) list_for_ms.append(this_m) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = ccv_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with MNB and a =", a, "and m =", m, "is:", working_log_loss) alpha_tuning = [0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 10.0] methods = ['sigmoid', 'isotonic'] start = time.clock() for this_a in alpha_tuning: for this_m in methods: MNB_calibrated(this_a, this_m) index_best_logloss = np.argmin(list_for_log_loss) print('For MNB the best log loss with hyperparameter tuning and calibration is',list_for_log_loss[index_best_logloss], 'with alpha =', list_for_as[index_best_logloss], 'and method =', list_for_ms[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Model calibration: MultinomialNB Here we will calibrate the MNB classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respectively. End of explanation """ mnb_param_grid = {'alpha': [0.2, 0.4, 0.6, 0.8]} MNB = GridSearchCV(MultinomialNB(), param_grid=mnb_param_grid, scoring = 'neg_log_loss') MNB.fit(train_data, train_labels) print("the best alpha value is:", str(MNB.best_params_['alpha'])) mnb_param_grid = {'alpha': [0.3, 0.35, 0.4, 0.45, 0.5]} MNB = GridSearchCV(MultinomialNB(), param_grid=mnb_param_grid, scoring = 'neg_log_loss') MNB.fit(train_data, train_labels) print("the best alpha value is:", str(MNB.best_params_['alpha'])) mnb_param_grid = {'alpha': [0.31, 0.33, 0.35, 0.37, 0.39]} MNB = GridSearchCV(MultinomialNB(), param_grid=mnb_param_grid, scoring = 'neg_log_loss') MNB.fit(train_data, train_labels) print("the best alpha value is:", str(MNB.best_params_['alpha'])) # Generate the log loss from what we have tuned thus far MNBPredictionProbabilities = MNB.predict_proba(dev_data) print("Multi-class Log Loss:", log_loss(y_true = dev_labels, y_pred = MNBPredictionProbabilities, labels = crime_labels), "\n\n") mnb_param_grid = {'alpha': [0.340, 0.345, 0.35, 0.355, 0.360]} MNB = GridSearchCV(MultinomialNB(), param_grid=mnb_param_grid, scoring = 'neg_log_loss') MNB.fit(train_data, train_labels) print("the best alpha value is:", str(MNB.best_params_['alpha'])) # Generate the log loss from what we have tuned thus far MNBPredictionProbabilities = MNB.predict_proba(dev_data) print("Multi-class Log Loss:", log_loss(y_true = dev_labels, y_pred = MNBPredictionProbabilities, labels = crime_labels), "\n\n") """ Explanation: GridSearch for best parameters for Logistic Regression (run separate from this notebook on PySpark) End of explanation """ def GNB_pre_tune(): gnb_pre_tuned = GaussianNB().fit(mini_train_data, mini_train_labels) dev_prediction_probabilities =gnb_pre_tuned.predict_proba(mini_dev_data) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) print("Multi-class Log Loss with pre-tuned GNB is:", working_log_loss) GNB_pre_tune() def GNB_post_tune(): # Gaussian Naive Bayes requires the data to have a relative normal distribution. Sometimes # adding noise can improve performance by making the data more normal: mini_train_data_noise = np.random.rand(mini_train_data.shape[0],mini_train_data.shape[1]) modified_mini_train_data = np.multiply(mini_train_data,mini_train_data_noise) gnb_with_noise = GaussianNB().fit(modified_mini_train_data,mini_train_labels) dev_prediction_probabilities =gnb_with_noise.predict_proba(mini_dev_data) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) print("Multi-class Log Loss with tuned GNB via addition of noise to normalize the data's distribution is:", working_log_loss) GNB_post_tune() """ Explanation: Tuning: Gaussian Naive Bayes For the Gaussian Naive Bayes classifier there are no inherent parameters within the classifier function to optimize, but we will look at our log loss before and after adding noise to the data that is hypothesized to give it a more normal (Gaussian) distribution, which is required by the GNB classifier. End of explanation """ list_for_ms = [] list_for_log_loss = [] def GNB_calibrated(m): # Gaussian Naive Bayes requires the data to have a relative normal distribution. Sometimes # adding noise can improve performance by making the data more normal: mini_train_data_noise = np.random.rand(mini_train_data.shape[0],mini_train_data.shape[1]) modified_mini_train_data = np.multiply(mini_train_data,mini_train_data_noise) gnb_with_noise = GaussianNB().fit(modified_mini_train_data,mini_train_labels) ccv = CalibratedClassifierCV(gnb_with_noise, method = m, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilities = ccv.predict_proba(mini_dev_data) list_for_ms.append(this_m) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = ccv_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with tuned GNB via addition of noise to normalize the data's distribution and after calibration is:", working_log_loss, 'with calibration method =', m) methods = ['sigmoid', 'isotonic'] start = time.clock() for this_m in methods: GNB_calibrated(this_m) index_best_logloss = np.argmin(list_for_log_loss) print('For GNB the best log loss with tuning and calibration is',list_for_log_loss[index_best_logloss], 'with method =', list_for_ms[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Model calibration: GaussianNB Here we will calibrate the GNB classifier with both Platt Scaling and with Isotonic Regression using CalibratedClassifierCV with various parameter settings. The "method" parameter can be set to "sigmoid" or to "isotonic", corresponding to Platt Scaling and to Isotonic Regression respectively. End of explanation """ cValsL1 = [7.5, 10.0, 12.5, 20.0] methods = ['sigmoid', 'isotonic'] cv = 2 tol = 0.01 for c in cValsL1: for m in methods: ccvL1 = CalibratedClassifierCV(LogisticRegression(penalty='l1', C=c, tol=tol), method=m, cv=cv) ccvL1.fit(mini_train_data, mini_train_labels) print(ccvL1.get_params) ccvL1_prediction_probabilities = ccvL1.predict_proba(mini_dev_data) ccvL1_predictions = ccvL1.predict(mini_dev_data) print("L1 Multi-class Log Loss:", log_loss(y_true = mini_dev_labels, y_pred = ccvL1_prediction_probabilities, labels = crime_labels_mini_dev), "\n\n") print() """ Explanation: Logistic Regression Hyperparameter tuning: For the Logistic Regression classifier, we can seek to optimize the following classifier parameters: penalty (l1 or l2), C (inverse of regularization strength), solver ('newton-cg', 'lbfgs', 'liblinear', or 'sag') End of explanation """ cValsL1 = [15.0, 20.0, 25.0, 50.0] method = 'sigmoid' cv = 2 tol = 0.01 for c in cValsL1: ccvL1 = CalibratedClassifierCV(LogisticRegression(penalty='l1', C=c, tol=tol), method=method, cv=cv) ccvL1.fit(mini_train_data, mini_train_labels) print(ccvL1.get_params) ccvL1_prediction_probabilities = ccvL1.predict_proba(mini_dev_data) ccvL1_predictions = ccvL1.predict(mini_dev_data) print("L1 Multi-class Log Loss:", log_loss(y_true = mini_dev_labels, y_pred = ccvL1_prediction_probabilities, labels = crime_labels_mini_dev), "\n\n") print() """ Explanation: Model calibration End of explanation """ #L1 #lr_param_grid_1 = {'C': [0, 0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0]} lr_param_grid_1 = {'C': [7.5, 10.0, 12.5, 15.0, 20.0, 30.0, 50.0, 100.0]} LR_l1 = GridSearchCV(LogisticRegression(penalty='l1'), param_grid=lr_param_grid_1, scoring='neg_log_loss') LR_l1.fit(train_data, train_labels) print('L1: best C value:', str(LR_l1.best_params_['C'])) LR_l1_prediction_probabilities = LR_l1.predict_proba(dev_data) LR_l1_predictions = LR_l1.predict(dev_data) print("L1 Multi-class Log Loss:", log_loss(y_true = dev_labels, y_pred = LR_l1_prediction_probabilities, labels = crime_labels), "\n\n") #create an LR-L1 classifier with the best params bestL1 = LogisticRegression(penalty='l1', C=LR_l1.best_params_['C']) bestL1.fit(train_data, train_labels) #L1weights = bestL1.coef_ columns = ['hour_of_day','dayofweek',\ 'x','y','bayview','ingleside','northern',\ 'central','mission','southern','tenderloin',\ 'park','richmond','taraval','HOURLYDRYBULBTEMPF',\ 'HOURLYRelativeHumidity','HOURLYWindSpeed',\ 'HOURLYSeaLevelPressure','HOURLYVISIBILITY',\ 'Daylight'] allCoefsL1 = pd.DataFrame(index=columns) for a in range(len(bestL1.coef_)): allCoefsL1[crime_labels[a]] = bestL1.coef_[a] allCoefsL1 f = plt.figure(figsize=(15,8)) allCoefsL1.plot(kind='bar', figsize=(15,8)) plt.legend(loc='center left', bbox_to_anchor=(1.0,0.5)) plt.show() #L2 lr_param_grid_2 = {'C': [0.0001, 0.01, 1.0, 10.0, 50.0, 100.0, 150.0, 250.0, 500.0], \ 'solver':['liblinear','newton-cg','lbfgs', 'sag']} LR_l2 = GridSearchCV(LogisticRegression(penalty='l2'), param_grid=lr_param_grid_2, scoring='neg_log_loss') LR_l2.fit(train_data, train_labels) print('L2: best C value:', str(LR_l2.best_params_['C'])) print('L2: best solver:', str(LR_l2.best_params_['solver'])) LR_l2_prediction_probabilities = LR_l2.predict_proba(dev_data) LR_l2_predictions = LR_l2.predict(dev_data) print("L2 Multi-class Log Loss:", log_loss(y_true = dev_labels, y_pred = LR_l2_prediction_probabilities, labels = crime_labels), "\n\n") #create an LR-L2 classifier with the best params bestL2 = LogisticRegression(penalty='l2', solver=LR_l2.best_params_['solver'], C=LR_l2.best_params_['C']) bestL2.fit(train_data, train_labels) #L2weights = bestL2.coef_ columns = ['hour_of_day','dayofweek',\ 'x','y','bayview','ingleside','northern',\ 'central','mission','southern','tenderloin',\ 'park','richmond','taraval','HOURLYDRYBULBTEMPF',\ 'HOURLYRelativeHumidity','HOURLYWindSpeed',\ 'HOURLYSeaLevelPressure','HOURLYVISIBILITY',\ 'Daylight'] allCoefsL2 = pd.DataFrame(index=columns) for a in range(len(bestL2.coef_)): allCoefsL2[crime_labels[a]] = bestL2.coef_[a] allCoefsL2 f = plt.figure(figsize=(15,8)) allCoefsL2.plot(kind='bar', figsize=(15,8)) plt.legend(loc='center left', bbox_to_anchor=(1.0,0.5)) plt.show() """ Explanation: GridSearch for best parameters for Logistic Regression (run separate from this notebook on PySpark) End of explanation """ list_for_cs = [] list_for_ss = [] list_for_mds = [] list_for_mss = [] list_for_cws = [] list_for_fs = [] list_for_log_loss = [] def DT_tuned(c,s,md,ms,cw,f): tuned_DT = DecisionTreeClassifier(criterion=c, splitter=s, max_depth=md, min_samples_leaf=ms, max_features=f, class_weight=cw).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = tuned_DT.predict_proba(mini_dev_data) list_for_cs.append(this_c) list_for_ss.append(this_s) list_for_mds.append(this_md) list_for_mss.append(this_ms) list_for_cws.append(this_cw) list_for_fs.append(this_f) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = dev_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with DT and c,s,md,ms,cw,f =", c,",",s,",", md,",",ms,",",cw,",",f,"is:", working_log_loss) criterion_tuning = ['gini', 'entropy'] splitter_tuning = ['best', 'random'] max_depth_tuning = ([None,6,7,8,9,10,11,12,13,14,15,16,17,18,19]) min_samples_leaf_tuning = [x + 1 for x in [i for i in range(0,int(0.091*len(mini_train_data)),100)]] class_weight_tuning = [None, 'balanced'] max_features_tuning = ['auto', 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] start = time.clock() for this_c in criterion_tuning: for this_s in splitter_tuning: for this_md in max_depth_tuning: for this_ms in min_samples_leaf_tuning: for this_cw in class_weight_tuning: for this_f in max_features_tuning: DT_tuned(this_c, this_s, this_md, this_ms, this_cw, this_f) index_best_logloss = np.argmin(list_for_log_loss) print('For DT the best log loss with hyperparameter tuning is',list_for_log_loss[index_best_logloss], 'with criterion =', list_for_cs[index_best_logloss], 'splitter =', list_for_ss[index_best_logloss], 'max_depth =', list_for_mds[index_best_logloss], 'min_samples_leaf =', list_for_mss[index_best_logloss], 'class_weight =', list_for_cws[index_best_logloss], 'max_features =', list_for_fs[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Decision Tree Hyperparameter tuning: For the Decision Tree classifier, we can seek to optimize the following classifier parameters: criterion: The function to measure the quality of a split; can be either Gini impurity "gini" or information gain "entropy" splitter: The strategy used to choose the split at each node; can be either "best" to choose the best split or "random" to choose the best random split min_samples_leaf: The minimum number of samples required to be at a leaf node max_depth: The maximum depth of trees. If default "None" then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples class_weight: The weights associated with classes; can be "None" giving all classes weight of one, or can be "balanced", which uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data max_features: The number of features to consider when looking for the best split; can be "int", "float" (percent), "auto", "sqrt", or "None" Other adjustable parameters include: - min_samples_split: The minimum number of samples required to split an internal node; can be an integer or a float (percentage and ceil as the minimum number of samples for each node) - min_weight_fraction_leaf: The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node; default = 0 - max_leaf_nodes: Grosw a tree with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If "None" then unlimited number of leaf nodes is used. - min_impurity_decrease: A node will be split if this split induces a decrease of the impurity greater than or equal to the min_impurity_decrease value. Default is zero. Setting min_samples_leaf to approximately 1% of the data points can stop the tree from inappropriately classifying outliers, which can help to improve accuracy (unsure if significantly improves MCLL) []. End of explanation """ list_for_cs = [] list_for_ss = [] list_for_mds = [] list_for_mss = [] list_for_cws = [] list_for_fs = [] list_for_cms = [] list_for_log_loss = [] def DT_calibrated(c,s,md,ms,cw,f,cm): tuned_DT = DecisionTreeClassifier(criterion=c, splitter=s, max_depth=md, min_samples_leaf=ms, max_features=f, class_weight=cw).fit(mini_train_data, mini_train_labels) ccv = CalibratedClassifierCV(tuned_DT, method = cm, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilities = ccv.predict_proba(mini_dev_data) list_for_cs.append(this_c) list_for_ss.append(this_s) list_for_mds.append(this_md) list_for_mss.append(this_ms) list_for_cws.append(this_cw) list_for_fs.append(this_f) list_for_cms.append(this_cm) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = ccv_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) print("Multi-class Log Loss with DT and c,s,md,ms,cw,f =", c,",",s,",", md,",",ms,",",cw,",",f,",",cm,"is:", working_log_loss) criterion_tuning = ['gini', 'entropy'] splitter_tuning = ['best', 'random'] max_depth_tuning = ([None,6,7,8,9,10,11,12,13,14,15,16,17,18,19]) min_samples_leaf_tuning = [x + 1 for x in [i for i in range(0,int(0.091*len(mini_train_data)),100)]] class_weight_tuning = [None, 'balanced'] max_features_tuning = ['auto', 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] methods = ['sigmoid', 'isotonic'] start = time.clock() for this_c in criterion_tuning: for this_s in splitter_tuning: for this_md in max_depth_tuning: for this_ms in min_samples_leaf_tuning: for this_cw in class_weight_tuning: for this_f in max_features_tuning: for this_cm in methods: DT_calibrated(this_c, this_s, this_md, this_ms, this_cw, this_f, this_cm) index_best_logloss = np.argmin(list_for_log_loss) print('For DT the best log loss with hyperparameter tuning and calibration is',list_for_log_loss[index_best_logloss], 'with criterion =', list_for_cs[index_best_logloss], 'splitter =', list_for_ss[index_best_logloss], 'max_depth =', list_for_mds[index_best_logloss], 'min_samples_leaf =', list_for_mss[index_best_logloss], 'class_weight =', list_for_cws[index_best_logloss], 'max_features =', list_for_fs[index_best_logloss], 'and calibration method =', list_for_cms[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Model calibration: End of explanation """ from sklearn import svm from sklearn.metrics import log_loss class_labels = list(set(train_labels)) def enumerateY(data): enumerated_data = np.zeros(data.size) for j in range(0,data.size): feature = data[j] i = class_labels.index(feature) enumerated_data[j]+= i return (np.array(enumerated_data)) train_labels_enum = enumerateY(mini_train_labels) dev_labels_enum = enumerateY(mini_dev_labels) # GridSearchCV to find optimal parameters parameters = {'C': (0.001, 0.01, 0.1, 0.5, 1, 5, 10, 25, 100), 'decision_function_shape': ('ovo', 'ovr'), 'kernel': ('linear', 'sigmoid', 'rbf', 'poly')} clf = GridSearchCV(svm.SVC(tol = 0.01, probability = True), parameters, scoring = "log_loss") clf.fit(mini_train_data, mini_train_labels).predict_proba(mini_dev_data) print("optimal parameters:", clf.best_params_) # Most optimal parameters returned score of 2.62651014795 clf_svc = svm.SVC(kernel='rbf', C=100, decision_function_shape='ovr', probability = True).fit(mini_train_data, train_labels_enum) predicted = clf_svc.fit(mini_train_data, train_labels_enum).predict_proba(mini_dev_data) print(log_loss(y_true = dev_labels_enum, y_pred = predicted, labels = dev_labels_enum)) """ Explanation: Support Vector Machines Hyperparameter tuning: For the SVM classifier, we can seek to optimize the following classifier parameters: C (penalty parameter C of the error term), kernel ('linear', 'poly', 'rbf', sigmoid', or 'precomputed') See source [2] for parameter optimization in SVM. End of explanation """ # One of the iterations of gridSearchCV we ran import itertools hidden_layers = [2, 3, 4] for i in hidden_layers: hidden_layer_sizes = [x for x in itertools.product((4, 8, 12, 16, 20),repeat=i)] parameters = {'activation' : ('logistic', 'tanh', 'relu'), 'batch_size': (50, 100, 200), 'alpha': (0.001, 0.01, 0.1, 0.25), 'hidden_layer_sizes': hidden_layer_sizes} clf = GridSearchCV(MLPClassifier(tol = 0.01), parameters, scoring = "log_loss") clf.fit(mini_train_data, mini_train_labels).predict_proba(mini_dev_data) print("optimal parameters: ",clf.best_params_) # Our best parameter return clf = MLPClassifier(tol=0.01, activation = 'tanh', hidden_layer_sizes = (20,), batch_size = 10, alpha = 0.01).fit(mini_train_data, mini_train_labels) predicted = clf.predict(mini_dev_data) predicted_prob = clf.predict_proba(mini_dev_data) score = log_loss(mini_dev_labels, predicted_prob) print(score) """ Explanation: Neural Nets Hyperparameter tuning: The benefit of Neural Nets is that it can learn a non-linear function for classification. Relative to that of logistic regression, you have multiple "hidden" layers in between the input and output layers. The disadvantages are however that 1) you could have more than one local minimum due to a convex loss function which means depending on where the weights initialize you could end up with very different results and 2) the number of hyperparameters to tune is high -- requires lots of computing power. MLP trains using backpropgation - it trains using gradient descent and for classification, it minimizes the Cross-Entropy loss function, giving a vector of probability estimates. For the Neural Networks MLP classifier, the following classifier parameters are subject to optimization: 1) hidden_layer_sizes - which includes number of hidden layers as well as number of hidden nodes; 2) activation function - 'identity', 'logistic', 'tanh', 'relu'; 3) alpha - L2 regularization term to avoid overfitting; 4) learning_rate - 'constant', 'invscaling','adaptive'; 5) solver - 'lbfgs','sgd', adam' and 6) batch size. Given the limitations to compute power, we took a targeted approach to training our MLP model. We ran gridsearchCV several times over subsets of parameters which is obviously not ideal given the number of parameters. We also attempted to test the potential impact of scikit's neural network classifier which also can incorporate drop out methods. End of explanation """ from sknn.mlp import Classifier, Layer nn = Classifier( layers=[ Layer("Tanh", units = 20, dropout = .25), Layer("Softmax")], batch_size = 10, learning_rate = .001) clf = nn.fit(mini_train_data, mini_train_labels) predicted = clf.predict(mini_dev_data) predicted_prob = clf.predict_proba(mini_dev_data) score = log_loss(mini_dev_labels, predicted_prob) print(score) ##We attempted to run a more comprehensive hyperparameter tuning procedure including number of iterations and ranges for dropout method. It was too computationally intensive. Even on a remote AWS instance on pyspark it kept stalling out. from sklearn.grid_search import GridSearchCV gs = GridSearchCV(nn, param_grid={ 'learning_rate': [0.05, 0.01, 0.005, 0.001], 'n_iter': [25, 50, 100, 200], 'hidden0__units': [4, 8, 12, 16, 20], 'hidden0__type': ["Rectifier", "Sigmoid", "Tanh"], 'hidden0__dropout':[0.2, 0.3, 0.4], 'hidden1__units': [4, 8, 12, 16, 20], 'hidden1__type': ["Rectifier", "Sigmoid", "Tanh"], 'hidden1__dropout':[0.2, 0.3, 0.4], 'hidden2__units': [4, 8, 12, 16, 20], 'hidden2__type': ["Rectifier", "Sigmoid", "Tanh"], 'hidden2__dropout':[0.2, 0.3, 0.4]}) gs.fit(mini_train_data, mini_train_labels) predicted = gs.predict(mini_dev_data) predicted_prob = gs.predict_proba(mini_dev_data) score = log_loss(mini_dev_labels, predicted_prob) """ Explanation: We take the best performing parameters from the tuning procedures above and add dropout method to illustrate the potential impact there. Dropout method would not have materially improved the score had we used it. End of explanation """ # Further calibration using CalibratedClassifierCV list_for_log_loss = [] def NN_calibrated(): tuned_NN = clf = MLPClassifier(tol=0.01, activation = 'tanh', hidden_layer_sizes = (20,), batch_size = 10, alpha = 0.001).fit(mini_train_data, mini_train_labels) dev_prediction_probabilities = tuned_NN.predict_proba(mini_dev_data) ccv = CalibratedClassifierCV(tuned_NN, method = m, cv = 'prefit') ccv.fit(mini_calibrate_data, mini_calibrate_labels) ccv_prediction_probabilities = ccv.predict_proba(mini_dev_data) working_log_loss = log_loss(y_true = mini_dev_labels, y_pred = ccv_prediction_probabilities, labels = crime_labels_mini_dev) list_for_log_loss.append(working_log_loss) print("Multi-class Log Loss with NN is:", working_log_loss) methods = ['sigmoid', 'isotonic'] for m in methods: NN_calibrated() index_best_logloss = np.argmin(list_for_log_loss) print('For NN the best log loss with hyperparameter tuning and calibration is',list_for_log_loss[index_best_logloss]) """ Explanation: Model calibration: End of explanation """ #learning_rate : float, optional (default=0.1) #n_estimators : int (default=100) #max_depth : integer, optional (default=3) #criterion : string, optional (default=”friedman_mse”) #min_samples_split : int, float, optional (default=2) #min_samples_leaf : int, float, optional (default=1) #min_weight_fraction_leaf : float, optional (default=0.) #subsample : float, optional (default=1.0) #max_features : int, float, string or None, optional (default=None) #max_leaf_nodes : int or None, optional (default=None) nList = [75, 125] depthList = [1, 5] leafList = [2, 7] featuresList = [8, 17] #gb_param_grid = {'n_estimators':[25, 75, 250, 750], 'max_depth': [1, 5, 9], \ # 'min_samples_leaf': [2, 7, 12], 'max_features': [3, 8, 17]} #GB = GridSearchCV(GradientBoostingClassifier(), param_grid=gb_param_grid, scoring='neg_log_loss') #GB.fit(train_data, train_labels) for n_estimators in nList: for max_depth in depthList: for min_samples_leaf in leafList: for max_features in featuresList: gbTest = GradientBoostingClassifier(n_estimators=n_estimators, max_depth=max_depth, \ min_samples_leaf=min_samples_leaf, max_features=max_features) gbTest.fit(mini_train_data, mini_train_labels) gbTestPredictionProbabilities = gbTest.predict_proba(mini_dev_data) print("Parameters:") print("n_estimators:", str(n_estimators)+";", " max_depth:", str(max_depth)+";", \ " min_samples_leaf:", str(min_samples_leaf)+";", " max_features:", str(max_features)) print("Multi-class Log Loss:", log_loss(y_true = mini_dev_labels, y_pred = gbTestPredictionProbabilities, \ labels = crime_labels_mini_dev), "\n\n") print() """ Explanation: Random Forest Hyperparameter tuning: For the Random Forest classifier, we can seek to optimize the following classifier parameters: n_estimators (the number of trees in the forsest), max_features, max_depth, min_samples_leaf, bootstrap (whether or not bootstrap samples are used when building trees), oob_score (whether or not out-of-bag samples are used to estimate the generalization accuracy) This information is only included in our Final Notebook. Please refer to it. Model calibration: See Final Notebook please Gradient Boosting Classifier Hyperparameter tuning: For the Gradient Boosting classifier, we can seek to optimize the following classifier parameters: n_estimators (the number of trees in the forsest), max_depth, min_samples_leaf, and max_features End of explanation """ gb_param_grid = {'n_estimators':[25, 75, 250, 750], 'max_depth': [1, 5, 9], \ 'min_samples_leaf': [2, 7, 12], 'max_features': [3, 8, 17]} GB = GridSearchCV(GradientBoostingClassifier(), param_grid=gb_param_grid, scoring='neg_log_loss') GB.fit(train_data, train_labels) GB.best_params_ GBPredictionProbabilities = GB.predict_proba(dev_data) print("Multi-class Log Loss:", log_loss(y_true = dev_labels, y_pred = GBPredictionProbabilities, labels = crime_labels), "\n\n") """ Explanation: GridSearch for best parameters for Gradient Boosting (run separate from this notebook on PySpark) End of explanation """ RF_tuned = RandomForestClassifier(min_impurity_split=1, n_estimators=100, bootstrap= True, max_features=0.75, criterion='entropy', min_samples_leaf=10, max_depth=None).fit(train_data, train_labels) #RF_calibrated_and_tuned_pre_fit = CalibratedClassifierCV(RF_tuned, method = 'isotonic', cv = 'prefit') #RF_calibrated_and_tuned_fitted = RF_calibrated_and_tuned_pre_fit.fit(mini_calibrate_data,mini_calibrate_labels) list_for_ns = [] list_for_mss = [] list_for_mfs = [] list_for_bs = [] list_for_bfs = [] list_for_os = [] list_for_log_loss = [] def Bagging_RF(n,ms,mf,b,bf,o): bagging_clf = BaggingClassifier(base_estimator = RF_tuned, n_estimators = n, max_samples = ms, max_features = mf, bootstrap = b, bootstrap_features = bf, oob_score = o) bagging_clf_fitted = bagging_clf.fit(train_data,train_labels) bagging_prediction_probabilities = bagging_clf_fitted.predict_proba(dev_data) list_for_ns.append(this_ns) list_for_mss.append(this_mss) list_for_mfs.append(this_mfs) list_for_bs.append(this_bs) list_for_bfs.append(this_bfs) list_for_os.append(this_os) working_log_loss = log_loss(y_true = dev_labels, y_pred = bagging_prediction_probabilities, labels = crime_labels) list_for_log_loss.append(working_log_loss) #print("Multi-class Log Loss with RF tuned/calibrated/bagged and n,ms,mf,b,bf,o =", n,",",ms,",", mf,",",b,",",bf,",",o, "is:", working_log_loss) n_estimators_list = [i for i in range(1,1002,100)] max_samples_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] max_features_list = [0.1, 0.2, 0.4, 0.5, 0.75, 1.0] bootstrap_list =[True] bootstrap_features_list = [True, False] oob_score_list = [False] start = time.clock() for this_ns in n_estimators_list: for this_mss in max_samples_list: for this_mfs in max_features_list: for this_bs in bootstrap_list: for this_bfs in bootstrap_features_list: for this_os in oob_score_list: Bagging_RF(this_ns, this_mss, this_mfs, this_bs, this_bfs, this_os) index_best_logloss = np.argmin(list_for_log_loss) print('For RF the best log loss with hyperparameter tuning, calibration, and bagging is',list_for_log_loss[index_best_logloss], 'with n_estimators =', list_for_ns[index_best_logloss], 'max_samples =', list_for_mss[index_best_logloss], 'max_features =', list_for_mfs[index_best_logloss], 'bootstrap =', list_for_bs[index_best_logloss], 'bootstrap_features =', list_for_bfs[index_best_logloss], 'oob_score =', list_for_os[index_best_logloss]) end = time.clock() print("Computation time for this step is %.2f" % (end-start), 'seconds') """ Explanation: Meta-estimators AdaBoost Classifier Hyperparameter tuning: For the AdaBoostClassifier, one can seek to optimize the following meta-estimator parameters: base_estimator (the possible classifiers over which you are providing a meta-estimation with Adaptive Boosting), n_estimators (the max number of estimators at which boosting is terminated), algorithm ('SAMME' or 'SAMME.R'). Adaboosting each classifier: We considered running the AdaBoostClassifier on each different classifier from above, using the classifier settings with optimized Multi-class Log Loss after hyperparameter tuning and calibration. However, with further research, we discovered that Adaptive Boosting in its current state can either increase or decrease performance compared to the initial, non-boosted model. Further detail on this research with respect to KNN follows. As such, we decided to use the Bagging meta-estimator. Example: Adaboosting KNN: We will not seek to apply Adaptive Boosting (AdaBoost) to our K-nearest Neighbors classifier. It has been shown that AdaBoost actually reduces accuracy and other performance metrics when used with nearest neighbors classifiers [4]. This is because KNN is a stable algorithm with low variance, which leads to correlated errors during each iteration of AdaBoost. There is, however, on-going research in ways to modify the AdaBoost algorithm for KNN classifiers to increase accuracy and other performance metrics. Due to the aforementioned, we will omit Adaptive Boosting of our hyperparameter tuned and calibrated KNN classifier. Bagging Classifier Hyperparameter tuning: For the Bagging meta classifier, we can seek to optimize the following classifier parameters: n_estimators (the number of trees in the forsest), max_samples, max_features, bootstrap (whether or not bootstrap samples are used when building trees), bootstrap_features (whether features are drawn with replacement), and oob_score (whether or not out-of-bag samples are used to estimate the generalization accuracy) Bagging each classifier: We attempted to run the BaggingClassifier on out best model after performing the previous steps, which was Random FOrest hyperparameter-tuned and calibrated. However, we were not able to find a way to run this in a distributed fashion, and after > 18 hours of runtime the attempt was stopped. End of explanation """ pd.DataFrame(np.amax(ccv_prediction_probabilities_isotonic, axis=1)).hist() """ Explanation: Error Analysis On Our Best Classifier: Randon Forrest tuned_DT_calibrate_isotonic = RandomForestClassifier(min_impurity_split=1, n_estimators=100, bootstrap= True, max_features=15, criterion='entropy', min_samples_leaf=10, max_depth=None ).fit(train_data, train_labels) ccv_isotonic = CalibratedClassifierCV(tuned_DT_calibrate_isotonic, method = 'isotonic', cv = 'prefit') ccv_isotonic.fit(calibrate_data, calibrate_labels) ccv_predictions = ccv_isotonic.predict(dev_data) ccv_prediction_probabilities_isotonic = ccv_isotonic.predict_proba(dev_data) working_log_loss_isotonic = log_loss(y_true = dev_labels, y_pred = ccv_prediction_probabilities_isotonic, labels = crime_labels) print("Multi-class Log Loss with RF and calibration with isotonic is:", working_log_loss_isotonic) End of explanation """ #clf_probabilities, clf_predictions, labels def error_analysis_calibration(buckets, clf_probabilities, clf_predictions, labels): """inputs: clf_probabilities = clf.predict_proba(dev_data) clf_predictions = clf.predict(dev_data) labels = dev_labels""" #buckets = [0.05, 0.15, 0.3, 0.5, 0.8] #buckets = [0.15, 0.25, 0.3, 1.0] correct = [0 for i in buckets] total = [0 for i in buckets] lLimit = 0 uLimit = 0 for i in range(len(buckets)): uLimit = buckets[i] for j in range(clf_probabilities.shape[0]): if (np.amax(clf_probabilities[j]) > lLimit) and (np.amax(clf_probabilities[j]) <= uLimit): if clf_predictions[j] == labels[j]: correct[i] += 1 total[i] += 1 lLimit = uLimit print(sum(correct)) print(sum(total)) print(correct) print(total) #here we report the classifier accuracy for each posterior probability bucket accuracies = [] for k in range(len(buckets)): print(1.0*correct[k]/total[k]) accuracies.append(1.0*correct[k]/total[k]) print('p(pred) <= %.13f total = %3d correct = %3d accuracy = %.3f' \ %(buckets[k], total[k], correct[k], 1.0*correct[k]/total[k])) plt.plot(buckets,accuracies) plt.title("Calibration Analysis") plt.xlabel("Posterior Probability") plt.ylabel("Classifier Accuracy") return buckets, accuracies # Look at how the posteriors are distributed in order to set the best bins in 'buckets' pd.DataFrame(np.amax(bestLRPredictionProbabilities, axis=1)).hist() buckets = [0.15, 0.25, 0.3, 1.0] calibration_buckets, calibration_accuracies = error_analysis_calibration(buckets, clf_probabilities=bestLRPredictionProbabilities, \ clf_predictions=bestLRPredictions, \ labels=mini_dev_labels) """ Explanation: Error Analysis: Calibration End of explanation """ def error_analysis_classification_report(clf_predictions, labels): """inputs: clf_predictions = clf.predict(dev_data) labels = dev_labels""" print('Classification Report:') report = classification_report(labels, clf_predictions) print(report) return report classification_report = error_analysis_classification_report(clf_predictions=bestLRPredictions, \ labels=mini_dev_labels) """ Explanation: Error Analysis: Classification Report End of explanation """ def error_analysis_confusion_matrix(label_names, clf_predictions, labels): """inputs: clf_predictions = clf.predict(dev_data) labels = dev_labels""" cm = pd.DataFrame(confusion_matrix(labels, clf_predictions, labels=label_names)) cm.columns=label_names cm.index=label_names cm.to_csv(path_or_buf="./confusion_matrix.csv") #print(cm) return cm error_analysis_confusion_matrix(label_names=crime_labels_mini_dev, clf_predictions=bestLRPredictions, \ labels=mini_dev_labels) """ Explanation: Error Analysis: Confusion Matrix End of explanation """
peterhanlon/botdefender
ECI_Presentation.ipynb
mit
!pip install transformers !pip install torch !pip install keybert """ Explanation: <a href="https://colab.research.google.com/github/peterhanlon/botdefender/blob/master/ECI_Presentation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Examples from the ECI presentation on Natural Language Processing End of explanation """ from keybert import KeyBERT kw_model = KeyBERT() document=''' My electricity isn't working, and I've not had any power for five hours, can you send someone to fix it please. ''' kw_model.extract_keywords(document, keyphrase_ngram_range=(1, 3), stop_words='english') """ Explanation: Key Phrase Extraction - Keybert italicised text bold text End of explanation """ from transformers import pipeline sentiment_pipeline = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion") data = ["The product is amazing, I really love it", "I was really frustrated they didn't get back to me"] sentiment_pipeline(data) """ Explanation: Sentiment Analysis - Huggingface End of explanation """ from transformers import pipeline classification_pipeline = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") candidate_labels = ["renewable", "politics", "emissions", "temperature","emergency","advertisement"] sentence = ["The smoke from the car exhaust was unbearable"] classification_pipeline (sentence, candidate_labels) """ Explanation: Zero Shot Classification - Huggingface End of explanation """ from transformers import pipeline examples=''' sentence: "My car needs a service" intent: repair ### sentence: "My car is dirty" intent: valet ### sentence: "I want to sell my car" intent: sale ### sentence: "My cars engine is making a funny noise" intent:''' generator = pipeline('text-generation', model='EleutherAI/gpt-neo-2.7B') generator(examples, do_sample=True, max_new_tokens=3, temperature=0.1, end_sequence="###") """ Explanation: Few Shot Classification - Huggingface NOTE : This seems to be too large for free colab, if you have a PC with plenty of memory it will work End of explanation """ from transformers import pipeline classification_pipeline = pipeline("ner", model="dbmdz/bert-large-cased-finetuned-conll03-english") sentence = ["Pete wanted to go to London to present NLP stuff for ECI"] classification_pipeline (sentence) """ Explanation: Named Entity Extraction - Huggingface End of explanation """ from transformers import pipeline classification_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad") document="A reusable launch system (RLS, or reusable launch vehicle RLV) is a launch system which is capable of launching a payload into space more than once." question = ["Whas it an RLS"] classification_pipeline (question=question, context=document) """ Explanation: Question Answering End of explanation """
gigjozsa/HI_analysis_course
chapter_12_abs/01_00_introduction.ipynb
gpl-2.0
import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS """ Explanation: Content Glossary 1. Somename Next: 1.1 Somename 2 Import standard modules: End of explanation """ pass HTML('../style/code_toggle.html') """ Explanation: Import section specific modules: End of explanation """
google-research/google-research
building_detection/open_buildings_spatial_analysis_examples.ipynb
apache-2.0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License """ Explanation: Copyright 2021 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Open Buildings - spatial analysis examples This notebook demonstrates some analysis methods with Open Buildings data: Generating heatmaps of building density and size. A simple analysis of accessibility to health facilities. End of explanation """ #@markdown Select a region from either the [Natural Earth low res](https://www.naturalearthdata.com/downloads/110m-cultural-vectors/110m-admin-0-countries/) (fastest), [Natural Earth high res](https://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-0-countries/) or [World Bank high res](https://datacatalog.worldbank.org/dataset/world-bank-official-boundaries) shapefiles: region_border_source = 'Natural Earth (Low Res 110m)' #@param ["Natural Earth (Low Res 110m)", "Natural Earth (High Res 10m)", "World Bank (High Res 10m)"] region = 'GHA (Ghana)' #@param ["", "AGO (Angola)", "BDI (Burundi)", "BEN (Benin)", "BFA (Burkina Faso)", "BWA (Botswana)", "CAF (Central African Republic)", "CIV (Côte d'Ivoire)", "COD (Democratic Republic of the Congo)", "COG (Republic of the Congo)", "DJI (Djibouti)", "DZA (Algeria)", "EGY (Egypt)", "ERI (Eritrea)", "ETH (Ethiopia)", "GAB (Gabon)", "GHA (Ghana)", "GIN (Guinea)", "GMB (The Gambia)", "GNB (Guinea-Bissau)", "GNQ (Equatorial Guinea)", "KEN (Kenya)", "LBR (Liberia)", "LSO (Lesotho)", "MDG (Madagascar)", "MOZ (Mozambique)", "MRT (Mauritania)", "MWI (Malawi)", "NAM (Namibia)", "NER (Niger)", "NGA (Nigeria)", "RWA (Rwanda)", "SDN (Sudan)", "SEN (Senegal)", "SLE (Sierra Leone)", "SOM (Somalia)", "SWZ (eSwatini)", "TGO (Togo)", "TUN (Tunisia)", "TZA (Tanzania)", "UGA (Uganda)", "ZAF (South Africa)", "ZMB (Zambia)", "ZWE (Zimbabwe)"] # @markdown Alternatively, specify an area of interest in [WKT format](https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry) (assumes crs='EPSG:4326'); this [tool](https://arthur-e.github.io/Wicket/sandbox-gmaps3.html) might be useful. your_own_wkt_polygon = '' #@param {type:"string"} !pip install s2geometry pygeos geopandas import functools import glob import gzip import multiprocessing import os import shutil import tempfile from typing import List, Optional, Tuple import gdal import geopandas as gpd from google.colab import files from IPython import display from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.pyplot as plt import numpy as np import pandas as pd import s2geometry as s2 import shapely import tensorflow as tf import tqdm.notebook BUILDING_DOWNLOAD_PATH = ('gs://open-buildings-data/v1/' 'polygons_s2_level_6_gzip_no_header') def get_filename_and_region_dataframe( region_border_source: str, region: str, your_own_wkt_polygon: str) -> Tuple[str, gpd.geodataframe.GeoDataFrame]: """Returns output filename and a geopandas dataframe with one region row.""" if your_own_wkt_polygon: filename = 'open_buildings_v1_polygons_your_own_wkt_polygon.csv.gz' region_df = gpd.GeoDataFrame( geometry=gpd.GeoSeries.from_wkt([your_own_wkt_polygon]), crs='EPSG:4326') if not isinstance(region_df.iloc[0].geometry, shapely.geometry.polygon.Polygon) and not isinstance( region_df.iloc[0].geometry, shapely.geometry.multipolygon.MultiPolygon): raise ValueError("`your_own_wkt_polygon` must be a POLYGON or " "MULTIPOLYGON.") print(f'Preparing your_own_wkt_polygon.') return filename, region_df if not region: raise ValueError('Please select a region or set your_own_wkt_polygon.') if region_border_source == 'Natural Earth (Low Res 110m)': url = ('https://www.naturalearthdata.com/http//www.naturalearthdata.com/' 'download/110m/cultural/ne_110m_admin_0_countries.zip') !wget -N {url} display.clear_output() region_shapefile_path = os.path.basename(url) source_name = 'ne_110m' elif region_border_source == 'Natural Earth (High Res 10m)': url = ('https://www.naturalearthdata.com/http//www.naturalearthdata.com/' 'download/10m/cultural/ne_10m_admin_0_countries.zip') !wget -N {url} display.clear_output() region_shapefile_path = os.path.basename(url) source_name = 'ne_10m' elif region_border_source == 'World Bank (High Res 10m)': url = ('https://development-data-hub-s3-public.s3.amazonaws.com/ddhfiles/' '779551/wb_countries_admin0_10m.zip') !wget -N {url} !unzip -o {os.path.basename(url)} display.clear_output() region_shapefile_path = 'WB_countries_Admin0_10m' source_name = 'wb_10m' region_iso_a3 = region.split(' ')[0] filename = f'open_buildings_v1_polygons_{source_name}_{region_iso_a3}.csv.gz' region_df = gpd.read_file(region_shapefile_path).query( f'ISO_A3 == "{region_iso_a3}"').dissolve(by='ISO_A3')[['geometry']] print(f'Preparing {region} from {region_border_source}.') return filename, region_df def get_bounding_box_s2_covering_tokens( region_geometry: shapely.geometry.base.BaseGeometry) -> List[str]: region_bounds = region_geometry.bounds s2_lat_lng_rect = s2.S2LatLngRect_FromPointPair( s2.S2LatLng_FromDegrees(region_bounds[1], region_bounds[0]), s2.S2LatLng_FromDegrees(region_bounds[3], region_bounds[2])) coverer = s2.S2RegionCoverer() # NOTE: Should be kept in-sync with s2 level in BUILDING_DOWNLOAD_PATH. coverer.set_fixed_level(6) coverer.set_max_cells(1000000) return [cell.ToToken() for cell in coverer.GetCovering(s2_lat_lng_rect)] def s2_token_to_shapely_polygon( s2_token: str) -> shapely.geometry.polygon.Polygon: s2_cell = s2.S2Cell(s2.S2CellId_FromToken(s2_token, len(s2_token))) coords = [] for i in range(4): s2_lat_lng = s2.S2LatLng(s2_cell.GetVertex(i)) coords.append((s2_lat_lng.lng().degrees(), s2_lat_lng.lat().degrees())) return shapely.geometry.Polygon(coords) def download_s2_token( s2_token: str, region_df: gpd.geodataframe.GeoDataFrame) -> Optional[str]: """Downloads the matching CSV file with polygons for the `s2_token`. NOTE: Only polygons inside the region are kept. NOTE: Passing output via a temporary file to reduce memory usage. Args: s2_token: S2 token for which to download the CSV file with building polygons. The S2 token should be at the same level as the files in BUILDING_DOWNLOAD_PATH. region_df: A geopandas dataframe with only one row that contains the region for which to keep polygons. Returns: Either filepath which contains a gzipped CSV without header for the `s2_token` subfiltered to only contain building polygons inside the region or None which means that there were no polygons inside the region for this `s2_token`. """ s2_cell_geometry = s2_token_to_shapely_polygon(s2_token) region_geometry = region_df.iloc[0].geometry prepared_region_geometry = shapely.prepared.prep(region_geometry) # If the s2 cell doesn't intersect the country geometry at all then we can # know that all rows would be dropped so instead we can just return early. if not prepared_region_geometry.intersects(s2_cell_geometry): return None try: # Using tf.io.gfile.GFile gives better performance than passing the GCS path # directly to pd.read_csv. with tf.io.gfile.GFile( os.path.join(BUILDING_DOWNLOAD_PATH, f'{s2_token}_buildings.csv.gz'), 'rb') as gf: # If the s2 cell is fully covered by country geometry then can skip # filtering as we need all rows. if prepared_region_geometry.covers(s2_cell_geometry): with tempfile.NamedTemporaryFile(mode='w+b', delete=False) as tmp_f: shutil.copyfileobj(gf, tmp_f) return tmp_f.name # Else take the slow path. # NOTE: We read in chunks to save memory. csv_chunks = pd.read_csv( gf, chunksize=2000000, dtype=object, compression='gzip', header=None) tmp_f = tempfile.NamedTemporaryFile(mode='w+b', delete=False) tmp_f.close() for csv_chunk in csv_chunks: points = gpd.GeoDataFrame( geometry=gpd.points_from_xy(csv_chunk[1], csv_chunk[0]), crs='EPSG:4326') # sjoin 'within' was faster than using shapely's 'within' directly. points = gpd.sjoin(points, region_df, predicate='within') csv_chunk = csv_chunk.iloc[points.index] csv_chunk.to_csv( tmp_f.name, mode='ab', index=False, header=False, compression={ 'method': 'gzip', 'compresslevel': 1 }) return tmp_f.name except tf.errors.NotFoundError: return None # Clear output after pip install. display.clear_output() filename, region_df = get_filename_and_region_dataframe(region_border_source, region, your_own_wkt_polygon) # Remove any old outputs to not run out of disk. for f in glob.glob('/tmp/open_buildings_*'): os.remove(f) # Write header to the compressed CSV file. with gzip.open(f'/tmp/{filename}', 'wt') as merged: merged.write(','.join([ 'latitude', 'longitude', 'area_in_meters', 'confidence', 'geometry', 'full_plus_code' ]) + '\n') download_s2_token_fn = functools.partial(download_s2_token, region_df=region_df) s2_tokens = get_bounding_box_s2_covering_tokens(region_df.iloc[0].geometry) # Downloads CSV files for relevant S2 tokens and after filtering appends them # to the compressed output CSV file. Relies on the fact that concatenating # gzipped files produces a valid gzip file. # NOTE: Uses a pool to speed up output preparation. with open(f'/tmp/{filename}', 'ab') as merged: with multiprocessing.Pool(4) as e: for fname in tqdm.notebook.tqdm( e.imap_unordered(download_s2_token_fn, s2_tokens), total=len(s2_tokens)): if fname: with open(fname, 'rb') as tmp_f: shutil.copyfileobj(tmp_f, merged) os.unlink(fname) """ Explanation: Download buildings data for a region in Africa [takes up to 15 minutes for large countries] End of explanation """ buildings = pd.read_csv( f"/tmp/{filename}", engine="c", usecols=['latitude', 'longitude', 'area_in_meters', 'confidence']) print(f"Read {len(buildings):,} records.") """ Explanation: Visualise the data First we convert the CSV file into a GeoDataFrame. The CSV files can be quite large because they include the polygon outline of every building. For this example we only need longitude and latitude, so we only process those columns to save memory. End of explanation """ sample_size = 200000 #@param buildings_sample = (buildings.sample(sample_size) if len(buildings) > sample_size else buildings) plt.plot(buildings_sample.longitude, buildings_sample.latitude, 'k.', alpha=0.25, markersize=0.5) plt.gcf().set_size_inches(10, 10) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.axis('equal'); """ Explanation: For some countries there can be tens of millions of buildings, so we also take a random sample for doing plots. End of explanation """ max_grid_dimension = 1000 #@param confidence_threshold = 0.75 #@param buildings = buildings.query(f"confidence > {confidence_threshold}") # Create a grid covering the dataset bounds min_lon = buildings.longitude.min() max_lon = buildings.longitude.max() min_lat = buildings.latitude.min() max_lat = buildings.latitude.max() grid_density_degrees = (max(max_lon - min_lon, max_lat - min_lat) / max_grid_dimension) bounds = [min_lon, min_lat, max_lon, max_lat] xcoords = np.arange(min_lon, max_lon, grid_density_degrees) ycoords = np.arange(max_lat, min_lat, -grid_density_degrees) xv, yv = np.meshgrid(xcoords, ycoords) xy = np.stack([xv.ravel(), yv.ravel()]).transpose() print(f"Calculated grid of size {xv.shape[0]} x {xv.shape[1]}.") """ Explanation: Prepare the data for mapping building statistics Set up a grid, which we will use to calculate statistics about buildings. We also want to select the examples most likely to be buildings, using a threshold on the confidence score. End of explanation """ geotransform = (min_lon, grid_density_degrees, 0, max_lat, 0, -grid_density_degrees) def lonlat_to_xy(lon, lat, geotransform): x = int((lon - geotransform[0])/geotransform[1]) y = int((lat - geotransform[3])/geotransform[5]) return x,y """ Explanation: To calculate statistics, we need a function to convert between (longitude, latitude) coordinates in the world and (x, y) coordinates in the grid. End of explanation """ counts = np.zeros(xv.shape) area_totals = np.zeros(xv.shape) for lat, lon, area in tqdm.notebook.tqdm( zip(buildings.latitude, buildings.longitude, buildings.area_in_meters)): x, y = lonlat_to_xy(lon, lat, geotransform) if x >= 0 and y >= 0 and x < len(xcoords) and y < len(ycoords): counts[y, x] += 1 area_totals[y, x] += area area_totals[counts == 0] = np.nan counts[counts == 0] = np.nan mean_area = area_totals / counts """ Explanation: Now we can count how many buildings there are on each cell of the grid. End of explanation """ plt.imshow(np.log10(np.nan_to_num(counts) + 1.), cmap="viridis") plt.gcf().set_size_inches(15, 15) cbar = plt.colorbar(shrink=0.5) cbar.ax.set_yticklabels([f'{x:.0f}' for x in 10 ** cbar.ax.get_yticks()]) plt.title("Building counts per grid cell"); """ Explanation: Plot the counts of buildings Knowing the counts of buildings is useful for example in planning service delivery, estimating population or designing census enumeration areas. End of explanation """ def save_geotiff(filename, values, geotransform): driver = gdal.GetDriverByName("GTiff") dataset = driver.Create(filename, values.shape[1], values.shape[0], 1, gdal.GDT_Float32) dataset.SetGeoTransform(geotransform) band = dataset.GetRasterBand(1) band.WriteArray(values) band.SetNoDataValue(-1) dataset.FlushCache() filename = "building_counts.tiff" save_geotiff(filename, counts, geotransform) files.download(filename) """ Explanation: [optional] Export a GeoTIFF file This can be useful to carry our further analysis with software such as QGIS. End of explanation """ # Only calculate the mean building size for grid locations with at # least a few buildings, so that we get more reliable averages. mean_area_filtered = mean_area.copy() mean_area_filtered[counts < 10] = 0 # Set a maximum value for the colour scale, to make the plot brighter. plt.imshow(np.nan_to_num(mean_area_filtered), vmax=250, cmap="viridis") plt.title("Mean building size (m$^2$)") plt.colorbar(shrink=0.5, extend="max") plt.gcf().set_size_inches(15, 15) """ Explanation: Generate a map of building sizes Knowing average building sizes is useful too -- it is linked, for example, to how much economic activity there is in each area. End of explanation """ health_sites = pd.read_csv("https://data.humdata.org/dataset/364c5aca-7cd7-4248-b394-335113293c7a/" "resource/b7e55f34-9e3b-417f-b329-841cff6a9554/download/ghana.csv") health_sites = gpd.GeoDataFrame( health_sites, geometry=gpd.points_from_xy(health_sites.X, health_sites.Y)) health_sites.head() """ Explanation: Health facility accessibility We can combine different types of geospatial data to get various insights. If we have information on the locations of clinics and hospitals across Ghana, for example, then one interesting analysis is how accessible health services are in different places. In this example, we'll look at the average distance to the nearest health facility. We use this data made available by Global Healthsites Mapping Project. End of explanation """ health_sites = health_sites[['X', 'Y', 'amenity', 'name', 'geometry']] health_sites.dropna(axis=0, inplace=True) health_sites = health_sites[health_sites['amenity'].isin(['hospital','clinic','health_post', 'doctors'])] health_sites = health_sites.query( f'Y > {min_lat} and Y < {max_lat}' f'and X > {min_lon} and X < {max_lon}') health_sites.head() """ Explanation: We drop all columns not relevant to the computation of mean distance from health facilities. We also exclude all rows with empty or NaN values, select amenities captured as hospitals in the new geodata and choose values within the range of our area of interest. End of explanation """ plt.plot(buildings_sample.longitude, buildings_sample.latitude, 'k.', alpha=0.25, markersize=0.5) plt.plot(health_sites.X, health_sites.Y, marker='$\\oplus$', color= 'red', alpha = 0.8, markersize=10, linestyle='None') plt.gcf().set_size_inches(10, 10) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.legend(['Building', 'Health center']) plt.axis('equal'); """ Explanation: Have a look at the locations of health facilities compared to the locations of buildings. Note: this data may not be complete. End of explanation """ buildings_sample = gpd.GeoDataFrame(buildings_sample, geometry=gpd.points_from_xy(buildings_sample.longitude, buildings_sample.latitude)) buildings_sample["distance_to_nearest_health_facility"] = buildings_sample.geometry.apply( lambda g: health_sites.distance(g).min()) buildings_sample.head() """ Explanation: Next we calculate, for each building, the distance to the nearest health facility. We use the sample of the buildings data that we took earlier, so that the computations don't take too long. End of explanation """ buildings_sample["distance_to_nearest_health_facility"] *= 111.32 """ Explanation: That has computed the distance in degrees (longitude and latitude), which is not very intuitive. We can convert this approximately to kilometers by multiplying with the distance spanned by one degree at the equator. End of explanation """ !wget https://data.humdata.org/dataset/dc4c17cf-59d9-478c-b2b7-acd889241194/resource/4443ddba-eeaf-4367-9457-7820ea482f7f/download/gha_admbnda_gss_20210308_shp.zip !unzip gha_admbnda_gss_20210308_shp.zip display.clear_output() admin_areas = gpd.read_file("gha_admbnda_gss_20210308_SHP/gha_admbnda_adm2_gss_20210308.shp") """ Explanation: Now we can then find the mean distance to the nearest health facility by administrative area. First, we load data on the shapes of adminstrative areas. We use this data made available by OCHA ROWCA - United Nations Office for the Coordination of Humanitarian Affairs for West and Central Africa. End of explanation """ # Both data frames have the same coordinate system. buildings_sample.crs = admin_areas.crs # Spatial join to find out which administrative area every building is in. points_polys = gpd.sjoin(buildings_sample, admin_areas, how="left") # Aggregate by admin area to get the average distance to nearest health facility. stats = points_polys.groupby("index_right")["distance_to_nearest_health_facility"].agg(["mean"]) admin_areas_with_distances = gpd.GeoDataFrame(stats.join(admin_areas)) admin_areas_with_distances.plot( column="mean", legend=True, legend_kwds={"shrink": 0.5}) plt.title("Average distance to the nearest health facility (km)") plt.gcf().set_size_inches(15, 15) """ Explanation: Next, find the average distance to the nearest health facility within each area. End of explanation """
ocelot-collab/ocelot
demos/ipython_tutorials/1_introduction.ipynb
gpl-3.0
from IPython.display import Image # Image(filename='gui_example.png') """ Explanation: This notebook was created by Sergey Tomin (sergey.tomin@desy.de). Source and license info is on GitHub. April 2020. An Introduction to Ocelot Ocelot is a multiphysics simulation toolkit designed for studying FEL and storage ring based light sources. Ocelot is written in Python. Its central concept is the writing of python's scripts for simulations with the usage of Ocelot's modules and functions and the standard Python libraries. Ocelot includes following main modules: Charged particle beam dynamics module (CPBD) optics tracking matching collective effects (description can be found here and here) Space Charge (3D Laplace solver) CSR (Coherent Synchrotron Radiation) (1D model with arbitrary number of dipoles). Wakefields (Taylor expansion up to second order for arbitrary geometry). MOGA (Multi Objective Genetics Algorithm) ref. Native module for spontaneous radiation calculation (some details can be found here and here) FEL calculations: interface to GENESIS and pre/post-processing Modules for online beam control and online optimization of accelerator performances. ref1, ref2, ref3, ref4. This module is being developed in collaboration with other accelerator groups. The module has been migrated to a separate repository (in ocelot-collab organization) for ease of collaborative development. Ocelot extensively uses Python's NumPy (Numerical Python) and SciPy (Scientific Python) libraries, which enable efficient in-core numerical and scientific computation within Python and give you access to various mathematical and optimization techniques and algorithms. To produce high quality figures Python's matplotlib library is used. It is an open source project and it is being developed by physicists from The European XFEL, DESY (Germany), NRC Kurchatov Institute (Russia). We still have no documentation but you can find a lot of examples in /demos/ folder including this tutorial Ocelot user profile Ocelot is designed for researchers who want to have the flexibility that is given by high-level languages such as Matlab, Python (with Numpy and SciPy) or Mathematica. However if someone needs a GUI it can be developed using Python's libraries like a PyQtGraph or PyQt. For example, you can see GUI for SASE optimization (uncomment and run next block) End of explanation """ import IPython print('IPython:', IPython.__version__) import numpy print('numpy:', numpy.__version__) import scipy print('scipy:', scipy.__version__) import matplotlib print('matplotlib:', matplotlib.__version__) import ocelot print('ocelot:', ocelot.__version__) """ Explanation: Tutorials Preliminaries: Setup & introduction Beam dynamics Introduction. Tutorial N1. Linear optics.. Web version. Linear optics. Double Bend Achromat (DBA). Simple example of usage OCELOT functions to get periodic solution for a storage ring cell. Tutorial N2. Tracking.. Web version. Linear optics of the European XFEL Injector. Tracking. First and second order. Artificial beam matching - BeamTransform Tutorial N3. Space Charge.. Web version. Tracking through RF cavities with SC effects and RF focusing. Tutorial N4. Wakefields.. Web version. Tracking through corrugated structure (energy chirper) with Wakefields Tutorial N5. CSR.. Web version. Tracking trough bunch compressor with CSR effect. Tutorial N6. RF Coupler Kick.. Web version. Coupler Kick. Example of RF coupler kick influence on trajectory and optics. Tutorial N7. Lattice design.. Web version. Lattice design, twiss matching, twiss backtracking Tutorial N8. Physics process addition. Laser heater. Web version. Theory of Laser Heater, implementation of new Physics Process, track particles w/o laser heater effect. Tutorial N9. Simple accelerator based THz source. Web version. A simple accelerator with the electron beam formation system and an undulator to generate THz radiation. Photon field simulation PFS tutorial N1. Synchrotron radiation module. Web version. Simple examples how to calculate synchrotron radiation with OCELOT Synchrotron Radiation Module. PFS tutorial N2. Coherent radiation module and RadiationField object. Web version. PFS tutorial N3. Reflection from imperfect highly polished mirror. Web version. PFS tutorial N4. Converting synchrotron radiation Screen object to RadiationField object for viewing and propagation. Web version. PFS tutorial N5: SASE estimation and imitation. Web version. Appendixes Undulator matching. Web version. brief theory and example in OCELOT Some useful OCELOT functions. Web version Aperture, RK tracking Example of an accelerator section optimization. Web version A simple demo of accelerator section optimization with a standard scipy numerical optimization method. Preliminaries The tutorial includes 9 examples dedicated to the beam dynamics and optics and 5 to Photon Field Simulation module. However, you should have a basic understanding of Computer Programming terminologies. A basic understanding of Python language is a plus. This tutorial requires the following packages: Python 3.6 - 3.8 numpy version 1.8 or later: http://www.numpy.org/ scipy version 0.15 or later: http://www.scipy.org/ matplotlib version 3.3 or later: http://matplotlib.org/ ipython version 2.4 or later, with notebook support: http://ipython.org Optional to speed up python - numexpr (version 2.6.1) - pyfftw (version 0.10) - numba Orbit Correction module - pandas The easiest way to get these is to download and install the Anaconda software distribution. Alternatively, you can download and install miniconda. The following command will install all required packages: $ conda install numpy scipy matplotlib jupyter Ocelot installation Anaconda Cloud The easiest way to install OCELOT is to use Anaconda cloud. In that case use command: $ conda install -c ocelot-collab ocelot Explicit installation Another way is download ocelot from GitHub 1. you have to download from GitHub zip file. 2. Unzip ocelot-master.zip to your working folder /your_working_dir/. 3. Add ../your_working_dir/ocelot-master to PYTHONPATH - Windows 7: go to Control Panel -> System and Security -> System -> Advance System Settings -> Environment Variables. and in User variables add /your_working_dir/ocelot-master/ to PYTHONPATH. If variable PYTHONPATH does not exist, create it Variable name: PYTHONPATH Variable value: ../your_working_dir/ocelot-master/ - Linux: ``` $ export PYTHONPATH=/your_working_dir/ocelot-master:$PYTHONPATH ``` To launch "ipython notebook" or "jupyter notebook" in command line run following commands: $ ipython notebook or $ ipython notebook --notebook-dir="path_to_your_directory" or $ jupyter notebook --notebook-dir="path_to_your_directory" Checking your installation You can run the following code to check the versions of the packages on your system: (in IPython notebook, press shift and return together to execute the contents of a cell) End of explanation """ from __future__ import print_function # the output of plotting commands is displayed inline within frontends, # directly below the code cell that produced it %matplotlib inline # import from Ocelot main modules and functions from ocelot import * # import from Ocelot graphical modules from ocelot.gui.accelerator import * """ Explanation: <a id="tutorial1"></a> Tutorial N1. Double Bend Achromat. We designed a simple lattice to demonstrate the basic concepts and syntax of the optics functions calculation. Also, we chose DBA to demonstrate the periodic solution for the optical functions calculation. End of explanation """ # defining of the drifts D1 = Drift(l=2.) D2 = Drift(l=0.6) D3 = Drift(l=0.3) D4 = Drift(l=0.7) D5 = Drift(l=0.9) D6 = Drift(l=0.2) # defining of the quads Q1 = Quadrupole(l=0.4, k1=-1.3) Q2 = Quadrupole(l=0.8, k1=1.4) Q3 = Quadrupole(l=0.4, k1=-1.7) Q4 = Quadrupole(l=0.5, k1=1.3) # defining of the bending magnet B = Bend(l=2.7, k1=-.06, angle=2*pi/16., e1=pi/16., e2=pi/16.) # defining of the sextupoles SF = Sextupole(l=0.01, k2=1.5) #random value SD = Sextupole(l=0.01, k2=-1.5) #random value # cell creating cell = (D1, Q1, D2, Q2, D3, Q3, D4, B, D5, SD, D5, SF, D6, Q4, D6, SF, D5, SD, D5, B, D4, Q3, D3, Q2, D2, Q1, D1) cell """ Explanation: Creating lattice Ocelot has following elements: Drift, Quadrupole, Sextupole, Octupole, Bend, SBend, RBend, Edge, Multipole, Hcor, Vcor, Solenoid, Cavity, Monitor, Marker, Undulator. End of explanation """ print(B) """ Explanation: hint: to see a simple description of the function put cursor inside () and press Shift-Tab or you can type sign ? before function. To extend dialog window press +* * Also, one can get more info about element just using print(element) End of explanation """ lat = MagneticLattice(cell) # to see total lenth of the lattice print("length of the cell: ", lat.totalLen, "m") """ Explanation: The cell is a list of the simple objects which contain a physical information of lattice elements such as length, strength, voltage and so on. In order to create a transport map for every element and bind it with lattice object we have to create new Ocelot object - MagneticLattice() which makes these things automatically. MagneticLattice(sequence, start=None, stop=None, method=MethodTM()): * sequence - list of the elements, other parameters we will consider in tutorial N2. End of explanation """ tws = twiss(lat, nPoints=1000) # to see twiss paraments at the begining of the cell, uncomment next line # print(tws[0]) print("length = ", len(tws)) # to see twiss paraments at the end of the cell, uncomment next line print(tws[998] == tws[-1]) # plot optical functions. plot_opt_func(lat, tws, top_plot = ["Dx", "Dy"], legend=False, font_size=10) plt.show() # you also can use standard matplotlib functions for plotting #s = [tw.s for tw in tws] #bx = [tw.beta_x for tw in tws] #plt.plot(s, bx) #plt.show() # you can play with quadrupole strength and try to make achromat Q4.k1 = 1.18 # to make achromat uncomment next line # Q4.k1 = 1.18543769836 # To use matching function, please see ocelot/demos/ebeam/dba.py # updating transfer maps after changing element parameters. lat.update_transfer_maps() # recalculate twiss parameters tws=twiss(lat, nPoints=1000) plot_opt_func(lat, tws, legend=False) plt.show() """ Explanation: Optical function calculation Uses: * twiss() function and, * Twiss() object contains twiss parameters and other information at one certain position (s) of lattice To calculate twiss parameters you have to run twiss(lattice, tws0=None, nPoints=None) function. If you want to get a periodic solution leave tws0 by default. You can change the number of points over the cell, If nPoints=None, then twiss parameters are calculated at the end of each element. twiss() function returns list of Twiss() objects. You will see the Twiss object contains more information than just twiss parameters. End of explanation """
statsmodels/statsmodels.github.io
v0.13.0/examples/notebooks/generated/statespace_arma_0.ipynb
bsd-3-clause
%matplotlib inline import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.graphics.api import qqplot """ Explanation: Autoregressive Moving Average (ARMA): Sunspots data This notebook replicates the existing ARMA notebook using the statsmodels.tsa.statespace.SARIMAX class rather than the statsmodels.tsa.ARMA class. End of explanation """ print(sm.datasets.sunspots.NOTE) dta = sm.datasets.sunspots.load_pandas().data dta.index = pd.Index(pd.date_range("1700", end="2009", freq="A-DEC")) del dta["YEAR"] dta.plot(figsize=(12,4)); fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(211) fig = sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=ax1) ax2 = fig.add_subplot(212) fig = sm.graphics.tsa.plot_pacf(dta, lags=40, ax=ax2) arma_mod20 = sm.tsa.statespace.SARIMAX(dta, order=(2,0,0), trend='c').fit(disp=False) print(arma_mod20.params) arma_mod30 = sm.tsa.statespace.SARIMAX(dta, order=(3,0,0), trend='c').fit(disp=False) print(arma_mod20.aic, arma_mod20.bic, arma_mod20.hqic) print(arma_mod30.params) print(arma_mod30.aic, arma_mod30.bic, arma_mod30.hqic) """ Explanation: Sunspots Data End of explanation """ sm.stats.durbin_watson(arma_mod30.resid) fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(111) ax = plt.plot(arma_mod30.resid) resid = arma_mod30.resid stats.normaltest(resid) fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(111) fig = qqplot(resid, line='q', ax=ax, fit=True) fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(211) fig = sm.graphics.tsa.plot_acf(resid, lags=40, ax=ax1) ax2 = fig.add_subplot(212) fig = sm.graphics.tsa.plot_pacf(resid, lags=40, ax=ax2) r,q,p = sm.tsa.acf(resid, fft=True, qstat=True) data = np.c_[r[1:], q, p] index = pd.Index(range(1,q.shape[0]+1), name="lag") table = pd.DataFrame(data, columns=["AC", "Q", "Prob(>Q)"], index=index) print(table) """ Explanation: Does our model obey the theory? End of explanation """ predict_sunspots = arma_mod30.predict(start='1990', end='2012', dynamic=True) fig, ax = plt.subplots(figsize=(12, 8)) dta.loc['1950':].plot(ax=ax) predict_sunspots.plot(ax=ax, style='r'); def mean_forecast_err(y, yhat): return y.sub(yhat).mean() mean_forecast_err(dta.SUNACTIVITY, predict_sunspots) """ Explanation: This indicates a lack of fit. In-sample dynamic prediction. How good does our model do? End of explanation """
astroumd/GradMap
notebooks/Lectures2021/Lecture2/challenge_problem2_student_version.ipynb
gpl-3.0
# your code here """ Explanation: Welcome to your projectile motion challenge problem! Here you'll write code that will plot the trajectory of a projectile in ideal conditions, with the standard assumptions of no air resistance and constant gravitational acceleration. You'll use the path-length function you created earlier to compare the total distance traveled in the air by the projectile for different launch angles and launch velocities. We'll track the projectile's position using an $xy$ coordinate system. It is launched from position (0,0) with launch angle $\theta$ above the positive $x$ axis, launch speed $v_0$, and gravitational acceleration $g$ in the $-y$ direction. We'll use a time coordinate $t$ to specify the time since launch. First, in the cell below, write functions that return x position and y position when passed values of $t$, $v_0$, $\theta$, and $g$. Assume the angle is passed in units of radians. Hint: You can treat the x and y directions separately. For example, the equation of motion for the x-coordinate is $$x = v_{0x} t$$ where $v_{0x}$ is the x-component of initial velocity vector. How do you compute $v_{0x}$ given $v_0$ and $\theta$? End of explanation """ # your code here """ Explanation: Now write a function that returns the total time the projectile will stay in the air (which means return to $y = 0$), in units of seconds, given $v_0$ (with units m /s), $\theta$ (in radians) , and $g$ (with units m / s$^2$). Hint: the equation of motion along y-direction is $$y = v_{0y}t - \frac{1}{2}gt^2$$ When $y = 0$, $t$ either equals $0$, or $$t = t_f = \frac{2v_y}{g}$$ where $t_f$ represents the time the projectile will stay in the air. End of explanation """ plt.close() # leave this here. it makes sure that if you run this cell again, the plot appears below # parameters # calculate the trajectory # plot-don't forget to label your axes! """ Explanation: In the cell below, make a plot of a projectile trajectory when $g$ = 9.8 m/$s^2$ in the -y direction, $v_0$ is 100 m/s, and $\theta$ is 45 degrees ($\pi$/4 radians). To do this, you might find the following steps helpful: First, create an array of time values linearly spaced between 0 and $t_f$. You get to choose the number of time values. A reasonable choice might be 128, but you can see what happens if you use more or less than that. You'll be recording the $x$ and $y$ positions of the particle at each time, so you'll need arrays for those, too. Loop through the time values and determine the value of $x$ and $y$ at each time. Then plot $y$ vs $x$. $\textit{Recall}:$ $\theta_{radians} = \frac{\theta_{degree}\pi}{180}$ End of explanation """ plt.close() # keep this here # your code here """ Explanation: Next, let's see what happens when we change the launch angle. Make the same plot as above, but for several different values of the launch angle $\theta$, all displayed together in a single plot. For example, you could use 9 angles linearly spaced between 5 and 85 degrees. Plot all the trajectories on the same graph in the cell below. Once you've done that, save the trajectory information for later. In the same loop that you're using to make the plot, save the $x$ and $y$ values for each value of theta, using np.save(). Give them descriptive names that include the value of theta so that you can retrieve them later. End of explanation """ # your code here """ Explanation: Now we want to estimate the total distance traveled by the projectile in the air. You've already written a path-length function. Rewrite the path-length function (and any helper functions) into the cell below. End of explanation """ plt.close() # your code here """ Explanation: Loop through the launch angles again, load the trajectories, and determine the total distance traveled in the air for each angle. Plot these distances versus launch angle. End of explanation """
statsmodels/statsmodels.github.io
v0.12.1/examples/notebooks/generated/mediation_survival.ipynb
bsd-3-clause
import pandas as pd import numpy as np import statsmodels.api as sm from statsmodels.stats.mediation import Mediation """ Explanation: Mediation analysis with duration data This notebook demonstrates mediation analysis when the mediator and outcome are duration variables, modeled using proportional hazards regression. These examples are based on simulated data. End of explanation """ np.random.seed(3424) """ Explanation: Make the notebook reproducible. End of explanation """ n = 1000 """ Explanation: Specify a sample size. End of explanation """ exp = np.random.normal(size=n) """ Explanation: Generate an exposure variable. End of explanation """ def gen_mediator(): mn = np.exp(exp) mtime0 = -mn * np.log(np.random.uniform(size=n)) ctime = -2 * mn * np.log(np.random.uniform(size=n)) mstatus = (ctime >= mtime0).astype(np.int) mtime = np.where(mtime0 <= ctime, mtime0, ctime) return mtime0, mtime, mstatus """ Explanation: Generate a mediator variable. End of explanation """ def gen_outcome(otype, mtime0): if otype == "full": lp = 0.5*mtime0 elif otype == "no": lp = exp else: lp = exp + mtime0 mn = np.exp(-lp) ytime0 = -mn * np.log(np.random.uniform(size=n)) ctime = -2 * mn * np.log(np.random.uniform(size=n)) ystatus = (ctime >= ytime0).astype(np.int) ytime = np.where(ytime0 <= ctime, ytime0, ctime) return ytime, ystatus """ Explanation: Generate an outcome variable. End of explanation """ def build_df(ytime, ystatus, mtime0, mtime, mstatus): df = pd.DataFrame({"ytime": ytime, "ystatus": ystatus, "mtime": mtime, "mstatus": mstatus, "exp": exp}) return df """ Explanation: Build a dataframe containing all the relevant variables. End of explanation """ def run(otype): mtime0, mtime, mstatus = gen_mediator() ytime, ystatus = gen_outcome(otype, mtime0) df = build_df(ytime, ystatus, mtime0, mtime, mstatus) outcome_model = sm.PHReg.from_formula("ytime ~ exp + mtime", status="ystatus", data=df) mediator_model = sm.PHReg.from_formula("mtime ~ exp", status="mstatus", data=df) med = Mediation(outcome_model, mediator_model, "exp", "mtime", outcome_predict_kwargs={"pred_only": True}) med_result = med.fit(n_rep=20) print(med_result.summary()) """ Explanation: Run the full simulation and analysis, under a particular population structure of mediation. End of explanation """ run("full") """ Explanation: Run the example with full mediation End of explanation """ run("partial") """ Explanation: Run the example with partial mediation End of explanation """ run("no") """ Explanation: Run the example with no mediation End of explanation """
mauroalberti/gsf
checks/Check Runge-Kutta-Fehlberg interpolation.ipynb
gpl-3.0
%matplotlib inline import matplotlib.pyplot as plt """ Explanation: Preliminary settings Created by Mauro Alberti Last run: 2019-06-22 In order to plot fields, we run the following commands: End of explanation """ import math """ Explanation: We import the math library: End of explanation """ from pygsf.mathematics.arrays import * from pygsf.spatial.rasters.geotransform import * from pygsf.spatial.rasters.fields import * """ Explanation: The modules to import for dealing with grids are: End of explanation """ from pygsf.spatial.movements import interpolate_rkf """ Explanation: For calculating pathlines: End of explanation """ k = 2 * math.pi def z_func_fx(x, y): return k*y def z_func_fy(x, y): return -k*x """ Explanation: Velocity field with circular motion The example circular motion vector field has components: v = y i - x j as deriving from the equation: v = - z x r where z is the vertical vector, r the position vector and x the vector product. End of explanation """ rows=100; cols=100 size_x = 1; size_y = 1 tlx = -50.0; tly = 50.0 gt1 = GeoTransform( inTopLeftX=tlx, inTopLeftY=tly, inPixWidth=size_x, inPixHeight=size_y) """ Explanation: The velocity field parameters for testing the results are: v = w * r w = v / r |v| = sqrt(k^2y^2 + k^2x^2) = k * r 1 cycle -> 2 pi r v = ds / dt -> ds = v * dt 2 pi r = v dt 2 pi r = v T -> T = 2 pi r / v = 2 pi / k geotransform and grid definitions End of explanation """ fx1 = array_from_function( row_num=rows, col_num=cols, geotransform=gt1, z_transfer_func=z_func_fx) print(fx1) """ Explanation: vector field x-component End of explanation """ fy1 = array_from_function( row_num=rows, col_num=cols, geotransform=gt1, z_transfer_func=z_func_fy) print(fy1) """ Explanation: vector field y-component End of explanation """ X, Y = gtToxyCellCenters( gt=gt1, num_rows=rows, num_cols=cols) """ Explanation: flow characteristics: magnitude and streamlines To visualize the parameters of the flow, we calculate the geographic coordinates: End of explanation """ magn = magnitude( fld_x=fx1, fld_y=fy1) fig = plt.figure(figsize=(14, 6)) plt.contourf(X, Y, np.log10(magn), cmap="bwr") cbar = plt.colorbar() cbar.ax.set_ylabel('Magnitude (log10)') plt.streamplot(X, Y, fx1/magn, fy1/magn, color="black") plt.axis("image") plt.title('Vector field magnitude and streamlines') plt.xlabel('x') plt.ylabel('y') import math from pygsf.spatial.vectorial.geometries import Point from pygsf.spatial.rasters.geoarray import GeoArray ga = GeoArray( inGeotransform=gt1, inProjection="undef", inLevels=[fx1, fy1]) time_increm = 1.0e-4 period = 2 * math.pi / k number_of_cycles = 100 steps = number_of_cycles * (period / time_increm) print (steps) first_pt = Point(0, 20) str_pt = first_pt pts_x, pts_y = [first_pt.x], [first_pt.y] for n in range(int(steps)): end_pt, error = interpolate_rkf( geoarray=ga, delta_time=time_increm, start_pt=str_pt) if end_pt is None: break pts_x.append(end_pt.x) pts_y.append(end_pt.y) str_pt = end_pt print (end_pt) """ Explanation: and the vector field magnitude: End of explanation """ fig = plt.figure(figsize=(14, 6)) plt.contourf(X, Y, np.log10(magn), cmap="bwr") cbar = plt.colorbar() cbar.ax.set_ylabel('Magnitude (log10)') plt.streamplot(X, Y, fx1/magn, fy1/magn, color="black") plt.scatter(pts_x, pts_y, color='b') plt.axis("image") plt.title('Vector field magnitude and streamlines') plt.xlabel('x') plt.ylabel('y') """ Explanation: After 100 cycles the calculated point position is in the expected (initial) position: x=0, y=20. End of explanation """
gcallah/Indra
notebooks/AFirstModel.ipynb
gpl-3.0
from indra.agent import Agent, AgentEncoder from indra.composite import Composite from indra.env import Env """ Explanation: A First Model Using Indra2 The aim of re-writing the library code upon which Indra models relied was to reduce the complexity of the system, and achieve greater expressiveness with fewer lines of code. So far, the results look promising. Let's take a look at the beginnings of the first model being written based on the indra2 library. This is a classic <a href="https://en.wikipedia.org/wiki/Lotka–Volterra_equations">predator-prey model</a>, often called "wolf-sheep" in the ABM world. The central idea is to model how populations of predators and their prey will cycle in a circumscribed environment. The first thing to do is import the (few!) items we need to get going: End of explanation """ NUM_WOLVES = 3 NUM_SHEEP = 12 WOLF_LIFESPAN = 5 WOLF_REPRO_PERIOD = 6 SHEEP_LIFESPAN = 8 SHEEP_REPRO_PERIOD = 6 """ Explanation: Next define a few constants -- these will be params in the fully developed system: End of explanation """ def sheep_action(agent): print("I'm " + agent.name + " and I eat grass.") def wolf_action(agent): print("I'm " + agent.name + " and my remaining life is: " + str(agent.duration)) """ Explanation: Now we will define what wolves and sheep do when called upon to act -- the model is far from done at this point, and these actions are trivial, but they illustrate the use of the system: End of explanation """ def create_wolf(i): return Agent("wolf" + str(i), duration=WOLF_LIFESPAN, action=wolf_action, attrs={"time_to_repr": WOLF_REPRO_PERIOD}) def create_sheep(i): return Agent("sheep" + str(i), duration=SHEEP_LIFESPAN, action=sheep_action, attrs={"time_to_repr": SHEEP_REPRO_PERIOD}) """ Explanation: Next let's create to helper functions to create wolves and sheep, just to make the code following this a little simpler: End of explanation """ wolves = Composite("wolves") for i in range(NUM_WOLVES): wolves += create_wolf(i) sheep = Composite("sheep") for i in range(NUM_SHEEP): sheep += create_sheep(i) """ Explanation: Now we have everything we need to create our populations and put them in a meadow to interact: End of explanation """ meadow = Env("meadow") meadow += wolves meadow += sheep """ Explanation: Now we will create a "meadow" in which these critters will interact -- the meadow is an instance of Env: End of explanation """ meadow() 3 + 7 3 + + 7 3 + * + 7 """ Explanation: Lastly, we set things going in the meadow: End of explanation """
tensorflow/examples
courses/udacity_intro_to_tensorflow_for_deep_learning/l05c02_dogs_vs_cats_with_augmentation.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 The TensorFlow Authors. End of explanation """ import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator import os import numpy as np import matplotlib.pyplot as plt """ Explanation: Dogs vs Cats Image Classification With Image Augmentation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l05c02_dogs_vs_cats_with_augmentation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l05c02_dogs_vs_cats_with_augmentation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> In this tutorial, we will discuss how to classify images into pictures of cats or pictures of dogs. We'll build an image classifier using tf.keras.Sequential model and load data using tf.keras.preprocessing.image.ImageDataGenerator. Specific concepts that will be covered: In the process, we will build practical experience and develop intuition around the following concepts Building data input pipelines using the tf.keras.preprocessing.image.ImageDataGenerator class — How can we efficiently work with data on disk to interface with our model? Overfitting - what is it, how to identify it, and how can we prevent it? Data Augmentation and Dropout - Key techniques to fight overfitting in computer vision tasks that we will incorporate into our data pipeline and image classifier model. We will follow the general machine learning workflow: Examine and understand data Build an input pipeline Build our model Train our model Test our model Improve our model/Repeat the process <hr> Before you begin Before running the code in this notebook, reset the runtime by going to Runtime -> Reset all runtimes in the menu above. If you have been working through several notebooks, this will help you avoid reaching Colab's memory limits. Importing packages Let's start by importing required packages: os — to read files and directory structure numpy — for some matrix math outside of TensorFlow matplotlib.pyplot — to plot the graph and display images in our training and validation data End of explanation """ _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' zip_dir = tf.keras.utils.get_file('cats_and_dogs_filterted.zip', origin=_URL, extract=True) """ Explanation: Data Loading To build our image classifier, we begin by downloading the dataset. The dataset we are using is a filtered version of <a href="https://www.kaggle.com/c/dogs-vs-cats/data" target="_blank">Dogs vs. Cats</a> dataset from Kaggle (ultimately, this dataset is provided by Microsoft Research). In previous Colabs, we've used <a href="https://www.tensorflow.org/datasets" target="_blank">TensorFlow Datasets</a>, which is a very easy and convenient way to use datasets. In this Colab however, we will make use of the class tf.keras.preprocessing.image.ImageDataGenerator which will read data from disk. We therefore need to directly download Dogs vs. Cats from a URL and unzip it to the Colab filesystem. End of explanation """ base_dir = os.path.join(os.path.dirname(zip_dir), 'cats_and_dogs_filtered') train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') train_cats_dir = os.path.join(train_dir, 'cats') # directory with our training cat pictures train_dogs_dir = os.path.join(train_dir, 'dogs') # directory with our training dog pictures validation_cats_dir = os.path.join(validation_dir, 'cats') # directory with our validation cat pictures validation_dogs_dir = os.path.join(validation_dir, 'dogs') # directory with our validation dog pictures """ Explanation: The dataset we have downloaded has following directory structure. <pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" > <b>cats_and_dogs_filtered</b> |__ <b>train</b> |______ <b>cats</b>: [cat.0.jpg, cat.1.jpg, cat.2.jpg ....] |______ <b>dogs</b>: [dog.0.jpg, dog.1.jpg, dog.2.jpg ...] |__ <b>validation</b> |______ <b>cats</b>: [cat.2000.jpg, cat.2001.jpg, cat.2002.jpg ....] |______ <b>dogs</b>: [dog.2000.jpg, dog.2001.jpg, dog.2002.jpg ...] </pre> We'll now assign variables with the proper file path for the training and validation sets. End of explanation """ num_cats_tr = len(os.listdir(train_cats_dir)) num_dogs_tr = len(os.listdir(train_dogs_dir)) num_cats_val = len(os.listdir(validation_cats_dir)) num_dogs_val = len(os.listdir(validation_dogs_dir)) total_train = num_cats_tr + num_dogs_tr total_val = num_cats_val + num_dogs_val print('total training cat images:', num_cats_tr) print('total training dog images:', num_dogs_tr) print('total validation cat images:', num_cats_val) print('total validation dog images:', num_dogs_val) print("--") print("Total training images:", total_train) print("Total validation images:", total_val) """ Explanation: Understanding our data Let's look at how many cats and dogs images we have in our training and validation directory End of explanation """ BATCH_SIZE = 100 IMG_SHAPE = 150 # Our training data consists of images with width of 150 pixels and height of 150 pixels """ Explanation: Setting Model Parameters For convenience, let us set up variables that will be used later while pre-processing our dataset and training our network. End of explanation """ # This function will plot images in the form of a grid with 1 row and 5 columns where images are placed in each column. def plotImages(images_arr): fig, axes = plt.subplots(1, 5, figsize=(20,20)) axes = axes.flatten() for img, ax in zip(images_arr, axes): ax.imshow(img) plt.tight_layout() plt.show() """ Explanation: After defining our generators for training and validation images, flow_from_directory method will load images from the disk and will apply rescaling and will resize them into required dimensions using single line of code. Data Augmentation Overfitting often occurs when we have a small number of training examples. One way to fix this problem is to augment our dataset so that it has sufficient number and variety of training examples. Data augmentation takes the approach of generating more training data from existing training samples, by augmenting the samples through random transformations that yield believable-looking images. The goal is that at training time, your model will never see the exact same picture twice. This exposes the model to more aspects of the data, allowing it to generalize better. In tf.keras we can implement this using the same ImageDataGenerator class we used before. We can simply pass different transformations we would want to our dataset as a form of arguments and it will take care of applying it to the dataset during our training process. To start off, let's define a function that can display an image, so we can see the type of augmentation that has been performed. Then, we'll look at specific augmentations that we'll use during training. End of explanation """ image_gen = ImageDataGenerator(rescale=1./255, horizontal_flip=True) train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE)) """ Explanation: Flipping the image horizontally We can begin by randomly applying horizontal flip augmentation to our dataset and seeing how individual images will look after the transformation. This is achieved by passing horizontal_flip=True as an argument to the ImageDataGenerator class. End of explanation """ augmented_images = [train_data_gen[0][0][0] for i in range(5)] plotImages(augmented_images) """ Explanation: To see the transformation in action, let's take one sample image from our training set and repeat it five times. The augmentation will be randomly applied (or not) to each repetition. End of explanation """ image_gen = ImageDataGenerator(rescale=1./255, rotation_range=45) train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, shuffle=True, target_size=(IMG_SHAPE, IMG_SHAPE)) """ Explanation: Rotating the image The rotation augmentation will randomly rotate the image up to a specified number of degrees. Here, we'll set it to 45. End of explanation """ augmented_images = [train_data_gen[0][0][0] for i in range(5)] plotImages(augmented_images) """ Explanation: To see the transformation in action, let's once again take a sample image from our training set and repeat it. The augmentation will be randomly applied (or not) to each repetition. End of explanation """ image_gen = ImageDataGenerator(rescale=1./255, zoom_range=0.5) train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, shuffle=True, target_size=(IMG_SHAPE, IMG_SHAPE)) """ Explanation: Applying Zoom We can also apply Zoom augmentation to our dataset, zooming images up to 50% randomly. End of explanation """ augmented_images = [train_data_gen[0][0][0] for i in range(5)] plotImages(augmented_images) """ Explanation: One more time, take a sample image from our training set and repeat it. The augmentation will be randomly applied (or not) to each repetition. End of explanation """ image_gen_train = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') train_data_gen = image_gen_train.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE), class_mode='binary') """ Explanation: Putting it all together We can apply all these augmentations, and even others, with just one line of code, by passing the augmentations as arguments with proper values. Here, we have applied rescale, rotation of 45 degrees, width shift, height shift, horizontal flip, and zoom augmentation to our training images. End of explanation """ augmented_images = [train_data_gen[0][0][0] for i in range(5)] plotImages(augmented_images) """ Explanation: Let's visualize how a single image would look like five different times, when we pass these augmentations randomly to our dataset. End of explanation """ image_gen_val = ImageDataGenerator(rescale=1./255) val_data_gen = image_gen_val.flow_from_directory(batch_size=BATCH_SIZE, directory=validation_dir, target_size=(IMG_SHAPE, IMG_SHAPE), class_mode='binary') """ Explanation: Creating Validation Data generator Generally, we only apply data augmentation to our training examples, since the original images should be representative of what our model needs to manage. So, in this case we are only rescaling our validation images and converting them into batches using ImageDataGenerator. End of explanation """ model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Dropout(0.5), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(2) ]) """ Explanation: Model Creation Define the model The model consists of four convolution blocks with a max pool layer in each of them. Before the final Dense layers, we're also applying a Dropout probability of 0.5. It means that 50% of the values coming into the Dropout layer will be set to zero. This helps to prevent overfitting. Then we have a fully connected layer with 512 units, with a relu activation function. The model will output class probabilities for two classes — dogs and cats — using softmax. End of explanation """ model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) """ Explanation: Compiling the model As usual, we will use the adam optimizer. Since we output a softmax categorization, we'll use sparse_categorical_crossentropy as the loss function. We would also like to look at training and validation accuracy on each epoch as we train our network, so we are passing in the metrics argument. End of explanation """ model.summary() """ Explanation: Model Summary Let's look at all the layers of our network using summary method. End of explanation """ epochs=100 history = model.fit_generator( train_data_gen, steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))), epochs=epochs, validation_data=val_data_gen, validation_steps=int(np.ceil(total_val / float(BATCH_SIZE))) ) """ Explanation: Train the model It's time we train our network. Since our batches are coming from a generator (ImageDataGenerator), we'll use fit_generator instead of fit. End of explanation """ acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(epochs) plt.figure(figsize=(8, 8)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.show() """ Explanation: Visualizing results of the training We'll now visualize the results we get after training our network. End of explanation """
Alexoner/skynet
notebooks/TransferLearning.ipynb
mit
# A bit of setup import numpy as np import matplotlib.pyplot as plt from time import time %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading extenrnal modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 """ Explanation: Transfer learning In the previous exercise we introduced the TinyImageNet-100-A dataset, and combined a handful of pretrained models on this dataset to improve our classification performance. In this exercise we will explore several ways to adapt one of these same pretrained models to the TinyImageNet-100-B dataset, which does not share any images or object classes with TinyImage-100-A. We will see that we can use a pretrained classfier together with a small amount of training data from TinyImageNet-100-B to achieve reasonable performance on the TinyImageNet-100-B validation set. End of explanation """ # Load the TinyImageNet-100-B dataset from skynet.utils.data_utils import load_tiny_imagenet, load_models tiny_imagenet_b = '../skynet/datasets/tiny-imagenet-100-B' data = load_tiny_imagenet(tiny_imagenet_b, subtract_mean=True) # Zero-mean the data # mean_img = np.mean(X_train, axis=0) # X_train -= mean_img # X_val -= mean_img # X_test -= mean_img mean_img = data['mean_image'] X_train = data['X_train'] X_val = data['X_val'] X_test = data['X_test'] y_train = data['y_train'] y_val = data['y_val'] y_test = data['y_test'] # We will use a subset of the TinyImageNet-B training data mask = np.random.choice(data['X_train'].shape[0], size=5000, replace=False) X_train = data['X_train'][mask] y_train = data['y_train'][mask] # Load a pretrained model; it is a five layer convnet. models_dir = '../skynet/datasets/tiny-100-A-pretrained' model = load_models(models_dir)['model1'] """ Explanation: Load data and model You should already have downloaded the TinyImageNet-100-A and TinyImageNet-100-B datasets along with the pretrained models. Run the cell below to load (a subset of) the TinyImageNet-100-B dataset and one of the models that was pretrained on TinyImageNet-100-A. TinyImageNet-100-B contains 50,000 training images in total (500 per class for all 100 classes) but for this exercise we will use only 5,000 training images (50 per class on average). End of explanation """ for names in data['class_names']: print(' '.join('"%s"' % name for name in names)) """ Explanation: TinyImageNet-100-B classes In the previous assignment we printed out a list of all classes in TinyImageNet-100-A. We can do the same on TinyImageNet-100-B; if you compare with the list in the previous exercise you will see that there is no overlap between the classes in TinyImageNet-100-A and TinyImageNet-100-B. End of explanation """ # Visualize some examples of the training data class_names = data['class_names'] mean_img = data['mean_image'] classes_to_show = 7 examples_per_class = 5 class_idxs = np.random.choice(len(class_names), size=classes_to_show, replace=False) for i, class_idx in enumerate(class_idxs): train_idxs, = np.nonzero(y_train == class_idx) train_idxs = np.random.choice(train_idxs, size=examples_per_class, replace=False) for j, train_idx in enumerate(train_idxs): img = X_train[train_idx] + mean_img img = img.transpose(1, 2, 0).astype('uint8') plt.subplot(examples_per_class, classes_to_show, 1 + i + classes_to_show * j) if j == 0: plt.title(class_names[class_idx][0]) plt.imshow(img) plt.gca().axis('off') plt.show() """ Explanation: Visualize Examples Similar to the previous exercise, we can visualize examples from the TinyImageNet-100-B dataset. The images are similar to TinyImageNet-100-A, but the images and classes in the two datasets are disjoint. End of explanation """ from skynet.neural_network.classifiers.convnet import five_layer_convnet # These should store extracted features for the training and validation sets # respectively. # # More concretely, X_train_feats should be an array of shape # (X_train.shape[0], 512) where X_train_feats[i] is the 512-dimensional # feature vector extracted from X_train[i] using model. # # Similarly X_val_feats should have shape (X_val.shape[0], 512) and # X_val_feats[i] should be the 512-dimensional feature vector extracted from # X_val[i] using model. X_train_feats = None X_val_feats = None # Use our pre-trained model to extract features on the subsampled training set # and the validation set. ################################################################################ # TODO: Use the pretrained model to extract features for the training and # # validation sets for TinyImageNet-100-B. # # # # HINT: Similar to computing probabilities in the previous exercise, you # # should split the training and validation sets into small batches to avoid # # using absurd amounts of memory. # ################################################################################ X_train_feats = five_layer_convnet(X_train, model, y=None, reg=0.0, extract_features=True) X_val_feats = five_layer_convnet(X_val, model, y=None, reg=0.0, extract_features=True) pass ################################################################################ # END OF YOUR CODE # ################################################################################ """ Explanation: Extract features ConvNets tend to learn generalizable high-level image features. For the five layer ConvNet architecture, we will use the (rectified) activations of the first fully-connected layer as our high-level image features. Open the file cs231n/classifiers/convnet.py and modify the five_layer_convnet function to return features when the extract_features flag is True. This should be VERY simple. Once you have done that, fill in the cell below, which should use the pretrained model in the model variable to extract features from all images in the training and validation sets. End of explanation """ from skynet.linear.k_nearest_neighbor import KNearestNeighbor # Predicted labels for X_val using a k-nearest-neighbor classifier trained on # the features extracted from X_train. knn_y_val_pred[i] = c indicates that # the kNN classifier predicts that X_val[i] has label c. knn_y_val_pred = None ################################################################################ # TODO: Use a k-nearest neighbor classifier to compute knn_y_val_pred. # # You may need to experiment with k to get the best performance. # ################################################################################ knn = KNearestNeighbor() knn.train(X_train_feats, y_train) knn_y_val_pred = knn.predict(X_val_feats, k=25) pass ################################################################################ # END OF YOUR CODE # ################################################################################ print('Validation set accuracy: %f' % np.mean(knn_y_val_pred == y_val)) """ Explanation: kNN with ConvNet features A simple way to implement transfer learning is to use a k-nearest neighborhood classifier. However instead of computing the distance between images using their pixel values as we did in Assignment 1, we will instead say that the distance between a pair of images is equal to the L2 distance between their feature vectors extracted using our pretrained ConvNet. Implement this idea in the cell below. You can use the KNearestNeighbor class in the file linear/classifiers/k_nearest_neighbor.py. End of explanation """ dists = knn.compute_distances_no_loops(X_val_feats) num_imgs = 5 neighbors_to_show = 6 query_idxs = np.random.randint(X_val.shape[0], size=num_imgs) next_subplot = 1 first_row = True for query_idx in query_idxs: query_img = X_val[query_idx] + mean_img query_img = query_img.transpose(1, 2, 0).astype('uint8') plt.subplot(num_imgs, neighbors_to_show + 1, next_subplot) plt.imshow(query_img) plt.gca().axis('off') if first_row: plt.title('query') next_subplot += 1 o = np.argsort(dists[query_idx]) for i in range(neighbors_to_show): img = X_train[o[i]] + mean_img img = img.transpose(1, 2, 0).astype('uint8') plt.subplot(num_imgs, neighbors_to_show + 1, next_subplot) plt.imshow(img) plt.gca().axis('off') if first_row: plt.title('neighbor %d' % (i + 1)) next_subplot += 1 first_row = False """ Explanation: Visualize neighbors Recall that the kNN classifier computes the distance between all of its training instances and all of its test instances. We can use this distance matrix to help understand what the ConvNet features care about; specifically, we can select several random images from the validation set and visualize their nearest neighbors in the training set. You will see that many times the nearest neighbors are quite far away from each other in pixel space; for example two images that show the same object from different perspectives may appear nearby in ConvNet feature space. Since the following cell selects random validation images, you can run it several times to get different results. End of explanation """ from skynet.linear.linear_classifier import Softmax softmax_y_train_pred = None softmax_y_val_pred = None ################################################################################ # TODO: Train a softmax classifier to predict a TinyImageNet-100-B class from # # features extracted from our pretrained ConvNet. Use this classifier to make # # predictions for the TinyImageNet-100-B training and validation sets, and # # store them in softmax_y_train_pred and softmax_y_val_pred. # # # # You may need to experiment with number of iterations, regularization, and # # learning rate in order to get good performance. The softmax classifier # # should achieve a higher validation accuracy than the kNN classifier. # ################################################################################ softmax = Softmax() # NOTE: the input X of softmax classifier if an array of shape D x N softmax.train(X_train_feats, y_train, learning_rate=1e-2, reg=1e-4, num_iters=1000) y_train_pred = softmax.predict(X_train_feats) y_val_pred = softmax.predict(X_val_feats) pass ################################################################################ # END OF YOUR CODE # ################################################################################ print(y_val_pred.shape, y_train_pred.shape) train_acc = np.mean(y_train == y_train_pred) val_acc = np.mean(y_val_pred == y_val) print(train_acc, val_acc) """ Explanation: Softmax on ConvNet features Another way to implement transfer learning is to train a linear classifier on top of the features extracted from our pretrained ConvNet. In the cell below, train a softmax classifier on the features extracted from the training set of TinyImageNet-100-B and use this classifier to predict on the validation set for TinyImageNet-100-B. You can use the Softmax class in the file cs231n/classifiers/linear_classifier.py. End of explanation """ from skynet.solvers.classifier_trainer import ClassifierTrainer # Make a copy of the pretrained model model_copy = {k: v.copy() for k, v in model.items()} # Initialize the weights of the last affine layer using the trained weights from # the softmax classifier above print(X_train.shape, softmax.W.shape) model_copy['W5'] = softmax.W.copy().astype(model_copy['W5'].dtype) model_copy['b5'] = np.zeros_like(model_copy['b5']) # Fine-tune the model. You will need to adjust the training parameters to get good results. trainer = ClassifierTrainer() learning_rate = 1e-4 reg = 1e-1 dropout = 0.5 num_epochs = 2 finetuned_model = trainer.train(X_train, y_train, X_val, y_val, model_copy, five_layer_convnet, learning_rate=learning_rate, reg=reg, update='rmsprop', dropout=dropout, num_epochs=num_epochs, verbose=True)[0] """ Explanation: Fine-tuning We can improve our classification results on TinyImageNet-100-B further by fine-tuning our ConvNet. In other words, we will train a new ConvNet with the same architecture as our pretrained model, and use the weights of the pretrained model as an initialization to our new model. Usually when fine-tuning you would re-initialize the weights of the final affine layer randomly, but in this case we will initialize the weights of the final affine layer using the weights of the trained softmax classifier from above. In the cell below, use fine-tuning to improve your classification performance on TinyImageNet-100-B. You should be able to outperform the softmax classifier from above using fewer than 5 epochs over the training data. You will need to adjust the learning rate and regularization to achieve good fine-tuning results. End of explanation """
PAIR-code/what-if-tool
keras_sklearn_compare_caip_e2e.ipynb
apache-2.0
import sys python_version = sys.version_info[0] # If you're running on Colab, you'll need to install the What-if Tool package and authenticate def pip_install(module): if python_version == '2': !pip install {module} --quiet else: !pip3 install {module} --quiet try: import google.colab IN_COLAB = True except: IN_COLAB = False if IN_COLAB: pip_install('witwidget') from google.colab import auth auth.authenticate_user() import pandas as pd import numpy as np import tensorflow as tf import witwidget import os import pickle from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential from sklearn.utils import shuffle from sklearn.linear_model import LinearRegression from witwidget.notebook.visualization import WitWidget, WitConfigBuilder # This has been tested on TF 1.14 print(tf.__version__) """ Explanation: Comparing Keras and Scikit models deployed on Cloud AI Platform with the What-if Tool In this notebook we'll use the UCI wine quality dataset to train both tf.keras and Scikit learn regression models that will predict the quality rating of a wine given 11 numerical data points about the wine. You'll learn how to: * Build, train, and then deploy tf.keras and Scikit Learn models to Cloud AI Platform * Use the What-if Tool to compare two different models deployed on CAIP You will need a Google Cloud Platform account and project to run this notebook. Instructions for creating a project can be found here. Installing dependencies End of explanation """ !wget 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv' data = pd.read_csv('winequality-white.csv', index_col=False, delimiter=';') data = shuffle(data, random_state=4) data.head() labels = data['quality'] print(labels.value_counts()) data = data.drop(columns=['quality']) train_size = int(len(data) * 0.8) train_data = data[:train_size] train_labels = labels[:train_size] test_data = data[train_size:] test_labels = labels[train_size:] train_data.head() """ Explanation: Download and process data In this section we'll: * Download the wine quality data directly from UCI Machine Learning * Read it into a Pandas dataframe and preview it * Split the data and labels into train and test sets End of explanation """ # This is the size of the array we'll be feeding into our model for each wine example input_size = len(train_data.iloc[0]) print(input_size) model = Sequential() model.add(Dense(200, input_shape=(input_size,), activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(25, activation='relu')) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') model.summary() model.fit(train_data.values,train_labels.values, epochs=4, batch_size=32, validation_split=0.1) """ Explanation: Train tf.keras model In this section we'll: Build a regression model using tf.keras to predict a wine's quality score Train the model Add a layer to the model to prepare it for serving End of explanation """ # Update these to your own GCP project + model names GCP_PROJECT = 'your_gcp_project' KERAS_MODEL_BUCKET = 'gs://your_storage_bucket' KERAS_VERSION_NAME = 'v1' # Add the serving input layer below in order to serve our model on AI Platform class ServingInput(tf.keras.layers.Layer): # the important detail in this boilerplate code is "trainable=False" def __init__(self, name, dtype, batch_input_shape=None): super(ServingInput, self).__init__(trainable=False, name=name, dtype=dtype, batch_input_shape=batch_input_shape) def get_config(self): return {'batch_input_shape': self._batch_input_shape, 'dtype': self.dtype, 'name': self.name } restored_model = model serving_model = tf.keras.Sequential() serving_model.add(ServingInput('serving', tf.float32, (None, input_size))) serving_model.add(restored_model) tf.contrib.saved_model.save_keras_model(serving_model, os.path.join(KERAS_MODEL_BUCKET, 'keras_export')) # export the model to your GCS bucket export_path = KERAS_MODEL_BUCKET + '/keras_export' # Configure gcloud to use your project !gcloud config set project $GCP_PROJECT # Create a new model in our project, you only need to run this once !gcloud ai-platform models create keras_wine # Deploy the model to Cloud AI Platform !gcloud beta ai-platform versions create $KERAS_VERSION_NAME --model keras_wine \ --origin=$export_path \ --python-version=3.5 \ --runtime-version=1.14 \ --framework='TENSORFLOW' %%writefile predictions.json [7.8, 0.21, 0.49, 1.2, 0.036, 20.0, 99.0, 0.99, 3.05, 0.28, 12.1] # Test the deployed model on an example from our test set # The correct score for this prediction is 7 prediction = !gcloud ai-platform predict --model=keras_wine --json-instances=predictions.json --version=$KERAS_VERSION_NAME print(prediction[1]) """ Explanation: Deploy keras model to Cloud AI Platform In this section we'll: * Set up some global variables for our GCP project * Add a serving layer to our model so we can deploy it on Cloud AI Platform * Run the deploy command to deploy our model * Generate a test prediction on our deployed model End of explanation """ SKLEARN_VERSION_NAME = 'v1' SKLEARN_MODEL_BUCKET = 'gs://sklearn_model_bucket' scikit_model = LinearRegression().fit(train_data.values, train_labels.values) # Export the model to a local file using pickle pickle.dump(scikit_model, open('model.pkl', 'wb')) """ Explanation: Build and train Scikit learn model In this section we'll: * Train a regression model using Scikit Learn * Save the model to a local file using pickle End of explanation """ # Copy the saved model to Cloud Storage !gsutil cp ./model.pkl gs://wine_sklearn/model.pkl # Create a new model in our project, you only need to run this once !gcloud ai-platform models create sklearn_wine !gcloud beta ai-platform versions create $SKLEARN_VERSION_NAME --model=sklearn_wine \ --origin=$SKLEARN_MODEL_BUCKET \ --runtime-version=1.14 \ --python-version=3.5 \ --framework='SCIKIT_LEARN' # Test the model usnig the same example instance from above !gcloud ai-platform predict --model=sklearn_wine --json-instances=predictions.json --version=$SKLEARN_VERSION_NAME """ Explanation: Deploy Scikit model to CAIP In this section we'll: * Copy our saved model file to Cloud Storage * Run the gcloud command to deploy our model * Generate a prediction on our deployed model End of explanation """ # Create np array of test examples + their ground truth labels test_examples = np.hstack((test_data[:200].values,test_labels[:200].values.reshape(-1,1))) print(test_examples.shape) # Create a What-if Tool visualization, it may take a minute to load # See the cell below this for exploration ideas # We use `set_predict_output_tensor` here becuase our tf.keras model returns a dict with a 'sequential' key config_builder = (WitConfigBuilder(test_examples.tolist(), data.columns.tolist() + ['quality']) .set_ai_platform_model(GCP_PROJECT, 'keras_wine', KERAS_VERSION_NAME).set_predict_output_tensor('sequential').set_uses_predict_api(True) .set_target_feature('quality') .set_model_type('regression') .set_compare_ai_platform_model(GCP_PROJECT, 'sklearn_wine', SKLEARN_VERSION_NAME)) WitWidget(config_builder, height=800) """ Explanation: Compare tf.keras and Scikit models with the What-if Tool Now we're ready for the What-if Tool! In this section we'll: * Create an array of our test examples with their ground truth values. The What-if Tool works best when we send the actual values for each example input. * Instantiate the What-if Tool using the set_compare_ai_platform_model method. This lets us compare 2 models deployed on Cloud AI Platform. End of explanation """
IanHawke/Southampton-PV-NumericalMethods-2016
notebooks/03-Root-finding.ipynb
mit
from __future__ import division import numpy from matplotlib import pyplot %matplotlib notebook def f(Rs): return 3.5 -3.2*(numpy.exp((10+3*Rs)/20.0 - 1.0) - 1.0) - (10.0 + 3.0*Rs)/300.0 - 3 Rs = numpy.linspace(0, 10) pyplot.figure(figsize=(10,6)) pyplot.plot(Rs, f(Rs)) pyplot.xlabel(r"$R_s$") pyplot.ylabel(r"$f$") pyplot.show() """ Explanation: Root finding There are a number of papers, which seem to follow from Xiao, Dunford and Capel, on modelling the $I, V$ (current versus voltage) curve of a PV cell. A typical model has \begin{equation} I = I_{\text{ph}} - I_0 \left[ \exp \left( \frac{V + I \times R_s}{a} - 1 \right) - 1 \right] - \frac{V + I \times R_s}{R_p}. \end{equation} The parameters $I_{\text{ph}}, I_0, a, R_s, R_p$ all need to be determined. To do this we'll need five pairs of $I, V$ values, determined by experiment. Even given those values the equation still can't be solved algebraically: it's nonlinear. Finding values that solve this equation is the realm of nonlinear root finding, and is crucial for a range of numerical methods. One dimensional case Let's assume we know the values of three of the parameters, \begin{equation} I_{\text{ph}} = 3.5, \quad I_0 = 3.2, \quad a = 20, \quad R_p = 300. \end{equation} We'll also assume that a voltage $V = 10$ gives a current $I = 3$. So we have to solve the equation \begin{align} f(R_s) &= I_{\text{ph}} - I_0 \left[ \exp \left( \frac{V + I \times R_s}{a} - 1 \right) - 1 \right] - \frac{V + I \times R_s}{R_p} - I \ &= 3.5 - 3.2 \left[ \exp \left( \frac{10 + 3 R_s}{20} - 1 \right) - 1 \right] - \frac{10 + 3 R_s}{300} - 3\ &= 0. \end{align} Where this equation is satisfied we have the value of $R_s$. Let's check that there is a solution, by plotting values of $f$ for different possible values of $R_s$: End of explanation """ print("When Rs=0, f(Rs)={}".format(f(0))) print("When Rs=10, f(Rs)={}".format(f(10))) """ Explanation: We see that there is a solution at around $R_s = 4$. We want to find it precisely. Bisection It's clear from the figure that there's a solution in the middle: the curve is continuous, and has different signs at either end. End of explanation """ def df(Rs): return -3.2*3/20.0*numpy.exp((10+3*Rs)/20.0 - 1.0) - 3.0/300.0 """ Explanation: We could pick the point in the middle, where $R_s=5$, and check its value: So the sign of $f$ changes between $0$ and $5$ (as expected): This suggests an algorithm - the bisection algorithm. Pick $R_s^{\text{L}}$ and $R_s^{\text{R}}$ such that $f(R_s^{\text{L}}) \times f(R_s^{\text{R}}) < 0$. Compute the midpoint $R_s^{\text{M}} = \tfrac{1}{2}(R_s^{\text{L}} + R_s^{\text{R}})$. Compute the function $f(R_s^{\text{M}})$. If $f(R_s^{\text{L}}) \times f(R_s^{\text{M}}) < 0$ then the root is between the left point and the midpoint. So set $R_s^{\text{R}} = R_s^{\text{M}}$. Otherwise the root is between the midpoint and the right point. So set $R_s^{\text{L}} = R_s^{\text{M}}$. Repeat from 2 until the value of $f(R_s^{\text{M}})$ is sufficiently small. Let's implement that, requiring that $| f(R_s^{\text{M}}) | < 10^{-12}$. Newton's method Bisection is safe - it will always converge. It has two problems. The first is that it's slow: requiring tens or hundreds of function evaluations (which could be expensive) to find the root. The second is that it's very difficult to generalize to multiple dimensions. Instead we use Newton's method. This starts from a guess for $R_s$, $R_s^{(0)}$. It then updates this guess, computing \begin{equation} R_s^{(k+1)} = R_s^{(k)} - \frac{f \left( R_s^{(k)} \right)}{f' \left( R_s^{(k)} \right)}. \end{equation} This is computing the tangent to the curve $f(R_s)$ at the guess $R_s^{(k)}$. It then moves along a straight line with this slope until it intersects the horizontal axis: that becomes our new guess. Newton's method is much faster. Its disadvantages are that it isn't safe - it's not guaranteed to converge - and there's the additional effort of computing the derivative. Let's check how fast it is, starting from a guess of 5: End of explanation """ Vk = [0, 10, 20] Ik = [3.97, 3.01, 1.88] Rs = 4.165 Rp = 300 def f_vector(p): Iph, I0, a = p f = numpy.zeros_like(p) for k in range(len(Vk)): f[k] = Iph - I0*(numpy.exp((Vk[k] + Ik[k]*Rs)/a-1.0)-1.0) - (Vk[k] + Ik[k]*Rs)/Rp - Ik[k] return f """ Explanation: The huge improvement in speed is extremely important when solving complex problems. However, the choice of initial guess is crucial to the method converging to the right answer (or at all!). Multi-dimensional case In the more general case we want to solve for all the parameters. We're going to assume that the previous calculation has given us $R_s = 4.165$, and that $R_p = 300$ is also known, and so only need to find $I_{\text{ph}}, I_0, R_p$. This means we'll need three bits of information: three experimental measurements $(I^{[k]}, V^{[k]})$. We'll assume that they are \begin{align} V^{[1]} &= 0, & I^{[1]} & = 3.97, \ V^{[2]} &= 10, & I^{[2]} & = 3.01, \ V^{[3]} &= 20, & I^{[3]} & = 1.88. \end{align} This means we can write down four equations. We'll write this as a vector equation \begin{equation} {\bf f} \left( {\bf P} \right) = 0 \end{equation} where ${\bf P} = \left( I_{\text{ph}}, I_0, a \right)$ are the parameters to be determined. The components of the vector equation each have the form \begin{equation} f_k \left( {\bf P} \right) = I_{\text{ph}} - I_0 \left[ \exp \left( \frac{V^{[k]} + I^{[k]} \times R_s}{a} - 1 \right) - 1 \right] - \frac{V^{[k]} + I^{[k]} \times R_s}{R_p} - I^{[k]}. \end{equation} We can write this down as a single function: End of explanation """ def jacobian(p): Iph, I0, a = p J = numpy.zeros((len(p),len(p))) for k in range(len(p)): J[k,0] = 1.0 J[k,1] = 1.0 - numpy.exp((Vk[k] + Ik[k]*Rs)/a - 1.0) J[k,2] = I0 * (Vk[k] + Ik[k]*Rs)/a**2*numpy.exp((Vk[k] + Ik[k]*Rs)/a - 1.0) return J """ Explanation: We now need Newton's method applied to a vector function. The generalization of the derivative of a scalar function of a scalar to a vector function of a vector is the Jacobian matrix \begin{equation} \frac{\partial {\bf f}}{\partial {\bf p}} = J = \begin{pmatrix} \frac{\partial f_1}{\partial p_1} & \dots & \frac{\partial f_n}{\partial p_1} \ \vdots & \ddots & \vdots \ \frac{\partial f_n}{\partial p_1} & \dots & \frac{\partial f_n}{\partial p_n} \end{pmatrix}. \end{equation} We roughly think of Newton's method as going from \begin{equation} p^{(k+1)} = p^{(k)} - \frac{f \left( p^{(k)} \right)}{f' \left( p^{(k)} \right)} \end{equation} to \begin{equation} {\bf p}^{(k+1)} = {\bf p}^{(k)} - \frac{{\bf f} \left( {\bf p}^{(k)} \right)}{J \left( {\bf p}^{(k)} \right)}. \end{equation} However, this equation makes no sense: dividing a vector by a matrix doesn't mean anything. What we really want to do is the "equivalent" linear system \begin{equation} J \left( {\bf p}^{(k)} \right) \cdot \left( {\bf p}^{(k+1)} - {\bf p}^{(k)} \right) = -{\bf f} \left( {\bf p}^{(k)} \right). \end{equation} By defining the vector ${\bf c}^{(k)} = {\bf p}^{(k+1)} - {\bf p}^{(k)}$, Newton's method becomes \begin{align} J \cdot {\bf c}^{(k)} & = -{\bf f}^{(k)}, \ {\bf p}^{(k+1)} &= {\bf p}^{(k)} + {\bf c}^{(k)}. \end{align} Digression The equation $J \cdot {\bf c}^{(k)} = -{\bf f}^{(k)}$ is an example of a linear system: a known matrix multiplies an unknown vector to match the known vector on the right hand side. The linear system problem is a fundamental building block of numerical methods, and there are lots of algorithms to solve it. We'll use the simple numpy.linalg.solve here: be aware that when the matrix gets large (bigger than say $1,000^2$), much better algorithms will be required. Of course, analytically we would solve this by inverting the matrix. In numerical methods you should never invert the matrix: it's expensive and prone to nasty problems. In nearly all cases, you actually want to solve a linear system. Implementation In this case all components of our vector function have the same form, so computing the Jacobian matrix is just tedious: \begin{align} \frac{\partial f_k}{\partial p_1} & = \frac{\partial f_k}{\partial I_{\text{ph}}} \ &= 1, \ \frac{\partial f_k}{\partial p_2} & = \frac{\partial f_k}{\partial I_0} \ &= 1 - \exp \left( \frac{V^{[k]} + I^{[k]} \times R_s}{a} - 1 \right), \ \frac{\partial f_k}{\partial p_3} & = \frac{\partial f_k}{\partial a} \ &= I_0 \frac{V^{[k]} + I^{[k]} \times R_s}{a^2} \exp \left( \frac{V^{[k]} + I^{[k]} \times R_s}{a} - 1 \right). \end{align} End of explanation """
GoogleCloudPlatform/vertex-ai-samples
notebooks/official/migration/UJ11 Vertex SDK Hyperparameter Tuning.ipynb
apache-2.0
import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG """ Explanation: Vertex AI: Vertex AI Migration: Hyperparameter Tuning <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/vertex-ai-samples/tree/master/notebooks/official/migration/UJ11%20Vertex%20SDK%20Hyperparameter%20Tuning.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/vertex-ai-samples/tree/master/notebooks/official/migration/UJ11%20Vertex%20SDK%20Hyperparameter%20Tuning.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> </table> <br/><br/><br/> Dataset The dataset used for this tutorial is the Boston Housing Prices dataset. The version of the dataset you will use in this tutorial is built into TensorFlow. The trained model predicts the median price of a house in units of 1K USD. Costs This tutorial uses billable components of Google Cloud: Vertex AI Cloud Storage Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Set up your local development environment If you are using Colab or Google Cloud Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step. Otherwise, make sure your environment meets this notebook's requirements. You need the following: The Cloud Storage SDK Git Python 3 virtualenv Jupyter notebook running in a virtual environment with Python 3 The Cloud Storage guide to Setting up a Python development environment and the Jupyter installation guide provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions: Install and initialize the SDK. Install Python 3. Install virtualenv and create a virtual environment that uses Python 3. Activate the virtual environment. To install Jupyter, run pip3 install jupyter on the command-line in a terminal shell. To launch Jupyter, run jupyter notebook on the command-line in a terminal shell. Open this notebook in the Jupyter Notebook Dashboard. Installation Install the latest version of Vertex SDK for Python. End of explanation """ ! pip3 install -U google-cloud-storage $USER_FLAG """ Explanation: Install the latest GA version of google-cloud-storage library as well. End of explanation """ import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) """ Explanation: Restart the kernel Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages. End of explanation """ PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:", PROJECT_ID) ! gcloud config set project $PROJECT_ID """ Explanation: Before you begin GPU runtime This tutorial does not require a GPU runtime. Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage. If you are running this notebook locally, you will need to install the Cloud SDK. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $. End of explanation """ REGION = "us-central1" # @param {type: "string"} """ Explanation: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services. Learn more about Vertex AI regions End of explanation """ from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") """ Explanation: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial. End of explanation """ # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. import os import sys # If on Google Cloud Notebook, then don't execute this code if not os.path.exists("/opt/deeplearning/metadata/env_version"): if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): %env GOOGLE_APPLICATION_CREDENTIALS '' """ Explanation: Authenticate your Google Cloud account If you are using Google Cloud Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, go to the Create service account key page. Click Create service account. In the Service account name field, enter a name, and click Create. In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex" into the filter box, and select Vertex Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin. Click Create. A JSON file that contains your key downloads to your local environment. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. End of explanation """ BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP """ Explanation: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions. Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. End of explanation """ ! gsutil mb -l $REGION $BUCKET_NAME """ Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket. End of explanation """ ! gsutil ls -al $BUCKET_NAME """ Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents: End of explanation """ import google.cloud.aiplatform as aip """ Explanation: Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants End of explanation """ aip.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME) """ Explanation: Initialize Vertex SDK for Python Initialize the Vertex SDK for Python for your project and corresponding bucket. End of explanation """ if os.getenv("IS_TESTING_TRAIN_GPU"): TRAIN_GPU, TRAIN_NGPU = ( aip.gapic.AcceleratorType.NVIDIA_TESLA_K80, int(os.getenv("IS_TESTING_TRAIN_GPU")), ) else: TRAIN_GPU, TRAIN_NGPU = (None, None) if os.getenv("IS_TESTING_DEPLOY_GPU"): DEPLOY_GPU, DEPLOY_NGPU = ( aip.gapic.AcceleratorType.NVIDIA_TESLA_K80, int(os.getenv("IS_TESTING_DEPLOY_GPU")), ) else: DEPLOY_GPU, DEPLOY_NGPU = (None, None) """ Explanation: Set hardware accelerators You can set hardware accelerators for training and prediction. Set the variables TRAIN_GPU/TRAIN_NGPU and DEPLOY_GPU/DEPLOY_NGPU to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Telsa K80 GPUs allocated to each VM, you would specify: (aip.AcceleratorType.NVIDIA_TESLA_K80, 4) Otherwise specify (None, None) to use a container image to run on a CPU. Learn more here hardware accelerator support for your region Note: TF releases before 2.3 for GPU support will fail to load the custom model in this tutorial. It is a known issue and fixed in TF 2.3 -- which is caused by static graph ops that are generated in the serving function. If you encounter this issue on your own custom models, use a container image for TF 2.3 with GPU support. End of explanation """ if os.getenv("IS_TESTING_TF"): TF = os.getenv("IS_TESTING_TF") else: TF = "2-1" if TF[0] == "2": if TRAIN_GPU: TRAIN_VERSION = "tf-gpu.{}".format(TF) else: TRAIN_VERSION = "tf-cpu.{}".format(TF) if DEPLOY_GPU: DEPLOY_VERSION = "tf2-gpu.{}".format(TF) else: DEPLOY_VERSION = "tf2-cpu.{}".format(TF) else: if TRAIN_GPU: TRAIN_VERSION = "tf-gpu.{}".format(TF) else: TRAIN_VERSION = "tf-cpu.{}".format(TF) if DEPLOY_GPU: DEPLOY_VERSION = "tf-gpu.{}".format(TF) else: DEPLOY_VERSION = "tf-cpu.{}".format(TF) TRAIN_IMAGE = "gcr.io/cloud-aiplatform/training/{}:latest".format(TRAIN_VERSION) DEPLOY_IMAGE = "gcr.io/cloud-aiplatform/prediction/{}:latest".format(DEPLOY_VERSION) print("Training:", TRAIN_IMAGE, TRAIN_GPU, TRAIN_NGPU) print("Deployment:", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU) """ Explanation: Set pre-built containers Set the pre-built Docker container image for training and prediction. For the latest list, see Pre-built containers for training. For the latest list, see Pre-built containers for prediction. End of explanation """ if os.getenv("IS_TESTING_TRAIN_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_TRAIN_MACHINE") else: MACHINE_TYPE = "n1-standard" VCPU = "4" TRAIN_COMPUTE = MACHINE_TYPE + "-" + VCPU print("Train machine type", TRAIN_COMPUTE) if os.getenv("IS_TESTING_DEPLOY_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_DEPLOY_MACHINE") else: MACHINE_TYPE = "n1-standard" VCPU = "4" DEPLOY_COMPUTE = MACHINE_TYPE + "-" + VCPU print("Deploy machine type", DEPLOY_COMPUTE) """ Explanation: Set machine type Next, set the machine type to use for training and prediction. Set the variables TRAIN_COMPUTE and DEPLOY_COMPUTE to configure the compute resources for the VMs you will use for for training and prediction. machine type n1-standard: 3.75GB of memory per vCPU. n1-highmem: 6.5GB of memory per vCPU n1-highcpu: 0.9 GB of memory per vCPU vCPUs: number of [2, 4, 8, 16, 32, 64, 96 ] Note: The following is not supported for training: standard: 2 vCPUs highcpu: 2, 4 and 8 vCPUs Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs. End of explanation """ # Make folder for Python training script ! rm -rf custom ! mkdir custom # Add package information ! touch custom/README.md setup_cfg = "[egg_info]\n\ntag_build =\n\ntag_date = 0" ! echo "$setup_cfg" > custom/setup.cfg setup_py = "import setuptools\n\nsetuptools.setup(\n\n install_requires=[\n\n 'tensorflow_datasets==1.3.0',\n\n ],\n\n packages=setuptools.find_packages())" ! echo "$setup_py" > custom/setup.py pkg_info = "Metadata-Version: 1.0\n\nName: Boston Housing tabular regression\n\nVersion: 0.0.0\n\nSummary: Demostration training script\n\nHome-page: www.google.com\n\nAuthor: Google\n\nAuthor-email: aferlitsch@google.com\n\nLicense: Public\n\nDescription: Demo\n\nPlatform: Vertex" ! echo "$pkg_info" > custom/PKG-INFO # Make the training subfolder ! mkdir custom/trainer ! touch custom/trainer/__init__.py """ Explanation: Examine the training package Package layout Before you start the training, you will look at how a Python package is assembled for a custom training job. When unarchived, the package contains the following directory/file layout. PKG-INFO README.md setup.cfg setup.py trainer __init__.py task.py The files setup.cfg and setup.py are the instructions for installing the package into the operating environment of the Docker image. The file trainer/task.py is the Python script for executing the custom training job. Note, when we referred to it in the worker pool specification, we replace the directory slash with a dot (trainer.task) and dropped the file suffix (.py). Package Assembly In the following cells, you will assemble the training package. End of explanation """ %%writefile custom/trainer/task.py # Custom Training for Boston Housing import tensorflow_datasets as tfds import tensorflow as tf from tensorflow.python.client import device_lib from hypertune import HyperTune import numpy as np import argparse import os import sys tfds.disable_progress_bar() parser = argparse.ArgumentParser() parser.add_argument('--model-dir', dest='model_dir', default=os.getenv('AIP_MODEL_DIR'), type=str, help='Model dir.') parser.add_argument('--lr', dest='lr', default=0.001, type=float, help='Learning rate.') parser.add_argument('--decay', dest='decay', default=0.98, type=float, help='Decay rate') parser.add_argument('--units', dest='units', default=64, type=int, help='Number of units.') parser.add_argument('--epochs', dest='epochs', default=20, type=int, help='Number of epochs.') parser.add_argument('--steps', dest='steps', default=200, type=int, help='Number of steps per epoch.') parser.add_argument('--param-file', dest='param_file', default='/tmp/param.txt', type=str, help='Output file for parameters') parser.add_argument('--distribute', dest='distribute', type=str, default='single', help='distributed training strategy') args = parser.parse_args() print('Python Version = {}'.format(sys.version)) print('TensorFlow Version = {}'.format(tf.__version__)) print('TF_CONFIG = {}'.format(os.environ.get('TF_CONFIG', 'Not found'))) def make_dataset(): # Scaling Boston Housing data features def scale(feature): max = np.max(feature) feature = (feature / max).astype(np.float) return feature, max (x_train, y_train), (x_test, y_test) = tf.keras.datasets.boston_housing.load_data( path="boston_housing.npz", test_split=0.2, seed=113 ) params = [] for _ in range(13): x_train[_], max = scale(x_train[_]) x_test[_], _ = scale(x_test[_]) params.append(max) # store the normalization (max) value for each feature with tf.io.gfile.GFile(args.param_file, 'w') as f: f.write(str(params)) return (x_train, y_train), (x_test, y_test) # Build the Keras model def build_and_compile_dnn_model(): model = tf.keras.Sequential([ tf.keras.layers.Dense(args.units, activation='relu', input_shape=(13,)), tf.keras.layers.Dense(args.units, activation='relu'), tf.keras.layers.Dense(1, activation='linear') ]) model.compile( loss='mse', optimizer=tf.keras.optimizers.RMSprop(learning_rate=args.lr, decay=args.decay)) return model model = build_and_compile_dnn_model() # Instantiate the HyperTune reporting object hpt = HyperTune() # Reporting callback class HPTCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): global hpt hpt.report_hyperparameter_tuning_metric( hyperparameter_metric_tag='val_loss', metric_value=logs['val_loss'], global_step=epoch) # Train the model BATCH_SIZE = 16 (x_train, y_train), (x_test, y_test) = make_dataset() model.fit(x_train, y_train, epochs=args.epochs, batch_size=BATCH_SIZE, validation_split=0.1, callbacks=[HPTCallback()]) model.save(args.model_dir) """ Explanation: Task.py contents In the next cell, you write the contents of the hyperparameter tuning script task.py. I won't go into detail, it's just there for you to browse. In summary: Parse the command line arguments for the hyperparameter settings for the current trial. Get the directory where to save the model artifacts from the command line (--model_dir), and if not specified, then from the environment variable AIP_MODEL_DIR. Download and preprocess the Boston Housing dataset. Build a DNN model. The number of units per dense layer and learning rate hyperparameter values are used during the build and compile of the model. A definition of a callback HPTCallback which obtains the validation loss at the end of each epoch (on_epoch_end()) and reports it to the hyperparameter tuning service using hpt.report_hyperparameter_tuning_metric(). Train the model with the fit() method and specify a callback which will report the validation loss back to the hyperparameter tuning service. End of explanation """ ! rm -f custom.tar custom.tar.gz ! tar cvf custom.tar custom ! gzip custom.tar ! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_boston.tar.gz """ Explanation: Store training script on your Cloud Storage bucket Next, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket. End of explanation """ if TRAIN_GPU: machine_spec = { "machine_type": TRAIN_COMPUTE, "accelerator_type": TRAIN_GPU, "accelerator_count": TRAIN_NGPU, } else: machine_spec = {"machine_type": TRAIN_COMPUTE, "accelerator_count": 0} """ Explanation: Train a model training.using-hyperparamter-tuning Prepare your machine specification Now define the machine specification for your custom training job. This tells Vertex what type of machine instance to provision for the training. - machine_type: The type of GCP instance to provision -- e.g., n1-standard-8. - accelerator_type: The type, if any, of hardware accelerator. In this tutorial if you previously set the variable TRAIN_GPU != None, you are using a GPU; otherwise you will use a CPU. - accelerator_count: The number of accelerators. End of explanation """ DISK_TYPE = "pd-ssd" # [ pd-ssd, pd-standard] DISK_SIZE = 200 # GB disk_spec = {"boot_disk_type": DISK_TYPE, "boot_disk_size_gb": DISK_SIZE} """ Explanation: Prepare your disk specification (optional) Now define the disk specification for your custom training job. This tells Vertex what type and size of disk to provision in each machine instance for the training. boot_disk_type: Either SSD or Standard. SSD is faster, and Standard is less expensive. Defaults to SSD. boot_disk_size_gb: Size of disk in GB. End of explanation """ JOB_NAME = "custom_job_" + TIMESTAMP MODEL_DIR = "{}/{}".format(BUCKET_NAME, JOB_NAME) if not TRAIN_NGPU or TRAIN_NGPU < 2: TRAIN_STRATEGY = "single" else: TRAIN_STRATEGY = "mirror" EPOCHS = 20 STEPS = 100 DIRECT = True if DIRECT: CMDARGS = [ "--model-dir=" + MODEL_DIR, "--epochs=" + str(EPOCHS), "--steps=" + str(STEPS), "--distribute=" + TRAIN_STRATEGY, ] else: CMDARGS = [ "--epochs=" + str(EPOCHS), "--steps=" + str(STEPS), "--distribute=" + TRAIN_STRATEGY, ] worker_pool_spec = [ { "replica_count": 1, "machine_spec": machine_spec, "disk_spec": disk_spec, "python_package_spec": { "executor_image_uri": TRAIN_IMAGE, "package_uris": [BUCKET_NAME + "/trainer_boston.tar.gz"], "python_module": "trainer.task", "args": CMDARGS, }, } ] """ Explanation: Define the worker pool specification Next, you define the worker pool specification for your custom training job. The worker pool specification will consist of the following: replica_count: The number of instances to provision of this machine type. machine_spec: The hardware specification. disk_spec : (optional) The disk storage specification. python_package: The Python training package to install on the VM instance(s) and which Python module to invoke, along with command line arguments for the Python module. Let's dive deeper now into the python package specification: -executor_image_spec: This is the docker image which is configured for your custom training job. -package_uris: This is a list of the locations (URIs) of your python training packages to install on the provisioned instance. The locations need to be in a Cloud Storage bucket. These can be either individual python files or a zip (archive) of an entire package. In the later case, the job service will unzip (unarchive) the contents into the docker image. -python_module: The Python module (script) to invoke for running the custom training job. In this example, you will be invoking trainer.task.py -- note that it was not neccessary to append the .py suffix. -args: The command line arguments to pass to the corresponding Pythom module. In this example, you will be setting: - "--model-dir=" + MODEL_DIR : The Cloud Storage location where to store the model artifacts. There are two ways to tell the training script where to save the model artifacts: - direct: You pass the Cloud Storage location as a command line argument to your training script (set variable DIRECT = True), or - indirect: The service passes the Cloud Storage location as the environment variable AIP_MODEL_DIR to your training script (set variable DIRECT = False). In this case, you tell the service the model artifact location in the job specification. - "--epochs=" + EPOCHS: The number of epochs for training. - "--steps=" + STEPS: The number of steps (batches) per epoch. - "--distribute=" + TRAIN_STRATEGY" : The training distribution strategy to use for single or distributed training. - "single": single device. - "mirror": all GPU devices on a single compute instance. - "multi": all GPU devices on all compute instances. End of explanation """ job = aip.CustomJob( display_name="boston_" + TIMESTAMP, worker_pool_specs=worker_pool_spec ) # print(job) """ Explanation: training.create-custom-job Create a custom job Use the class CustomJob to create a custom job, such as for hyperparameter tuning, with the following parameters: display_name: A human readable name for the custom job. worker_pool_specs: The specification for the corresponding VM instances. End of explanation """ from google.cloud.aiplatform import hyperparameter_tuning as hpt hpt_job = aip.HyperparameterTuningJob( display_name="boston_" + TIMESTAMP, custom_job=job, metric_spec={ "val_loss": "minimize", }, parameter_spec={ "lr": hpt.DoubleParameterSpec(min=0.001, max=0.1, scale="log"), "units": hpt.IntegerParameterSpec(min=4, max=128, scale="linear"), }, max_trial_count=6, parallel_trial_count=1, ) # print(hpt_job) """ Explanation: Create a hyperparameter tuning job Use the class HyperparameterTuningJob to create a hyperparameter tuning job, with the following parameters: display_name: A human readable name for the custom job. custom_job: The worker pool spec from this custom job applies to the CustomJobs created in all the trials. metrics_spec: The metrics to optimize. The dictionary key is the metric_id, which is reported by your training job, and the dictionary value is the optimization goal of the metric('minimize' or 'maximize'). parameter_spec: The parameters to optimize. The dictionary key is the metric_id, which is passed into your training job as a command line key word argument, and the dictionary value is the parameter specification of the metric. End of explanation """ hpt_job.run() """ Explanation: Run the hyperparameter tuning job Use the run() method to execute the hyperparameter tuning job. End of explanation """ print(hpt_job.trials) """ Explanation: Example output: INFO:google.cloud.aiplatform.jobs:Creating HyperparameterTuningJob INFO:google.cloud.aiplatform.jobs:HyperparameterTuningJob created. Resource name: projects/759209241365/locations/us-central1/hyperparameterTuningJobs/760969798560514048 INFO:google.cloud.aiplatform.jobs:To use this HyperparameterTuningJob in another session: INFO:google.cloud.aiplatform.jobs:hpt_job = aiplatform.HyperparameterTuningJob.get('projects/759209241365/locations/us-central1/hyperparameterTuningJobs/760969798560514048') INFO:google.cloud.aiplatform.jobs:View HyperparameterTuningJob: https://console.cloud.google.com/ai/platform/locations/us-central1/training/760969798560514048?project=759209241365 INFO:google.cloud.aiplatform.jobs:HyperparameterTuningJob projects/759209241365/locations/us-central1/hyperparameterTuningJobs/760969798560514048 current state: JobState.JOB_STATE_RUNNING INFO:google.cloud.aiplatform.jobs:HyperparameterTuningJob projects/759209241365/locations/us-central1/hyperparameterTuningJobs/760969798560514048 current state: JobState.JOB_STATE_RUNNING ... INFO:google.cloud.aiplatform.jobs:HyperparameterTuningJob projects/759209241365/locations/us-central1/hyperparameterTuningJobs/760969798560514048 current state: JobState.JOB_STATE_SUCCEEDED INFO:google.cloud.aiplatform.jobs:HyperparameterTuningJob run completed. Resource name: projects/759209241365/locations/us-central1/hyperparameterTuningJobs/760969798560514048 Display the hyperparameter tuning job trial results After the hyperparameter tuning job has completed, the property trials will return the results for each trial. End of explanation """ delete_all = True if delete_all: # Delete the dataset using the Vertex dataset object try: if "dataset" in globals(): dataset.delete() except Exception as e: print(e) # Delete the model using the Vertex model object try: if "model" in globals(): model.delete() except Exception as e: print(e) # Delete the endpoint using the Vertex endpoint object try: if "endpoint" in globals(): endpoint.delete() except Exception as e: print(e) # Delete the AutoML or Pipeline trainig job try: if "dag" in globals(): dag.delete() except Exception as e: print(e) # Delete the custom trainig job try: if "job" in globals(): job.delete() except Exception as e: print(e) # Delete the batch prediction job using the Vertex batch prediction object try: if "batch_predict_job" in globals(): batch_predict_job.delete() except Exception as e: print(e) # Delete the hyperparameter tuning job using the Vertex hyperparameter tuning object try: if "hpt_job" in globals(): hpt_job.delete() except Exception as e: print(e) if "BUCKET_NAME" in globals(): ! gsutil rm -r $BUCKET_NAME """ Explanation: Example output: [id: "1" state: SUCCEEDED parameters { parameter_id: "lr" value { number_value: 0.010000000000000002 } } parameters { parameter_id: "units" value { number_value: 66.0 } } final_measurement { step_count: 19 metrics { metric_id: "val_loss" value: 24.61802691948123 } } start_time { seconds: 1629414344 nanos: 232151761 } end_time { seconds: 1629414825 } , id: "2" state: SUCCEEDED parameters { parameter_id: "lr" value { number_value: 0.0036327633937958217 } } parameters { parameter_id: "units" value { number_value: 94.0 } } final_measurement { step_count: 19 metrics { metric_id: "val_loss" value: 25.499705989186356 } } start_time { seconds: 1629414960 nanos: 618333580 } end_time { seconds: 1629415021 } ... , id: "6" state: SUCCEEDED parameters { parameter_id: "lr" value { number_value: 0.002775175422799751 } } parameters { parameter_id: "units" value { number_value: 104.0 } } final_measurement { step_count: 7 metrics { metric_id: "val_loss" value: 24.655450123112377 } } start_time { seconds: 1629415735 nanos: 998711852 } end_time { seconds: 1629415766 } ] Cleaning up To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: Dataset Pipeline Model Endpoint AutoML Training Job Batch Job Custom Job Hyperparameter Tuning Job Cloud Storage Bucket End of explanation """
thaophung/Udacity_deep_learning
image-classification/dlnd_image_classification.ipynb
mit
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifar10_location = '/input/cifar-10/python.tar.gz' if isfile(floyd_cifar10_location): tar_gz_path = floyd_cifar10_location else: tar_gz_path = 'cifar-10-python.tar.gz' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(tar_gz_path): with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar: urlretrieve( 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', tar_gz_path, pbar.hook) if not isdir(cifar10_dataset_folder_path): with tarfile.open(tar_gz_path) as tar: tar.extractall() tar.close() tests.test_folder_path(cifar10_dataset_folder_path) """ Explanation: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images. Get the Data Run the following cell to download the CIFAR-10 dataset for python. End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 5 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) """ Explanation: Explore the Data The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following: * airplane * automobile * bird * cat * deer * dog * frog * horse * ship * truck Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch. Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions. End of explanation """ import tensorflow as tf def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ # TODO: Implement Function a = 0. b = 1. grayscale_min=0 grayscale_max=255 return a + (((x - grayscale_min)*(b-a)/(grayscale_max-grayscale_min))) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_normalize(normalize) """ Explanation: Implement Preprocess Functions Normalize In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. End of explanation """ def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ # TODO: Implement Function one_hot_labels = np.zeros((len(x),10)) for i in range(len(x)): label = x[i] one_hot_labels[i,label] = 1 return one_hot_labels """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_one_hot_encode(one_hot_encode) """ Explanation: One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function. Hint: Don't reinvent the wheel. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode) """ Explanation: Randomize Data As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save it Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb')) """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function input_data = tf.placeholder(tf.float32, (None, 32,32,3), name='x') return input_data def neural_net_label_input(n_classes): """ Return a Tensor for a batch of label input : n_classes: Number of classes : return: Tensor for label input. """ # TODO: Implement Function label = tf.placeholder(tf.float32, (None, 10), name='y') return label def neural_net_keep_prob_input(): """ Return a Tensor for keep probability : return: Tensor for keep probability. """ # TODO: Implement Function keep_prop = tf.placeholder(tf.float32,name='keep_prob') return keep_prop """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tf.reset_default_graph() tests.test_nn_image_inputs(neural_net_image_input) tests.test_nn_label_inputs(neural_net_label_input) tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input) """ Explanation: Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project. Note: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the "Convolutional and Max Pooling Layer" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup. However, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d. Let's begin! Input The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions * Implement neural_net_image_input * Return a TF Placeholder * Set the shape using image_shape with batch size set to None. * Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_label_input * Return a TF Placeholder * Set the shape using n_classes with batch size set to None. * Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_keep_prob_input * Return a TF Placeholder for dropout keep probability. * Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder. These names will be used at the end of the project to load your saved model. Note: None for shapes in TensorFlow allow for a dynamic size. End of explanation """ def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple for the convolutional layer :param conv_strides: Stride 2-D Tuple for convolution :param pool_ksize: kernal size 2-D Tuple for pool :param pool_strides: Stride 2-D Tuple for pool : return: A tensor that represents convolution and max pooling of x_tensor """ # TODO: Implement Function height = conv_ksize[0] width = conv_ksize[1] depth = x_tensor.shape.as_list()[3] # Convolution layer weights = tf.Variable(tf.truncated_normal((height, width, depth , conv_num_outputs))) bias = tf.Variable(tf.zeros(conv_num_outputs)) padding = 'SAME' conv_value = conv_strides[0] conv_strides = [1, conv_value, conv_value, 1] x_tensor = tf.nn.conv2d(x_tensor, weights, conv_strides, padding) + bias # Add a nonlinear activation x_tensor = tf.nn.relu(x_tensor) # Pooling layer pool_k_value = pool_ksize[0] pool_ksize=[1, pool_k_value, pool_k_value, 1] pool_strides_val = pool_strides[0] pool_strides = [1, pool_strides_val, pool_strides_val, 1] x_tensor = tf.nn.max_pool(x_tensor, pool_ksize, pool_strides, padding) return x_tensor """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_con_pool(conv2d_maxpool) """ Explanation: Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor using weight and conv_strides. * We recommend you use same padding, but you're welcome to use any padding. * Add bias * Add a nonlinear activation to the convolution. * Apply Max Pooling using pool_ksize and pool_strides. * We recommend you use same padding, but you're welcome to use any padding. Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers. End of explanation """ def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ # TODO: Implement Function _, height, width, depth = x_tensor.shape.as_list() x_tensor = tf.reshape(x_tensor,[-1, height*width*depth]) return x_tensor """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_flatten(flatten) """ Explanation: Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function x_tensor = tf.layers.dense(x_tensor, num_outputs) x_tensor = tf.nn.relu(x_tensor) return x_tensor """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_fully_conn(fully_conn) """ Explanation: Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function x_tensor = tf.layers.dense(x_tensor, num_outputs) return x_tensor """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_output(output) """ Explanation: Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. Note: Activation, softmax, or cross entropy should not be applied to this. End of explanation """ def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers # Play around with different number of outputs, kernel size and stride # Function Definition from Above: # conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides) conv1_max1 = conv2d_maxpool(x, 32, [5,5], [1,1],[2,2],[2,2]) conv2_max2 = conv2d_maxpool(x, 64, [3,3], [1,1],[2,2],[2,2]) conv3_max3 = conv2d_maxpool(x, 128, [3,3], [1,1],[2,2],[2,2]) conv3_max3 = tf.nn.dropout(conv3_max3, keep_prob) # TODO: Apply a Flatten Layer # Function Definition from Above: # flatten(x_tensor) flat1 = flatten(conv3_max3) # TODO: Apply 1, 2, or 3 Fully Connected Layers # Play around with different number of outputs # Function Definition from Above: # fully_conn(x_tensor, num_outputs) fc1 = fully_conn(flat1, 128) fc2 = fully_conn(fc1, 64) fc3 = fully_conn(fc2, 32) # TODO: Apply an Output Layer # Set this to the number of classes # Function Definition from Above: # output(x_tensor, num_outputs) output1 = output(fc3, 10) # TODO: return output return output1 """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ ############################## ## Build the Neural Network ## ############################## # Remove previous weights, bias, inputs, etc.. tf.reset_default_graph() # Inputs x = neural_net_image_input((32, 32, 3)) y = neural_net_label_input(10) keep_prob = neural_net_keep_prob_input() # Model logits = conv_net(x, keep_prob) # Name logits Tensor, so that is can be loaded from disk after training logits = tf.identity(logits, name='logits') # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') tests.test_conv_net(conv_net) """ Explanation: Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Fully Connected Layers Apply an Output Layer Return the output Apply TensorFlow's Dropout to one or more layers in the model using keep_prob. End of explanation """ def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data """ # TODO: Implement Function op = session.run(optimizer, feed_dict={ x: feature_batch, y: label_batch, keep_prob: keep_probability[0]}) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_train_nn(train_neural_network) """ Explanation: Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be called for each batch, so tf.global_variables_initializer() has already been called. Note: Nothing needs to be returned. This function is only optimizing the neural network. End of explanation """ def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy: TensorFlow accuracy function """ loss = session.run(cost, feed_dict={ x: feature_batch, y: label_batch, keep_prob: 1.0 }) acc = session.run(accuracy, feed_dict={ x: valid_features, y: valid_labels, keep_prob: 1.0 }) print("Loss: " + str(loss)) print("Accuracy: " + str(acc)) """ Explanation: Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. End of explanation """ # TODO: Tune Parameters epochs = 20 batch_size = 128 keep_probability = [0.75] """ Explanation: Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the probability of keeping a node using dropout End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): print(epoch) batch_i = 1 for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) """ Explanation: Train on a Single CIFAR-10 Batch Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batches = 5 for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) """ Explanation: Fully Train the Model Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_classification' n_samples = 4 top_n_predictions = 3 def test_model(): """ Test the saved model against the test dataset """ test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb')) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load model loader = tf.train.import_meta_graph(save_model_path + '.meta') loader.restore(sess, save_model_path) # Get Tensors from loaded model loaded_x = loaded_graph.get_tensor_by_name('x:0') loaded_y = loaded_graph.get_tensor_by_name('y:0') loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') loaded_logits = loaded_graph.get_tensor_by_name('logits:0') loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0') # Get accuracy in batches for memory limitations test_batch_acc_total = 0 test_batch_count = 0 for test_feature_batch, test_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size): test_batch_acc_total += sess.run( loaded_acc, feed_dict={loaded_x: test_feature_batch, loaded_y: test_label_batch, loaded_keep_prob: 1.0}) test_batch_count += 1 print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count)) # Print Random Samples random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples))) random_test_predictions = sess.run( tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions), feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0}) helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions) test_model() """ Explanation: Checkpoint The model has been saved to disk. Test Model Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters. End of explanation """
jorisvanzundert/reynaert-as-graph
notebook/07 The Distracting Interface.ipynb
gpl-3.0
from IPython.display import HTML HTML(''' <script src="resources/d3/d3.min.js"></script> <script src="resources/d3/d3.hive.min.js"></script> ''') """ Explanation: Chapter 7 — The Distracting Interface As I (and others) have argued elsewhere (<a href="#bibref_001" name="backref_bibref_001" id="backref_bibref_001">Van Zundert 2016.</a>, <a href="#backref_bibref_002" name="bibref_002" id="bibref_002">Van Zundert &amp; Andrews 2016</a>) interfaces are questionable goodies. Certainly if we are trying to uncover the outlines of a new computational literacy that would serve hermeneutic purposes in the scholarly domain, then hiding the code behind several layers of interface is part of the problem rather than the solution. Yet we cannot do without interface when we are working with any (digital) computational technology. Even computer languages themselves are in fact interfaces towards underlying machine code, byte code and eventually the hardware flipflops within the microchips of computers themselves. Graphical interfaces are the top most interfaces of a stack of interfaces that stand between the user and what is actually going on inside the computer. These interfaces are not neutral lenses, they filter, transform, and adapt digital information into a form that designers, engineers, and computer scientists think are suitable to users of any or a particular kind. The point of this notebook is to argue and search for a computational literacy that allows humanities researchers to engage with text through code in a more hermeneutic fashion, focusing away a bit from the well trodden paths of big data and statistic modeling. In this respect chapter 4 of this notebook comes far more closer to what I have in mind than the currently last chapter on visualization. There we find the start of an attempt to OO model the parts of a text. If anything it is the work of that chapter that should be discussed, progressed, and elaborated, much rather than to package up the results in some visualization which in many respects is more of an end than the start of a journey. Yet, no computational humanities application feels remotely complete at this moment in time without some visualization. Hence we try to add some wow-factor in this chapter. I contend however that like authors write novels and scholars learned books, at some point New Literacy will make writing the hybrid form of code and text as found in this notebook by far complete enough. Reaching that point would indeed mean a New Literacy has taken root within humanities (or well beyond) as a new semiotic to speak of and about culture and science. Tool switching As the focus switches from an 'internal' object oriented modeling towards the 'external' visualization, I need to switch to a different tool set. The Jupyter Notebook at this moment (it is Wednesday June 8th of 2016 when I write this) does support Ruby, but the iRuby back end (or kernel) is not very well adapted yet to outputting anything different than text results. So it will not allow me to inject HTML, SVG or any other formats nicely fit for creating visualizations. That is why this chapter is partly written in Python. Actually only very partly, just enough to allow me to write the most part in Javascript, CSS and HTML. This note book integration code for this visualization is greatly indepted to the example for integrating technologies into Jupyter Notebooks given by Brian Coffey and summarized by K. Hong. The visualization is based on the ideas of hive plots (<a href="#backref_bibref_003" name="bibref_003" id="bibref_003">Krzywinski, M. et al., 2012</a> and the code driving the visualization is certainly indepted to the examples by Mike Bostock (https://bost.ocks.org/mike/hive/ and https://bl.ocks.org/mbostock/2066415). Building the Visualization First we import the d3js libraries that we need directly into the HTML code (DOM) of the notebook page: End of explanation """ from string import Template html_template = Template(''' <style> $css_text </style> <script> $js_text </script> <div id="chart"></div> <div id="info_text"></div> ''') """ Explanation: Then we create a template that will let iPython take care of all the html chore that we need but do not want to waste time on. End of explanation """ css_text = ''' .axis { stroke: #000; stroke-width: 1.5px; } .node circle { stroke: #000; } .link { fill: none; stroke: #999; stroke-width: 1.5px; stroke-opacity: .3; } .link.active { stroke: red; stroke-width: 2px; stroke-opacity: 1; } .node circle.active { stroke: red; stroke-width: 3px; } #info_text { height: 100px; } ''' """ Explanation: So that we can concentrate on what's mildy important, like the CSS styling… End of explanation """ js_text = ''' var width = 970, height = 800, innerRadius = 40, outerRadius = 15000; number_of_categories = 2 var nodes; d3.json("./resources/visualization_data.json", function(data) { nodes = data.nodes; } ); var links = []; var node_index = 0; var last_text_node_index = nodes.length; nodes.forEach( function( node ) { if( node.denotation != null ){ var annotation_index = 0; node.denotation.annotations.forEach( function( annotation ) { var annotation_node = { x: 1, y: annotation_index, text: annotation.annotation }; nodes.push( annotation_node ); var link = {source: nodes[node_index], target: nodes[annotation_index + last_text_node_index]}; links.push( link ); annotation_index += 1; }) } node_index += 1; }) // Range var angle = d3.scale.ordinal().domain(d3.range( number_of_categories )) .rangePoints([ 0.1 * Math.PI, 0.4 * Math.PI ]), radius = d3.scale.linear().domain([0,1500]).range([innerRadius, outerRadius]), color = d3.scale.category10().domain(d3.range(20)); var svg = d3.select("#chart").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 100 + "," + height + ")"); svg.selectAll(".axis") .data(d3.range( number_of_categories ) ) .enter().append("line") .attr("class", "axis") .attr("transform", function(d) { return "rotate(" + degrees(angle(d)) + ")"; }) .attr("x1", radius.range()[0]) .attr("x2", radius.range()[1]); svg.selectAll(".link") .data(links) .enter().append("path") .attr("class", "link") .attr("d", d3.hive.link() .angle(function(d) { return angle(d.x); }) .radius(function(d) { return radius(d.y+4); })) .style("stroke", function(d) { return color(d.source.x); }) .on("mouseover", linkMouseover) .on("mouseout", mouseout); svg.selectAll(".node") .data(nodes) .enter().append("circle") .attr("class", "node") .attr("transform", function(d) { return "rotate(" + degrees(angle(d.x)) + ")"; }) .attr("cx", function(d) { return radius(d.y+4); }) .attr("r", 5) .style("fill", function(d) { return color(d.x); }) .on("mouseover", nodeMouseover) .on("mouseout", mouseout); function degrees(radians) { return radians / Math.PI * 180 - 90; } // Highlight the link and connected nodes on mouseover. function linkMouseover(d) { svg.selectAll(".link").classed("active", function(p) { if ( p === d ) { this.style="stroke: red" } return p === d; }); svg.selectAll(".node circle").classed("active", function(p) { return p === d.source || p === d.target; }); info.text(d.source.wrd + " → " + d.target.text); } // Highlight the node and connected links on mouseover. function nodeMouseover(d) { svg.selectAll(".link").classed("active", function(p) { if ( p.source === d || p.target === d ) { this.style="stroke: red;" } return p.source === d || p.target === d; }); d3.select(this).classed("active", function(p) { this.style="stroke: red; fill: " + color(d.x) + ";"; return true; }); info.text(d.wrd); } // Clear any highlighted nodes or links. function mouseout(d) { svg.selectAll(".active").classed("active", function(p) { var style; if( p.source != null ) { style = "stroke: " + color(p.source.x) + ";"; } else { style = "stroke: " + color(p.x) + "; fill: " + color(p.x) + ";"; } this.style = style; return false; }); info.text(defaultInfo); } // Initialize the info display. var info = d3.select("#info_text") .text(defaultInfo = "Move over nodes or links to browse data"); ''' """ Explanation: And the real important JavaScript that actually takes in the data, constructs the plot, and adds a little interactivity. End of explanation """ HTML(html_template.substitute({'css_text': css_text, 'js_text': js_text})) """ Explanation: And finally we can combine the CSS and JS code with the template, which will add the visualization into the output of the cell below. End of explanation """
sdpython/ensae_teaching_cs
_doc/notebooks/td1a_algo/td1a_correction_session9.ipynb
mit
from jyquickhelper import add_notebook_menu add_notebook_menu() """ Explanation: 1A.algo - Optimisation sous contrainte (correction) Un peu plus de détails dans cet article : Damped Arrow-Hurwicz algorithm for sphere packing. End of explanation """ from cvxopt import solvers, matrix import random def fonction(x=None,z=None) : if x is None : x0 = matrix ( [[ random.random(), random.random() ]]) return 0,x0 f = x[0]**2 + x[1]**2 - x[0]*x[1] + x[1] d = matrix ( [ x[0]*2 - x[1], x[1]*2 - x[0] + 1 ] ).T if z is None: return f, d else : h = z[0] * matrix ( [ [ 2.0, -1.0], [-1.0, 2.0] ]) return f, d, h A = matrix([ [ 1.0, 2.0 ] ]).trans() b = matrix ( [[ 1.0] ] ) sol = solvers.cp ( fonction, A = A, b = b) print (sol) print ("solution:",sol['x'].T) """ Explanation: On rappelle le problème d'optimisation à résoudre : $\left { \begin{array}{l} \min_U J(U) = u_1^2 + u_2^2 - u_1 u_2 + u_2 \ sous \; contrainte \; \theta(U) = u_1 + 2u_2 - 1 = 0 \; et \; u_1 \geqslant 0.5 \end{array}\right .$ Les implémentations de l'algorithme Arrow-Hurwicz proposées ici ne sont pas génériques. Il n'est pas suggéré de les réutiliser à moins d'utiliser pleinement le calcul matriciel de numpy. Exercice 1 : optimisation avec cvxopt Le module cvxopt utilise une fonction qui retourne la valeur de la fonction à optimiser, sa dérivée, sa dérivée seconde. $\begin{array}{rcl} f(x,y) &=& x^2 + y^2 - xy + y \ \frac{\partial f(x,y)}{\partial x} &=& 2x - y \ \frac{\partial f(x,y)}{\partial y} &=& 2y - x + 1 \ \frac{\partial^2 f(x,y)}{\partial x^2} &=& 2 \ \frac{\partial^2 f(x,y)}{\partial y^2} &=& 2 \ \frac{\partial^2 f(x,y)}{\partial x\partial y} &=& -1 \end{array}$ Le paramètre le plus complexe est la fonction F pour lequel il faut lire la documentation de la fonction solvers.cp qui détaille les trois cas d'utilisation de la fonction F : F() ou F(None,None), ce premier cas est sans doute le plus déroutant puisqu'il faut retourner le nombre de contraintes non linéaires et le premier $x_0$ F(x) ou F(x,None) F(x,z) L'algorithme de résolution est itératif : on part d'une point $x_0$ qu'on déplace dans les directions opposés aux gradients de la fonction à minimiser et des contraintes jusqu'à ce que le point $x_t$ n'évolue plus. C'est pourquoi le premier d'utilisation de la focntion $F$ est en fait une initialisation. L'algorithme d'optimisation a besoin d'un premier point $x_0$ dans le domaine de défintion de la fonction $f$. End of explanation """ def fonction(X) : x,y = X f = x**2 + y**2 - x*y + y d = [ x*2 - y, y*2 - x + 1 ] return f, d def contrainte(X) : x,y = X f = x+2*y-1 d = [ 1,2] return f, d X0 = [ random.random(),random.random() ] p0 = random.random() epsilon = 0.1 rho = 0.1 diff = 1 iter = 0 while diff > 1e-10 : f,d = fonction( X0 ) th,dt = contrainte( X0 ) Xt = [ X0[i] - epsilon*(d[i] + dt[i] * p0) for i in range(len(X0)) ] th,dt = contrainte( Xt ) pt = p0 + rho * th iter += 1 diff = sum ( [ abs(Xt[i] - X0[i]) for i in range(len(X0)) ] ) X0 = Xt p0 = pt if iter % 100 == 0 : print ("i {0} diff {1:0.000}".format(iter,diff),":", f,X0,p0,th) print (diff,iter,p0) print("solution:",X0) """ Explanation: Exercice 2 : l'algorithme de Arrow-Hurwicz End of explanation """ def fonction(X,c) : x,y = X f = x**2 + y**2 - x*y + y d = [ x*2 - y, y*2 - x + 1 ] v = x+2*y-1 v = c/2 * v**2 # la fonction retourne maintenant dv (ce qu'elle ne faisait pas avant) dv = [ 2*(x+2*y-1), 4*(x+2*y-1) ] dv = [ c/2 * dv[0], c/2 * dv[1] ] return f + v, d, dv def contrainte(X) : x,y = X f = x+2*y-1 d = [ 1,2] return f, d X0 = [ random.random(),random.random() ] p0 = random.random() epsilon = 0.1 rho = 0.1 c = 1 diff = 1 iter = 0 while diff > 1e-10 : f,d,dv = fonction( X0,c ) th,dt = contrainte( X0 ) # le dv[i] est nouveau Xt = [ X0[i] - epsilon*(d[i] + dt[i] * p0 + dv[i]) for i in range(len(X0)) ] th,dt = contrainte( Xt ) pt = p0 + rho * th iter += 1 diff = sum ( [ abs(Xt[i] - X0[i]) for i in range(len(X0)) ] ) X0 = Xt p0 = pt if iter % 100 == 0 : print ("i {0} diff {1:0.000}".format(iter,diff),":", f,X0,p0,th) print (diff,iter,p0) print("solution:",X0) """ Explanation: La code proposé ici a été repris et modifié de façon à l'inclure dans une fonction qui s'adapte à n'importe quel type de fonction et contrainte dérivables : Arrow_Hurwicz. Il faut distinguer l'algorithme en lui-même et la preuve de sa convergence. Cet algorithme fonctionne sur une grande classe de fonctions mais sa convergence n'est assurée que lorsque les fonctions sont quadratiques. Exercice 3 : le lagrangien augmenté End of explanation """ from cvxopt import solvers, matrix import random def fonction(x=None,z=None) : if x is None : x0 = matrix ( [[ random.random(), random.random() ]]) return 0,x0 f = x[0]**2 + x[1]**2 - x[0]*x[1] + x[1] d = matrix ( [ x[0]*2 - x[1], x[1]*2 - x[0] + 1 ] ).T h = matrix ( [ [ 2.0, -1.0], [-1.0, 2.0] ]) if z is None: return f, d else : return f, d, h A = matrix([ [ 1.0, 2.0 ] ]).trans() b = matrix ( [[ 1.0] ] ) G = matrix ( [[0.0, -1.0] ]).trans() h = matrix ( [[ -0.3] ] ) sol = solvers.cp ( fonction, A = A, b = b, G=G, h=h) print (sol) print ("solution:",sol['x'].T) """ Explanation: Prolongement 1 : inégalité Le problème à résoudre est le suivant : $\left{ \begin{array}{l} \min_U J(U) = u_1^2 + u_1^2 - u_1 u_2 + u_2 \ \; sous \; contrainte \; \theta(U) = u_1 + 2u_2 - 1 = 0 \; et \; u_1 \geqslant 0.3 \end{array}\right.$ End of explanation """ import numpy,random X0 = numpy.matrix ( [[ random.random(), random.random() ]]).transpose() P0 = numpy.matrix ( [[ random.random(), random.random() ]]).transpose() A = numpy.matrix([ [ 1.0, 2.0 ], [ 0.0, -1.0] ]) tA = A.transpose() b = numpy.matrix ( [[ 1.0], [-0.30] ] ) epsilon = 0.1 rho = 0.1 c = 1 first = True iter = 0 while first or abs(J - oldJ) > 1e-8 : if first : J = X0[0,0]**2 + X0[1,0]**2 - X0[0,0]*X0[1,0] + X0[1,0] oldJ = J+1 first = False else : oldJ = J J = X0[0,0]**2 + X0[1,0]**2 - X0[0,0]*X0[1,0] + X0[1,0] dj = numpy.matrix ( [ X0[0,0]*2 - X0[1,0], X0[1,0]*2 - X0[0,0] + 1 ] ).transpose() Xt = X0 - ( dj + tA * P0 ) * epsilon Pt = P0 + ( A * Xt - b) * rho if Pt [1,0] < 0 : Pt[1,0] = 0 X0,P0 = Xt,Pt iter += 1 if iter % 100 == 0 : print ("iteration",iter, J) print (iter) print ("solution:",Xt.T) """ Explanation: Version avec l'algorithme de Arrow-Hurwicz End of explanation """
shikhar413/openmc
examples/jupyter/mdgxs-part-i.ipynb
mit
from IPython.display import Image Image(filename='images/mdgxs.png', width=350) """ Explanation: Multigroup (Delayed) Cross Section Generation Part I: Introduction This IPython Notebook introduces the use of the openmc.mgxs module to calculate multi-energy-group and multi-delayed-group cross sections for an infinite homogeneous medium. In particular, this Notebook introduces the the following features: Creation of multi-delayed-group cross sections for an infinite homogeneous medium Calculation of delayed neutron precursor concentrations Introduction to Multi-Delayed-Group Cross Sections (MDGXS) Many Monte Carlo particle transport codes, including OpenMC, use continuous-energy nuclear cross section data. However, most deterministic neutron transport codes use multi-group cross sections defined over discretized energy bins or energy groups. Furthermore, kinetics calculations typically separate out parameters that involve delayed neutrons into prompt and delayed components and further subdivide delayed components by delayed groups. An example is the energy spectrum for prompt and delayed neutrons for U-235 and Pu-239 computed for a light water reactor spectrum. End of explanation """ %matplotlib inline import numpy as np import matplotlib.pyplot as plt import openmc import openmc.mgxs as mgxs """ Explanation: A variety of tools employing different methodologies have been developed over the years to compute multi-group cross sections for certain applications, including NJOY (LANL), MC$^2$-3 (ANL), and Serpent (VTT). The openmc.mgxs Python module is designed to leverage OpenMC's tally system to calculate multi-group cross sections with arbitrary energy discretizations and different delayed group models (e.g. 6, 7, or 8 delayed group models) for fine-mesh heterogeneous deterministic neutron transport applications. Before proceeding to illustrate how one may use the openmc.mgxs module, it is worthwhile to define the general equations used to calculate multi-energy-group and multi-delayed-group cross sections. This is only intended as a brief overview of the methodology used by openmc.mgxs - we refer the interested reader to the large body of literature on the subject for a more comprehensive understanding of this complex topic. Introductory Notation The continuous real-valued microscopic cross section may be denoted $\sigma_{n,x}(\mathbf{r}, E)$ for position vector $\mathbf{r}$, energy $E$, nuclide $n$ and interaction type $x$. Similarly, the scalar neutron flux may be denoted by $\Phi(\mathbf{r},E)$ for position $\mathbf{r}$ and energy $E$. Note: Although nuclear cross sections are dependent on the temperature $T$ of the interacting medium, the temperature variable is neglected here for brevity. Spatial and Energy Discretization The energy domain for critical systems such as thermal reactors spans more than 10 orders of magnitude of neutron energies from 10$^{-5}$ - 10$^7$ eV. The multi-group approximation discretization divides this energy range into one or more energy groups. In particular, for $G$ total groups, we denote an energy group index $g$ such that $g \in {1, 2, ..., G}$. The energy group indices are defined such that the smaller group the higher the energy, and vice versa. The integration over neutron energies across a discrete energy group is commonly referred to as energy condensation. The delayed neutrons created from fissions are created from > 30 delayed neutron precursors. Modeling each of the delayed neutron precursors is possible, but this approach has not recieved much attention due to large uncertainties in certain precursors. Therefore, the delayed neutrons are often combined into "delayed groups" that have a set time constant, $\lambda_d$. Some cross section libraries use the same group time constants for all nuclides (e.g. JEFF 3.1) while other libraries use different time constants for all nuclides (e.g. ENDF/B-VII.1). Multi-delayed-group cross sections can either be created with the entire delayed group set, a subset of delayed groups, or integrated over all delayed groups. Multi-group cross sections are computed for discretized spatial zones in the geometry of interest. The spatial zones may be defined on a structured and regular fuel assembly or pin cell mesh, an arbitrary unstructured mesh or the constructive solid geometry used by OpenMC. For a geometry with $K$ distinct spatial zones, we designate each spatial zone an index $k$ such that $k \in {1, 2, ..., K}$. The volume of each spatial zone is denoted by $V_{k}$. The integration over discrete spatial zones is commonly referred to as spatial homogenization. General Scalar-Flux Weighted MDGXS The multi-group cross sections computed by openmc.mgxs are defined as a scalar flux-weighted average of the microscopic cross sections across each discrete energy group. This formulation is employed in order to preserve the reaction rates within each energy group and spatial zone. In particular, spatial homogenization and energy condensation are used to compute the general multi-group cross section. For instance, the delayed-nu-fission multi-energy-group and multi-delayed-group cross section, $\nu_d \sigma_{f,x,k,g}$, can be computed as follows: $$\nu_d \sigma_{n,x,k,g} = \frac{\int_{E_{g}}^{E_{g-1}}\mathrm{d}E'\int_{\mathbf{r} \in V_{k}}\mathrm{d}\mathbf{r} \nu_d \sigma_{f,x}(\mathbf{r},E')\Phi(\mathbf{r},E')}{\int_{E_{g}}^{E_{g-1}}\mathrm{d}E'\int_{\mathbf{r} \in V_{k}}\mathrm{d}\mathbf{r}\Phi(\mathbf{r},E')}$$ This scalar flux-weighted average microscopic cross section is computed by openmc.mgxs for only the delayed-nu-fission and delayed neutron fraction reaction type at the moment. These double integrals are stochastically computed with OpenMC's tally system - in particular, filters on the energy range and spatial zone (material, cell, universe, or mesh) define the bounds of integration for both numerator and denominator. Multi-Group Prompt and Delayed Fission Spectrum The energy spectrum of neutrons emitted from fission is denoted by $\chi_{n}(\mathbf{r},E' \rightarrow E'')$ for incoming and outgoing energies $E'$ and $E''$, respectively. Unlike the multi-group cross sections $\sigma_{n,x,k,g}$ considered up to this point, the fission spectrum is a probability distribution and must sum to unity. The outgoing energy is typically much less dependent on the incoming energy for fission than for scattering interactions. As a result, it is common practice to integrate over the incoming neutron energy when computing the multi-group fission spectrum. The fission spectrum may be simplified as $\chi_{n}(\mathbf{r},E)$ with outgoing energy $E$. Computing the cumulative energy spectrum of emitted neutrons, $\chi_{n}(\mathbf{r},E)$, has been presented in the mgxs-part-i.ipynb notebook. Here, we will present the energy spectrum of prompt and delayed emission neutrons, $\chi_{n,p}(\mathbf{r},E)$ and $\chi_{n,d}(\mathbf{r},E)$, respectively. Unlike the multi-group cross sections defined up to this point, the multi-group fission spectrum is weighted by the fission production rate rather than the scalar flux. This formulation is intended to preserve the total fission production rate in the multi-group deterministic calculation. In order to mathematically define the multi-group fission spectrum, we denote the microscopic fission cross section as $\sigma_{n,f}(\mathbf{r},E)$ and the average number of neutrons emitted from fission interactions with nuclide $n$ as $\nu_{n,p}(\mathbf{r},E)$ and $\nu_{n,d}(\mathbf{r},E)$ for prompt and delayed neutrons, respectively. The multi-group fission spectrum $\chi_{n,k,g,d}$ is then the probability of fission neutrons emitted into energy group $g$ and delayed group $d$. There are not prompt groups, so inserting $p$ in place of $d$ just denotes all prompt neutrons. Similar to before, spatial homogenization and energy condensation are used to find the multi-energy-group and multi-delayed-group fission spectrum $\chi_{n,k,g,d}$ as follows: $$\chi_{n,k,g',d} = \frac{\int_{E_{g'}}^{E_{g'-1}}\mathrm{d}E''\int_{0}^{\infty}\mathrm{d}E'\int_{\mathbf{r} \in V_{k}}\mathrm{d}\mathbf{r}\chi_{n,d}(\mathbf{r},E'\rightarrow E'')\nu_{n,d}(\mathbf{r},E')\sigma_{n,f}(\mathbf{r},E')\Phi(\mathbf{r},E')}{\int_{0}^{\infty}\mathrm{d}E'\int_{\mathbf{r} \in V_{k}}\mathrm{d}\mathbf{r}\nu_{n,d}(\mathbf{r},E')\sigma_{n,f}(\mathbf{r},E')\Phi(\mathbf{r},E')}$$ The fission production-weighted multi-energy-group and multi-delayed-group fission spectrum for delayed neutrons is computed using OpenMC tallies with energy in, energy out, and delayed group filters. Alternatively, the delayed group filter can be omitted to compute the fission spectrum integrated over all delayed groups. This concludes our brief overview on the methodology to compute multi-energy-group and multi-delayed-group cross sections. The following sections detail more concretely how users may employ the openmc.mgxs module to power simulation workflows requiring multi-group cross sections for downstream deterministic calculations. Generate Input Files End of explanation """ # Instantiate a Material and register the Nuclides inf_medium = openmc.Material(name='moderator') inf_medium.set_density('g/cc', 5.) inf_medium.add_nuclide('H1', 0.03) inf_medium.add_nuclide('O16', 0.015) inf_medium.add_nuclide('U235', 0.0001) inf_medium.add_nuclide('U238', 0.007) inf_medium.add_nuclide('Pu239', 0.00003) inf_medium.add_nuclide('Zr90', 0.002) """ Explanation: First we need to define materials that will be used in the problem. Let's create a material for the homogeneous medium. End of explanation """ # Instantiate a Materials collection and export to XML materials_file = openmc.Materials([inf_medium]) materials_file.export_to_xml() """ Explanation: With our material, we can now create a Materials object that can be exported to an actual XML file. End of explanation """ # Instantiate boundary Planes min_x = openmc.XPlane(boundary_type='reflective', x0=-0.63) max_x = openmc.XPlane(boundary_type='reflective', x0=0.63) min_y = openmc.YPlane(boundary_type='reflective', y0=-0.63) max_y = openmc.YPlane(boundary_type='reflective', y0=0.63) """ Explanation: Now let's move on to the geometry. This problem will be a simple square cell with reflective boundary conditions to simulate an infinite homogeneous medium. The first step is to create the outer bounding surfaces of the problem. End of explanation """ # Instantiate a Cell cell = openmc.Cell(cell_id=1, name='cell') # Register bounding Surfaces with the Cell cell.region = +min_x & -max_x & +min_y & -max_y # Fill the Cell with the Material cell.fill = inf_medium """ Explanation: With the surfaces defined, we can now create a cell that is defined by intersections of half-spaces created by the surfaces. End of explanation """ # Create Geometry and set root Universe openmc_geometry = openmc.Geometry([cell]) # Export to "geometry.xml" openmc_geometry.export_to_xml() """ Explanation: We now must create a geometry and export it to XML. End of explanation """ # OpenMC simulation parameters batches = 50 inactive = 10 particles = 5000 # Instantiate a Settings object settings_file = openmc.Settings() settings_file.batches = batches settings_file.inactive = inactive settings_file.particles = particles settings_file.output = {'tallies': True} # Create an initial uniform spatial source distribution over fissionable zones bounds = [-0.63, -0.63, -0.63, 0.63, 0.63, 0.63] uniform_dist = openmc.stats.Box(bounds[:3], bounds[3:], only_fissionable=True) settings_file.source = openmc.Source(space=uniform_dist) # Export to "settings.xml" settings_file.export_to_xml() """ Explanation: Next, we must define simulation parameters. In this case, we will use 10 inactive batches and 40 active batches each with 2500 particles. End of explanation """ # Instantiate a 100-group EnergyGroups object energy_groups = mgxs.EnergyGroups() energy_groups.group_edges = np.logspace(-3, 7.3, 101) # Instantiate a 1-group EnergyGroups object one_group = mgxs.EnergyGroups() one_group.group_edges = np.array([energy_groups.group_edges[0], energy_groups.group_edges[-1]]) delayed_groups = list(range(1,7)) """ Explanation: Now we are ready to generate multi-group cross sections! First, let's define a 100-energy-group structure and 1-energy-group structure using the built-in EnergyGroups class. We will also create a 6-delayed-group list. End of explanation """ # Instantiate a few different sections chi_prompt = mgxs.Chi(domain=cell, groups=energy_groups, by_nuclide=True, prompt=True) prompt_nu_fission = mgxs.FissionXS(domain=cell, groups=energy_groups, by_nuclide=True, nu=True, prompt=True) chi_delayed = mgxs.ChiDelayed(domain=cell, energy_groups=energy_groups, by_nuclide=True) delayed_nu_fission = mgxs.DelayedNuFissionXS(domain=cell, energy_groups=energy_groups, delayed_groups=delayed_groups, by_nuclide=True) beta = mgxs.Beta(domain=cell, energy_groups=energy_groups, delayed_groups=delayed_groups, by_nuclide=True) decay_rate = mgxs.DecayRate(domain=cell, energy_groups=one_group, delayed_groups=delayed_groups, by_nuclide=True) chi_prompt.nuclides = ['U235', 'Pu239'] prompt_nu_fission.nuclides = ['U235', 'Pu239'] chi_delayed.nuclides = ['U235', 'Pu239'] delayed_nu_fission.nuclides = ['U235', 'Pu239'] beta.nuclides = ['U235', 'Pu239'] decay_rate.nuclides = ['U235', 'Pu239'] """ Explanation: We can now use the EnergyGroups object and delayed group list, along with our previously created materials and geometry, to instantiate some MGXS objects from the openmc.mgxs module. In particular, the following are subclasses of the generic and abstract MGXS class: TotalXS TransportXS AbsorptionXS CaptureXS FissionXS NuFissionMatrixXS KappaFissionXS ScatterXS ScatterMatrixXS Chi InverseVelocity A separate abstract MDGXS class is used for cross-sections and parameters that involve delayed neutrons. The subclasses of MDGXS include: DelayedNuFissionXS ChiDelayed Beta DecayRate These classes provide us with an interface to generate the tally inputs as well as perform post-processing of OpenMC's tally data to compute the respective multi-group cross sections. In this case, let's create the multi-group chi-prompt, chi-delayed, and prompt-nu-fission cross sections with our 100-energy-group structure and multi-group delayed-nu-fission and beta cross sections with our 100-energy-group and 6-delayed-group structures. The prompt chi and nu-fission data can actually be gathered using the Chi and FissionXS classes, respectively, by passing in a value of True for the optional prompt parameter upon initialization. End of explanation """ decay_rate.tallies """ Explanation: Each multi-group cross section object stores its tallies in a Python dictionary called tallies. We can inspect the tallies in the dictionary for our Decay Rate object as follows. End of explanation """ # Instantiate an empty Tallies object tallies_file = openmc.Tallies() # Add chi-prompt tallies to the tallies file tallies_file += chi_prompt.tallies.values() # Add prompt-nu-fission tallies to the tallies file tallies_file += prompt_nu_fission.tallies.values() # Add chi-delayed tallies to the tallies file tallies_file += chi_delayed.tallies.values() # Add delayed-nu-fission tallies to the tallies file tallies_file += delayed_nu_fission.tallies.values() # Add beta tallies to the tallies file tallies_file += beta.tallies.values() # Add decay rate tallies to the tallies file tallies_file += decay_rate.tallies.values() # Export to "tallies.xml" tallies_file.export_to_xml() """ Explanation: The Beta object includes tracklength tallies for the 'nu-fission' and 'delayed-nu-fission' scores in the 100-energy-group and 6-delayed-group structure in cell 1. Now that each MGXS and MDGXS object contains the tallies that it needs, we must add these tallies to a Tallies object to generate the "tallies.xml" input file for OpenMC. End of explanation """ # Run OpenMC openmc.run() """ Explanation: Now we a have a complete set of inputs, so we can go ahead and run our simulation. End of explanation """ # Load the last statepoint file sp = openmc.StatePoint('statepoint.50.h5') """ Explanation: Tally Data Processing Our simulation ran successfully and created statepoint and summary output files. We begin our analysis by instantiating a StatePoint object. End of explanation """ # Load the tallies from the statepoint into each MGXS object chi_prompt.load_from_statepoint(sp) prompt_nu_fission.load_from_statepoint(sp) chi_delayed.load_from_statepoint(sp) delayed_nu_fission.load_from_statepoint(sp) beta.load_from_statepoint(sp) decay_rate.load_from_statepoint(sp) """ Explanation: In addition to the statepoint file, our simulation also created a summary file which encapsulates information about the materials and geometry. By default, a Summary object is automatically linked when a StatePoint is loaded. This is necessary for the openmc.mgxs module to properly process the tally data. The statepoint is now ready to be analyzed by our multi-group cross sections. We simply have to load the tallies from the StatePoint into each object as follows and our MGXS objects will compute the cross sections for us under-the-hood. End of explanation """ delayed_nu_fission.get_condensed_xs(one_group).get_xs() """ Explanation: Voila! Our multi-group cross sections are now ready to rock 'n roll! Extracting and Storing MGXS Data Let's first inspect our delayed-nu-fission section by printing it to the screen after condensing the cross section down to one group. End of explanation """ df = delayed_nu_fission.get_pandas_dataframe() df.head(10) df = decay_rate.get_pandas_dataframe() df.head(12) """ Explanation: Since the openmc.mgxs module uses tally arithmetic under-the-hood, the cross section is stored as a "derived" Tally object. This means that it can be queried and manipulated using all of the same methods supported for the Tally class in the OpenMC Python API. For example, we can construct a Pandas DataFrame of the multi-group cross section data. End of explanation """ beta.export_xs_data(filename='beta', format='excel') """ Explanation: Each multi-group cross section object can be easily exported to a variety of file formats, including CSV, Excel, and LaTeX for storage or data processing. End of explanation """ chi_prompt.build_hdf5_store(filename='mdgxs', append=True) chi_delayed.build_hdf5_store(filename='mdgxs', append=True) """ Explanation: The following code snippet shows how to export the chi-prompt and chi-delayed MGXS to the same HDF5 binary data store. End of explanation """ # Get the decay rate data dr_tally = decay_rate.xs_tally dr_u235 = dr_tally.get_values(nuclides=['U235']).flatten() dr_pu239 = dr_tally.get_values(nuclides=['Pu239']).flatten() # Compute the exponential decay of the precursors time = np.logspace(-3,3) dr_u235_points = np.exp(-np.outer(dr_u235, time)) dr_pu239_points = np.exp(-np.outer(dr_pu239, time)) # Create a plot of the fraction of the precursors remaining as a f(time) colors = ['b', 'g', 'r', 'c', 'm', 'k'] legend = [] fig = plt.figure(figsize=(8,6)) for g,c in enumerate(colors): plt.semilogx(time, dr_u235_points [g,:], color=c, linestyle='--', linewidth=3) plt.semilogx(time, dr_pu239_points[g,:], color=c, linestyle=':' , linewidth=3) legend.append('U-235 $t_{1/2}$ = ' + '{0:1.2f} seconds'.format(np.log(2) / dr_u235[g])) legend.append('Pu-239 $t_{1/2}$ = ' + '{0:1.2f} seconds'.format(np.log(2) / dr_pu239[g])) plt.title('Delayed Neutron Precursor Decay Rates') plt.xlabel('Time (s)') plt.ylabel('Fraction Remaining') plt.legend(legend, loc=1, bbox_to_anchor=(1.55, 0.95)) """ Explanation: Using Tally Arithmetic to Compute the Delayed Neutron Precursor Concentrations Finally, we illustrate how one can leverage OpenMC's tally arithmetic data processing feature with MGXS objects. The openmc.mgxs module uses tally arithmetic to compute multi-group cross sections with automated uncertainty propagation. Each MGXS object includes an xs_tally attribute which is a "derived" Tally based on the tallies needed to compute the cross section type of interest. These derived tallies can be used in subsequent tally arithmetic operations. For example, we can use tally artithmetic to compute the delayed neutron precursor concentrations using the Beta, DelayedNuFissionXS, and DecayRate objects. The delayed neutron precursor concentrations are modeled using the following equations: $$\frac{\partial}{\partial t} C_{k,d} (t) = \int_{0}^{\infty}\mathrm{d}E'\int_{\mathbf{r} \in V_{k}}\mathrm{d}\mathbf{r} \beta_{k,d} (t) \nu_d \sigma_{f,x}(\mathbf{r},E',t)\Phi(\mathbf{r},E',t) - \lambda_{d} C_{k,d} (t) $$ $$C_{k,d} (t=0) = \frac{1}{\lambda_{d}} \int_{0}^{\infty}\mathrm{d}E'\int_{\mathbf{r} \in V_{k}}\mathrm{d}\mathbf{r} \beta_{k,d} (t=0) \nu_d \sigma_{f,x}(\mathbf{r},E',t=0)\Phi(\mathbf{r},E',t=0) $$ First, let's investigate the decay rates for U235 and Pu235. The fraction of the delayed neutron precursors remaining as a function of time after fission for each delayed group and fissioning isotope have been plotted below. End of explanation """ # Use tally arithmetic to compute the precursor concentrations precursor_conc = beta.get_condensed_xs(one_group).xs_tally.summation(filter_type=openmc.EnergyFilter, remove_filter=True) * \ delayed_nu_fission.get_condensed_xs(one_group).xs_tally.summation(filter_type=openmc.EnergyFilter, remove_filter=True) / \ decay_rate.xs_tally.summation(filter_type=openmc.EnergyFilter, remove_filter=True) # Get the Pandas DataFrames for inspection precursor_conc.get_pandas_dataframe() """ Explanation: Now let's compute the initial concentration of the delayed neutron precursors: End of explanation """ energy_filter = [f for f in beta.xs_tally.filters if type(f) is openmc.EnergyFilter] beta_integrated = beta.get_condensed_xs(one_group).xs_tally.summation(filter_type=openmc.EnergyFilter, remove_filter=True) beta_u235 = beta_integrated.get_values(nuclides=['U235']) beta_pu239 = beta_integrated.get_values(nuclides=['Pu239']) # Reshape the betas beta_u235.shape = (beta_u235.shape[0]) beta_pu239.shape = (beta_pu239.shape[0]) df = beta_integrated.summation(filter_type=openmc.DelayedGroupFilter, remove_filter=True).get_pandas_dataframe() print('Beta (U-235) : {:.6f} +/- {:.6f}'.format(df[df['nuclide'] == 'U235']['mean'][0], df[df['nuclide'] == 'U235']['std. dev.'][0])) print('Beta (Pu-239): {:.6f} +/- {:.6f}'.format(df[df['nuclide'] == 'Pu239']['mean'][1], df[df['nuclide'] == 'Pu239']['std. dev.'][1])) beta_u235 = np.append(beta_u235[0], beta_u235) beta_pu239 = np.append(beta_pu239[0], beta_pu239) # Create a step plot for the MGXS plt.plot(np.arange(0.5, 7.5, 1), beta_u235, drawstyle='steps', color='b', linewidth=3) plt.plot(np.arange(0.5, 7.5, 1), beta_pu239, drawstyle='steps', color='g', linewidth=3) plt.title('Delayed Neutron Fraction (beta)') plt.xlabel('Delayed Group') plt.ylabel('Beta(fraction total neutrons)') plt.legend(['U-235', 'Pu-239']) plt.xlim([0,7]) """ Explanation: We can plot the delayed neutron fractions for each nuclide. End of explanation """ chi_d_u235 = np.squeeze(chi_delayed.get_xs(nuclides=['U235'], order_groups='decreasing')) chi_d_pu239 = np.squeeze(chi_delayed.get_xs(nuclides=['Pu239'], order_groups='decreasing')) chi_p_u235 = np.squeeze(chi_prompt.get_xs(nuclides=['U235'], order_groups='decreasing')) chi_p_pu239 = np.squeeze(chi_prompt.get_xs(nuclides=['Pu239'], order_groups='decreasing')) chi_d_u235 = np.append(chi_d_u235 , chi_d_u235[0]) chi_d_pu239 = np.append(chi_d_pu239, chi_d_pu239[0]) chi_p_u235 = np.append(chi_p_u235 , chi_p_u235[0]) chi_p_pu239 = np.append(chi_p_pu239, chi_p_pu239[0]) # Create a step plot for the MGXS plt.semilogx(energy_groups.group_edges, chi_d_u235 , drawstyle='steps', color='b', linestyle='--', linewidth=3) plt.semilogx(energy_groups.group_edges, chi_d_pu239, drawstyle='steps', color='g', linestyle='--', linewidth=3) plt.semilogx(energy_groups.group_edges, chi_p_u235 , drawstyle='steps', color='b', linestyle=':', linewidth=3) plt.semilogx(energy_groups.group_edges, chi_p_pu239, drawstyle='steps', color='g', linestyle=':', linewidth=3) plt.title('Energy Spectrum for Fission Neutrons') plt.xlabel('Energy (eV)') plt.ylabel('Fraction on emitted neutrons') plt.legend(['U-235 delayed', 'Pu-239 delayed', 'U-235 prompt', 'Pu-239 prompt'],loc=2) plt.xlim(1.0e3, 20.0e6) """ Explanation: We can also plot the energy spectrum for fission emission of prompt and delayed neutrons. End of explanation """
sbailey/knltest
doc/extract-size.ipynb
bsd-3-clause
%pylab inline import numpy as np from astropy.table import Table knl = Table.read('../doc/data/extract-size/knl.txt', format='ascii') hsw = Table.read('../doc/data/extract-size/hsw.txt', format='ascii') hsw.colnames knl.sort('ntot') hsw.sort('ntot') def table2rate2d(data): nwave_opts = sorted(set(data['nwave'])) nspec_opts = sorted(set(data['nspec'])) rate = np.zeros((len(nwave_opts), len(nspec_opts))) for row in data: i = nwave_opts.index(row['nwave']) j = nspec_opts.index(row['nspec']) rate[i,j] = row['rate'] return rate rate_knl = table2rate2d(knl) rate_hsw = table2rate2d(hsw) def plotimg(rate, xlabels, ylabels): imshow(rate) colorbar() xticks(range(len(xlabels)), xlabels) yticks(range(len(ylabels)), ylabels) xlabel('nspec'); ylabel('nwave') """ Explanation: Extraction performance as a function of divide-and-conquer size Context: a naive implementation of the DESI spectral extraction algorithm would involve eigen-decomposition of a 2M x 2M matrix, assembled from some 16M x 16M and 16M x 2M matrices. This is computationally intractable as-is, but we use the sparseness of the matrix to subdivide the problem into overlapping sub-extractions. Our current default is to extract 25 spectra x 50 wavelengths + edge effect boundaries at a time. This notebook explores potential speedups from even smaller sub-extractions. Stephen Bailey<br> Lawrence Berkeley National Lab<br> Spring 2017 Code to run This code requires https://github.com/desihub/specter and https://github.com/sbailey/knlcode. A minimal setup is: bash git clone https://github.com/sbailey/knltest git clone https://github.com/desihub/specter export PYTHONPATH=`pwd`/specter/py:$PYTHONPATH cd knltest/code export OMP_NUM_THREADS=1 python extract-size.py End of explanation """ xlabels = sorted(set(hsw['nspec'])) ylabels = sorted(set(knl['nwave'])) set_cmap('viridis') figure(figsize=(12,4)) subplot(121); plotimg(rate_hsw, xlabels, ylabels); title('Haswell rate') subplot(122); plotimg(rate_knl, xlabels, ylabels); title('KNL rate') """ Explanation: Extraction rate vs. extraction size Current default is 25 spectra x 50 wavelengths extracted at a time. On both KNL and Haswell, we could do better with smaller sub-extractions. End of explanation """ figure(figsize=(12,4)) subplot(121); plotimg(rate_hsw/rate_hsw[-1,-1], xlabels, ylabels); title('Haswell rate improvement') subplot(122); plotimg(rate_knl/rate_knl[-1,-1], xlabels, ylabels); title('KNL rate improvement') """ Explanation: 3x improvement is possible Going to 5-10 spectra x 20 wavelengths gains a factor of 3x speed on both KNL and Haswell. End of explanation """ r = np.max(rate_hsw) / np.max(rate_knl) print("Haswell/KNL = {}".format(r)) plotimg(rate_hsw/rate_knl, xlabels, ylabels) title('Haswell / KNL performance') """ Explanation: Haswell to KNL performance The best parameters for Haswell are ~7x faster than the best parameters for KNL, and for a given extraction size (nspec,nwave), Haswell is 5x-8x faster than KNL per process. End of explanation """
simonsfoundation/CaImAn
demos/notebooks/demo_pipeline.ipynb
gpl-2.0
import bokeh.plotting as bpl import cv2 import glob import logging import matplotlib.pyplot as plt import numpy as np import os try: cv2.setNumThreads(0) except(): pass try: if __IPYTHON__: # this is used for debugging purposes only. allows to reload classes # when changed get_ipython().magic('load_ext autoreload') get_ipython().magic('autoreload 2') except NameError: pass import caiman as cm from caiman.motion_correction import MotionCorrect from caiman.source_extraction.cnmf import cnmf as cnmf from caiman.source_extraction.cnmf import params as params from caiman.utils.utils import download_demo from caiman.utils.visualization import plot_contours, nb_view_patches, nb_plot_contour bpl.output_notebook() """ Explanation: <html><head><meta content="text/html; charset=UTF-8" http-equiv="content-type"><style type="text/css">ol</style></head><body class="c5"><p class="c0 c4"><span class="c3"></span></p><p class="c2 title" id="h.rrbabt268i6e"><h1>CaImAn&rsquo;s Demo pipeline</h1></p><p class="c0"><span class="c3">This notebook will help to demonstrate the process of CaImAn and how it uses different functions to denoise, deconvolve and demix neurons from a two-photon Calcium Imaging dataset. The demo shows how to construct the params, MotionCorrect and cnmf objects and call the relevant functions. You can also run a large part of the pipeline with a single method (cnmf.fit_file). See inside for details. Dataset couresy of Sue Ann Koay and David Tank (Princeton University) This demo pertains to two photon data. For a complete analysis pipeline for one photon microendoscopic data see demo_pipeline_cnmfE.ipynb</span></p> <p class="c0"><span class="c3">More information can be found in the companion paper. </span></p> </html> End of explanation """ logging.basicConfig(format= "%(relativeCreated)12d [%(filename)s:%(funcName)20s():%(lineno)s] [%(process)d] %(message)s", # filename="/tmp/caiman.log", level=logging.WARNING) """ Explanation: Set up logger (optional) You can log to a file using the filename parameter, or make the output more or less verbose by setting level to logging.DEBUG, logging.INFO, logging.WARNING, or logging.ERROR. A filename argument can also be passed to store the log file End of explanation """ fnames = ['Sue_2x_3000_40_-46.tif'] # filename to be processed if fnames[0] in ['Sue_2x_3000_40_-46.tif', 'demoMovie.tif']: fnames = [download_demo(fnames[0])] """ Explanation: Select file(s) to be processed The download_demo function will download the specific file for you and return the complete path to the file which will be stored in your caiman_data directory. If you adapt this demo for your data make sure to pass the complete path to your file(s). Remember to pass the fname variable as a list. End of explanation """ display_movie = False if display_movie: m_orig = cm.load_movie_chain(fnames) ds_ratio = 0.2 m_orig.resize(1, 1, ds_ratio).play( q_max=99.5, fr=30, magnification=2) """ Explanation: Play the movie (optional) Play the movie (optional). This will require loading the movie in memory which in general is not needed by the pipeline. Displaying the movie uses the OpenCV library. Press q to close the video panel. End of explanation """ # dataset dependent parameters fr = 30 # imaging rate in frames per second decay_time = 0.4 # length of a typical transient in seconds # motion correction parameters strides = (48, 48) # start a new patch for pw-rigid motion correction every x pixels overlaps = (24, 24) # overlap between pathes (size of patch strides+overlaps) max_shifts = (6,6) # maximum allowed rigid shifts (in pixels) max_deviation_rigid = 3 # maximum shifts deviation allowed for patch with respect to rigid shifts pw_rigid = True # flag for performing non-rigid motion correction # parameters for source extraction and deconvolution p = 1 # order of the autoregressive system gnb = 2 # number of global background components merge_thr = 0.85 # merging threshold, max correlation allowed rf = 15 # half-size of the patches in pixels. e.g., if rf=25, patches are 50x50 stride_cnmf = 6 # amount of overlap between the patches in pixels K = 4 # number of components per patch gSig = [4, 4] # expected half size of neurons in pixels method_init = 'greedy_roi' # initialization method (if analyzing dendritic data using 'sparse_nmf') ssub = 1 # spatial subsampling during initialization tsub = 1 # temporal subsampling during intialization # parameters for component evaluation min_SNR = 2.0 # signal to noise ratio for accepting a component rval_thr = 0.85 # space correlation threshold for accepting a component cnn_thr = 0.99 # threshold for CNN based classifier cnn_lowest = 0.1 # neurons with cnn probability lower than this value are rejected """ Explanation: Setup some parameters We set some parameters that are relevant to the file, and then parameters for motion correction, processing with CNMF and component quality evaluation. Note that the dataset Sue_2x_3000_40_-46.tif has been spatially downsampled by a factor of 2 and has a lower than usual spatial resolution (2um/pixel). As a result several parameters (gSig, strides, max_shifts, rf, stride_cnmf) have lower values (halved compared to a dataset with spatial resolution 1um/pixel). End of explanation """ opts_dict = {'fnames': fnames, 'fr': fr, 'decay_time': decay_time, 'strides': strides, 'overlaps': overlaps, 'max_shifts': max_shifts, 'max_deviation_rigid': max_deviation_rigid, 'pw_rigid': pw_rigid, 'p': p, 'nb': gnb, 'rf': rf, 'K': K, 'stride': stride_cnmf, 'method_init': method_init, 'rolling_sum': True, 'only_init': True, 'ssub': ssub, 'tsub': tsub, 'merge_thr': merge_thr, 'min_SNR': min_SNR, 'rval_thr': rval_thr, 'use_cnn': True, 'min_cnn_thr': cnn_thr, 'cnn_lowest': cnn_lowest} opts = params.CNMFParams(params_dict=opts_dict) """ Explanation: Create a parameters object You can creating a parameters object by passing all the parameters as a single dictionary. Parameters not defined in the dictionary will assume their default values. The resulting params object is a collection of subdictionaries pertaining to the dataset to be analyzed (params.data), motion correction (params.motion), data pre-processing (params.preprocess), initialization (params.init), patch processing (params.patch), spatial and temporal component (params.spatial), (params.temporal), quality evaluation (params.quality) and online processing (params.online) End of explanation """ #%% start a cluster for parallel processing (if a cluster already exists it will be closed and a new session will be opened) if 'dview' in locals(): cm.stop_server(dview=dview) c, dview, n_processes = cm.cluster.setup_cluster( backend='local', n_processes=None, single_thread=False) """ Explanation: Setup a cluster To enable parallel processing a (local) cluster needs to be set up. This is done with a cell below. The variable backend determines the type of cluster used. The default value 'local' uses the multiprocessing package. The ipyparallel option is also available. More information on these choices can be found here. The resulting variable dview expresses the cluster option. If you use dview=dview in the downstream analysis then parallel processing will be used. If you use dview=None then no parallel processing will be employed. End of explanation """ # first we create a motion correction object with the parameters specified mc = MotionCorrect(fnames, dview=dview, **opts.get_group('motion')) # note that the file is not loaded in memory """ Explanation: Motion Correction First we create a motion correction object with the parameters specified. Note that the file is not loaded in memory End of explanation """ %%capture #%% Run piecewise-rigid motion correction using NoRMCorre mc.motion_correct(save_movie=True) m_els = cm.load(mc.fname_tot_els) border_to_0 = 0 if mc.border_nan is 'copy' else mc.border_to_0 # maximum shift to be used for trimming against NaNs """ Explanation: Now perform motion correction. From the movie above we see that the dateset exhibits non-uniform motion. We will perform piecewise rigid motion correction using the NoRMCorre algorithm. This has already been selected by setting pw_rigid=True when defining the parameters object. End of explanation """ #%% compare with original movie display_movie = False if display_movie: m_orig = cm.load_movie_chain(fnames) ds_ratio = 0.2 cm.concatenate([m_orig.resize(1, 1, ds_ratio) - mc.min_mov*mc.nonneg_movie, m_els.resize(1, 1, ds_ratio)], axis=2).play(fr=60, gain=15, magnification=2, offset=0) # press q to exit """ Explanation: Inspect the results by comparing the original movie. A more detailed presentation of the motion correction method can be found in the demo motion correction notebook. End of explanation """ #%% MEMORY MAPPING # memory map the file in order 'C' fname_new = cm.save_memmap(mc.mmap_file, base_name='memmap_', order='C', border_to_0=border_to_0, dview=dview) # exclude borders # now load the file Yr, dims, T = cm.load_memmap(fname_new) images = np.reshape(Yr.T, [T] + list(dims), order='F') #load frames in python format (T x X x Y) """ Explanation: Memory mapping The cell below memory maps the file in order 'C' and then loads the new memory mapped file. The saved files from motion correction are memory mapped files stored in 'F' order. Their paths are stored in mc.mmap_file. End of explanation """ #%% restart cluster to clean up memory cm.stop_server(dview=dview) c, dview, n_processes = cm.cluster.setup_cluster( backend='local', n_processes=None, single_thread=False) """ Explanation: Now restart the cluster to clean up memory End of explanation """ %%capture #%% RUN CNMF ON PATCHES # First extract spatial and temporal components on patches and combine them # for this step deconvolution is turned off (p=0). If you want to have # deconvolution within each patch change params.patch['p_patch'] to a # nonzero value cnm = cnmf.CNMF(n_processes, params=opts, dview=dview) cnm = cnm.fit(images) """ Explanation: Run CNMF on patches in parallel The FOV is split is different overlapping patches that are subsequently processed in parallel by the CNMF algorithm. The results from all the patches are merged with special attention to idendtified components on the border. The results are then refined by additional CNMF iterations. End of explanation """ # cnm1 = cnmf.CNMF(n_processes, params=opts, dview=dview) # cnm1.fit_file(motion_correct=True) """ Explanation: Run the entire pipeline up to this point with one command It is possible to run the combined steps of motion correction, memory mapping, and cnmf fitting in one step as shown below. The command is commented out since the analysis has already been performed. It is recommended that you familiriaze yourself with the various steps and the results of the various steps before using it. End of explanation """ #%% plot contours of found components Cn = cm.local_correlations(images.transpose(1,2,0)) Cn[np.isnan(Cn)] = 0 cnm.estimates.plot_contours_nb(img=Cn) """ Explanation: Inspecting the results Briefly inspect the results by plotting contours of identified components against correlation image. The results of the algorithm are stored in the object cnm.estimates. More information can be found in the definition of the estimates object and in the wiki. End of explanation """ %%capture #%% RE-RUN seeded CNMF on accepted patches to refine and perform deconvolution cnm2 = cnm.refit(images, dview=dview) """ Explanation: Re-run (seeded) CNMF on the full Field of View You can re-run the CNMF algorithm seeded on just the selected components from the previous step. Be careful, because components rejected on the previous step will not be recovered here. End of explanation """ #%% COMPONENT EVALUATION # the components are evaluated in three ways: # a) the shape of each component must be correlated with the data # b) a minimum peak SNR is required over the length of a transient # c) each shape passes a CNN based classifier cnm2.estimates.evaluate_components(images, cnm2.params, dview=dview) """ Explanation: Component Evaluation The processing in patches creates several spurious components. These are filtered out by evaluating each component using three different criteria: the shape of each component must be correlated with the data at the corresponding location within the FOV a minimum peak SNR is required over the length of a transient each shape passes a CNN based classifier End of explanation """ #%% PLOT COMPONENTS cnm2.estimates.plot_contours_nb(img=Cn, idx=cnm2.estimates.idx_components) """ Explanation: Plot contours of selected and rejected components End of explanation """ # accepted components cnm2.estimates.nb_view_components(img=Cn, idx=cnm2.estimates.idx_components) # rejected components if len(cnm2.estimates.idx_components_bad) > 0: cnm2.estimates.nb_view_components(img=Cn, idx=cnm2.estimates.idx_components_bad) else: print("No components were rejected.") """ Explanation: View traces of accepted and rejected components. Note that if you get data rate error you can start Jupyter notebooks using: 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10' End of explanation """ #%% Extract DF/F values cnm2.estimates.detrend_df_f(quantileMin=8, frames_window=250) """ Explanation: Extract DF/F values End of explanation """ cnm2.estimates.select_components(use_object=True) """ Explanation: Select only high quality components End of explanation """ cnm2.estimates.nb_view_components(img=Cn, denoised_color='red') print('you may need to change the data rate to generate this one: use jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 before opening jupyter notebook') """ Explanation: Display final results End of explanation """ save_results = False if save_results: cnm2.save('analysis_results.hdf5') """ Explanation: Closing, saving, and creating denoised version You can save an hdf5 file with all the fields of the cnmf object End of explanation """ #%% STOP CLUSTER and clean up log files cm.stop_server(dview=dview) log_files = glob.glob('*_LOG_*') for log_file in log_files: os.remove(log_file) """ Explanation: Stop cluster and clean up log files End of explanation """ cnm2.estimates.play_movie(images, q_max=99.9, gain_res=2, magnification=2, bpx=border_to_0, include_bck=False) """ Explanation: View movie with the results We can inspect the denoised results by reconstructing the movie and playing alongside the original data and the resulting (amplified) residual movie End of explanation """ #%% reconstruct denoised movie denoised = cm.movie(cnm2.estimates.A.dot(cnm2.estimates.C) + \ cnm2.estimates.b.dot(cnm2.estimates.f)).reshape(dims + (-1,), order='F').transpose([2, 0, 1]) """ Explanation: The denoised movie can also be explicitly constructed using: End of explanation """
lionell/laboratories
num_methods/first/lab2.ipynb
mit
def is_square(a): return a.shape[0] == a.shape[1] def has_solutions(a, b): return np.linalg.matrix_rank(a) == np.linalg.matrix_rank(np.append(a, b[np.newaxis].T, axis=1)) """ Explanation: Linear systems <img src="https://i.ytimg.com/vi/7ujEpq7MWfE/maxresdefault.jpg" width="400" /> Given square matrix $A_{nxn}$, and vector $\mathbf{b}$, find such vector $\mathbf{x}$ that $A \cdot \mathbf{x} = \mathbf{b}$. Example 1 $$ \begin{bmatrix} 10 & -1 & 2 & 0 \ -1 & 11 & -1 & 3 \ 2 & -1 & 10 & -1 \ 0 & 3 & -1 & 8 \end{bmatrix} \cdot \begin{bmatrix} x_1 \ x_2 \ x_3 \ x_4 \end{bmatrix} = \begin{bmatrix} 6 \ 25 \ -11 \ 15 \end{bmatrix} $$ Equation above can be rewritten as $$ \left{ \begin{aligned} 10x_1 - x_2 + 2x_3 + 0x_4 &= 6 \ -x_1 + 11x_2 + -x_3 + 3x_4 &= 25 \ 2x_1 - x_2 + 10x_3 - x_4 &= -11 \ 0x_1 + 3x_2 - 2x_3 + 8x_4 &= 15 \end{aligned} \right. $$ We can easily check that $\mathbf{x} = [1, 2, -1, 1]$ is a solution. This particular example has only one solution, but generaly speaking matrix equation can have no, one or infinite number of solutions. Some methods can found them all(eg. Gauss), but some can only converge to one solution(eg. Seidel, Jacobi). To start, let's define some helper functions End of explanation """ def is_dominant(a): return np.all(np.abs(a).sum(axis=1) <= 2 * np.abs(a).diagonal()) and \ np.any(np.abs(a).sum(axis=1) < 2 * np.abs(a).diagonal()) def make_dominant(a): for i in range(a.shape[0]): a[i][i] = max(abs(a[i][i]), np.abs(a[i]).sum() - abs(a[i][i]) + 1) return a """ Explanation: Diagonally dominance We say that matrix $A_{nxn}$ is diagonally dominant iff $$ |a_{ii}| \geq \sum_{j\neq i} |a_{ij}|, \quad \forall i=1, n \, $$ equivalent $$ 2 \cdot |a_{ii}| \geq \sum_{j = 1, n} |a_{ij}|, \quad \forall i=1, n \, $$ Also we say that matrix $A_{nxn}$ is strictly diagonally dominant iff it's diagonally dominant and $$ \exists i : |a_{ii}| > \sum_{j\neq i} |a_{ij}|$$ End of explanation """ def generate_random(n): return make_dominant(np.random.rand(n, n) * n), np.random.rand(n) * n def generate_hilbert(n): return make_dominant(sp.linalg.hilbert(n)), np.arange(1, n + 1, dtype=np.float) def linalg(a, b, debug=False): return np.linalg.solve(a, b), """ Explanation: NOTE! All generate functions will return already strictly diagonally dominant matrices End of explanation """ def gauss(a, b, debug=False): assert is_square(a) and has_solutions(a, b) a = np.append(a.copy(), b[np.newaxis].T, axis=1) i = 0 k = 0 while i < a.shape[0]: r = np.argmax(a[i:, i]) + i a[[i, r]] = a[[r, i]] if a[i][i] == 0: break for j in range(a.shape[0]): if j == i: continue a[j] -= (a[j][i] / a[i][i]) * a[i] a[i] = a[i] / a[i][i] i += 1 assert np.count_nonzero(a[i:]) == 0 return a[:, -1], """ Explanation: Gauss method To perform row reduction on a matrix, one uses a sequence of elementary row operations to modify the matrix until the lower left-hand corner of the matrix is filled with zeros, as much as possible. There are three types of elementary row operations: Swapping two rows Multiplying a row by a non-zero number Adding a multiple of one row to another row. Using these operations, a matrix can always be transformed into an upper triangular matrix, and in fact one that is in row echelon form. Once all of the leading coefficients (the left-most non-zero entry in each row) are 1, and every column containing a leading coefficient has zeros elsewhere, the matrix is said to be in reduced row echelon form. This final form is unique; in other words, it is independent of the sequence of row operations used. For example, in the following sequence of row operations (where multiple elementary operations might be done at each step), the third and fourth matrices are the ones in row echelon form, and the final matrix is the unique reduced row echelon form. $$\left[\begin{array}{rrr|r} 1 & 3 & 1 & 9 \ 1 & 1 & -1 & 1 \ 3 & 11 & 5 & 35 \end{array}\right]\to \left[\begin{array}{rrr|r} 1 & 3 & 1 & 9 \ 0 & -2 & -2 & -8 \ 0 & 2 & 2 & 8 \end{array}\right]\to \left[\begin{array}{rrr|r} 1 & 3 & 1 & 9 \ 0 & -2 & -2 & -8 \ 0 & 0 & 0 & 0 \end{array}\right]\to \left[\begin{array}{rrr|r} 1 & 0 & -2 & -3 \ 0 & 1 & 1 & 4 \ 0 & 0 & 0 & 0 \end{array}\right] $$ Using row operations to convert a matrix into reduced row echelon form is sometimes called Gauss–Jordan elimination. Some authors use the term Gaussian elimination to refer to the process until it has reached its upper triangular, or (non-reduced) row echelon form. For computational reasons, when solving systems of linear equations, it is sometimes preferable to stop row operations before the matrix is completely reduced. End of explanation """ def seidel(a, b, x0 = None, limit=20000, debug=False): assert is_square(a) and is_dominant(a) and has_solutions(a, b) if x0 is None: x0 = np.zeros_like(b, dtype=np.float) x = x0.copy() while limit > 0: tx = x.copy() for i in range(a.shape[0]): x[i] = (b[i] - a[i, :].dot(x)) / a[i][i] + x[i] if debug: print(x) if np.allclose(x, tx, atol=ATOL, rtol=RTOL): return x, limit limit -= 1 return x, limit """ Explanation: Gauss-Seidel method The Gauss–Seidel method is an iterative technique for solving a square system of $n$ linear equations with unknown $x$: $$ A \mathbf{x} = \mathbf{b} $$ It is defined by the iteration $$ L_* \mathbf{x}^{(k+1)} = \mathbf{b} - U \mathbf{x}^{(k)}, $$ where $\mathbf{x}^{(k)}$ is the $k$-th approximation or iteration of $\mathbf{x},\,\mathbf{x}^{k+1}$ is the next or $k + 1$ iteration of $\mathbf{x}$, and the matrix $A$ is decomposed into a lower triangular component $L_$, and a strictly upper triangular component $U: A = L_ + U $. In more detail, write out $A$, $\mathbf{x}$ and $\mathbf{b}$ in their components: $$A=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \a_{n1} & a_{n2} & \cdots & a_{nn} \end{bmatrix}, \qquad \mathbf{x} = \begin{bmatrix} x_{1} \ x_2 \ \vdots \ x_n \end{bmatrix} , \qquad \mathbf{b} = \begin{bmatrix} b_{1} \ b_2 \ \vdots \ b_n \end{bmatrix}.$$ Then the decomposition of $A$ into its lower triangular component and its strictly upper triangular component is given by: $$A=L_+U \qquad \text{where} \qquad L_ = \begin{bmatrix} a_{11} & 0 & \cdots & 0 \ a_{21} & a_{22} & \cdots & 0 \ \vdots & \vdots & \ddots & \vdots \a_{n1} & a_{n2} & \cdots & a_{nn} \end{bmatrix}, \quad U = \begin{bmatrix} 0 & a_{12} & \cdots & a_{1n} \ 0 & 0 & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \0 & 0 & \cdots & 0 \end{bmatrix}.$$ The system of linear equations may be rewritten as: $$L_* \mathbf{x} = \mathbf{b} - U \mathbf{x} $$ The Gauss–Seidel method now solves the left hand side of this expression for $\mathbf{x}$, using previous value for $\mathbf{x}$ on the right hand side. Analytically, this may be written as: $$ \mathbf{x}^{(k+1)} = L_*^{-1} (\mathbf{b} - U \mathbf{x}^{(k)}). $$ However, by taking advantage of the triangular form of $L_$, the elements of $\mathbf{x}^{(k + 1)}$ can be computed sequentially using forward substitution*: $$ x^{(k+1)}i = \frac{1}{a{ii}} \left(b_i - \sum_{j=1}^{i-1}a_{ij}x^{(k+1)}j - \sum{j=i+1}^{n}a_{ij}x^{(k)}_j \right),\quad i=1,2,\dots,n. $$ The procedure is generally continued until the changes made by an iteration are below some tolerance. End of explanation """ def jacobi(a, b, x0 = None, limit=20000, debug=False): assert is_square(a) and is_dominant(a) and has_solutions(a, b) if x0 is None: x0 = np.zeros_like(b, dtype=np.float) x = x0.copy() while limit > 0: tx = x.copy() for i in range(a.shape[0]): x[i] = (b[i] - a[i, :].dot(tx)) / a[i][i] + tx[i] if debug: print(x) if np.allclose(x, tx, atol=ATOL, rtol=RTOL): return x, limit limit -= 1 return x, limit """ Explanation: Jacobi method The Jacobi method is an iterative technique for solving a square system of $n$ linear equations with unknown $x$: $$ A \mathbf{x} = \mathbf{b} $$ where $$A=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \a_{n1} & a_{n2} & \cdots & a_{nn} \end{bmatrix}, \qquad \mathbf{x} = \begin{bmatrix} x_{1} \ x_2 \ \vdots \ x_n \end{bmatrix} , \qquad \mathbf{b} = \begin{bmatrix} b_{1} \ b_2 \ \vdots \ b_n \end{bmatrix}.$$ Then $A$ can be decomposed into a diagonal component $D$, and the remainder $R$: $$A=D+R \qquad \text{where} \qquad D = \begin{bmatrix} a_{11} & 0 & \cdots & 0 \ 0 & a_{22} & \cdots & 0 \ \vdots & \vdots & \ddots & \vdots \0 & 0 & \cdots & a_{nn} \end{bmatrix} \text{ and } R = \begin{bmatrix} 0 & a_{12} & \cdots & a_{1n} \ a_{21} & 0 & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{n1} & a_{n2} & \cdots & 0 \end{bmatrix}. $$ The solution is then obtained iteratively via $$ \mathbf{x}^{(k+1)} = D^{-1} (\mathbf{b} - R \mathbf{x}^{(k)}), $$ where $\mathbf{x}^{(k)}$ is the $k$-th approximation or iteration of $\mathbf{x}$ and $\mathbf{x}^{(k+1)}$ is the next or $k + 1$ iteration of $\mathbf{x}$. The element-based formula is thus: $$ x^{(k+1)}i = \frac{1}{a{ii}} \left(b_i -\sum_{j\ne i}a_{ij}x^{(k)}_j\right),\quad i=1,2,\ldots,n. $$ The computation of $x_{i}^{(k+1)}$ requires each element in $\mathbf{x}^k$ except itself. Unlike the Gauss–Seidel method, we can't overwrite $x_i^k$ with $x_i^{(k+1)}$, as that value will be needed by the rest of the computation. The minimum amount of storage is two vectors of size $n$. End of explanation """ def norm(a, b, res): return np.linalg.norm(a.dot(res) - b) def run(method, a, b, verbose=False, **kwargs): if not verbose: print("-" * 100) print(method.__name__.upper()) res = method(a, b, **kwargs) score = norm(a, b, res[0]) if not verbose: print("res =", res) print("score =", score) return score """ Explanation: Evaluation To evaluate algorithm we are going to calculate $$ score = || A \cdot \mathbf{x^*} - \mathbf{b} || $$ where $\mathbf{x}^*$ is a result of algorithm. End of explanation """ a4 = np.array([[10., -1., 2., 0.], [-1., 11., -1., 3.], [2., -1., 10., -1.], [0., 3., -1., 8.]]) print(a4) b = np.array([6., 25., -11., 15.]) print("b =", b) _ = run(linalg, a4, b) _ = run(gauss, a4, b) _ = run(seidel, a4, b) _ = run(jacobi, a4, b) """ Explanation: Back to examples Example 1 Do you remember example from the problem statement? Now, we are going to see how iterative algorithms converges for that example. End of explanation """ a4 = np.array([[1., -1/8, 1/32, 1/64], [-1/2, 2., 1/16, 1/32], [-1., 1/4, 4., 1/16], [-1., 1/4, 1/8, 8.]]) print(a4) b = np.array([1., 4., 16., 64.]) print("b =", b) _ = run(linalg, a4, b) _ = run(gauss, a4, b) _ = run(seidel, a4, b) _ = run(jacobi, a4, b) """ Explanation: Seidel vs Jacobi Here is tricky example of linear system, when Jacobi method converges faster than Gauss-Seidel. As you will see, Jacobi needs only 1 iteration to find an answer, while Gauss-Seidel needs over 10 iterations to find approximate solution. End of explanation """ a, b = generate_hilbert(1000) print("LINALG =", run(linalg, a, b, verbose=True)) print("GAUSS =", run(gauss, a, b, verbose=True)) print("SEIDEL =", run(seidel, a, b, x0=np.zeros_like(b, dtype=np.float), verbose=True)) print("JACOBI =", run(jacobi, a, b, x0=np.zeros_like(b, dtype=np.float), verbose=True)) """ Explanation: Hilbert matrices Now, let's have a look at Hilbert matrix. It's said that non-iterative methods should do bad here. Proof? End of explanation """ def plot_hilbert_score_by_matrix_size(method, sizes): scores = np.zeros_like(sizes, dtype=np.float) for i in range(len(sizes)): a, b = generate_hilbert(sizes[i]) scores[i] = run(method, a, b, verbose=True) plt.plot(sizes, scores, label=method.__name__) sizes = np.linspace(1, 600, num=50, dtype=np.int) plt.figure(figsize=(15, 10)) plot_hilbert_score_by_matrix_size(linalg, sizes) plot_hilbert_score_by_matrix_size(gauss, sizes) plot_hilbert_score_by_matrix_size(seidel, sizes) plot_hilbert_score_by_matrix_size(jacobi, sizes) plt.title("Scores of different methods for Hilbert matrices") \ .set_fontsize("xx-large") plt.xlabel("n").set_fontsize("xx-large") plt.ylabel("score").set_fontsize("xx-large") legend = plt.legend(loc="upper right") for label in legend.get_texts(): label.set_fontsize("xx-large") plt.show() """ Explanation: As we can see, it's true for huge $n>1000$, that direct methods works bad on Hilbert matrices. But how about the size of matrix? Is $n=500$ enough? End of explanation """ a, b = generate_random(20) _ = run(linalg, a, b) _ = run(gauss, a, b) _ = run(seidel, a, b) _ = run(jacobi, a, b) """ Explanation: Random matrices It's time to test our methods on random generated matrices. To be deterministic, we are going to set seed equals to $17$ every time, we call generate_random(...) End of explanation """ a, b = generate_random(200) %timeit run(linalg, a, b, verbose=True) %timeit run(gauss, a, b, verbose=True) %timeit run(seidel, a, b, verbose=True) %timeit run(jacobi, a, b, verbose=True) """ Explanation: Runtime Now, let's compare our methods by actual time running. To have more accurate results, we need to run them on large matrix(eg. random $200x200$). End of explanation """ def plot_convergence(method, a, b, limits): scores = np.zeros_like(limits, dtype=np.float) for i in range(len(limits)): scores[i] = run(method, a, b, x0 = np.zeros_like(b, dtype=np.float), limit=limits[i], verbose=True) plt.plot(limits, scores, label=method.__name__) a, b = generate_random(15) limits = np.arange(0, 350) plt.figure(figsize=(15, 10)) plot_convergence(seidel, a, b, limits) plot_convergence(jacobi, a, b, limits) plt.title("Convergence of Seidel/Jacobi methods for random matrix").set_fontsize("xx-large") plt.xlabel("n_iters").set_fontsize("xx-large") plt.ylabel("score").set_fontsize("xx-large") plt.xscale("log") legend = plt.legend(loc="upper right") for label in legend.get_texts(): label.set_fontsize("xx-large") plt.show() """ Explanation: Convergence speed We already have compared methods by accuracy and time, but how about speed. Now we are going to show what will be the error of method after some number of iterations. To be more clear we use logarithmic x-scale. End of explanation """
satishgoda/learning
web/jquery.ipynb
mit
%%javascript console.info($); window.alert($); """ Explanation: Back to Html jQuery https://jquery.org https://en.wikipedia.org/wiki/JQuery https://weblogs.asp.net/scottgu/jquery-and-microsoft Overview Press CTRL + SHIFT + I to open the Browser debug console End of explanation """ %%javascript var sequence = [1, 2 ,3]; $.each(sequence, function() { var sequence_item = this; window.alert(sequence_item + " -> " + Number(sequence_item + 1)); }); """ Explanation: Usage Styles $, $. No Conflict Mode jQuery &gt;&gt; $ &gt;&gt; jQuery &lt;- function x() &gt;&gt; $() &gt;&gt; jQuery() &lt;- Object { } End of explanation """
jorgemauricio/INIFAP_Course
ejercicios/Numpy/1_Arreglos Numpy.ipynb
mit
my_list = [1,2,3] my_list np.array(my_list) my_matrix = [[1,2,3],[4,5,6],[7,8,9]] my_matrix """ Explanation: Crear Numpy Arrays De una lista de python Creamos el arreglo directamente de una lista o listas de python End of explanation """ np.arange(0,10) np.arange(0,11,2) """ Explanation: Métodos arange End of explanation """ np.zeros(3) np.zeros((5,5)) np.ones(3) np.ones((3,3)) """ Explanation: ceros y unos Generar arreglos de ceros y unos End of explanation """ np.linspace(0,10,3) np.linspace(0,10,50) """ Explanation: linspace Generar un arreglo especificando un intervalo End of explanation """ np.eye(4) """ Explanation: eye Generar matrices de identidad End of explanation """ np.random.rand(2) np.random.rand(5,5) """ Explanation: Random rand Generar un arreglo con una forma determinada de numeros con una distribución uniforme [0,1] End of explanation """ np.random.randn(2) np.random.randn(5,5) """ Explanation: randn Generar un arreglo con una distribucion estandar a diferencia de rand que es uniforme End of explanation """ np.random.randint(1,100) np.random.randint(1,100,10) """ Explanation: randint Generar numeros aleatorios en un rango determinado End of explanation """ arr = np.arange(25) ranarr = np.random.randint(0,50,10) arr ranarr """ Explanation: Metodos y atributos de arreglos End of explanation """ arr.reshape(5,5) """ Explanation: Reshape Regresa el mismo arreglo pero en diferente forma End of explanation """ ranarr ranarr.max() ranarr.argmax() ranarr.min() ranarr.argmin() """ Explanation: max, min, argmax, argmin Metodos para encontrar máximos y mínimos de los valores y sus indices End of explanation """ # Vector arr.shape # Tomar en cuenta que se implementan dos corchetes arr.reshape(1,25) arr.reshape(1,25).shape arr.reshape(25,1) arr.reshape(25,1).shape """ Explanation: Shape Atributo para desplegar la forma que tienen el arreglo End of explanation """ arr.dtype """ Explanation: dtype Despliega el tipo de dato de los objetos del arreglo End of explanation """
mne-tools/mne-tools.github.io
0.16/_downloads/plot_decoding_csp_eeg.ipynb
bsd-3-clause
# Authors: Martin Billinger <martin.billinger@tugraz.at> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import ShuffleSplit, cross_val_score from mne import Epochs, pick_types, find_events from mne.channels import read_layout from mne.io import concatenate_raws, read_raw_edf from mne.datasets import eegbci from mne.decoding import CSP print(__doc__) # ############################################################################# # # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = -1., 4. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_fnames = eegbci.load_data(subject, runs) raw_files = [read_raw_edf(f, preload=True, stim_channel='auto') for f in raw_fnames] raw = concatenate_raws(raw_files) # strip channel names of "." characters raw.rename_channels(lambda x: x.strip('.')) # Apply band-pass filter raw.filter(7., 30., fir_design='firwin', skip_by_annotation='edge') events = find_events(raw, shortest_event=0, stim_channel='STI 014') picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=True) epochs_train = epochs.copy().crop(tmin=1., tmax=2.) labels = epochs.events[:, -1] - 2 """ Explanation: =========================================================================== Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP) =========================================================================== Decoding of motor imagery applied to EEG data decomposed using CSP. Here the classifier is applied to features extracted on CSP filtered signals. See http://en.wikipedia.org/wiki/Common_spatial_pattern and [1]. The EEGBCI dataset is documented in [2]. The data set is available at PhysioNet [3]_. References .. [1] Zoltan J. Koles. The quantitative extraction and topographic mapping of the abnormal components in the clinical EEG. Electroencephalography and Clinical Neurophysiology, 79(6):440--447, December 1991. .. [2] Schalk, G., McFarland, D.J., Hinterberger, T., Birbaumer, N., Wolpaw, J.R. (2004) BCI2000: A General-Purpose Brain-Computer Interface (BCI) System. IEEE TBME 51(6):1034-1043. .. [3] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh, Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. (2000) PhysioBank, PhysioToolkit, and PhysioNet: Components of a New Research Resource for Complex Physiologic Signals. Circulation 101(23):e215-e220. End of explanation """ # Define a monte-carlo cross-validation generator (reduce variance): scores = [] epochs_data = epochs.get_data() epochs_data_train = epochs_train.get_data() cv = ShuffleSplit(10, test_size=0.2, random_state=42) cv_split = cv.split(epochs_data_train) # Assemble a classifier lda = LinearDiscriminantAnalysis() csp = CSP(n_components=4, reg=None, log=True, norm_trace=False) # Use scikit-learn Pipeline with cross_val_score function clf = Pipeline([('CSP', csp), ('LDA', lda)]) scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) # plot CSP patterns estimated on full data for visualization csp.fit_transform(epochs_data, labels) layout = read_layout('EEG1005') csp.plot_patterns(epochs.info, layout=layout, ch_type='eeg', units='Patterns (AU)', size=1.5) """ Explanation: Classification with linear discrimant analysis End of explanation """ sfreq = raw.info['sfreq'] w_length = int(sfreq * 0.5) # running classifier: window length w_step = int(sfreq * 0.1) # running classifier: window step size w_start = np.arange(0, epochs_data.shape[2] - w_length, w_step) scores_windows = [] for train_idx, test_idx in cv_split: y_train, y_test = labels[train_idx], labels[test_idx] X_train = csp.fit_transform(epochs_data_train[train_idx], y_train) X_test = csp.transform(epochs_data_train[test_idx]) # fit classifier lda.fit(X_train, y_train) # running classifier: test classifier on sliding window score_this_window = [] for n in w_start: X_test = csp.transform(epochs_data[test_idx][:, :, n:(n + w_length)]) score_this_window.append(lda.score(X_test, y_test)) scores_windows.append(score_this_window) # Plot scores over time w_times = (w_start + w_length / 2.) / sfreq + epochs.tmin plt.figure() plt.plot(w_times, np.mean(scores_windows, 0), label='Score') plt.axvline(0, linestyle='--', color='k', label='Onset') plt.axhline(0.5, linestyle='-', color='k', label='Chance') plt.xlabel('time (s)') plt.ylabel('classification accuracy') plt.title('Classification score over time') plt.legend(loc='lower right') plt.show() """ Explanation: Look at performance over time End of explanation """
PythonFreeCourse/Notebooks
week04/5_Builtins.ipynb
mit
print(abs(-5)) numbers = [5, -5, 1.337, -1.337] for number in numbers: print(f"abs({number:>6}) = {abs(number)}") """ Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוגן המופיע מעל לשם הקורס הוא מיזם חינמי ללימוד תכנות בעברית."> <span style="text-align: right; direction: rtl; float: right;">פונקציות מובנות</span> <span style="text-align: right; direction: rtl; float: right; clear: both;">הקדמה</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אנו פוגשים הרבה בעיות בתכנות לעיתים קרובות ובמגוון מצבים: </p> <ul style="text-align: right; direction: rtl; float: right; clear: both;"> <li>מציאת הערך הקטן או הגדול ביותר ברשימת ערכים.</li> <li>יצירת רשימת מספרים המתחילה בערך מסוים ומסתיימת בערך אחר.</li> <li>שינוי מיקום הערכים לפי סדר מסוים.</li> <li>המרה של ערך כלשהו למספר, למחרוזת, לבוליאני או לרשימה (נשמע מוכר?)</li> </ul> <p style="text-align: right; direction: rtl; float: right; clear: both;"> כדי שלא נצטרך לכתוב שוב ושוב את אותו פתרון, שפות רבות מצוידות בכלים מוכנים מראש שמטרתם לפתור בעיות נפוצות.<br> פייתון מתגאה בכך שהיא שפה ש"הבטריות בה כלולות" (batteries included), היגד שנועד לתאר את העובדה שהיא מכילה פתרונות מוכנים לאותן בעיות.<br> במחברת זו נכיר חלק מהפונקציות שפייתון מספקת לנו במטרה להקל על חיינו. </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> השם הנפוץ עבור הפונקציות הללו הוא <dfn>builtins</dfn>, ואפשר למצוא את התיעוד של כולן <a href="https://docs.python.org/3/library/functions.html">כאן</a>. </p> <div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;"> <div style="display: flex; width: 10%; float: right; clear: both;"> <img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול"> </div> <div style="width: 70%"> <p style="text-align: right; direction: rtl; float: right; clear: both;"> חשבו על פונקציות כאלו שאתם כבר מכירים משיעורים קודמים.<br> חלק מהפתרונות האפשריים: <span style="background: black;">len, int, float, str, list, type</span> </p> </div> <div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;"> <p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;"> <strong>חשוב!</strong><br> פתרו לפני שתמשיכו! </p> </div> </div> <div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/tip.png" style="height: 50px !important;" alt="טיפ!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: rtl;"> בהמשך המחברת ישנן דוגמאות עבור כל פונקציה חדשה שנכיר.<br> למען הבהירות אני מדפיס דוגמה בודדת, ואז אני משתמש בלולאה כדי להדפיס כמה דוגמאות ברצף.<br> הדוגמאות ירווחו בצורה מוזרה כדי שיהיה נוח להסתכל על הפלט. אל תשתמשו בריווחים כאלו בקוד שלכם. </p> </div> </div> <span style="text-align: right; direction: rtl; float: right; clear: both;">מתמטיקה</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> ישנן פעולות מתמטיות שנצטרך לעיתים תכופות, שאת חלקן אפילו מימשנו שוב ושוב לאורך הקורס.<br> נראה מה יש לארגז הכלים של פייתון להציע לנו. </p> <span style="text-align: right; direction: rtl; float: right; clear: both;">ערך מוחלט</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> הפונקציה <code>abs</code> מחזירה את הערך המוחלט של המספר שנעביר לה.<br> אם נעביר לה כארגומנט מספר שלם או עשרוני, היא תחזיר את המרחק של המספר מ־0 על ציר המספרים:<br> </p> End of explanation """ numbers = [6, 7, 3, 4, 5] words = ['apple', 'ginger', 'tomato', 'sushi'] print(max(numbers)) print(f"max(numbers) = {max(numbers)}") print(f"min(numbers) = {min(numbers)}") print(f"max(words) = {max(words)}") print(f"min(words) = {min(words)}") """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/tip.png" style="height: 50px !important;" alt="טיפ!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: rtl;"> המשמעות של <code dir="ltr" style="direction: ltr">:>6</code> ב־fstring היא "דאג שיהיו לפחות 6 תווים, וישר את הערך לימין".<br> אפשר להחליף את <code dir="ltr" style="direction: ltr">&gt;</code> בתו <code dir="ltr" style="direction: ltr">^</code> לצורך יישור לאמצע, או בתו <code dir="ltr" style="direction: ltr">&lt;</code> לצורך יישור לשמאל. </p> </div> </div> <span style="text-align: right; direction: rtl; float: right; clear: both;">מקסימום ומינימום</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> הפונקציות <code>max</code> ו־<code>min</code> מקבלות iterable, ומחזירות את האיבר הגבוה או הנמוך ביותר ב־iterable (בהתאמה). </p> End of explanation """ words.append('ZEBRA') print(f"Minimum in {words} is {min(words)}??") """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: rtl;"> מחרוזות בפייתון מושוות לפי הערך המספרי של התווים שמהם הן מורכבות.<br> כשמדובר ב־iterable שיש בו מחרוזות, פייתון מוצאת את הערך המרבי או המזערי לפי הייצוג המספרי של האותיות באותן מחרוזות.<br> מהסיבה הזו, הסידור האלפבתי לא יחזיר את הערך הרצוי במצב שבו יש גם אותיות גדולות וגם אותיות וקטנות: </p> </div> </div> End of explanation """ numbers = [1, 1, 2, 3, 5, 8] sum(numbers) i = 1 while i <= len(numbers): sum_until_i = sum(numbers[:i]) print(f"The sum of the first {i} items in 'numbers' is {sum_until_i}") i = i + 1 """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> זה קורה כיוון שהערכים המספריים של אותיות גדולות קטנים מאלו של אותיות קטנות.<br> הערך המספרי של Z במילה <em>ZEBRA</em> הוא 90, והערך המספרי של a (במילה <em>apple</em>, שציפינו שתיחשב כקטנה ביותר) הוא 97. </p> <span style="text-align: right; direction: rtl; float: right; clear: both;">סכום</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אפשר לחשב את סכום האיברים ב־iterable באמצעות הפונקציה <code>sum</code>: </p> End of explanation """ number = 5.9 round(number) numbers = [6, 3.1415, 0.9, -0.9, 0.5, -0.5] for number in numbers: print(f"round({number:>6}) = {round(number)}") """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">עיגול</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אפשר גם לעגל מספרים בעזרת הפונקציה <code>round</code>: </p> End of explanation """ pi = 3.141592653589793 round(pi, 3) # הפרמטר השני פה, 3, מייצג את הדיוק numbers = [6, 3.1415, 0.9, -0.9, 0.5, -0.5] round_options = [-1, 1, 2, 3] for number in numbers: for round_argument in round_options: result = round(number, round_argument) print(f"round({number:>6}, {round_argument}) = {result}") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> ואפשר להחליט על מספר הספרות אחרי הנקודה שלפיו העיגול יתבצע: </p> End of explanation """ list('hello') # Iterable -> List """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">המרות</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> טוב, על המרות (casting) כבר למדנו.<br> אבל בואו בכל זאת נראה כמה דוגמאות מגניבות. </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אפשר להמיר מחרוזת לרשימה. הפעולה הזו תפריד כל אחת מהאותיות לתא נפרד ברשימה: </p> End of explanation """ bool_checks = [ 'hello', '', 0, 1, -1, 0.0, 0.1, 1000, '\n', ' ', [], {}, [1], ] for check in bool_checks: print(f"bool({check!r:>7}) is {bool(check)}") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> עוד פרט טריוויה נחמד הוא שלכל ערך בפייתון יש ערך בוליאני שקול.<br> בדרך כלל, ערכים ריקים שקולים ל־<code>False</code> וערכים שאינם ריקים שקולים ל־<code>True</code>: </p> End of explanation """ print(int(True)) print(int(False)) """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/tip.png" style="height: 50px !important;" alt="טיפ!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: rtl;"> המשמעות של <code dir="ltr" style="direction: ltr">!r</code> ב־fstring היא "הצג את הערך בתצורתו הגולמית" (raw).<br> לדוגמה, מחרוזות יוצגו עם הגרשיים משני צידיהן. </p> </div> </div> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אפשר להמיר ערכים בוליאניים למספר שלם: </p> End of explanation """ stock = [('apples', 2), ('banana', 3), ('crembo', 4)] print(dict(stock)) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> מה בנוגע לטריקים על מילונים?<br> אם יש לנו iterable שמכיל זוגות של ערכים, אפשר להפוך אותו למילון: </p> End of explanation """ print(int(5.5)) print(float('5.5')) print(str(True)) print(bool(0)) print(dict([('name', 'Yam'), ('age', 27)])) tuple_until_4 = (1, 2, 3, 4) print(list(tuple_until_4)) print(tuple('yo!')) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> וכטיפ כללי, אפשר להמיר את סוג הערכים שלנו לטיפוס שונה, בעזרת הפונקציה שנקראת על שם הטיפוס שאליו אנחנו רוצים להמיר: </p> End of explanation """ print(list(5)) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> אבל צריך לזכור שלא כל טיפוס אפשר להמיר לטיפוס אחר: </p> End of explanation """ values = ['1337', [1, 3, 3, 7], 1337, ['1', '3', '3', '7']] for value in values: id_of_value = id(value) print(f'id({str(value):>20}) -> {id_of_value}') """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">מאחורי הקלעים של פייתון</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> ישנן פונקציות מובנות רבות שמטרתן להנגיש לנו דברים שקורים מאחורי הקלעים של פייתון. במחברת זו נסביר על שלוש מהן. </p> <span style="text-align: right; direction: rtl; float: right; clear: both;">id</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> על הפונקציה <code>id</code> כבר למדנו בעבר. היא מקבלת כארגומנט ערך, ומחזירה לנו את "הזהות" שלו – ערך אחר שמייצג רק את אותו.<br> בגרסת הפייתון שאנחנו משתמשים בה, מדובר בכתובת של הערך ב<a href="https://he.wikipedia.org/wiki/%D7%96%D7%99%D7%9B%D7%A8%D7%95%D7%9F_%D7%92%D7%99%D7%A9%D7%94_%D7%90%D7%A7%D7%A8%D7%90%D7%99%D7%AA">זיכרון המחשב</a>.<br> כל אדם שיריץ את הקוד הבא יקבל ערכים שונים, אבל לעולם לא יודפסו לו 2 ערכים זהים באותה ריצה.<br> הסיבה לכך שתמיד יודפסו 4 ערכים שונים היא שכל הנתונים שמופיעים ברשימה <var>values</var> שונים זה מזה. </p> End of explanation """ song1 = ["I've", 'got', 'a', 'lovely', 'bunch', 'of', 'coconuts'] song2 = song1 # שתי הרשימות כרגע מצביעות לאותו מקום song3 = song1[:] # הערך זהה, אך שכפלנו את הרשימה כך שהמשתנה הזה יצביע למקום אחר print(f"id(song1): {id(song1)}") print(f"id(song2): {id(song2)} # Same id!") print(f"id(song3): {id(song3)} # Another id!") # נשים לב שהן מתנהגות בהתאם: song2.append("🎵") print(f"song1: {song1}") print(f"song2: {song2}") print(f"song3: {song3}") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> אם ניצור מצב שבו 2 שמות מצביעים על אותו ערך בדיוק, <code>id</code> תחזיר את אותה התוצאה עבור שני הערכים: </p> End of explanation """ collections_of_numbers = [[0, 0, 0]] * 3 # ניצור 3 רשימות של 3 איברים בכל אחת print(collections_of_numbers) collections_of_numbers[0].append(100) # נוסיף את האיבר 100 לרשימה הראשונה בלבד print(collections_of_numbers) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> הפונקציה הזו יכולה לסייע לנו להגיע לתובנות בנוגע לדרך שבה פייתון עובדת בכל מיני מצבים.<br> קשה להבין, לדוגמה, מה קורה בקוד הבא: </p> End of explanation """ print(id(collections_of_numbers[0])) print(id(collections_of_numbers[1])) print(id(collections_of_numbers[2])) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> בדיקה בעזרת <code>id</code> תעזור לנו לראות שהרשימות הפנימיות בתוך <var>collections_of_numbers</var> מצביעות לאותו מקום: </p> End of explanation """ dir('hello') """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;"> <div style="display: flex; width: 10%; float: right; clear: both;"> <img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול"> </div> <div style="width: 70%"> <p style="text-align: right; direction: rtl; float: right; clear: both;"> נסו לכתוב קוד של שורה אחת או יותר, שיחליף את השורה הראשונה בקוד שלמעלה.<br> גרמו לכך שהקוד שמוסיף את הערך 100 לרשימה הראשונה לא ישפיע על שאר הרשימות. </p> </div> <div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;"> <p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;"> <strong>חשוב!</strong><br> פתרו לפני שתמשיכו! </p> </div> </div> <span style="text-align: right; direction: rtl; float: right; clear: both;">dir</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> גם על הפונקציה <code>dir</code> כבר למדנו. ראיתם אותה לאחרונה במחברת שעסקה בדוקומנטציה.<br> הפונקציה <code>dir</code> תחזיר לנו את כל הפעולות שאפשר לבצע על משתנה מסוים או על טיפוס מסוים.<br> נוכל להעביר לה כארגומנט את הערך שנרצה להבין מה הפעולות שאפשר לבצע עליו: </p> End of explanation """ dir(str) """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">או שנוכל להעביר לה ממש שם של טיפוס:</span> End of explanation """ x = [] eval("x.append('So lonely')") print(x) """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">eval</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> על <code>eval</code> אנחנו מלמדים בעיקר כדי להזהיר ממנה – זו פונקציה שאחראית למחדלי אבטחה בכל שפת תכנות שבה היא קיימת.<br> אתם לא אמורים להשתמש בה בקורס, וכדאי לזכור שכשהתשובה היא <code>eval</code>, ברוב המוחלט של המקרים שאלתם את השאלה הלא נכונה. </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אחרי ההקדמה המלודרמטית, נספר לכם ש־<code>eval</code> (מלשון evaluation) פשוט מקבלת קוד כמחרוזת, ומריצה אותו בעזרת פייתון. </p> End of explanation """ # לנסות בבית עם כפפות – בסדר. לא לכתוב בשום קוד אחר print(eval(input("Please enter any mathematical expression: "))) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> לעיתים קרובות הפיתוי להשתמש ב־<code>eval</code> הוא גדול.<br> אפשר לתכנת, לדוגמה, את המחשבון מהתרגול בשבוע השני בצורה הפשוטה הבאה: </p> End of explanation """ max_number = int(input()) current_number = 0 total = 0 while current_number <= max_number: total = total + current_number current_number = current_number + 1 print(total) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> אבל כשחושבים על זה – המשתמש שמתבקש להכניס תרגיל מתמטי, יכול להריץ כל קוד שיתחשק לו, והקוד הזה יבוצע!<br> הוא יכול לקרוא קבצים שנמצאים על מחשב או למחוק אותם, לחטט בסיסמאות, ולמעשה – לעשות ככל העולה על רוחו.<br> לקריאה נוספת על הסכנות, חפשו על <a href="https://en.wikipedia.org/wiki/Code_injection">code injection</a>. </p> <span style="text-align: right; direction: rtl; float: right; clear: both;">כלים שימושיים נוספים</span> <span style="text-align: right; direction: rtl; float: right; clear: both;">טווח מספרים</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> פעמים רבות אנחנו נתקלים במצבים שבהם אנחנו רוצים לעבור על כל המספרים מ־0 ועד ערך מסוים.<br> לדוגמה, כך פתרנו את התרגיל שמחשב את סכום המספרים עד מספר שהתקבל כקלט: </p> End of explanation """ for i in range(5): print(i) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> מטרת הפונקציה <code>range</code> היא לפתור לנו את הבעיה הזו בקלות.<br> תנו ל־<code>range</code> מספר כארגומנט, והיא תחזיר לכם iterable שמכיל את כל המספרים הטבעיים עד המספר שנתתם לה, ללא המספר האחרון: </p> End of explanation """ for i in range(12, 14): print(i) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> הפונקציה יודעת גם לקבל ערך שממנו היא תתחיל לספור: </p> End of explanation """ for i in range(0, 101, 10): print(i) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> וגם ערך דילוג, שקובע על כמה מספרים <code>range</code> תדלג בכל פעם: </p> End of explanation """ sorted('spoilage') """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: rtl;"> הפונקציה <code>range</code> מזכירה את פעולת החיתוך מהשבוע השלישי, שבה משתמשים בסוגריים מרובעים ובנקודתיים.<br> <code>range</code>, לעומת חיתוך, היא פונקציה – קוראים לה בעזרת סוגריים עגולים, ומפרידים בין הארגומנטים שנשלחים אליה בעזרת פסיקים. </p> </div> </div> <div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;"> <div style="display: flex; width: 10%; float: right; clear: both;"> <img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול"> </div> <div style="width: 70%"> <p style="text-align: right; direction: rtl; float: right; clear: both;"> כתבו בעצמכם קוד שמחשב את סכום המספרים מ־0 ועד המספר שהתקבל כקלט.<br> השתמשו ב־<code>range</code>. </p> </div> <div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;"> <p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;"> <strong>חשוב!</strong><br> פתרו לפני שתמשיכו! </p> </div> </div> <span style="text-align: right; direction: rtl; float: right; clear: both;">סידור</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> עד כה ארגז הכלים שלנו כלל רק את פעולת הסידור ששייכת לרשימות, <code>sort</code>.<br> אף שמעשית רוב פעולות הסידור מבוצעות על רשימות, לפעמים יעלה הצורך לסדר טיפוסי נתונים אחרים.<br> במקרים האלה נשתמש בפונקציה המובנית <code>sorted</code>: </p> End of explanation """ numbers = (612314, 4113, 1, 11, 31) sorted(numbers) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> <code>sorted</code> מקבלת iterable, ומחזירה רשימה מסודרת של האיברים ב־iterable. </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> נראה דוגמה נוספת של סידור tuple.<br> שימו לב שטיפוס הנתונים שמוחזר מ־<code>sorted</code> הוא תמיד רשימה: </p> End of explanation """ sorted('deflow', reverse=True) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> גם ל־<code>sorted</code> וגם לפעולה <code>sort</code> שיכולה להתבצע על רשימות, יש 2 פרמטרים שלא למדנו עליהם.<br> לפרמטר הראשון קוראים <em>reverse</em>, והוא הפשוט להבנה מבין השניים – ברגע שמועבר אליו <var>True</var>, הוא מחזיר את הרשימה מסודרת בסדר יורד:</p> End of explanation """ staff = ["Dafi", "Efrat", "Ido", "Itamar", "Yam"] """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> הפרמטר השני, <em>key</em>, מסובך קצת יותר להבנה.<br> כשנעביר לפרמטר הזה פונקציה, הסידור של איברי ה־iterable יתבצע לפי הערך שחוזר מהפונקציה הזו עבור כל אחד מהאיברים שצריך למיין.<br> מבולבלים? נראה, לדוגמה, את הרשימה הבאה, שמורכבת משמות אנשי הסגל של אחד מהמחזורים הקודמים: </p> End of explanation """ staff = sorted(staff, key=len) print(staff) """ Explanation: <table style="font-size: 2rem; border: 0px solid black; border-spacing: 0px;"> <tr> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid;">0</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">1</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">4</td> </tr> <tbody> <tr> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Dafi"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Efrat"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Ido"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Itamar"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Yam"</td> </tr> <tr style="background: #f5f5f5;"> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: right;">-5</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: right; border-left: 1px solid #555555;">-4</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: right; border-left: 1px solid #555555;">-3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: right; border-left: 1px solid #555555;">-2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: right; border-left: 1px solid #555555;">-1</td> </tr> </tbody> </table> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אם ארצה לסדר את הרשימה הזו לפי האורך (<code>len</code>) של שמות כל אחד מאנשי הסגל, אשתמש ב־key בצורה הבאה: </p> End of explanation """ paintings = ['Mona Lisa', 'The Creation of Adam', 'The Scream', 'The Starry Night'] artists = ['Leonardo da Vinci', 'Michelangelo', 'Edvard Munch', 'Vincent van Gogh'] """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> מה קרה שם בפועל?<br> הפונקציה <code>len</code> הופעלה על כל אחד מהאיברים. התוצאות מופיעות בתרשים הבא: </p> <table style="font-size: 2rem; border: 0px solid black; border-spacing: 0px;"> <tr> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid;">0</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">1</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">4</td> </tr> <tbody> <tr> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Dafi"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Efrat"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Ido"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Itamar"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Yam"</td> </tr> <tr style="background: #f5f5f5; color: black;"> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center;"><strong>4</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>5</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>3</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>6</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>3</strong></td> </tr> </tbody> </table> <p style="text-align: right; direction: rtl; float: right; clear: both;"> בפועל, אנחנו מחזיקים עכשיו רשימה ראשית (שמות אנשי הסגל), ועוד רשימה משנית שבה מאוחסנים אורכי האיברים שברשימה הראשית.<br> פייתון תמיין את הרשימה המשנית, ובכל פעם שהיא תזיז את אחד האיברים בה, היא תזיז איתו את האיבר התואם ברשימה המקורית: </p> <table style="font-size: 2rem; border: 0px solid black; border-spacing: 0px;"> <tr> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid;">0</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">1</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid; border-bottom: 1px solid; background: #d1d1d1;">2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">4</td> </tr> <tbody> <tr> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Dafi"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Efrat"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid; background: #d1d1d1">"Ido"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Itamar"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Yam"</td> </tr> <tr style="background: #f5f5f5; color: black;"> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center;"><strong>4</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>5</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555; background: #d1d1d1"><strong>3</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>6</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>3</strong></td> </tr> </tbody> </table> <table style="font-size: 2rem; border: 0px solid black; border-spacing: 0px;"> <tr> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid; border-bottom: 1px solid; background: #d1d1d1;">0</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid; border-left: 1px solid #555555;">1</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">4</td> </tr> <tbody> <tr> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid; background: #d1d1d1">"Ido"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Dafi"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Efrat"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Itamar"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Yam"</td> </tr> <tr style="background: #f5f5f5; color: black;"> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555; background: #d1d1d1"><strong>3</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>4</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>5</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>6</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>3</strong></td> </tr> </tbody> </table> <span style="text-align: right; direction: rtl; float: right; clear: both;">הרשימה המשנית עדיין לא מסודרת. נמשיך:</span> <table style="font-size: 2rem; border: 0px solid black; border-spacing: 0px;"> <tr> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid;">0</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid; border-left: 1px solid #555555;;">1</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid; background: #d1d1d1;">4</td> </tr> <tbody> <tr> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid; border-left: 2px solid #555555;">"Ido"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Dafi"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Efrat"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Itamar"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid; background: #d1d1d1">"Yam"</td> </tr> <tr style="background: #f5f5f5; color: black;"> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 0px solid #555555;"><strong>3</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>4</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>5</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>6</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555; background: #d1d1d1"><strong>3</strong></td> </tr> </tbody> </table> <table style="font-size: 2rem; border: 0px solid black; border-spacing: 0px;"> <tr> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid;">0</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-bottom: 1px solid; border-left: 1px solid #555555; background: #d1d1d1;">1</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">2</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">3</td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; color: #777; text-align: left; border-left: 1px solid #555555; border-bottom: 1px solid;">4</td> </tr> <tbody> <tr> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid; border-left: 2px solid #555555;">"Ido"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid; background: #d1d1d1;">"Yam"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Dafi"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Efrat"</td> <td style="padding-top: 8px; padding-bottom: 8px; padding-left: 10px; padding-right: 10px; vertical-align: bottom; border: 2px solid;">"Itamar"</td> </tr> <tr style="background: #f5f5f5; color: black;"> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 0px solid #555555;"><strong>3</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555; background: #d1d1d1"><strong>3</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>4</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>5</strong></td> <td style="padding-left: 4px; padding-top: 2px; padding-bottom: 3px; font-size: 1.3rem; text-align: center; border-left: 1px solid #555555;"><strong>6</strong></td> </tr> </tbody> </table> <p style="text-align: right; direction: rtl; float: right; clear: both;"> עכשיו הרשימה המשנית מסודרת, ואפשר להפסיק את פעולת הסידור.<br> הקסם הוא שאפשר להכניס ל־<code>key</code> כל פונקציה, ולקבל iterable מסודר לפי ערכי ההחזרה של אותה פונקציה עבור הערכים ב־iterable. </p> <div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;"> <div style="display: flex; width: 10%; float: right; clear: both;"> <img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול"> </div> <div style="width: 70%"> <p style="text-align: right; direction: rtl; float: right; clear: both;"> כתבו פונקציה שמקבלת כפרמטר את רשימת השמות של המשתתפות בכיתה.<br> הפונקציה תחזיר רשימה המורכבת מאותם שמות, מסודרים לפי סדר האלף־בית.<br> סדרו נכונה גם מקרים שבהם חלק מהשמות מתחילים באות גדולה, וחלק – באות קטנה. </p> </div> <div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;"> <p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;"> <strong>חשוב!</strong><br> פתרו לפני שתמשיכו! </p> </div> </div> <span style="text-align: right; direction: rtl; float: right; clear: both;">צימוד ערכים</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> הרבה פעמים נגיע למצב שבו יש לנו 2 iterables ואנחנו מעוניינים לעבור על הערכים שלהם, זה לצד זה.<br> נניח שיש לנו רשימה של ציורים, ורשימה של הציירים שציירו אותם: </p> End of explanation """ i = 0 max_iterations = len(paintings) while i < max_iterations: artist = artists[i] painting = paintings[i] print(f"{artist} painted '{painting}'.") i = i + 1 """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> צורה אחת לעבור על שתי הרשימות תהיה כזו: </p> End of explanation """ zipped_values = zip(paintings, artists) print(list(zipped_values)) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> אבל אפשר להסכים על כך שהדרך הזו לא נוחה במיוחד.<br> אפשרות אחרת היא להשתמש ב־<code>zip</code>, שיצמיד בין שני הערכים ויצור לנו את המבנה הבא: </p> End of explanation """ for artist, painting in zip(artists, paintings): print(f"{artist} painted '{painting}'.") """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: rtl;"> אם שתי הרשימות אינן זהות באורכן, <code>zip</code> לא יתייחס לאיברים העודפים של הרשימה הארוכה יותר. </p> </div> </div> <p style="text-align: right; direction: rtl; float: right; clear: both;"> אחד השימושים האפשריים ל־<code>zip</code> הוא unpacking בתוך לולאת <code>for</code>: </p> End of explanation """ paintings = ['Mona Lisa', 'The Creation of Adam', 'The Scream', 'The Starry Night'] artists = ['Leonardo da Vinci', 'Michelangelo', 'Edvard Munch', 'Vincent van Gogh'] years = [1503, 1512, 1893, 1889] for artist, painting, year in zip(artists, paintings, years): print(f"{artist} painted '{painting}' in {year}.") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> והיא אפילו לא מוגבלת ל־2 ארגומנטים בלבד: </p> End of explanation """ paintings = ['Mona Lisa', 'The Creation of Adam', 'The Scream', 'The Starry Night'] artists = ['Leonardo da Vinci', 'Michelangelo', 'Edvard Munch', 'Vincent van Gogh'] artists_from_paintings = dict(zip(paintings, artists)) """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;"> <div style="display: flex; width: 10%; float: right; clear: both;"> <img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול"> </div> <div style="width: 70%"> <p style="text-align: right; direction: rtl; float: right; clear: both;"> יש טיפוס נתונים שהיה מתאים יותר למקרה הזה מאשר 2 רשימות. מהו לדעתכם? </p> </div> <div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;"> <p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;"> <strong>חשוב!</strong><br> פתרו לפני שתמשיכו! </p> </div> </div> <p style="text-align: right; direction: rtl; float: right; clear: both;"> שימוש נפוץ ל־<code>zip</code> הוא במקרה שיש לנו שתי רשימות שמתאימות זו לזו, ויחד יכולות ליצור מילון.<br> אם רשימה אחת מתאימה להיות המפתחות במילון, והאחרת להיות הערכים באותו מילון, נוכל להשתמש ב־<code>zip</code> כדי לבצע את ההמרה: </p> End of explanation """ print(artists_from_paintings.get('Mona Lisa')) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> עכשיו נוכל לשאול מי צייר את המונה ליזה: </p> End of explanation """ for painting, artist in artists_from_paintings.items(): print(f"{artist} painted '{painting}'.") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> או לעבור על המילון ולהדפיס את הערכים, כמו שעשינו לפני כן: </p> End of explanation """ print(ord('A')) chars = 'a !א' for char in chars: print(f"ord({char!r}) = {ord(char)}") """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">המרת תווים למספרים ולהפך</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> כפי שהסברנו במחברת קבצים בשבוע שעבר, לכל תו מוצמד מספר שמזהה אותו.<br> בעזרת הפונקציה <code>ord</code> נוכל לאחזר את הערך הזה: </p> End of explanation """ ascii_numbers = [97, 32, 33, 1488] for ascii_number in ascii_numbers: # המקפים שם כדי שתראו את הרווח :) print(f"chr({ascii_number:>4}) = -{chr(ascii_number)}-") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> ויש גם דרך לעשות את הפעולה ההפוכה!<br> בעזרת הפונקציה <code>chr</code> נוכל לקבל את התו לפי המספר שמייצג אותו: </p> End of explanation """ with open('resources/haiku.txt') as haiku: haiku_text = haiku.readlines() line_number = 0 for line in haiku_text: print(f"{line_number}:\t{line.rstrip()}") line_number = line_number + 1 """ Explanation: <div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;"> <div style="display: flex; width: 10%; float: right; clear: both;"> <img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול"> </div> <div style="width: 70%"> <p style="text-align: right; direction: rtl; float: right; clear: both;"> כתבו תוכנית שמדפיסה זוג ערכים עבור כל מספר מ־9,760 ועד 10,100.<br> הערך הראשון יהיה המספר, והערך השני יהיה התו שאותו המספר מייצג. </p> </div> <div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;"> <p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;"> <strong>חשוב!</strong><br> פתרו לפני שתמשיכו! </p> </div> </div> <span style="text-align: right; direction: rtl; float: right; clear: both;">מניית איברים</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> נניח שאנחנו רוצים לעבור על כל השורות בקובץ מסוים, ולהדפיס ליד כל שורה את המספר הסידורי שלה: </p> End of explanation """ haiku_text_enumerated = enumerate(haiku_text) print(list(haiku_text_enumerated)) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> חייבת להיות דרך טובה יותר!<br> הפונקציה המובנית <code>enumerate</code> מאפשרת למתכנת להצמיד מספר רץ ל־iterable: </p> End of explanation """ for line_number, line in enumerate(haiku_text): print(f"{line_number}:\t{line.rstrip()}") """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> השימוש הנפוץ ביותר ל־<code>enumerate</code> הוא בלולאות <code>for</code>: </p> End of explanation """ for line_number, line in enumerate(haiku_text, 1): print(f"{line_number}:\t{line.rstrip()}") line_number = line_number + 1 """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> טריק מדליק: אם בא לנו להתחיל למספר ממספר שהוא לא 0, אפשר להעביר ל־<code>enumerate</code> את המספר הזה כפרמטר: </p> End of explanation """ def create_chars_from_numbers(numbers): chars = [] for number in numbers: chars.append(chr(number)) return chars def get_all_english_letters(): first_letter = ord('a') last_letter = ord('z') all_letters_by_number = range(first_letter, last_letter + 1) all_letters = create_chars_from_numbers(all_letters_by_number) return all_letters def get_ceaser_map(): letters = get_all_english_letters() shifted_letters = letters[3:] + letters[:3] return dict(zip(letters, shifted_letters)) get_ceaser_map() """ Explanation: <span style="text-align: right; direction: rtl; float: right; clear: both;">דוגמאות לשימושים</span> <span style="text-align: right; direction: rtl; float: right;">מפת צופן קיסר</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> צופן קיסר היא שיטת הצפנה, שבה כל תו מוחלף בתו שנמצא 3 תווים אחריו באלף־בית של השפה.<br> בעברית, לדוגמה, האות א' תוחלף באות ד', האות ג' באות ו' והאות ת' באות ג'.<br> נבנה מפת פענוח לצופן קיסר בעזרת הפונקציות שלמדנו במחברת: </p> End of explanation """ def encrypt(message, encryption_map): encrypted = '' for char in message.lower(): # If we can't find the character, assume it is not encrypted. encrypted = encrypted + encryption_map.get(char, char) return encrypted encryption_map = get_ceaser_map() encrypted_message = encrypt('This is the encrypted message!', encryption_map) print(encrypted_message) def create_decryption_map(encryption_map): """Actually just flip the keys and the values of the dictionary""" decryption_map = {} for key, value in encryption_map.items(): decryption_map[value] = key return decryption_map def decrypt(message, decryption_map): decrypted = '' for char in message.lower(): # If we can't find the character, assume it is not encrypted. decrypted = decrypted + decryption_map.get(char, char) return decrypted decryption_map = create_decryption_map(encryption_map) decrypted_message = decrypt(encrypted_message, decryption_map) print(decrypted_message) """ Explanation: <p style="text-align: right; direction: rtl; float: right; clear: both;"> ורק בשביל הכיף, נבנה קוד שיאפשר לנו להשתמש במפה כדי להצפין מסרים: </p> End of explanation """ def convert_to_integers(numbers): integers = [] for number in numbers: integers.append(int(number)) return integers numbers = input("Please enter numbers splitted by ',': ").split(',') integers = convert_to_integers(numbers) integers.sort(reverse=True) for i, number in enumerate(integers): current_sum = sum(integers[:i+1]) print(f"The sum until {number} is {current_sum}") """ Explanation: <span style="text-align: right; direction: rtl; float: right;">סכימה מדורגת</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> נבנה תוכנה קצרה שמאפשרת למשתמש להזין מספרים, מסדרת אותם בסדר הפוך, ומדפיסה עבור כל איבר את סכום האיברים עד המיקום של אותו איבר: </p> End of explanation """ def get_grades(student_name): grades = [] grade = input(f'Please enter a grade for {student_name}: ') while grade.isdecimal(): grades.append(int(grade)) grade = input(f'Please enter another grade for {student_name}: ') return grades def get_students(): students = [] student = input('Please enter a student: ') while student != '': students.append(student) student = input('Please enter another student: ') return students def get_students_and_grades(): grades = [] students = get_students() for student in students: student_grades = get_grades(student) grades.append(student_grades) return zip(students, grades) def get_average_grade(student_and_his_grades): grades = student_and_his_grades[1] if len(grades) == 0: return 0 return sum(grades) / len(grades) students_and_grades = get_students_and_grades() students_sorted_by_grades = sorted( # מפצלים שורה כדי שלא יהיו שורות ארוכות מדי students_and_grades, key=get_average_grade, reverse=True ) best_student_name, best_grade = students_sorted_by_grades[0] print(f"The best student is {best_student_name} with the grades: {best_grade}") """ Explanation: <span style="text-align: right; direction: rtl; float: right;">ממוצע ציונים</span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> קבלו רשימת שמות תלמידים, ועבור כל תלמיד את רשימת הציונים שלו.<br> הדפיסו את שם התלמיד שממוצע הציונים שלו הוא הגבוה ביותר, לצד הציונים שלו. </p> End of explanation """
robertoalotufo/ia898
src/logfilter.ipynb
mit
import numpy as np def logfilter(f, sigma): import ia898.src as ia f = np.array(f) if len(f.shape) == 1: f = f[newaxis,:] x = (np.array(f.shape)//2).astype(int) h = ia.log(f.shape, (np.array(f.shape)//2).astype(int), sigma) h = ia.dftshift(h) H = np.fft.fft2(h) if not ia.isccsym(H): raise ValueError('log filter is not symmetrical') G = np.fft.fft2(f) * H g = np.fft.ifft2(G).real return g """ Explanation: Function logfilter Synopse Laplacian of Gaussian filter. g = logfilter(f, sigma) g: Image. f: Image. input image sigma: Double. scaling factor Description Filters the image f by the Laplacian of Gaussian (LoG) filter with parameter sigma. This filter is also known as the Marr-Hildreth filter. Obs: to better efficiency, this implementation computes the filter in the frequency domain. End of explanation """ testing = (__name__ == "__main__") if testing: ! jupyter nbconvert --to python logfilter.ipynb import numpy as np import sys,os ia898path = os.path.abspath('../../') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia """ Explanation: Examples End of explanation """ if testing: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg f = mpimg.imread('../data/cameraman.tif') g07 = ia.logfilter(f, 0.7) nb = ia.nbshow(3) nb.nbshow(f, 'Imagem original') nb.nbshow(ia.normalize(g07), 'LoG filter') nb.nbshow(g07 > 0, 'positive values') nb.nbshow() """ Explanation: Example 1 End of explanation """ if testing: g5 = ia.logfilter(f, 5) g10 = ia.logfilter(f, 10) nb = ia.nbshow(2,2) nb.nbshow(ia.normalize(g5), 'sigma=5') nb.nbshow(g5 > 0, 'positive, sigma=5') nb.nbshow(ia.normalize(g10), 'sigma=10') nb.nbshow(g10 > 0, 'positive, sigma=10') nb.nbshow() """ Explanation: Example 2 End of explanation """
GoogleCloudPlatform/vertex-ai-samples
notebooks/community/gapic/automl/showcase_automl_image_object_detection_export_edge.ipynb
apache-2.0
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG """ Explanation: Vertex client library: AutoML image object detection model for export to edge <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_image_object_detection_export_edge.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_image_object_detection_export_edge.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> </table> <br/><br/><br/> Overview This tutorial demonstrates how to use the Vertex client library for Python to create image object detection models to export as an Edge model using Google Cloud's AutoML. Dataset The dataset used for this tutorial is the Salads category of the OpenImages dataset from TensorFlow Datasets. This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the bounding box locations and corresponding type of salad items in an image from a class of five items: salad, seafood, tomato, baked goods, or cheese. Objective In this tutorial, you create a AutoML image object detection model from a Python script using the Vertex client library, and then export the model as an Edge model in TFLite format. You can alternatively create models with AutoML using the gcloud command-line tool or online using the Google Cloud Console. The steps performed include: Create a Vertex Dataset resource. Train the model. Export the Edge model from the Model resource to Cloud Storage. Download the model locally. Make a local prediction. Costs This tutorial uses billable components of Google Cloud (GCP): Vertex AI Cloud Storage Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Installation Install the latest version of Vertex client library. End of explanation """ ! pip3 install -U google-cloud-storage $USER_FLAG """ Explanation: Install the latest GA version of google-cloud-storage library as well. End of explanation """ if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) """ Explanation: Restart the kernel Once you've installed the Vertex client library and Google cloud-storage, you need to restart the notebook kernel so it can find the packages. End of explanation """ PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:", PROJECT_ID) ! gcloud config set project $PROJECT_ID """ Explanation: Before you begin GPU runtime Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the Vertex APIs and Compute Engine APIs. The Google Cloud SDK is already installed in Google Cloud Notebook. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands. End of explanation """ REGION = "us-central1" # @param {type: "string"} """ Explanation: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see the Vertex locations documentation End of explanation """ from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") """ Explanation: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial. End of explanation """ # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. # If on Google Cloud Notebook, then don't execute this code if not os.path.exists("/opt/deeplearning/metadata/env_version"): if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): %env GOOGLE_APPLICATION_CREDENTIALS '' """ Explanation: Authenticate your Google Cloud account If you are using Google Cloud Notebook, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, go to the Create service account key page. Click Create service account. In the Service account name field, enter a name, and click Create. In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex" into the filter box, and select Vertex Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin. Click Create. A JSON file that contains your key downloads to your local environment. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. End of explanation """ BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP """ Explanation: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for exporting the trained model. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket. Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. End of explanation """ ! gsutil mb -l $REGION $BUCKET_NAME """ Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket. End of explanation """ ! gsutil ls -al $BUCKET_NAME """ Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents: End of explanation """ import time from google.cloud.aiplatform import gapic as aip from google.protobuf import json_format from google.protobuf.json_format import MessageToJson, ParseDict from google.protobuf.struct_pb2 import Struct, Value """ Explanation: Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants Import Vertex client library Import the Vertex client library into our Python environment. End of explanation """ # API service endpoint API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION) # Vertex location root path for your dataset, model and endpoint resources PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION """ Explanation: Vertex constants Setup up the following constants for Vertex: API_ENDPOINT: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services. PARENT: The Vertex location root path for dataset, model, job, pipeline and endpoint resources. End of explanation """ # Image Dataset type DATA_SCHEMA = "gs://google-cloud-aiplatform/schema/dataset/metadata/image_1.0.0.yaml" # Image Labeling type LABEL_SCHEMA = "gs://google-cloud-aiplatform/schema/dataset/ioformat/image_bounding_box_io_format_1.0.0.yaml" # Image Training task TRAINING_SCHEMA = "gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_image_object_detection_1.0.0.yaml" """ Explanation: AutoML constants Set constants unique to AutoML datasets and training: Dataset Schemas: Tells the Dataset resource service which type of dataset it is. Data Labeling (Annotations) Schemas: Tells the Dataset resource service how the data is labeled (annotated). Dataset Training Schemas: Tells the Pipeline resource service the task (e.g., classification) to train the model for. End of explanation """ # client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_dataset_client(): client = aip.DatasetServiceClient(client_options=client_options) return client def create_model_client(): client = aip.ModelServiceClient(client_options=client_options) return client def create_pipeline_client(): client = aip.PipelineServiceClient(client_options=client_options) return client clients = {} clients["dataset"] = create_dataset_client() clients["model"] = create_model_client() clients["pipeline"] = create_pipeline_client() for client in clients.items(): print(client) """ Explanation: Tutorial Now you are ready to start creating your own AutoML image object detection model. Set up clients The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server. You will use different clients in this tutorial for different steps in the workflow. So set them all up upfront. Dataset Service for Dataset resources. Model Service for Model resources. Pipeline Service for training. End of explanation """ TIMEOUT = 90 def create_dataset(name, schema, labels=None, timeout=TIMEOUT): start_time = time.time() try: dataset = aip.Dataset( display_name=name, metadata_schema_uri=schema, labels=labels ) operation = clients["dataset"].create_dataset(parent=PARENT, dataset=dataset) print("Long running operation:", operation.operation.name) result = operation.result(timeout=TIMEOUT) print("time:", time.time() - start_time) print("response") print(" name:", result.name) print(" display_name:", result.display_name) print(" metadata_schema_uri:", result.metadata_schema_uri) print(" metadata:", dict(result.metadata)) print(" create_time:", result.create_time) print(" update_time:", result.update_time) print(" etag:", result.etag) print(" labels:", dict(result.labels)) return result except Exception as e: print("exception:", e) return None result = create_dataset("salads-" + TIMESTAMP, DATA_SCHEMA) """ Explanation: Dataset Now that your clients are ready, your first step in training a model is to create a managed dataset instance, and then upload your labeled data to it. Create Dataset resource instance Use the helper function create_dataset to create the instance of a Dataset resource. This function does the following: Uses the dataset client service. Creates an Vertex Dataset resource (aip.Dataset), with the following parameters: display_name: The human-readable name you choose to give it. metadata_schema_uri: The schema for the dataset type. Calls the client dataset service method create_dataset, with the following parameters: parent: The Vertex location root path for your Database, Model and Endpoint resources. dataset: The Vertex dataset object instance you created. The method returns an operation object. An operation object is how Vertex handles asynchronous calls for long running operations. While this step usually goes fast, when you first use it in your project, there is a longer delay due to provisioning. You can use the operation object to get status on the operation (e.g., create Dataset resource) or to cancel the operation, by invoking an operation method: | Method | Description | | ----------- | ----------- | | result() | Waits for the operation to complete and returns a result object in JSON format. | | running() | Returns True/False on whether the operation is still running. | | done() | Returns True/False on whether the operation is completed. | | canceled() | Returns True/False on whether the operation was canceled. | | cancel() | Cancels the operation (this may take up to 30 seconds). | End of explanation """ # The full unique ID for the dataset dataset_id = result.name # The short numeric ID for the dataset dataset_short_id = dataset_id.split("/")[-1] print(dataset_id) """ Explanation: Now save the unique dataset identifier for the Dataset resource instance you created. End of explanation """ IMPORT_FILE = "gs://cloud-samples-data/vision/salads.csv" """ Explanation: Data preparation The Vertex Dataset resource for images has some requirements for your data: Images must be stored in a Cloud Storage bucket. Each image file must be in an image format (PNG, JPEG, BMP, ...). There must be an index file stored in your Cloud Storage bucket that contains the path and label for each image. The index file must be either CSV or JSONL. CSV For image object detection, the CSV index file has the requirements: No heading. First column is the Cloud Storage path to the image. Second column is the label. Third/Fourth columns are the upper left corner of bounding box. Coordinates are normalized, between 0 and 1. Fifth/Sixth/Seventh columns are not used and should be 0. Eighth/Ninth columns are the lower right corner of the bounding box. Location of Cloud Storage training data. Now set the variable IMPORT_FILE to the location of the CSV index file in Cloud Storage. End of explanation """ if "IMPORT_FILES" in globals(): FILE = IMPORT_FILES[0] else: FILE = IMPORT_FILE count = ! gsutil cat $FILE | wc -l print("Number of Examples", int(count[0])) print("First 10 rows") ! gsutil cat $FILE | head """ Explanation: Quick peek at your data You will use a version of the Salads dataset that is stored in a public Cloud Storage bucket, using a CSV index file. Start by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (wc -l) and then peek at the first few rows. End of explanation """ def import_data(dataset, gcs_sources, schema): config = [{"gcs_source": {"uris": gcs_sources}, "import_schema_uri": schema}] print("dataset:", dataset_id) start_time = time.time() try: operation = clients["dataset"].import_data( name=dataset_id, import_configs=config ) print("Long running operation:", operation.operation.name) result = operation.result() print("result:", result) print("time:", int(time.time() - start_time), "secs") print("error:", operation.exception()) print("meta :", operation.metadata) print( "after: running:", operation.running(), "done:", operation.done(), "cancelled:", operation.cancelled(), ) return operation except Exception as e: print("exception:", e) return None import_data(dataset_id, [IMPORT_FILE], LABEL_SCHEMA) """ Explanation: Import data Now, import the data into your Vertex Dataset resource. Use this helper function import_data to import the data. The function does the following: Uses the Dataset client. Calls the client method import_data, with the following parameters: name: The human readable name you give to the Dataset resource (e.g., salads). import_configs: The import configuration. import_configs: A Python list containing a dictionary, with the key/value entries: gcs_sources: A list of URIs to the paths of the one or more index files. import_schema_uri: The schema identifying the labeling type. The import_data() method returns a long running operation object. This will take a few minutes to complete. If you are in a live tutorial, this would be a good time to ask questions, or take a personal break. End of explanation """ def create_pipeline(pipeline_name, model_name, dataset, schema, task): dataset_id = dataset.split("/")[-1] input_config = { "dataset_id": dataset_id, "fraction_split": { "training_fraction": 0.8, "validation_fraction": 0.1, "test_fraction": 0.1, }, } training_pipeline = { "display_name": pipeline_name, "training_task_definition": schema, "training_task_inputs": task, "input_data_config": input_config, "model_to_upload": {"display_name": model_name}, } try: pipeline = clients["pipeline"].create_training_pipeline( parent=PARENT, training_pipeline=training_pipeline ) print(pipeline) except Exception as e: print("exception:", e) return None return pipeline """ Explanation: Train the model Now train an AutoML image object detection model using your Vertex Dataset resource. To train the model, do the following steps: Create an Vertex training pipeline for the Dataset resource. Execute the pipeline to start the training. Create a training pipeline You may ask, what do we use a pipeline for? You typically use pipelines when the job (such as training) has multiple steps, generally in sequential order: do step A, do step B, etc. By putting the steps into a pipeline, we gain the benefits of: Being reusable for subsequent training jobs. Can be containerized and ran as a batch job. Can be distributed. All the steps are associated with the same pipeline job for tracking progress. Use this helper function create_pipeline, which takes the following parameters: pipeline_name: A human readable name for the pipeline job. model_name: A human readable name for the model. dataset: The Vertex fully qualified dataset identifier. schema: The dataset labeling (annotation) training schema. task: A dictionary describing the requirements for the training job. The helper function calls the Pipeline client service'smethod create_pipeline, which takes the following parameters: parent: The Vertex location root path for your Dataset, Model and Endpoint resources. training_pipeline: the full specification for the pipeline training job. Let's look now deeper into the minimal requirements for constructing a training_pipeline specification: display_name: A human readable name for the pipeline job. training_task_definition: The dataset labeling (annotation) training schema. training_task_inputs: A dictionary describing the requirements for the training job. model_to_upload: A human readable name for the model. input_data_config: The dataset specification. dataset_id: The Vertex dataset identifier only (non-fully qualified) -- this is the last part of the fully-qualified identifier. fraction_split: If specified, the percentages of the dataset to use for training, test and validation. Otherwise, the percentages are automatically selected by AutoML. End of explanation """ PIPE_NAME = "salads_pipe-" + TIMESTAMP MODEL_NAME = "salads_model-" + TIMESTAMP task = json_format.ParseDict( { "budget_milli_node_hours": 20000, "model_type": "MOBILE_TF_LOW_LATENCY_1", "disable_early_stopping": False, }, Value(), ) response = create_pipeline(PIPE_NAME, MODEL_NAME, dataset_id, TRAINING_SCHEMA, task) """ Explanation: Construct the task requirements Next, construct the task requirements. Unlike other parameters which take a Python (JSON-like) dictionary, the task field takes a Google protobuf Struct, which is very similar to a Python dictionary. Use the json_format.ParseDict method for the conversion. The minimal fields you need to specify are: budget_milli_node_hours: The maximum time to budget (billed) for training the model, where 1000 = 1 hour. For image object detection, the budget must be a minimum of 20 hours. model_type: The type of deployed model: CLOUD_HIGH_ACCURACY_1: For deploying to Google Cloud and optimizing for accuracy. CLOUD_LOW_LATENCY_1: For deploying to Google Cloud and optimizing for latency (response time), MOBILE_TF_HIGH_ACCURACY_1: For deploying to the edge and optimizing for accuracy. MOBILE_TF_LOW_LATENCY_1: For deploying to the edge and optimizing for latency (response time). MOBILE_TF_VERSATILE_1: For deploying to the edge and optimizing for a trade off between latency and accuracy. disable_early_stopping: Whether True/False to let AutoML use its judgement to stop training early or train for the entire budget. Finally, create the pipeline by calling the helper function create_pipeline, which returns an instance of a training pipeline object. End of explanation """ # The full unique ID for the pipeline pipeline_id = response.name # The short numeric ID for the pipeline pipeline_short_id = pipeline_id.split("/")[-1] print(pipeline_id) """ Explanation: Now save the unique identifier of the training pipeline you created. End of explanation """ def get_training_pipeline(name, silent=False): response = clients["pipeline"].get_training_pipeline(name=name) if silent: return response print("pipeline") print(" name:", response.name) print(" display_name:", response.display_name) print(" state:", response.state) print(" training_task_definition:", response.training_task_definition) print(" training_task_inputs:", dict(response.training_task_inputs)) print(" create_time:", response.create_time) print(" start_time:", response.start_time) print(" end_time:", response.end_time) print(" update_time:", response.update_time) print(" labels:", dict(response.labels)) return response response = get_training_pipeline(pipeline_id) """ Explanation: Get information on a training pipeline Now get pipeline information for just this training pipeline instance. The helper function gets the job information for just this job by calling the the job client service's get_training_pipeline method, with the following parameter: name: The Vertex fully qualified pipeline identifier. When the model is done training, the pipeline state will be PIPELINE_STATE_SUCCEEDED. End of explanation """ while True: response = get_training_pipeline(pipeline_id, True) if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED: print("Training job has not completed:", response.state) model_to_deploy_id = None if response.state == aip.PipelineState.PIPELINE_STATE_FAILED: raise Exception("Training Job Failed") else: model_to_deploy = response.model_to_upload model_to_deploy_id = model_to_deploy.name print("Training Time:", response.end_time - response.start_time) break time.sleep(60) print("model to deploy:", model_to_deploy_id) """ Explanation: Deployment Training the above model may take upwards of 30 minutes time. Once your model is done training, you can calculate the actual time it took to train the model by subtracting end_time from start_time. For your model, you will need to know the fully qualified Vertex Model resource identifier, which the pipeline service assigned to it. You can get this from the returned pipeline instance as the field model_to_deploy.name. End of explanation """ def list_model_evaluations(name): response = clients["model"].list_model_evaluations(parent=name) for evaluation in response: print("model_evaluation") print(" name:", evaluation.name) print(" metrics_schema_uri:", evaluation.metrics_schema_uri) metrics = json_format.MessageToDict(evaluation._pb.metrics) for metric in metrics.keys(): print(metric) print("evaluatedBoundingBoxCount", metrics["evaluatedBoundingBoxCount"]) print( "boundingBoxMeanAveragePrecision", metrics["boundingBoxMeanAveragePrecision"], ) return evaluation.name last_evaluation = list_model_evaluations(model_to_deploy_id) """ Explanation: Model information Now that your model is trained, you can get some information on your model. Evaluate the Model resource Now find out how good the model service believes your model is. As part of training, some portion of the dataset was set aside as the test (holdout) data, which is used by the pipeline service to evaluate the model. List evaluations for all slices Use this helper function list_model_evaluations, which takes the following parameter: name: The Vertex fully qualified model identifier for the Model resource. This helper function uses the model client service's list_model_evaluations method, which takes the same parameter. The response object from the call is a list, where each element is an evaluation metric. For each evaluation -- you probably only have one, we then print all the key names for each metric in the evaluation, and for a small set (evaluatedBoundingBoxCount and boundingBoxMeanAveragePrecision) you will print the result. End of explanation """ MODEL_DIR = BUCKET_NAME + "/" + "salads" def export_model(name, format, gcs_dest): output_config = { "artifact_destination": {"output_uri_prefix": gcs_dest}, "export_format_id": format, } response = clients["model"].export_model(name=name, output_config=output_config) print("Long running operation:", response.operation.name) result = response.result(timeout=1800) metadata = response.operation.metadata artifact_uri = str(metadata.value).split("\\")[-1][4:-1] print("Artifact Uri", artifact_uri) return artifact_uri model_package = export_model(model_to_deploy_id, "tflite", MODEL_DIR) """ Explanation: Export as Edge model You can export an AutoML image object detection model as an Edge model which you can then custom deploy to an edge device, such as a mobile phone or IoT device, or download locally. Use this helper function export_model to export the model to Google Cloud, which takes the following parameters: name: The Vertex fully qualified identifier for the Model resource. format: The format to save the model format as. gcs_dest: The Cloud Storage location to store the SavedFormat model artifacts to. This function calls the Model client service's method export_model, with the following parameters: name: The Vertex fully qualified identifier for the Model resource. output_config: The destination information for the exported model. artifact_destination.output_uri_prefix: The Cloud Storage location to store the SavedFormat model artifacts to. export_format_id: The format to save the model format as. For AutoML image object detection: tf-saved-model: TensorFlow SavedFormat for deployment to a container. tflite: TensorFlow Lite for deployment to an edge or mobile device. edgetpu-tflite: TensorFlow Lite for TPU tf-js: TensorFlow for web client coral-ml: for Coral devices The method returns a long running operation response. We will wait sychronously for the operation to complete by calling the response.result(), which will block until the model is exported. End of explanation """ ! gsutil ls $model_package # Download the model artifacts ! gsutil cp -r $model_package tflite tflite_path = "tflite/model.tflite" """ Explanation: Download the TFLite model artifacts Now that you have an exported TFLite version of your model, you can test the exported model locally, but first downloading it from Cloud Storage. End of explanation """ import tensorflow as tf interpreter = tf.lite.Interpreter(model_path=tflite_path) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() input_shape = input_details[0]["shape"] print("input tensor shape", input_shape) """ Explanation: Instantiate a TFLite interpreter The TFLite version of the model is not a TensorFlow SavedModel format. You cannot directly use methods like predict(). Instead, one uses the TFLite interpreter. You must first setup the interpreter for the TFLite model as follows: Instantiate an TFLite interpreter for the TFLite model. Instruct the interpreter to allocate input and output tensors for the model. Get detail information about the models input and output tensors that will need to be known for prediction. End of explanation """ test_items = ! gsutil cat $IMPORT_FILE | head -n1 test_item = test_items[0].split(",")[0] with tf.io.gfile.GFile(test_item, "rb") as f: content = f.read() test_image = tf.io.decode_jpeg(content) print("test image shape", test_image.shape) test_image = tf.image.resize(test_image, (224, 224)) print("test image shape", test_image.shape, test_image.dtype) test_image = tf.cast(test_image, dtype=tf.uint8).numpy() """ Explanation: Get test item You will use an arbitrary example out of the dataset as a test item. Don't be concerned that the example was likely used in training the model -- we just want to demonstrate how to make a prediction. End of explanation """ import numpy as np data = np.expand_dims(test_image, axis=0) interpreter.set_tensor(input_details[0]["index"], data) interpreter.invoke() softmax = interpreter.get_tensor(output_details[0]["index"]) label = np.argmax(softmax) print(label) """ Explanation: Make a prediction with TFLite model Finally, you do a prediction using your TFLite model, as follows: Convert the test image into a batch of a single image (np.expand_dims) Set the input tensor for the interpreter to your batch of a single image (data). Invoke the interpreter. Retrieve the softmax probabilities for the prediction (get_tensor). Determine which label had the highest probability (np.argmax). End of explanation """ delete_dataset = True delete_pipeline = True delete_model = True delete_endpoint = True delete_batchjob = True delete_customjob = True delete_hptjob = True delete_bucket = True # Delete the dataset using the Vertex fully qualified identifier for the dataset try: if delete_dataset and "dataset_id" in globals(): clients["dataset"].delete_dataset(name=dataset_id) except Exception as e: print(e) # Delete the training pipeline using the Vertex fully qualified identifier for the pipeline try: if delete_pipeline and "pipeline_id" in globals(): clients["pipeline"].delete_training_pipeline(name=pipeline_id) except Exception as e: print(e) # Delete the model using the Vertex fully qualified identifier for the model try: if delete_model and "model_to_deploy_id" in globals(): clients["model"].delete_model(name=model_to_deploy_id) except Exception as e: print(e) # Delete the endpoint using the Vertex fully qualified identifier for the endpoint try: if delete_endpoint and "endpoint_id" in globals(): clients["endpoint"].delete_endpoint(name=endpoint_id) except Exception as e: print(e) # Delete the batch job using the Vertex fully qualified identifier for the batch job try: if delete_batchjob and "batch_job_id" in globals(): clients["job"].delete_batch_prediction_job(name=batch_job_id) except Exception as e: print(e) # Delete the custom job using the Vertex fully qualified identifier for the custom job try: if delete_customjob and "job_id" in globals(): clients["job"].delete_custom_job(name=job_id) except Exception as e: print(e) # Delete the hyperparameter tuning job using the Vertex fully qualified identifier for the hyperparameter tuning job try: if delete_hptjob and "hpt_job_id" in globals(): clients["job"].delete_hyperparameter_tuning_job(name=hpt_job_id) except Exception as e: print(e) if delete_bucket and "BUCKET_NAME" in globals(): ! gsutil rm -r $BUCKET_NAME """ Explanation: Cleaning up To clean up all GCP resources used in this project, you can delete the GCP project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: Dataset Pipeline Model Endpoint Batch Job Custom Job Hyperparameter Tuning Job Cloud Storage Bucket End of explanation """
mitdbg/modeldb
client/workflows/demos/setup-script.ipynb
mit
import six from verta import Client from verta.utils import ModelAPI HOST = "app.verta.ai" PROJECT_NAME = "Part-of-Speech Tagging" EXPERIMENT_NAME = "NLTK" client = Client(HOST) proj = client.set_project(PROJECT_NAME) expt = client.set_experiment(EXPERIMENT_NAME) run = client.set_experiment_run() """ Explanation: Part-of-Speech Tagging with NLTK This notebook is a quick demonstration of verta's run.log_setup_script() feature. We'll create a simple and lightweight text tokenizer and part-of-speech tagger using NLTK, which will require not only installing the nltk package itself, but also downloading pre-trained text processing models within Python code. Prepare Verta End of explanation """ import nltk nltk.__version__ """ Explanation: Prepare NLTK This Notebook was tested with nltk v3.4.5, though many versions should work just fine. End of explanation """ # for tokenizing nltk.download('punkt') # for part-of-speech tagging nltk.download('averaged_perceptron_tagger') """ Explanation: NLTK requires the separate installation of a tokenizer and part-of-speech tagger before these functionalities can be used. End of explanation """ class TextClassifier: def __init__(self, nltk): self.nltk = nltk def predict(self, data): predictions = [] for text in data: tokens = self.nltk.word_tokenize(text) predictions.append({ 'tokens': tokens, 'parts_of_speech': [list(pair) for pair in self.nltk.pos_tag(tokens)], }) return predictions model = TextClassifier(nltk) data = [ "I am a teapot.", "Just kidding I'm a bug?", ] model.predict(data) """ Explanation: Log Model for Deployment Create Model Our model will be a thin wrapper around nltk, returning the constituent tokens and their part-of-speech tags for each input sentence. End of explanation """ model_api = ModelAPI(data, model.predict(data)) run.log_model(model, model_api=model_api) run.log_requirements(["nltk"]) """ Explanation: Create Deployment Artifacts As always, we'll create a couple of descriptive artifacts to let the Verta platform know how to handle our model. End of explanation """ setup = """ import nltk nltk.download('punkt') nltk.download('averaged_perceptron_tagger') """ run.log_setup_script(setup) """ Explanation: Create Setup Script As we did in the beginning of this Notebook, the deployment needs these NLTK resources downloaded and installed before it can run the model, so we'll define a short setup script to send over and execute at the beginning of a model deployment. End of explanation """ run data = [ "Welcome to Verta!", ] from verta.deployment import DeployedModel DeployedModel(HOST, run.id).predict(data) """ Explanation: Make Live Predictions Now we can visit the Web App, deploy the model, and make successful predictions! End of explanation """
ChadFulton/statsmodels
examples/notebooks/statespace_local_linear_trend.ipynb
bsd-3-clause
%matplotlib inline import numpy as np import pandas as pd from scipy.stats import norm import statsmodels.api as sm import matplotlib.pyplot as plt """ Explanation: State space modeling: Local Linear Trends This notebook describes how to extend the Statsmodels statespace classes to create and estimate a custom model. Here we develop a local linear trend model. The Local Linear Trend model has the form (see Durbin and Koopman 2012, Chapter 3.2 for all notation and details): $$ \begin{align} y_t & = \mu_t + \varepsilon_t \qquad & \varepsilon_t \sim N(0, \sigma_\varepsilon^2) \ \mu_{t+1} & = \mu_t + \nu_t + \xi_t & \xi_t \sim N(0, \sigma_\xi^2) \ \nu_{t+1} & = \nu_t + \zeta_t & \zeta_t \sim N(0, \sigma_\zeta^2) \end{align} $$ It is easy to see that this can be cast into state space form as: $$ \begin{align} y_t & = \begin{pmatrix} 1 & 0 \end{pmatrix} \begin{pmatrix} \mu_t \ \nu_t \end{pmatrix} + \varepsilon_t \ \begin{pmatrix} \mu_{t+1} \ \nu_{t+1} \end{pmatrix} & = \begin{bmatrix} 1 & 1 \ 0 & 1 \end{bmatrix} \begin{pmatrix} \mu_t \ \nu_t \end{pmatrix} + \begin{pmatrix} \xi_t \ \zeta_t \end{pmatrix} \end{align} $$ Notice that much of the state space representation is composed of known values; in fact the only parts in which parameters to be estimated appear are in the variance / covariance matrices: $$ \begin{align} H_t & = \begin{bmatrix} \sigma_\varepsilon^2 \end{bmatrix} \ Q_t & = \begin{bmatrix} \sigma_\xi^2 & 0 \ 0 & \sigma_\zeta^2 \end{bmatrix} \end{align} $$ End of explanation """ """ Univariate Local Linear Trend Model """ class LocalLinearTrend(sm.tsa.statespace.MLEModel): def __init__(self, endog): # Model order k_states = k_posdef = 2 # Initialize the statespace super(LocalLinearTrend, self).__init__( endog, k_states=k_states, k_posdef=k_posdef, initialization='approximate_diffuse', loglikelihood_burn=k_states ) # Initialize the matrices self.ssm['design'] = np.array([1, 0]) self.ssm['transition'] = np.array([[1, 1], [0, 1]]) self.ssm['selection'] = np.eye(k_states) # Cache some indices self._state_cov_idx = ('state_cov',) + np.diag_indices(k_posdef) @property def param_names(self): return ['sigma2.measurement', 'sigma2.level', 'sigma2.trend'] @property def start_params(self): return [np.std(self.endog)]*3 def transform_params(self, unconstrained): return unconstrained**2 def untransform_params(self, constrained): return constrained**0.5 def update(self, params, *args, **kwargs): params = super(LocalLinearTrend, self).update(params, *args, **kwargs) # Observation covariance self.ssm['obs_cov',0,0] = params[0] # State covariance self.ssm[self._state_cov_idx] = params[1:] """ Explanation: To take advantage of the existing infrastructure, including Kalman filtering and maximum likelihood estimation, we create a new class which extends from statsmodels.tsa.statespace.MLEModel. There are a number of things that must be specified: k_states, k_posdef: These two parameters must be provided to the base classes in initialization. The inform the statespace model about the size of, respectively, the state vector, above $\begin{pmatrix} \mu_t & \nu_t \end{pmatrix}'$, and the state error vector, above $\begin{pmatrix} \xi_t & \zeta_t \end{pmatrix}'$. Note that the dimension of the endogenous vector does not have to be specified, since it can be inferred from the endog array. update: The method update, with argument params, must be specified (it is used when fit() is called to calculate the MLE). It takes the parameters and fills them into the appropriate state space matrices. For example, below, the params vector contains variance parameters $\begin{pmatrix} \sigma_\varepsilon^2 & \sigma_\xi^2 & \sigma_\zeta^2\end{pmatrix}$, and the update method must place them in the observation and state covariance matrices. More generally, the parameter vector might be mapped into many different places in all of the statespace matrices. statespace matrices: by default, all state space matrices (obs_intercept, design, obs_cov, state_intercept, transition, selection, state_cov) are set to zeros. Values that are fixed (like the ones in the design and transition matrices here) can be set in initialization, whereas values that vary with the parameters should be set in the update method. Note that it is easy to forget to set the selection matrix, which is often just the identity matrix (as it is here), but not setting it will lead to a very different model (one where there is not a stochastic component to the transition equation). start params: start parameters must be set, even if it is just a vector of zeros, although often good start parameters can be found from the data. Maximum likelihood estimation by gradient methods (as employed here) can be sensitive to the starting parameters, so it is important to select good ones if possible. Here it does not matter too much (although as variances, they should't be set zero). initialization: in addition to defined state space matrices, all state space models must be initialized with the mean and variance for the initial distribution of the state vector. If the distribution is known, initialize_known(initial_state, initial_state_cov) can be called, or if the model is stationary (e.g. an ARMA model), initialize_stationary can be used. Otherwise, initialize_approximate_diffuse is a reasonable generic initialization (exact diffuse initialization is not yet available). Since the local linear trend model is not stationary (it is composed of random walks) and since the distribution is not generally known, we use initialize_approximate_diffuse below. The above are the minimum necessary for a successful model. There are also a number of things that do not have to be set, but which may be helpful or important for some applications: transform / untransform: when fit is called, the optimizer in the background will use gradient methods to select the parameters that maximize the likelihood function. By default it uses unbounded optimization, which means that it may select any parameter value. In many cases, that is not the desired behavior; variances, for example, cannot be negative. To get around this, the transform method takes the unconstrained vector of parameters provided by the optimizer and returns a constrained vector of parameters used in likelihood evaluation. untransform provides the reverse operation. param_names: this internal method can be used to set names for the estimated parameters so that e.g. the summary provides meaningful names. If not present, parameters are named param0, param1, etc. End of explanation """ import requests from io import BytesIO from zipfile import ZipFile # Download the dataset ck = requests.get('http://staff.feweb.vu.nl/koopman/projects/ckbook/OxCodeAll.zip').content zipped = ZipFile(BytesIO(ck)) df = pd.read_table( BytesIO(zipped.read('OxCodeIntroStateSpaceBook/Chapter_2/NorwayFinland.txt')), skiprows=1, header=None, sep='\s+', engine='python', names=['date','nf', 'ff'] ) """ Explanation: Using this simple model, we can estimate the parameters from a local linear trend model. The following example is from Commandeur and Koopman (2007), section 3.4., modeling motor vehicle fatalities in Finland. End of explanation """ # Load Dataset df.index = pd.date_range(start='%d-01-01' % df.date[0], end='%d-01-01' % df.iloc[-1, 0], freq='AS') # Log transform df['lff'] = np.log(df['ff']) # Setup the model mod = LocalLinearTrend(df['lff']) # Fit it using MLE (recall that we are fitting the three variance parameters) res = mod.fit(disp=False) print(res.summary()) """ Explanation: Since we defined the local linear trend model as extending from MLEModel, the fit() method is immediately available, just as in other Statsmodels maximum likelihood classes. Similarly, the returned results class supports many of the same post-estimation results, like the summary method. End of explanation """ # Perform prediction and forecasting predict = res.get_prediction() forecast = res.get_forecast('2014') fig, ax = plt.subplots(figsize=(10,4)) # Plot the results df['lff'].plot(ax=ax, style='k.', label='Observations') predict.predicted_mean.plot(ax=ax, label='One-step-ahead Prediction') predict_ci = predict.conf_int(alpha=0.05) predict_index = np.arange(len(predict_ci)) ax.fill_between(predict_index[2:], predict_ci.iloc[2:, 0], predict_ci.iloc[2:, 1], alpha=0.1) forecast.predicted_mean.plot(ax=ax, style='r', label='Forecast') forecast_ci = forecast.conf_int() forecast_index = np.arange(len(predict_ci), len(predict_ci) + len(forecast_ci)) ax.fill_between(forecast_index, forecast_ci.iloc[:, 0], forecast_ci.iloc[:, 1], alpha=0.1) # Cleanup the image ax.set_ylim((4, 8)); legend = ax.legend(loc='lower left'); """ Explanation: Finally, we can do post-estimation prediction and forecasting. Notice that the end period can be specified as a date. End of explanation """
garth-wells/notebooks-3M1
02-LeastSquares.ipynb
bsd-2-clause
%matplotlib inline import matplotlib.pyplot as plt # Use seaborn to style the plots and use accessible colors import seaborn as sns sns.set() sns.set_palette("colorblind") import numpy as np N = 100 x = np.linspace(-1, 1, N) def runge(x): return 1 /(25 * (x**2) + 1) plt.xlabel('$x$') plt.ylabel('$y$') plt.title('Runge function') plt.plot(x, runge(x),'-'); """ Explanation: Least squares problems We sometimes wish to solve problems of the form $$ \boldsymbol{A} \boldsymbol{x} = \boldsymbol{b} $$ where $\boldsymbol{A}$ is a $m \times n$ matrix. If $m > n$, in general no solution to the problem exists. This is a typical of an over-determined problem - we have more equations than unknowns. A classical example is when trying to fit an $k$th-order polynomial to $p > k + 1$ data points - the degree of the polynomial is not high enough to construct an interpolating polynomial. In this notebook we assume that $\boldsymbol{A}$ is full rank, i.e. the columns of $\boldsymbol{A}$ are linearly independent. We will look at the case when $\boldsymbol{A}$ is not full rank later. Before computing least-squares problems, we start with examples of polynomial interpolation. Note: This notebook uses interactive widgets to interactively explore various effects. The widget sliders will be be visiable through nbviewer. Polynomial interpolation Polynomial interpolation involves fitting a $n$th-order polynomial to values at $n + 1$ data points. Interpolating the Runge function We will investigate interpolating the Runge function $$ y = \frac{1}{1 + 25 x^{2}} $$ on the interval $[-1, 1]$: End of explanation """ n_p = 5 x_p = np.linspace(-1, 1, n_p) A = np.vander(x_p, n_p) print(x_p) print(A) """ Explanation: Next, we will sample the Runge function at points and fit a polynomial to these evaluation points. If we sample the function at $n$ points we can fit a polynomial of degree $n - 1$: $$ f = c_{n-1} x^{n-1} + c_{n-2} x^{n-2} + \ldots + c_{1} x + c_{0}. $$ We can find the polynomial coefficients $c_{i}$ by solving $\boldsymbol{A} \boldsymbol{c} = \boldsymbol{y}p$, where $\boldsymbol{A}$ is the Vandermonde matrix: $$ \boldsymbol{A} = \begin{bmatrix} x{1}^{n-1} & x_{1}^{n-2} & \ldots & x_{1}^{2} & x_{1} & 1 \ x_{2}^{n-1} & x_{2}^{n-2} & \ldots & x_{2}^{2} & x_{2} & 1 \ \vdots & \vdots & \vdots & \ldots & \vdots \ x_{n}^{n-1} & x_{n}^{n-2} & \ldots & x_{n}^{2} & x_{n} & 1 \end{bmatrix} $$ and the vector $\boldsymbol{c}$ contains the unknown polynomial coefficients $$ \boldsymbol{c} = \begin{bmatrix} c_{19} & c_{20} & \ldots & c_{0} \end{bmatrix}^{T} $$ and the vector $\boldsymbol{y}p$ contains the points $y(x{i})$ that we wish to fit. Note: the ordering in each row of the Vandermonde matrix above is reversed with respect to what you will find in most books. We do this because the default NumPy function for generating the Vandermonde matrix uses the above ordering. Using the NumPy built-in function to generate the Vandermonde matrix for $n_p$ points (polynomial degree $n_{p} -1)$: End of explanation """ y_p = runge(x_p) c = np.linalg.solve(A, y_p) """ Explanation: Solving for the coefficients: End of explanation """ p = np.poly1d(c) print(p) """ Explanation: NumPy has a function poly1d to turn the coefficients into a polynomial object, and it can display a representation of the polynomial: End of explanation """ # Create an array of 200 equally spaced points on [-1, 1] x_fit = np.linspace(-1, 1, 200) # Evaluate the polynomial at the points y_fit = p(x_fit) # Plot the interpolating polynomial and the sample points plt.xlabel('$x$') plt.ylabel('$f$') plt.title('Points of the Runge function interpolated by a polynomial') plot = plt.plot(x_p, y_p, 'o', label='points') plot = plt.plot(x_fit, y_fit,'-', label='interpolate') plot = plt.plot(x, runge(x), '--', label='exact') plt.legend(); """ Explanation: To plot the fitted polynomial, we evaluate it at at 200 points: End of explanation """ n_p = 13 x_p = np.linspace(-1, 1, n_p) A = np.vander(x_p, n_p) y_p = runge(x_p) c = np.linalg.solve(A, y_p) p = np.poly1d(c) y_fit = p(x_fit) # Plot the interpolating polynomial and the sample points plt.xlabel('$x$') plt.ylabel('$f$') plt.title('Points of the Runge function interpolated by a polynomial') plot = plt.plot(x_p, y_p, 'o', label='points') plot = plt.plot(x_fit, y_fit,'-', label='interpolate') plot = plt.plot(x, runge(x), '--', label='exact') plt.legend(); """ Explanation: Note how the polynomial fitting function oscillates near the ends of the interval. We might think that a richer, higher-order degree polynomial would provide a better fit: End of explanation """ from ipywidgets import widgets from ipywidgets import interact @interact(order=(0, 19)) def plot(order): x_p = np.linspace(-1, 1, order + 1) A = np.vander(x_p, order + 1) y_p = runge(x_p) c = np.linalg.solve(A, y_p) p = np.poly1d(c) y_fit = p(x_fit) # Plot the interpolating polynomial and the sample points plt.xlabel('$x$') plt.ylabel('$f$') plt.title('Points of the Runge function interpolated by a polynomial') plot = plt.plot(x_p, y_p, 'o', label='points') plot = plt.plot(x_fit, y_fit,'-', label='interpolate ' + str(order) ) plot = plt.plot(x, runge(x), '--', label='exact') plt.legend() """ Explanation: However, we see that the oscillations near the ends of the internal become worse with a higher degree polynomial. By wrapping this problem in a function we can make it interactive: End of explanation """ n_p = 13 x_p = np.linspace(-1, 1, n_p) A = np.vander(x_p, n_p) print(f"Condition number of the Vandermonde matrix: {np.linalg.cond(A, 2):e}") n_p = 20 x_p = np.linspace(-1, 1, n_p) A = np.vander(x_p, n_p) print(f"Condition number of the Vandermonde matrix: {np.linalg.cond(A, 2):e}") n_p = 30 x_p = np.linspace(-1, 1, n_p) A = np.vander(x_p, n_p) print(f"Condition number of the Vandermonde matrix: {np.linalg.cond(A, 2):e}") n_p = 30 x_p = np.linspace(-10, 10, n_p) A = np.vander(x_p, n_p) print(f"Condition number of the Vandermonde matrix: {np.linalg.cond(A, 2):e}") """ Explanation: There two issue to consider here. The first is that the polynmial clearly fluctuates near the ends of the interval. This is know as the Runge effect. A second issue that is less immediately obvious is that the Vandermonde matrix is very poorly conditioned. Conditioning of the Vandermonde matrix We compute the Vandermone matrix for increasing polynimial degree, and see below that the condition number of the Vandermonde matrix can become extremely large for high polynomial degrees. End of explanation """ for order in range(10): x, y = np.polynomial.legendre.Legendre.basis(order, [-1, 1]).linspace(100) plt.plot(x, y, label="P_{}".format(order)) plt.grid(True) plt.legend(); plt.savefig("legendre.pdf") """ Explanation: Orthogonal polynomials In the preceding, we worked with a monomial basis: $$ 1, \ x, \ x^{2}, \ldots , \ x^{n-1} $$ and considered polynomials of the form $$ f = c_{n-1} x^{n-1} + c_{n-2} x^{n-2} + \ldots + c_{1} x + c_{0}. $$ where we would pick (or solver for in the case of interpolation) the coefficients ${c_{i}}$. There are, however, alternatives to the monomial basis with remarkably rich and fascinating properties. We will consider Legendre polynomials on the internal $[-1, 1]$. There are various expressions for computing Legendre polynomials. One expressions for computing the Legendre polynomial of degree $n$, $P_{n}$, is: $$ (n+1) P_{n+1}(x) = (2n+1) x P_{n}(x) - n P_{n-1}(x) $$ where $P_{0} = 1$ and $P_{0} = x$. The special feature of Legendre polynomial is that: $$ \int_{-1}^{1} P_{m}(x) P_{n}(x) \, dx = 0 \quad {\rm if} \ m \ne n, $$ i.e. Legendre polynomials of different degree are orthogonal to each other. Plotting the Legendre polynomials up to $P_{9}$: End of explanation """ x_p = np.linspace(-1, 1, 100) for order in range(10): y_p = x_p**order plt.plot(x_p, y_p, label="m_{}".format(order)) plt.savefig("mononomial.pdf") """ Explanation: Comparing to the mononomal basis: End of explanation """ N = 20 x_p = np.linspace(-1, 1, N) A = np.vander(x_p, N) print(f"Condition number of the Vandermonde matrix (mononomial): {np.linalg.cond(A, 2):e}") A = np.polynomial.legendre.legvander(x_p, N) print(f"Condition number of the Vandermonde matrix (Legendre): {np.linalg.cond(A, 2):e}") """ Explanation: we see that the Legendre polynomial and the mononomials appear very different, depsite both spanning (being a basis) for the same space. Note how the higher order mononomial terms are indistinguishable near zero, whereas the Legendre polynomials are clearly distinct from each other. Legendre polynomials of degree up to and including $n$ span the same space as $1, x, x^{2},\ldots, x^{n}$, so we can express any polynomial of degree $n$ as $$ f = \alpha_{n} P_{n}(x) + \alpha_{n-1} P_{n-1}(x) + \ldots + \alpha_{0} P_{0}(x) $$ To find the ${ \alpha_{n} }$ coefficients can construct a generalised Vandermonde matrix $\boldsymbol{A}$ and solve $\boldsymbol{A} \boldsymbol{\alpha} = \boldsymbol{y}p$, where $$ \boldsymbol{A} = \begin{bmatrix} P{n}(x_{0}) & P_{n-1}(x_{0}) & \ldots & P_2(x_{0}) & P_1(x_{0}) & P_0(x_{0}) \ P_{n}(x_{1}) & P_{n-1}(x_{1}) & \ldots & P_2(x_{1}) & P_1(x_{1}) & P_0(x_{1}) \ \vdots & \vdots & \vdots & \ldots & \vdots \ P_{n}(x_{n}) & P_{n-1}(x_{n}) & \ldots & P_2(x_{n}) & P_1(x_{n}) & P_0(x_{n}) \end{bmatrix} $$ If we use the Legendre Vandermonde matrix to compute the coeffecients, in exact arithmetic we would compute the same polynomial as with the mononomial basis. However, comparing the condition number for the Vandermonde matrices: End of explanation """ @interact(N=(0, 30)) def plot(N): # Get the roots of the Legendre polynomials x_p = np.linspace(-1, 1, N) x_p = np.polynomial.legendre.leggauss(N)[0] print(f"Number of interpolation points: {len(x_p)} ") # Evaluate the Runge function y_p = runge(x_p) # Use NumPy function to compute the polynomial from numpy.polynomial import Legendre as P p = P.fit(x_p, y_p, N); x_e = np.linspace(-1, 1, N) # Evaluate the Runge function y_e = runge(x_e) # Use NumPy function to compute the polynomial from numpy.polynomial import Legendre as P p_e = P.fit(x_e, y_e, N); plt.xlabel('$x$') plt.ylabel('$y$') plt.plot(np.linspace(-1, 1, 100), runge( np.linspace(-1, 1, 100)),'--', label='Runge function'); plt.plot(x_p, np.zeros(len(x_p)),'o', label="Legendre roots"); plt.plot(*p.linspace(200), '-', label='interpolation (clustered)'); plt.plot(*p_e.linspace(200), '-', label='interpolation (equispaced)'); plt.plot(x_e, np.zeros(len(x_e)),'x', label="Equispaced points"); plt.ylim(-0.2, 1.5) plt.legend(); """ Explanation: Clearly the condition number for the Legendre case is dramatically smaller. Non-equispaced interpolaton points We have seen the Runge effect where interpolating polynomials can exhibit large oscillations close to the ends of the domain, with the effect becoming more pronounced as the polynomial degree is increased. A well-known approach to reducing the oscillations is to use evaluation points that clustered towards the ends of the domain. In particular, the roots of orthogonal polynomials can be particularly good evaluation points. To test, we will interpolate the Runge function at the roots of Legendre polynomials. End of explanation """ N = 20 def sine(x): return np.sin(2 * np.pi * x) x_p = np.linspace(-1, 1, N) y_p = sine(x_p) from numpy.polynomial import Polynomial as P y_fit = P.fit(x_p, sine(x_p), N); plt.xlabel('$x$') plt.ylabel('$y$') plt.title('Points on a sine graph') plt.plot(x_p, y_p,'ro'); plt.plot(*y_fit.linspace(200),'-', label='interpolated'); x = np.linspace(-1, 1, 200) plt.plot(x, sine(x),'--', label='sin(x)'); plt.legend(); """ Explanation: The polynomial that interpolates at points that are clustered near the ends of the interval exhibits very limited oscillation, whereas the oscillations for the equispaced case are very large. Interpolating the sine graph We consider now interpolating points takes from the sine graph. End of explanation """ N = 20 def noisy_sine(x, noise): return np.sin(2 * np.pi * x) + np.random.uniform(-noise/2.0, noise/2.0, len(x)) x_p = np.linspace(-1, 1, N) y_p = sine(x_p) from numpy.polynomial import Polynomial as P y_fit = P.fit(x_p, noisy_sine(x_p, 0.01), N); plt.xlabel('$x$') plt.ylabel('$y$') plt.title('Points on a sine graph') plt.plot(x_p, y_p,'x',label='interpolation points (noise)'); plt.plot(*y_fit.linspace(200),'-', label='interpolated'); x = np.linspace(-1, 1, 200) plt.plot(x, sine(x),'--', label='sin(x)'); plt.ylim(-1.2, 1.2) plt.legend(); """ Explanation: We can see from the graph that the polynomial closely ressambles the sine function in this case, despite the high degree of the polynomial. However, the picture changes if we introduce a very small amount of noise to the sine graph: End of explanation """ N = 20 x_p = np.linspace(-1, 1, N) A = np.vander(x_p, 6) """ Explanation: We see the Runge effect again, with large oscillations towards the ends of the domain. Least-squares fitting We will now looking at fitting a polynomial of degree $k < n + 1$ to points on the sine graph. The degree of the polynomial is not high enough to interpolate all points, so we will compute a best-fit in the least-squares sense. We have seen in lectures that solving the least squares solution involves solving $$ \boldsymbol{A}^{T}\boldsymbol{A} \boldsymbol{c} = \boldsymbol{A}^{T} \boldsymbol{y} $$ If we want ot fit a $5$th-order polynomial to 20 data points, $\boldsymbol{A}$ is the $20 \times 6$ matrix: $$ \boldsymbol{A} = \begin{bmatrix} x_{1}^{5} & x_{1}^{4} & \ldots & x_{1}^{2} & x_{1} & 1 \ x_{2}^{5} & x_{2}^{4} & \ldots & x_{2}^{2} & x_{2} & 1 \ \vdots & \vdots & \vdots & \ldots & \vdots \ \vdots & \vdots & \vdots & \ldots & \vdots \ x_{20}^{5} & x_{20}^{4} & \ldots & x_{20}^{2} & x_{20} & 1 \end{bmatrix} $$ and $\boldsymbol{c}$ contains the $6$ polynomial coefficients $$ \boldsymbol{c} = \begin{bmatrix} c_{0} & c_{1} & c_{2} & c_{3} & c_{4} \end{bmatrix} $$ and $\boldsymbol{y}$ contains the 20 points we want to fit. Fitting points on the Runge function Let's try fitting a lower-order polynomial to the 20 data points without noise. We start with a polynomial of degree 6. We first create the Vandermonde matrix: End of explanation """ ATA = (A.T).dot(A) y_p = runge(x_p) c_ls = np.linalg.solve(ATA, (A.T).dot(y_p)) p_ls = np.poly1d(c_ls) print(p_ls) """ Explanation: and then solve $$\boldsymbol{A}^{T}\boldsymbol{A} \boldsymbol{c} = \boldsymbol{A}^{T} \boldsymbol{y}$$ and create a NumPy polynomial from the coefficients: End of explanation """ # Evaluate polynomial at some points y_ls = p_ls(x_fit) # Plot plt.xlabel('$x$') plt.ylabel('$f$') # plt.ylim(-1.1, 1.1) plt.title('Least-squares fit of 20 points') plt.plot(x_p, y_p, 'o', x_fit, y_ls,'-'); """ Explanation: Plotting the polynomial: End of explanation """ @interact(order=(0, 19)) def plot(order): # Create Vandermonde matrix A = np.vander(x_p, order + 1) ATA = (A.T).dot(A) c_ls = np.linalg.solve(ATA, (A.T).dot(y_p)) p_ls = np.poly1d(c_ls) # Evaluate polynomial at some points y_ls = p_ls(x_fit) # Plot plt.xlabel('$x$') plt.ylabel('$f$') plt.ylim(-1.2, 1.2) plt.title('Least-squares fit of 20 points on the Runge graph with a ${}$th-order polynomial'.format(order)) plt.plot(x_p, y_p, 'o', x_fit, y_ls,'-') """ Explanation: To explore polynomial orders, we will create an interactive plot with a slider for the polynomial degree. End of explanation """
Hguimaraes/gtzan.keras
nbs/1.0-handcrafted_features.ipynb
mit
import os import librosa import itertools import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import kurtosis from scipy.stats import skew import sklearn from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.pipeline import Pipeline from sklearn.feature_selection import SelectKBest from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from sklearn.feature_selection import VarianceThreshold from sklearn.feature_selection import SelectFromModel import lightgbm as lgbm from sklearn.linear_model import LogisticRegression from sklearn.linear_model import SGDClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC # Set the seed np.random.seed(42) gtzan_dir = '../data/genres/' # Parameters song_samples = 22050*30 genres = {'metal': 0, 'disco': 1, 'classical': 2, 'hiphop': 3, 'jazz': 4, 'country': 5, 'pop': 6, 'blues': 7, 'reggae': 8, 'rock': 9} def get_features(y, sr, n_fft = 1024, hop_length = 512): # Features to concatenate in the final dictionary features = {'centroid': None, 'roloff': None, 'flux': None, 'rmse': None, 'zcr': None, 'contrast': None, 'bandwidth': None, 'flatness': None} # Count silence if 0 < len(y): y_sound, _ = librosa.effects.trim(y, frame_length=n_fft, hop_length=hop_length) features['sample_silence'] = len(y) - len(y_sound) # Using librosa to calculate the features features['centroid'] = librosa.feature.spectral_centroid(y, sr=sr, n_fft=n_fft, hop_length=hop_length).ravel() features['roloff'] = librosa.feature.spectral_rolloff(y, sr=sr, n_fft=n_fft, hop_length=hop_length).ravel() features['zcr'] = librosa.feature.zero_crossing_rate(y, frame_length=n_fft, hop_length=hop_length).ravel() features['rmse'] = librosa.feature.rms(y, frame_length=n_fft, hop_length=hop_length).ravel() features['flux'] = librosa.onset.onset_strength(y=y, sr=sr).ravel() features['contrast'] = librosa.feature.spectral_contrast(y, sr=sr).ravel() features['bandwidth'] = librosa.feature.spectral_bandwidth(y, sr=sr, n_fft=n_fft, hop_length=hop_length).ravel() features['flatness'] = librosa.feature.spectral_flatness(y, n_fft=n_fft, hop_length=hop_length).ravel() # MFCC treatment mfcc = librosa.feature.mfcc(y, n_fft = n_fft, hop_length = hop_length, n_mfcc=13) for idx, v_mfcc in enumerate(mfcc): features['mfcc_{}'.format(idx)] = v_mfcc.ravel() # Get statistics from the vectors def get_moments(descriptors): result = {} for k, v in descriptors.items(): result['{}_max'.format(k)] = np.max(v) result['{}_min'.format(k)] = np.min(v) result['{}_mean'.format(k)] = np.mean(v) result['{}_std'.format(k)] = np.std(v) result['{}_kurtosis'.format(k)] = kurtosis(v) result['{}_skew'.format(k)] = skew(v) return result dict_agg_features = get_moments(features) dict_agg_features['tempo'] = librosa.beat.tempo(y, sr=sr)[0] return dict_agg_features def read_process_songs(src_dir, debug = True): # Empty array of dicts with the processed features from all files arr_features = [] # Read files from the folders for x,_ in genres.items(): folder = src_dir + x for root, subdirs, files in os.walk(folder): for file in files: # Read the audio file file_name = folder + "/" + file signal, sr = librosa.load(file_name) # Debug process if debug: print("Reading file: {}".format(file_name)) # Append the result to the data structure features = get_features(signal, sr) features['genre'] = genres[x] arr_features.append(features) return arr_features %%time # Get list of dicts with features and convert to dataframe features = read_process_songs(gtzan_dir, debug=False) df_features = pd.DataFrame(features) df_features.shape df_features.head() df_features.to_csv('../data/gtzan_features.csv', index=False) X = df_features.drop(['genre'], axis=1).values y = df_features['genre'].values """ Explanation: Hand-crafted features for GTZAN The goal of this notebook is to create several audio features descriptors for the GTZAN dataset, as proposed for many year as input for machine learning algorithms. We are going to use timbral texture based features and tempo based features for this. The main goal is to produce this features, classify and then compare with our proposed deep learning approach, using CNNs on the raw audio. End of explanation """ # Standartize the dataset scale = StandardScaler() x_scaled = scale.fit_transform(X) # Use PCA only for visualization pca = PCA(n_components=35, whiten=True) x_pca = pca.fit_transform(x_scaled) print("cumulative explained variance ratio = {:.4f}".format(np.sum(pca.explained_variance_ratio_))) # Use LDA only for visualization lda = LDA() x_lda = lda.fit_transform(x_scaled, y) # Using tsne tsne = TSNE(n_components=2, verbose=1, learning_rate=250) x_tsne = tsne.fit_transform(x_scaled) plt.figure(figsize=(18, 4)) plt.subplot(131) plt.scatter(x_pca[:,0], x_pca[:,1], c=y) plt.colorbar() plt.title("Embedded space with PCA") plt.subplot(132) plt.scatter(x_lda[:,0], x_lda[:,1], c=y) plt.colorbar() plt.title("Embedded space with LDA") plt.subplot(133) plt.scatter(x_tsne[:,0], x_tsne[:,1], c=y) plt.colorbar() plt.title("Embedded space with TSNE") plt.show() """ Explanation: Visualization Linear (and nonlinear) dimensionality reduction of the GTZAN features for visualization purposes End of explanation """ # Helper to plot confusion matrix -- from Scikit-learn website def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y) """ Explanation: Classical Machine Learning End of explanation """ params = { "cls__penalty": ["l1", "l2"], "cls__C": [0.5, 1, 2, 5], "cls__max_iter": [500] } pipe_lr = Pipeline([ ('scale', StandardScaler()), ('var_tresh', VarianceThreshold(threshold=(.8 * (1 - .8)))), ('feature_selection', SelectFromModel(lgbm.LGBMClassifier())), ('cls', LogisticRegression()) ]) grid_lr = GridSearchCV(pipe_lr, params, scoring='accuracy', n_jobs=6, cv=5) grid_lr.fit(X_train, y_train) preds = grid_lr.predict(X_test) print("best score on validation set (accuracy) = {:.4f}".format(grid_lr.best_score_)) print("best score on test set (accuracy) = {:.4f}".format(accuracy_score(y_test, preds))) """ Explanation: Logistic Regression End of explanation """ params = { "cls__loss": ['log'], "cls__penalty": ["elasticnet"], "cls__l1_ratio": [0.15, 0.25, 0.5, 0.75], } pipe_en = Pipeline([ ('scale', StandardScaler()), ('var_tresh', VarianceThreshold(threshold=(.8 * (1 - .8)))), ('feature_selection', SelectFromModel(lgbm.LGBMClassifier())), ('cls', SGDClassifier()) ]) grid_en = GridSearchCV(pipe_en, params, scoring='accuracy', n_jobs=6, cv=5) grid_en.fit(X_train, y_train) preds = grid_en.predict(X_test) print("best score on validation set (accuracy) = {:.4f}".format(grid_en.best_score_)) print("best score on test set (accuracy) = {:.4f}".format(accuracy_score(y_test, preds))) """ Explanation: ElasticNet End of explanation """ params = { "cls__criterion": ["gini", "entropy"], "cls__splitter": ["best", "random"], } pipe_cart = Pipeline([ ('var_tresh', VarianceThreshold(threshold=(.8 * (1 - .8)))), ('feature_selection', SelectFromModel(lgbm.LGBMClassifier())), ('cls', DecisionTreeClassifier()) ]) grid_cart = GridSearchCV(pipe_cart, params, scoring='accuracy', n_jobs=6, cv=5) grid_cart.fit(X_train, y_train) preds = grid_cart.predict(X_test) print("best score on validation set (accuracy) = {:.4f}".format(grid_cart.best_score_)) print("best score on test set (accuracy) = {:.4f}".format(accuracy_score(y_test, preds))) """ Explanation: Decision Tree End of explanation """ params = { "cls__n_estimators": [100, 250, 500, 1000], "cls__criterion": ["gini", "entropy"], "cls__max_depth": [5, 7, None] } pipe_rf = Pipeline([ ('var_tresh', VarianceThreshold(threshold=(.8 * (1 - .8)))), ('feature_selection', SelectFromModel(lgbm.LGBMClassifier())), ('cls', RandomForestClassifier()) ]) grid_rf = GridSearchCV(pipe_rf, params, scoring='accuracy', n_jobs=6, cv=5) grid_rf.fit(X_train, y_train) preds = grid_rf.predict(X_test) print("best score on validation set (accuracy) = {:.4f}".format(grid_rf.best_score_)) print("best score on test set (accuracy) = {:.4f}".format(accuracy_score(y_test, preds))) """ Explanation: Random Forest End of explanation """ params = { "cls__C": [0.5, 1, 2, 5], "cls__kernel": ['rbf', 'linear', 'sigmoid'], } pipe_svm = Pipeline([ ('scale', StandardScaler()), ('var_tresh', VarianceThreshold(threshold=(.8 * (1 - .8)))), ('feature_selection', SelectFromModel(lgbm.LGBMClassifier())), ('cls', SVC()) ]) grid_svm = GridSearchCV(pipe_svm, params, scoring='accuracy', n_jobs=6, cv=5) grid_svm.fit(X_train, y_train) preds = grid_svm.predict(X_test) print("best score on validation set (accuracy) = {:.4f}".format(grid_svm.best_score_)) print("best score on test set (accuracy) = {:.4f}".format(accuracy_score(y_test, preds))) """ Explanation: SVM End of explanation """ cm = confusion_matrix(y_test, preds) classes = ['metal', 'disco', 'classical', 'hiphop', 'jazz', 'country', 'pop', 'blues', 'reggae', 'rock'] plt.figure(figsize=(10,10)) plot_confusion_matrix(cm, classes, normalize=True) from sklearn.externals import joblib joblib.dump(grid_svm, "../models/pipe_svm.joblib") """ Explanation: Results and save the model End of explanation """
jahuth/convis
examples/Quickstart - Fitting models to data.ipynb
gpl-3.0
%matplotlib inline import numpy as np import matplotlib.pylab as plt import convis inp, out = convis.samples.generate_sample_data(input='random',size=(2000,20,20)) print(inp.shape) """ Explanation: First, you need to get your data in a certain format: - videos or stimuli can be time by x by y numpy arrays, or 1 by channel by time by x by y. - all sequences have to have the same sampling frequency (bin-length) - if you want to fit a spike train and you only have the spike times, you need to convert them into a time sequence For this example we get a sample pair of input and output (which is generated by a randomized LN model): End of explanation """ m = convis.models.LN(kernel_dim=(12,7,7),population=True) """ Explanation: Then, you need to choose a model, eg. an LN model as well. For the LN cascade models in Convis, you can set a parameter population depending on whether you have a single or multiple responses that you want to fit. If population is True, the model will output an image at the last stage, if population is False, it will only return a time series. Our sample output is an image with the same size as the input, so population should be True (which is also the default). We also choose the size of the kernel that is used for the convolution. End of explanation """ print(m.compute_loss(inp,out,dt=500)) """ Explanation: We can have a look at how well our model is doing right now by looking at the loss: End of explanation """ m.set_optimizer.Adam() """ Explanation: The default loss function is the sum of squared errors, but any loss function can be used by supplying it as an argument. Since we didn't fit the parameters so far, the loss will be pretty bad (around $10^7$). compute_loss returns the loss for each chunk that is computed separately. You can add them up or take the mean using np.sum or np.mean. Next, we will choose an optimizer. Which optimizer works best for you will depend on the complexity of you model and the data you supply. We recommend trying out different ones. In this example, we will choose the Adam optimizer. A list of all optimizers can be tab-completed in IPython and jupyter notebooks when typing m.set_optimizer. and then pressing TAB. End of explanation """ for i in range(50): m.optimize(inp,out,dt=500) """ Explanation: Then, we can optimize the model using our complete input, but separated into smaller chunks of length dt (to make sure everything fits into memory). Most optimization algorithms need to be run more than once since they only take small steps in the direction of the gradient. End of explanation """ print(m.compute_loss(inp,out,dt=500)) convis.plot_5d_matshow(m.p.conv.weight) plt.title('Filter after fitting 50x Adam') """ Explanation: We can examine the loss again after a few steps of fitting and also visualize the filters. convis.plot_5d_matshow can plot a 5 dimensional filter as a sequence of images. Since we created a filter spanning 12 frames, we see 10 little matrices, separated by a 1px border. End of explanation """ convis.plot_5d_matshow(convis.samples._g.conv.weight) plt.title('Random Ground Truth Filter') """ Explanation: The loss decreased, but not by much. To compare this result visually to the true kernel of the sample data generator we can cheat a little and look at its parameter: End of explanation """ m.set_optimizer.LBFGS() losses = m.optimize(inp,out,dt=500) print('losses during fitting:') print(losses) """ Explanation: Let's use a different algorithm to optimize our parameters. LBFGS is a pseudo-Newton method and will evaluate the model multiple times per step. We do not necessarily have to run it multiple times over the data ourselves and in some cases running this optimizer too often can deteriorate our solution again, as the small gradients close to the real solution lead to numerical instabilities. End of explanation """ print(m.compute_loss(inp,out,dt=500)) convis.plot_5d_matshow(m.p.conv.weight) plt.title('Filter after fitting with LBFGS') """ Explanation: Did we improve? End of explanation """ m.plot_impulse_space() convis.samples._g.plot_impulse_space() """ Explanation: We can see clearly now that the size of our fitted kernel does not match the sample generator, which makes sense, since we normally don't have access to a ground-truth at all. But our model just set the border pixels and the first two frames to 0. You can use impulse responses to quickly compare Models independent of their kernel sizes. (however, for more complex models this will not capture the complete model response): End of explanation """ m.save_parameters('fitted_model.npz') """ Explanation: Finally, you can save the parameters into a compressed numpy file. End of explanation """
turbomanage/training-data-analyst
courses/machine_learning/deepdive/05_artandscience/c_neuralnetwork.ipynb
apache-2.0
import math import shutil import numpy as np import pandas as pd import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) pd.options.display.max_rows = 10 pd.options.display.float_format = '{:.1f}'.format """ Explanation: Neural Network Learning Objectives: * Use the DNNRegressor class in TensorFlow to predict median housing price The data is based on 1990 census data from California. This data is at the city block level, so these features reflect the total number of rooms in that block, or the total number of people who live on that block, respectively. <p> Let's use a set of features to predict house value. ## Set Up In this first cell, we'll load the necessary libraries. End of explanation """ df = pd.read_csv("https://storage.googleapis.com/ml_universities/california_housing_train.csv", sep=",") """ Explanation: Next, we'll load our data set. End of explanation """ df.head() df.describe() """ Explanation: Examine the data It's a good idea to get to know your data a little bit before you work with it. We'll print out a quick summary of a few useful statistics on each column. This will include things like mean, standard deviation, max, min, and various quantiles. End of explanation """ df['num_rooms'] = df['total_rooms'] / df['households'] df['num_bedrooms'] = df['total_bedrooms'] / df['households'] df['persons_per_house'] = df['population'] / df['households'] df.describe() df.drop(['total_rooms', 'total_bedrooms', 'population', 'households'], axis = 1, inplace = True) df.describe() """ Explanation: This data is at the city block level, so these features reflect the total number of rooms in that block, or the total number of people who live on that block, respectively. Let's create a different, more appropriate feature. Because we are predicing the price of a single house, we should try to make all our features correspond to a single house as well End of explanation """ featcols = { colname : tf.feature_column.numeric_column(colname) \ for colname in 'housing_median_age,median_income,num_rooms,num_bedrooms,persons_per_house'.split(',') } # Bucketize lat, lon so it's not so high-res; California is mostly N-S, so more lats than lons featcols['longitude'] = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('longitude'), np.linspace(-124.3, -114.3, 5).tolist()) featcols['latitude'] = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('latitude'), np.linspace(32.5, 42, 10).tolist()) featcols.keys() # Split into train and eval msk = np.random.rand(len(df)) < 0.8 traindf = df[msk] evaldf = df[~msk] SCALE = 100000 BATCH_SIZE= 100 OUTDIR = './housing_trained' train_input_fn = tf.estimator.inputs.pandas_input_fn(x = traindf[list(featcols.keys())], y = traindf["median_house_value"] / SCALE, num_epochs = None, batch_size = BATCH_SIZE, shuffle = True) eval_input_fn = tf.estimator.inputs.pandas_input_fn(x = evaldf[list(featcols.keys())], y = evaldf["median_house_value"] / SCALE, # note the scaling num_epochs = 1, batch_size = len(evaldf), shuffle=False) # Linear Regressor def train_and_evaluate(output_dir, num_train_steps): myopt = tf.train.FtrlOptimizer(learning_rate = 0.01) # note the learning rate estimator = tf.estimator.LinearRegressor( model_dir = output_dir, feature_columns = featcols.values(), optimizer = myopt) #Add rmse evaluation metric def rmse(labels, predictions): pred_values = tf.cast(predictions['predictions'],tf.float64) return {'rmse': tf.metrics.root_mean_squared_error(labels*SCALE, pred_values*SCALE)} estimator = tf.contrib.estimator.add_metrics(estimator,rmse) train_spec=tf.estimator.TrainSpec( input_fn = train_input_fn, max_steps = num_train_steps) eval_spec=tf.estimator.EvalSpec( input_fn = eval_input_fn, steps = None, start_delay_secs = 1, # start evaluating after N seconds throttle_secs = 10, # evaluate every N seconds ) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) # Run training shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time train_and_evaluate(OUTDIR, num_train_steps = (100 * len(traindf)) / BATCH_SIZE) # DNN Regressor def train_and_evaluate(output_dir, num_train_steps): myopt = tf.train.FtrlOptimizer(learning_rate = 0.01) # note the learning rate estimator = tf.estimator.DNNRegressor(model_dir = output_dir, hidden_units = [100, 50, 20], feature_columns = featcols.values(), optimizer = myopt, dropout = 0.1) #Add rmse evaluation metric def rmse(labels, predictions): pred_values = tf.cast(predictions['predictions'],tf.float64) return {'rmse': tf.metrics.root_mean_squared_error(labels*SCALE, pred_values*SCALE)} estimator = tf.contrib.estimator.add_metrics(estimator,rmse) train_spec=tf.estimator.TrainSpec( input_fn = train_input_fn, max_steps = num_train_steps) eval_spec=tf.estimator.EvalSpec( input_fn = eval_input_fn, steps = None, start_delay_secs = 1, # start evaluating after N seconds throttle_secs = 10, # evaluate every N seconds ) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) # Run training shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file train_and_evaluate(OUTDIR, num_train_steps = (100 * len(traindf)) / BATCH_SIZE) """ Explanation: Build a neural network model In this exercise, we'll be trying to predict median_house_value. It will be our label (sometimes also called a target). We'll use the remaining columns as our input features. To train our model, we'll first use the LinearRegressor interface. Then, we'll change to DNNRegressor End of explanation """
dereneaton/RADmissing
emp_nb_Barnacles.ipynb
mit
### Notebook 8 ### Data set 8: Barnacles ### Authors: Herrera et al. 2015 ### Data Location: SRP051026 """ Explanation: Notebook 8: This is an IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This notebook includes code to download, assemble and analyze a published RADseq data set. End of explanation """ %%bash ## make a new directory for this analysis mkdir -p empirical_8/fastq/ """ Explanation: Download the sequence data Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contains all of the information we need to download the data. Project SRA: SRP051026 BioProject ID: PRJNA269631 SRA link: http://trace.ncbi.nlm.nih.gov/Traces/study/?acc=SRP051026 End of explanation """ ## IPython code import pandas as pd import numpy as np import urllib2 import os ## open the SRA run table from github url url = "https://raw.githubusercontent.com/"+\ "dereneaton/RADmissing/master/empirical_8_SraRunTable.txt" intable = urllib2.urlopen(url) indata = pd.read_table(intable, sep="\t") ## print first few rows print indata.head() def wget_download(SRR, outdir, outname): """ Python function to get sra data from ncbi and write to outdir with a new name using bash call wget """ ## get output name output = os.path.join(outdir, outname+".sra") ## create a call string call = "wget -q -r -nH --cut-dirs=9 -O "+output+" "+\ "ftp://ftp-trace.ncbi.nlm.nih.gov/"+\ "sra/sra-instant/reads/ByRun/sra/SRR/"+\ "{}/{}/{}.sra;".format(SRR[:6], SRR, SRR) ## call bash script ! $call """ Explanation: For each ERS (individuals) get all of the ERR (sequence file accessions). End of explanation """ for ID, SRR in zip(indata.Sample_Name_s, indata.Run_s): wget_download(SRR, "empirical_8/fastq/", ID) %%bash ## convert sra files to fastq using fastq-dump tool ## output as gzipped into the fastq directory fastq-dump --gzip -O empirical_8/fastq/ empirical_8/fastq/*.sra ## remove .sra files rm empirical_8/fastq/*.sra %%bash ls -lh empirical_8/fastq/ """ Explanation: Here we pass the SRR number and the sample name to the wget_download function so that the files are saved with their sample names. End of explanation """ %%bash pyrad --version %%bash ## remove old params file if it exists rm params.txt ## create a new default params file pyrad -n """ Explanation: Make a params file End of explanation """ %%bash ## substitute new parameters into file sed -i '/## 1. /c\empirical_8/ ## 1. working directory ' params.txt sed -i '/## 6. /c\TGCAGG ## 6. cutters ' params.txt sed -i '/## 7. /c\20 ## 7. N processors ' params.txt sed -i '/## 9. /c\6 ## 9. NQual ' params.txt sed -i '/## 10./c\.85 ## 10. clust threshold ' params.txt sed -i '/## 12./c\4 ## 12. MinCov ' params.txt sed -i '/## 13./c\10 ## 13. maxSH ' params.txt sed -i '/## 14./c\empirical_8_m4 ## 14. output name ' params.txt sed -i '/## 18./c\empirical_8/fastq/*.gz ## 18. data location ' params.txt sed -i '/## 29./c\2,2 ## 29. trim overhang ' params.txt sed -i '/## 30./c\p,n,s ## 30. output formats ' params.txt cat params.txt """ Explanation: Note: The data here are from Illumina Casava <1.8, so the phred scores are offset by 64 instead of 33, so we use that in the params file below. End of explanation """ %%bash pyrad -p params.txt -s 234567 >> log.txt 2>&1 %%bash sed -i '/## 12./c\2 ## 12. MinCov ' params.txt sed -i '/## 14./c\empirical_8_m2 ## 14. output name ' params.txt %%bash pyrad -p params.txt -s 7 >> log.txt 2>&1 """ Explanation: Assemble in pyrad End of explanation """ import pandas as pd ## read in the data s2dat = pd.read_table("empirical_8/stats/s2.rawedit.txt", header=0, nrows=42) ## print summary stats print s2dat["passed.total"].describe() ## find which sample has the most raw data maxraw = s2dat["passed.total"].max() print "\nmost raw data in sample:" print s2dat['sample '][s2dat['passed.total']==maxraw] """ Explanation: Results We are interested in the relationship between the amount of input (raw) data between any two samples, the average coverage they recover when clustered together, and the phylogenetic distances separating samples. Raw data amounts The average number of raw reads per sample is 1.36M. End of explanation """ ## read in the s3 results s8dat = pd.read_table("empirical_8/stats/s3.clusters.txt", header=0, nrows=14) ## print summary stats print "summary of means\n==================" print s8dat['dpt.me'].describe() ## print summary stats print "\nsummary of std\n==================" print s8dat['dpt.sd'].describe() ## print summary stats print "\nsummary of proportion lowdepth\n==================" print pd.Series(1-s8dat['d>5.tot']/s8dat["total"]).describe() ## find which sample has the greatest depth of retained loci max_hiprop = (s8dat["d>5.tot"]/s8dat["total"]).max() print "\nhighest coverage in sample:" print s8dat['taxa'][s8dat['d>5.tot']/s8dat["total"]==max_hiprop] maxprop =(s8dat['d>5.tot']/s8dat['total']).max() print "\nhighest prop coverage in sample:" print s8dat['taxa'][s8dat['d>5.tot']/s8dat['total']==maxprop] import numpy as np ## print mean and std of coverage for the highest coverage sample with open("empirical_8/clust.85/82121_15.depths", 'rb') as indat: depths = np.array(indat.read().strip().split(","), dtype=int) print "Means for sample 82121_15" print depths.mean(), depths.std() print depths[depths>5].mean(), depths[depths>5].std() """ Explanation: Look at distributions of coverage pyrad v.3.0.63 outputs depth information for each sample which I read in here and plot. First let's ask which sample has the highest depth of coverage. The std of coverages is pretty low in this data set compared to several others. End of explanation """ import toyplot import toyplot.svg import numpy as np ## read in the depth information for this sample with open("empirical_8/clust.85/82121_15.depths", 'rb') as indat: depths = np.array(indat.read().strip().split(","), dtype=int) ## make a barplot in Toyplot canvas = toyplot.Canvas(width=350, height=300) axes = canvas.axes(xlabel="Depth of coverage (N reads)", ylabel="N loci", label="dataset8/sample=82121_15") ## select the loci with depth > 5 (kept) keeps = depths[depths>5] ## plot kept and discarded loci edat = np.histogram(depths, range(30)) # density=True) kdat = np.histogram(keeps, range(30)) #, density=True) axes.bars(edat) axes.bars(kdat) #toyplot.svg.render(canvas, "empirical_8_depthplot.svg") """ Explanation: Plot the coverage for the sample with highest mean coverage Green shows the loci that were discarded and orange the loci that were retained. The majority of data were discarded for being too low of coverage. End of explanation """ cat empirical_8/stats/empirical_8_m4.stats cat empirical_8/stats/empirical_8_m2.stats """ Explanation: Print final stats table End of explanation """ %%bash ## raxml argumement w/ ... raxmlHPC-PTHREADS-AVX -f a -m GTRGAMMA -N 100 -x 12345 -p 12345 -T 20 \ -w /home/deren/Documents/RADmissing/empirical_8/ \ -n empirical_8_m4 -s empirical_8/outfiles/empirical_8_m4.phy %%bash ## raxml argumement w/ ... raxmlHPC-PTHREADS-AVX -f a -m GTRGAMMA -N 100 -x 12345 -p 12345 -T 20 \ -w /home/deren/Documents/RADmissing/empirical_8/ \ -n empirical_8_m2 -s empirical_8/outfiles/empirical_8_m2.phy %%bash head -n 20 empirical_8/RAxML_info.empirical_8 """ Explanation: Infer ML phylogeny in raxml as an unrooted tree End of explanation """ %load_ext rpy2.ipython %%R -h 800 -w 800 library(ape) tre <- read.tree("empirical_8/RAxML_bipartitions.empirical_8") ltre <- ladderize(tre) par(mfrow=c(1,2)) plot(ltre, use.edge.length=F) nodelabels(ltre$node.label) plot(ltre, type='u') """ Explanation: Plot the tree in R using ape End of explanation """ %%R mean(cophenetic.phylo(ltre)) """ Explanation: Get phylo distances (GTRgamma dist) End of explanation """
open2c/bioframe
docs/tutorials/tutorial_assign_motifs_to_peaks.ipynb
mit
import bioframe import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import pearsonr, spearmanr base_dir = '/tmp/bioframe_tutorial_data/' assembly = 'GRCh38' """ Explanation: How to: assign TF Motifs to ChIP-seq peaks This tutorial demonstrates one way to assign CTCF motifs to CTCF ChIP-seq peaks using bioframe. End of explanation """ ctcf_peaks = bioframe.read_table("https://www.encodeproject.org/files/ENCFF401MQL/@@download/ENCFF401MQL.bed.gz", schema='narrowPeak') ctcf_peaks[0:5] """ Explanation: Load CTCF ChIP-seq peaks for HFF from ENCODE This approach makes use of the narrowPeak schema for bioframe.read_table . End of explanation """ ### CTCF motif: http://jaspar.genereg.net/matrix/MA0139.1/ jaspar_url = 'http://expdata.cmmt.ubc.ca/JASPAR/downloads/UCSC_tracks/2022/hg38/' jaspar_motif_file = 'MA0139.1.tsv.gz' ctcf_motifs = bioframe.read_table(jaspar_url+jaspar_motif_file,schema='jaspar',skiprows=1) ctcf_motifs[0:4] """ Explanation: Get CTCF motifs from JASPAR End of explanation """ df_peaks_motifs = bioframe.overlap(ctcf_peaks,ctcf_motifs, suffixes=('_1','_2'), return_index=True) """ Explanation: Overlap peaks & motifs End of explanation """ # note that counting motifs per peak can also be handled directly with bioframe.count_overlaps # but since we re-use df_peaks_motifs below we instead use the pandas operations directly motifs_per_peak = df_peaks_motifs.groupby(["index_1"])["index_2"].count().values plt.hist(motifs_per_peak,np.arange(0,np.max(motifs_per_peak))) plt.xlabel('number of overlapping motifs per peak') plt.ylabel('number of peaks') plt.semilogy(); print(f'fraction of peaks without motifs {np.round(np.sum(motifs_per_peak==0)/len(motifs_per_peak),2)}') """ Explanation: There are often multiple motifs overlapping one ChIP-seq peak, and a substantial number of peaks without motifs: End of explanation """ # since idxmax does not currently take NA, fill with -1 df_peaks_motifs['pval_2'] = df_peaks_motifs['pval_2'].fillna(-1) idxmax_peaks_motifs = df_peaks_motifs.groupby(["chrom_1", "start_1","end_1"])["pval_2"].idxmax().values df_peaks_maxmotif = df_peaks_motifs.loc[idxmax_peaks_motifs] df_peaks_maxmotif['pval_2'].replace(-1,np.nan,inplace=True) """ Explanation: assign the strongest motif to each peak End of explanation """ plt.rcParams['font.size']=12 df_peaks_maxmotif['fc_1'] = df_peaks_maxmotif['fc_1'].values.astype('float') plt.scatter(df_peaks_maxmotif['fc_1'].values, df_peaks_maxmotif['pval_2'].values, 5, alpha=0.5,lw=0) plt.xlabel('ENCODE CTCF peak strength, fc') plt.ylabel('JASPAR CTCF motif strength \n (-log10 pval *100)') plt.title('corr: '+str(np.round(df_peaks_maxmotif['fc_1'].corr(df_peaks_maxmotif['pval_2']),2))); """ Explanation: stronger peaks tend to have stronger motifs: End of explanation """ df_motifs_peaks = bioframe.overlap(ctcf_motifs,ctcf_peaks,how='left', suffixes=('_1','_2')) m = df_motifs_peaks.sort_values('pval_1') plt.plot( m['pval_1'].values[::-1] , np.cumsum(pd.isnull(m['chrom_2'].values[::-1])==0)/np.arange(1,len(m)+1)) plt.xlabel('pval') plt.ylabel('probability motif overlaps a peak'); """ Explanation: We can also ask the reverse question: how many motifs overlap a ChIP-seq peak? End of explanation """ blacklist = bioframe.read_table('https://www.encodeproject.org/files/ENCFF356LFX/@@download/ENCFF356LFX.bed.gz', schema='bed3') blacklist[0:3] """ Explanation: filter peaks overlapping blacklisted regions do any of our peaks overlap blacklisted genomic regions? End of explanation """ closest_to_blacklist = bioframe.closest(ctcf_peaks,blacklist) plt.hist(closest_to_blacklist['distance'].astype('Float64').astype('float'),np.arange(0,1e4,100)); """ Explanation: there appears to be a small spike in the number of peaks close to blacklist regions End of explanation """ # first let's select the columns we want for our final dataframe of peaks with motifs df_peaks_maxmotif = df_peaks_maxmotif[ ['chrom_1','start_1','end_1','fc_1', 'chrom_2','start_2','end_2','pval_2','strand_2']] # then rename columns for convenience when subtracting for i in df_peaks_maxmotif.keys(): if '_1' in i: df_peaks_maxmotif.rename(columns={i:i.split('_')[0]},inplace=True) # now subtract, expanding the blacklist by 1kb df_peaks_maxmotif_clean = bioframe.subtract(df_peaks_maxmotif,bioframe.expand(blacklist,1000)) """ Explanation: to be safe, let's remove anything +/- 1kb from a blacklisted region End of explanation """ df_peaks_maxmotif_clean.iloc[7:15] """ Explanation: there it is! we now have a dataframe containing positions of CTCF ChIP peaks, including the strongest motif underlying that peak, and after conservative filtering for proximity to blacklisted regions End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/cmcc/cmip6/models/cmcc-esm2-hr5/aerosol.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-esm2-hr5', 'aerosol') """ Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-ESM2-HR5 Topic: Aerosol Sub-Topics: Transport, Emissions, Concentrations, Optical Radiative Properties, Model. Properties: 69 (37 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:50 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Key Properties --&gt; Timestep Framework 4. Key Properties --&gt; Meteorological Forcings 5. Key Properties --&gt; Resolution 6. Key Properties --&gt; Tuning Applied 7. Transport 8. Emissions 9. Concentrations 10. Optical Radiative Properties 11. Optical Radiative Properties --&gt; Absorption 12. Optical Radiative Properties --&gt; Mixtures 13. Optical Radiative Properties --&gt; Impact Of H2o 14. Optical Radiative Properties --&gt; Radiative Scheme 15. Optical Radiative Properties --&gt; Cloud Interactions 16. Model 1. Key Properties Key properties of the aerosol model 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of aerosol model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of aerosol model code End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.scheme_scope') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "troposhere" # "stratosphere" # "mesosphere" # "mesosphere" # "whole atmosphere" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Scheme Scope Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Atmospheric domains covered by the aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.basic_approximations') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basic approximations made in the aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.prognostic_variables_form') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "3D mass/volume ratio for aerosols" # "3D number concenttration for aerosols" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.5. Prognostic Variables Form Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Prognostic variables in the aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.number_of_tracers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 1.6. Number Of Tracers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of tracers in the aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.family_approach') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.7. Family Approach Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are aerosol calculations generalized into families of species? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Software Properties Software properties of aerosol code 2.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Uses atmospheric chemistry time stepping" # "Specific timestepping (operator splitting)" # "Specific timestepping (integrated)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestep Framework Physical properties of seawater in ocean 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Mathematical method deployed to solve the time evolution of the prognostic variables End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.split_operator_advection_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.2. Split Operator Advection Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for aerosol advection (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.split_operator_physical_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.3. Split Operator Physical Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for aerosol physics (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.integrated_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.4. Integrated Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the aerosol model (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.timestep_framework.integrated_scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Explicit" # "Implicit" # "Semi-implicit" # "Semi-analytic" # "Impact solver" # "Back Euler" # "Newton Raphson" # "Rosenbrock" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3.5. Integrated Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the type of timestep scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.meteorological_forcings.variables_3D') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Meteorological Forcings ** 4.1. Variables 3D Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Three dimensionsal forcing variables, e.g. U, V, W, T, Q, P, conventive mass flux End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.meteorological_forcings.variables_2D') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.2. Variables 2D Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Two dimensionsal forcing variables, e.g. land-sea mask definition End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.meteorological_forcings.frequency') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.3. Frequency Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Frequency with which meteological forcings are applied (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.resolution.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Resolution Resolution in the aersosol model grid 5.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.2. Canonical Horizontal Resolution Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.resolution.number_of_horizontal_gridpoints') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 5.3. Number Of Horizontal Gridpoints Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Total number of horizontal (XY) points (or degrees of freedom) on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 5.4. Number Of Vertical Levels Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Number of vertical levels resolved on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.resolution.is_adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.5. Is Adaptive Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Default is False. Set true if grid resolution changes during execution. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Key Properties --&gt; Tuning Applied Tuning methodology for aerosol model 6.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview description of tuning: explain and motivate the main targets and metrics retained. &amp;Document the relative weight given to climate performance metrics versus process oriented metrics, &amp;and on the possible conflicts with parameterization level tuning. In particular describe any struggle &amp;with a parameter value that required pushing it to its limits to solve a particular model deficiency. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics of the global mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics of mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.transport.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Transport Aerosol transport 7.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of transport in atmosperic aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.transport.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Uses Atmospheric chemistry transport scheme" # "Specific transport scheme (eulerian)" # "Specific transport scheme (semi-lagrangian)" # "Specific transport scheme (eulerian and semi-lagrangian)" # "Specific transport scheme (lagrangian)" # TODO - please enter value(s) """ Explanation: 7.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for aerosol transport modeling End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.transport.mass_conservation_scheme') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Uses Atmospheric chemistry transport scheme" # "Mass adjustment" # "Concentrations positivity" # "Gradients monotonicity" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 7.3. Mass Conservation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Method used to ensure mass conservation. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.transport.convention') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Uses Atmospheric chemistry transport scheme" # "Convective fluxes connected to tracers" # "Vertical velocities connected to tracers" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 7.4. Convention Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Transport by convention End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Emissions Atmospheric aerosol emissions 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of emissions in atmosperic aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Prescribed (climatology)" # "Prescribed CMIP6" # "Prescribed above surface" # "Interactive" # "Interactive above surface" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.2. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Method used to define aerosol species (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Vegetation" # "Volcanos" # "Bare ground" # "Sea surface" # "Lightning" # "Fires" # "Aircraft" # "Anthropogenic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.3. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of the aerosol species are taken into account in the emissions scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.prescribed_climatology') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Interannual" # "Annual" # "Monthly" # "Daily" # TODO - please enter value(s) """ Explanation: 8.4. Prescribed Climatology Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify the climatology type for aerosol emissions End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.5. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of aerosol species emitted and prescribed via a climatology End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.6. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of aerosol species emitted and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.7. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of aerosol species emitted and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.8. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of aerosol species emitted and specified via an &quot;other method&quot; End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.emissions.other_method_characteristics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.9. Other Method Characteristics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Characteristics of the &quot;other method&quot; used for aerosol emissions End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.concentrations.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Concentrations Atmospheric aerosol concentrations 9.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of concentrations in atmosperic aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.concentrations.prescribed_lower_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.2. Prescribed Lower Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the lower boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.concentrations.prescribed_upper_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.3. Prescribed Upper Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the upper boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.concentrations.prescribed_fields_mmr') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.4. Prescribed Fields Mmr Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed as mass mixing ratios. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.concentrations.prescribed_fields_mmr') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.5. Prescribed Fields Mmr Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed as AOD plus CCNs. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10. Optical Radiative Properties Aerosol optical and radiative properties 10.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of optical and radiative properties End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.absorption.black_carbon') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 11. Optical Radiative Properties --&gt; Absorption Absortion properties in aerosol scheme 11.1. Black Carbon Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Absorption mass coefficient of black carbon at 550nm (if non-absorbing enter 0) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.absorption.dust') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 11.2. Dust Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Absorption mass coefficient of dust at 550nm (if non-absorbing enter 0) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.absorption.organics') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 11.3. Organics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Absorption mass coefficient of organics at 550nm (if non-absorbing enter 0) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.mixtures.external') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 12. Optical Radiative Properties --&gt; Mixtures ** 12.1. External Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there external mixing with respect to chemical composition? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.mixtures.internal') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 12.2. Internal Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there internal mixing with respect to chemical composition? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.mixtures.mixing_rule') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.3. Mixing Rule Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If there is internal mixing with respect to chemical composition then indicate the mixinrg rule End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.impact_of_h2o.size') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13. Optical Radiative Properties --&gt; Impact Of H2o ** 13.1. Size Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does H2O impact size? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.impact_of_h2o.internal_mixture') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.2. Internal Mixture Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does H2O impact internal mixture? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.radiative_scheme.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14. Optical Radiative Properties --&gt; Radiative Scheme Radiative scheme for aerosol 14.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of radiative scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.radiative_scheme.shortwave_bands') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.2. Shortwave Bands Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of shortwave bands End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.radiative_scheme.longwave_bands') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.3. Longwave Bands Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of longwave bands End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Optical Radiative Properties --&gt; Cloud Interactions Aerosol-cloud interactions 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of aerosol-cloud interactions End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.twomey') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.2. Twomey Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the Twomey effect included? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.twomey_minimum_ccn') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.3. Twomey Minimum Ccn Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If the Twomey effect is included, then what is the minimum CCN number? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.drizzle') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.4. Drizzle Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the scheme affect drizzle? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.cloud_lifetime') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.5. Cloud Lifetime Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the scheme affect cloud lifetime? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.optical_radiative_properties.cloud_interactions.longwave_bands') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.6. Longwave Bands Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of longwave bands End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.model.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 16. Model Aerosol model 16.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmosperic aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.model.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Dry deposition" # "Sedimentation" # "Wet deposition (impaction scavenging)" # "Wet deposition (nucleation scavenging)" # "Coagulation" # "Oxidation (gas phase)" # "Oxidation (in cloud)" # "Condensation" # "Ageing" # "Advection (horizontal)" # "Advection (vertical)" # "Heterogeneous chemistry" # "Nucleation" # TODO - please enter value(s) """ Explanation: 16.2. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Processes included in the Aerosol model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.model.coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Radiation" # "Land surface" # "Heterogeneous chemistry" # "Clouds" # "Ocean" # "Cryosphere" # "Gas phase chemistry" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.3. Coupling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other model components coupled to the Aerosol model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.model.gas_phase_precursors') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "DMS" # "SO2" # "Ammonia" # "Iodine" # "Terpene" # "Isoprene" # "VOC" # "NOx" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.4. Gas Phase Precursors Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of gas phase aerosol precursors. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.model.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Bulk" # "Modal" # "Bin" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.5. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Type(s) of aerosol scheme used by the aerosols model (potentially multiple: some species may be covered by one type of aerosol scheme and other species covered by another type). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.aerosol.model.bulk_scheme_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Nitrate" # "Sea salt" # "Dust" # "Ice" # "Organic" # "Black carbon / soot" # "SOA (secondary organic aerosols)" # "POM (particulate organic matter)" # "Polar stratospheric ice" # "NAT (Nitric acid trihydrate)" # "NAD (Nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particule)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.6. Bulk Scheme Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of species covered by the bulk scheme. End of explanation """
Naereen/notebooks
A tiny regex challenge solved without another regex.ipynb
mit
import sys print(sys.version) from typing import List, Tuple Position = int Interval = Tuple[Position, Position] """ Explanation: A tiny regex challenge solved without another regex This notebook presents a small challenge a friend of mine asked me (in Python). I'll write Python code valid for versions $\geq$ 3.6, and to show of I use the typing module to have type hints. End of explanation """ import re def bad_events(pattern: str, string: str) -> List[Interval]: # m.span(1) = (m.start(1), m.end(1)) return [m.span(1) for m in re.finditer(f"(?=({pattern}))", string)] pat = "aca" strng = "acacavcacabacacbbacacazdbacaca" # Do you know if there is a regex trick to obtain # [(0, 5), (7, 10), (11, 14), (17, 22), (25, 30)] # instead of bad_events(pat, strng) # [(0, 3), (2, 5), (7, 10), (11, 14), (17, 20), (19, 22), (25, 28), (27, 30)] # ? """ Explanation: Introduction: the problem a friend of mine asked me End of explanation """ def are_not_disjoint(interval1: Interval, interval2: Interval) -> bool: x1, y1 = interval1 assert x1 <= y1, f"Error: interval = {intervals1} is not a valid interval." x2, y2 = interval2 assert x2 <= y2, f"Error: interval = {intervals2} is not a valid interval." if x1 <= x2 <= y1 <= y2: # interval1 finishes in interval2 return True elif x2 <= x1 <= y2 <= y1: # interval2 finishes in interval1 return True elif x1 <= x2 <= y2 <= y1: # interval2 is included in interval1 return True elif x2 <= x1 <= y1 <= y2: # interval1 is included in interval2 return True return False assert are_not_disjoint((0, 3), (2, 5)) # True assert not are_not_disjoint((0, 5), (7, 10)) # False """ Explanation: The solution I came up with Let's write a simple function that will read this list of intervals, and compress the ones that are not disjoint. For instance, when reading [(0, 3), (2, 5)], the second interval is not disjoint from the first one, so both can be compressed to (0, 5), which is disjoint from the next one (7, 10). Let's test (in constant time wrt $n$ number of intervals) if two consecutive intervals are disjoint or not: End of explanation """ def union_intervals(interval1: Interval, interval2: Interval) -> bool: x1, y1 = interval1 assert x1 <= y1, f"Error: interval = {intervals1} is not a valid interval." x2, y2 = interval2 assert x2 <= y2, f"Error: interval = {intervals2} is not a valid interval." return (min(x1, x2), max(y1, y2)) union_intervals((0, 3), (2, 5)) """ Explanation: Let's compute the union of two consecutive intervals, if they are not disjoint: (again in constant time) End of explanation """ def compress_intervals(intervals: List[Interval]) -> List[Interval]: intervals_after_compression: List[Interval] = [] n = len(intervals) assert n > 0 current_interval = intervals[0] # eg (0, 3) i = 1 # as long as we can read another interval in the list while i < n: # ==> O(n) as the inside of the loop is O(1) next_interval = intervals[i] # eg (2, 5) if are_not_disjoint(current_interval, next_interval): # eg (0, 3) and (2, 5) -> (0, 5) current_interval = union_intervals(current_interval, next_interval) else: # eg (0, 5) and (7, 10) -> (0, 5) is added, intervals_after_compression.append(current_interval) # and current_interval = next_interval = (7, 10) current_interval = next_interval i += 1 # we add the last current interval if it was not yet added if current_interval not in intervals_after_compression: intervals_after_compression.append(current_interval) return intervals_after_compression """ Explanation: And now we are reading to compress the list of intervals (in linear time): End of explanation """ # Do you know if there is a regex trick to obtain # [(0, 5), (7, 10), (11, 14), (17, 22), (25, 30)] # instead of intervals = bad_events(pat, strng) print(intervals) # [(0, 3), (2, 5), (7, 10), (11, 14), (17, 20), (19, 22), (25, 28), (27, 30)] # ? compress_intervals(intervals) """ Explanation: Example: End of explanation """ def bad_events_compressed(pat: str, strng: str) -> List[Interval]: intervals1 = bad_events(pat, strng) intervals2 = compress_intervals(intervals1) return intervals2 def test(pat: str, strng: str) -> None: print(f"For pattern {pat} and string {strng}, the bad events uncompressed are:\n{bad_events(pat, strng)}\nand the bad events compressed are:\n{bad_events_compressed(pat, strng)}") test(pat, strng) """ Explanation: So now we can write the requested function: End of explanation """ test("acab", "acabacabacabacacavcacabacacbbacacazdbacacaacacavcacabacacbbacacazdbacacaacabacab") test("merci", "mercimerciderienmercimerki") """ Explanation: Other examples End of explanation """
bashtage/statsmodels
examples/notebooks/markov_autoregression.ipynb
bsd-3-clause
%matplotlib inline from datetime import datetime from io import BytesIO import matplotlib.pyplot as plt import numpy as np import pandas as pd import requests import statsmodels.api as sm # NBER recessions from pandas_datareader.data import DataReader usrec = DataReader( "USREC", "fred", start=datetime(1947, 1, 1), end=datetime(2013, 4, 1) ) """ Explanation: Markov switching autoregression models This notebook provides an example of the use of Markov switching models in statsmodels to replicate a number of results presented in Kim and Nelson (1999). It applies the Hamilton (1989) filter the Kim (1994) smoother. This is tested against the Markov-switching models from E-views 8, which can be found at http://www.eviews.com/EViews8/ev8ecswitch_n.html#MarkovAR or the Markov-switching models of Stata 14 which can be found at http://www.stata.com/manuals14/tsmswitch.pdf. End of explanation """ # Get the RGNP data to replicate Hamilton dta = pd.read_stata("https://www.stata-press.com/data/r14/rgnp.dta").iloc[1:] dta.index = pd.DatetimeIndex(dta.date, freq="QS") dta_hamilton = dta.rgnp # Plot the data dta_hamilton.plot(title="Growth rate of Real GNP", figsize=(12, 3)) # Fit the model mod_hamilton = sm.tsa.MarkovAutoregression( dta_hamilton, k_regimes=2, order=4, switching_ar=False ) res_hamilton = mod_hamilton.fit() res_hamilton.summary() """ Explanation: Hamilton (1989) switching model of GNP This replicates Hamilton's (1989) seminal paper introducing Markov-switching models. The model is an autoregressive model of order 4 in which the mean of the process switches between two regimes. It can be written: $$ y_t = \mu_{S_t} + \phi_1 (y_{t-1} - \mu_{S_{t-1}}) + \phi_2 (y_{t-2} - \mu_{S_{t-2}}) + \phi_3 (y_{t-3} - \mu_{S_{t-3}}) + \phi_4 (y_{t-4} - \mu_{S_{t-4}}) + \varepsilon_t $$ Each period, the regime transitions according to the following matrix of transition probabilities: $$ P(S_t = s_t | S_{t-1} = s_{t-1}) = \begin{bmatrix} p_{00} & p_{10} \ p_{01} & p_{11} \end{bmatrix} $$ where $p_{ij}$ is the probability of transitioning from regime $i$, to regime $j$. The model class is MarkovAutoregression in the time-series part of statsmodels. In order to create the model, we must specify the number of regimes with k_regimes=2, and the order of the autoregression with order=4. The default model also includes switching autoregressive coefficients, so here we also need to specify switching_ar=False to avoid that. After creation, the model is fit via maximum likelihood estimation. Under the hood, good starting parameters are found using a number of steps of the expectation maximization (EM) algorithm, and a quasi-Newton (BFGS) algorithm is applied to quickly find the maximum. End of explanation """ fig, axes = plt.subplots(2, figsize=(7, 7)) ax = axes[0] ax.plot(res_hamilton.filtered_marginal_probabilities[0]) ax.fill_between(usrec.index, 0, 1, where=usrec["USREC"].values, color="k", alpha=0.1) ax.set_xlim(dta_hamilton.index[4], dta_hamilton.index[-1]) ax.set(title="Filtered probability of recession") ax = axes[1] ax.plot(res_hamilton.smoothed_marginal_probabilities[0]) ax.fill_between(usrec.index, 0, 1, where=usrec["USREC"].values, color="k", alpha=0.1) ax.set_xlim(dta_hamilton.index[4], dta_hamilton.index[-1]) ax.set(title="Smoothed probability of recession") fig.tight_layout() """ Explanation: We plot the filtered and smoothed probabilities of a recession. Filtered refers to an estimate of the probability at time $t$ based on data up to and including time $t$ (but excluding time $t+1, ..., T$). Smoothed refers to an estimate of the probability at time $t$ using all the data in the sample. For reference, the shaded periods represent the NBER recessions. End of explanation """ print(res_hamilton.expected_durations) """ Explanation: From the estimated transition matrix we can calculate the expected duration of a recession versus an expansion. End of explanation """ # Get the dataset ew_excs = requests.get("http://econ.korea.ac.kr/~cjkim/MARKOV/data/ew_excs.prn").content raw = pd.read_table(BytesIO(ew_excs), header=None, skipfooter=1, engine="python") raw.index = pd.date_range("1926-01-01", "1995-12-01", freq="MS") dta_kns = raw.loc[:"1986"] - raw.loc[:"1986"].mean() # Plot the dataset dta_kns[0].plot(title="Excess returns", figsize=(12, 3)) # Fit the model mod_kns = sm.tsa.MarkovRegression( dta_kns, k_regimes=3, trend="n", switching_variance=True ) res_kns = mod_kns.fit() res_kns.summary() """ Explanation: In this case, it is expected that a recession will last about one year (4 quarters) and an expansion about two and a half years. Kim, Nelson, and Startz (1998) Three-state Variance Switching This model demonstrates estimation with regime heteroskedasticity (switching of variances) and no mean effect. The dataset can be reached at http://econ.korea.ac.kr/~cjkim/MARKOV/data/ew_excs.prn. The model in question is: $$ \begin{align} y_t & = \varepsilon_t \ \varepsilon_t & \sim N(0, \sigma_{S_t}^2) \end{align} $$ Since there is no autoregressive component, this model can be fit using the MarkovRegression class. Since there is no mean effect, we specify trend='n'. There are hypothesized to be three regimes for the switching variances, so we specify k_regimes=3 and switching_variance=True (by default, the variance is assumed to be the same across regimes). End of explanation """ fig, axes = plt.subplots(3, figsize=(10, 7)) ax = axes[0] ax.plot(res_kns.smoothed_marginal_probabilities[0]) ax.set(title="Smoothed probability of a low-variance regime for stock returns") ax = axes[1] ax.plot(res_kns.smoothed_marginal_probabilities[1]) ax.set(title="Smoothed probability of a medium-variance regime for stock returns") ax = axes[2] ax.plot(res_kns.smoothed_marginal_probabilities[2]) ax.set(title="Smoothed probability of a high-variance regime for stock returns") fig.tight_layout() """ Explanation: Below we plot the probabilities of being in each of the regimes; only in a few periods is a high-variance regime probable. End of explanation """ # Get the dataset filardo = requests.get("http://econ.korea.ac.kr/~cjkim/MARKOV/data/filardo.prn").content dta_filardo = pd.read_table( BytesIO(filardo), sep=" +", header=None, skipfooter=1, engine="python" ) dta_filardo.columns = ["month", "ip", "leading"] dta_filardo.index = pd.date_range("1948-01-01", "1991-04-01", freq="MS") dta_filardo["dlip"] = np.log(dta_filardo["ip"]).diff() * 100 # Deflated pre-1960 observations by ratio of std. devs. # See hmt_tvp.opt or Filardo (1994) p. 302 std_ratio = ( dta_filardo["dlip"]["1960-01-01":].std() / dta_filardo["dlip"][:"1959-12-01"].std() ) dta_filardo["dlip"][:"1959-12-01"] = dta_filardo["dlip"][:"1959-12-01"] * std_ratio dta_filardo["dlleading"] = np.log(dta_filardo["leading"]).diff() * 100 dta_filardo["dmdlleading"] = dta_filardo["dlleading"] - dta_filardo["dlleading"].mean() # Plot the data dta_filardo["dlip"].plot( title="Standardized growth rate of industrial production", figsize=(13, 3) ) plt.figure() dta_filardo["dmdlleading"].plot(title="Leading indicator", figsize=(13, 3)) """ Explanation: Filardo (1994) Time-Varying Transition Probabilities This model demonstrates estimation with time-varying transition probabilities. The dataset can be reached at http://econ.korea.ac.kr/~cjkim/MARKOV/data/filardo.prn. In the above models we have assumed that the transition probabilities are constant across time. Here we allow the probabilities to change with the state of the economy. Otherwise, the model is the same Markov autoregression of Hamilton (1989). Each period, the regime now transitions according to the following matrix of time-varying transition probabilities: $$ P(S_t = s_t | S_{t-1} = s_{t-1}) = \begin{bmatrix} p_{00,t} & p_{10,t} \ p_{01,t} & p_{11,t} \end{bmatrix} $$ where $p_{ij,t}$ is the probability of transitioning from regime $i$, to regime $j$ in period $t$, and is defined to be: $$ p_{ij,t} = \frac{\exp{ x_{t-1}' \beta_{ij} }}{1 + \exp{ x_{t-1}' \beta_{ij} }} $$ Instead of estimating the transition probabilities as part of maximum likelihood, the regression coefficients $\beta_{ij}$ are estimated. These coefficients relate the transition probabilities to a vector of pre-determined or exogenous regressors $x_{t-1}$. End of explanation """ mod_filardo = sm.tsa.MarkovAutoregression( dta_filardo.iloc[2:]["dlip"], k_regimes=2, order=4, switching_ar=False, exog_tvtp=sm.add_constant(dta_filardo.iloc[1:-1]["dmdlleading"]), ) np.random.seed(12345) res_filardo = mod_filardo.fit(search_reps=20) res_filardo.summary() """ Explanation: The time-varying transition probabilities are specified by the exog_tvtp parameter. Here we demonstrate another feature of model fitting - the use of a random search for MLE starting parameters. Because Markov switching models are often characterized by many local maxima of the likelihood function, performing an initial optimization step can be helpful to find the best parameters. Below, we specify that 20 random perturbations from the starting parameter vector are examined and the best one used as the actual starting parameters. Because of the random nature of the search, we seed the random number generator beforehand to allow replication of the result. End of explanation """ fig, ax = plt.subplots(figsize=(12, 3)) ax.plot(res_filardo.smoothed_marginal_probabilities[0]) ax.fill_between(usrec.index, 0, 1, where=usrec["USREC"].values, color="gray", alpha=0.2) ax.set_xlim(dta_filardo.index[6], dta_filardo.index[-1]) ax.set(title="Smoothed probability of a low-production state") """ Explanation: Below we plot the smoothed probability of the economy operating in a low-production state, and again include the NBER recessions for comparison. End of explanation """ res_filardo.expected_durations[0].plot( title="Expected duration of a low-production state", figsize=(12, 3) ) """ Explanation: Using the time-varying transition probabilities, we can see how the expected duration of a low-production state changes over time: End of explanation """
bmorris3/gsoc2015
timezones.ipynb
mit
from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.time import Time import astropy.units as u from astropy.coordinates import EarthLocation import pytz import datetime from astroplan import Observer # Set up an observer at ~Subaru location = EarthLocation.from_geodetic(-155.4*u.deg, 19.8*u.deg) obs = Observer(location=location, timezone=pytz.timezone('US/Hawaii')) # Pick a local (Hawaii) time to observe: midnight local_naive_datetime = datetime.datetime(2015, 7, 14, 0) # What is the astropy.time.Time equivalent for this datetime? astropy_time = obs.datetime_to_astropy_time(local_naive_datetime) print('astropy.time.Time (UTC):', astropy_time) """ Explanation: Time zones 🌐! This is a demo of some convenience methods for manipulating timezones with the Observer class. The two methods are: self.datetime_to_astropy_time(datetime) which converts a naive or timezone-aware datetime to an astropy.time.Time object. If the input datetime is naive, it assumes that the implied timezone is the one saved in the instance of Observer (in self.timezone). self.astropy_time_to_datetime(astropy_time) which converts an astropy.time.Time object into a localized datetime, in the timezone saved in the instance of Observer (in self.timezone). End of explanation """ localized_datetime = obs.astropy_time_to_datetime(astropy_time) print('datetime:', localized_datetime) print('new datetime equivalent to original naive datetime?:', local_naive_datetime == localized_datetime.replace(tzinfo=None)) """ Explanation: Convert that astropy.time.Time back to a localized datetime, arriving back at the original datetime (only this one is localized): End of explanation """ east_coast_datetime = pytz.timezone('US/Eastern').localize(datetime.datetime(2015, 7, 14, 6)) east_coast_astropy_time = obs.datetime_to_astropy_time(east_coast_datetime) print('Convert local East Coast time to UTC:', east_coast_astropy_time) print('Equivalent to original astropy time?:', east_coast_astropy_time == astropy_time) """ Explanation: Let's say the Subaru observer is remotely observing from the East Coast. Let's convert their local time (Eastern) to an astropy time. Since this datetime is localized, datetime_to_astropy_time will use the datetime's timezone (rather than assuming self.timezone): End of explanation """ tzinfo_kwarg = datetime.datetime(2015, 7, 14, 6, tzinfo=pytz.timezone('US/Eastern')) localized = pytz.timezone('US/Eastern').localize(datetime.datetime(2015, 7, 14, 6)) print('with tz assigned in kwarg:', tzinfo_kwarg) print('with localization by tz.localize(dt):', localized) """ Explanation: Warning How you construct your localized timezone is important! Don't initialize datetimes with the tzinfo kwarg. Here's an example of when it doesn't work. These two times should be equal, but are not. See pytz documentation for discussion. End of explanation """
tsarouch/data_science_references_python
core/regression_business-questions.ipynb
gpl-2.0
from sklearn.datasets import load_boston boston = load_boston() # features df = pd.DataFrame(boston.data) df.columns = boston.feature_names # dependent variable df['PRICE'] = boston.target df.head(3) """ Explanation: Get Data End of explanation """ # Lets use only one feature df1 = df[['LSTAT', 'PRICE']] X = df1['LSTAT'] y = df1['PRICE'] sns.jointplot(x="LSTAT", y="PRICE", data=df, kind="reg", size=4); import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score, explained_variance_score lr = LinearRegression() lr.fit(X.to_frame(), y.to_frame()) # check that the coeffients are the expected ones. b1 = lr.coef_[0] b0 = lr.intercept_ print "b0: ", b0 print "b1: ", b1 y_pred = lr.predict(X.to_frame()) print "Mean squared error: ", mean_squared_error(y, y_pred) print 'R^2 score : ', r2_score(y, y_pred) print 'Explained variance score (in simple regression = R^2): ', explained_variance_score(y, y_pred) # correlation from scipy.stats import pearsonr print "pearson correlation: ", pearsonr(X, y) # p-values # scikit-learn's LinearRegression doesn't calculate this information. # we can take a look at statsmodels for this kind of statistical analysis in Python. from scipy import stats slope, intercept, r_value, p_value, std_err = stats.linregress(df["LSTAT"], df["PRICE"]) print "slope: ", slope print "intercept: ", intercept print "R^2: ", r_value * r_value print "Standard Error: ", std_err print "p-value ", p_value """ Explanation: Simple Linear Regression We use only one variable (here we choose lstat) as feature and we want to predict price. - is there a relationship between price and lstat feature? - how strong is the relationship? - how accurately can we predict price based on lstat feature? - is the relationship linear? End of explanation """ # Lets use only one feature X = df[['LSTAT', 'AGE', 'INDUS']] y = df['PRICE'] """ Explanation: is there a relationship between price and lstat feature ? In simple linear regression setting, we can simply check whether β1 =0 or not. Here β1 =-0.95 != 0 so there is a relationship between price and lstat. Accordingly, the p-value (associated with the t-statistic) is << 1 so the alternative hypothesis is correct => there is some relationshop between lstat and price how strong is the relationship? This can be answered saying that, given a cerntain X, can we predict y with a a high level of accuracy? Or the prediction is slightly better than a random guess? The quantity to help us here is R^2 statistic. R^2 measures the proportion of the variability of y that can be explained using X. Also R^2, in simple linear regression, is equal to r^2 = squared correlation, a measure of the linear relationship between X and y. Hear R^2 = 0.5 so it is a relatively good value R^2ε[0,1]. It is challenging though to determine what is good R^2. It depends on the application. how accurately can we predict price (based on lstat feature) ? => use prediction interval: if we want to predict individual response<br> => use confidence interval: if we want to predict the average response. is the relationship linear? The reply can come by plotting the residuals. If the relationship is linear then the residuals should not show any pattern. Multiple Linear Regression We use few variables (here we choose lstat, age, and indus) as features and we want to predict price. - is at least one of the predictors useful in predicting the price? - which predictors help predicting price? All or a subset of them helping? - how well does the model fit the data ? - given a set of predictor values, what response value should we predict and what is our efficiency of prediction ? End of explanation """
strandbygaard/deep-learning
image-classification/dlnd_image_classification.ipynb
mit
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifar10_location = '/input/cifar-10/python.tar.gz' if isfile(floyd_cifar10_location): tar_gz_path = floyd_cifar10_location else: tar_gz_path = 'cifar-10-python.tar.gz' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(tar_gz_path): with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar: urlretrieve( 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', tar_gz_path, pbar.hook) if not isdir(cifar10_dataset_folder_path): with tarfile.open(tar_gz_path) as tar: tar.extractall() tar.close() tests.test_folder_path(cifar10_dataset_folder_path) """ Explanation: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images. Get the Data Run the following cell to download the CIFAR-10 dataset for python. End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 5 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) """ Explanation: Explore the Data The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following: * airplane * automobile * bird * cat * deer * dog * frog * horse * ship * truck Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch. Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions. End of explanation """ def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ norm = np.array (x / x.max()) return norm #norm=np.linalg.norm(x) #if norm==0: # return x #return x/norm """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_normalize(normalize) """ Explanation: Implement Preprocess Functions Normalize In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. End of explanation """ from sklearn import preprocessing one_hot_classes = None def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ global one_hot_classes # TODO: Implement Function return preprocessing.label_binarize(x,classes=[0,1,2,3,4,5,6,7,8,9]) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_one_hot_encode(one_hot_encode) """ Explanation: One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function. Hint: Don't reinvent the wheel. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode) """ Explanation: Randomize Data As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save it Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation. End of explanation """ stddev=0.05 """ DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb')) """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function x=tf.placeholder(tf.float32,(None, image_shape[0], image_shape[1], image_shape[2]), name='x') return x def neural_net_label_input(n_classes): """ Return a Tensor for a batch of label input : n_classes: Number of classes : return: Tensor for label input. """ # TODO: Implement Function return tf.placeholder(tf.float32, (None, n_classes), name='y') def neural_net_keep_prob_input(): """ Return a Tensor for keep probability : return: Tensor for keep probability. """ # TODO: Implement Function return tf.placeholder(tf.float32,name='keep_prob') """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tf.reset_default_graph() tests.test_nn_image_inputs(neural_net_image_input) tests.test_nn_label_inputs(neural_net_label_input) tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input) """ Explanation: Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project. Note: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the "Convolutional and Max Pooling Layer" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup. However, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d. Let's begin! Input The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions * Implement neural_net_image_input * Return a TF Placeholder * Set the shape using image_shape with batch size set to None. * Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_label_input * Return a TF Placeholder * Set the shape using n_classes with batch size set to None. * Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_keep_prob_input * Return a TF Placeholder for dropout keep probability. * Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder. These names will be used at the end of the project to load your saved model. Note: None for shapes in TensorFlow allow for a dynamic size. End of explanation """ import math def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple for the convolutional layer :param conv_strides: Stride 2-D Tuple for convolution :param pool_ksize: kernal size 2-D Tuple for pool :param pool_strides: Stride 2-D Tuple for pool : return: A tensor that represents convolution and max pooling of x_tensor """ # TODO: Implement Function height = math.ceil((float(x_tensor.shape[1].value - conv_ksize[0] + 1))/float((conv_strides[0]))) width = math.ceil(float((x_tensor.shape[2].value - conv_ksize[1] + 1))/float((conv_strides[1]))) #height = math.ceil((float(x_tensor.shape[1].value - conv_ksize[0] + 2))/float((conv_strides[0] + 1))) #width = math.ceil(float((x_tensor.shape[2].value - conv_ksize[1] + 2))/float((conv_strides[1] + 1))) weight = tf.Variable(tf.truncated_normal((height, width, x_tensor.shape[3].value, conv_num_outputs),stddev=stddev)) bias = tf.Variable(tf.zeros(conv_num_outputs)) conv_layer = tf.nn.conv2d(x_tensor, weight, strides=[1,conv_strides[0],conv_strides[1],1], padding='SAME') conv_layer = tf.nn.bias_add(conv_layer,bias) conv_layer = tf.nn.relu(conv_layer) maxpool_layer = tf.nn.max_pool(conv_layer, ksize=[1,pool_ksize[0],pool_ksize[1],1], strides=[1,pool_strides[0],pool_strides[1],1], padding='SAME') return maxpool_layer """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_con_pool(conv2d_maxpool) """ Explanation: Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor using weight and conv_strides. * We recommend you use same padding, but you're welcome to use any padding. * Add bias * Add a nonlinear activation to the convolution. * Apply Max Pooling using pool_ksize and pool_strides. * We recommend you use same padding, but you're welcome to use any padding. Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers. End of explanation """ def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ # TODO: Implement Function flattened = x_tensor.shape[1].value * x_tensor.shape[2].value * x_tensor.shape[3].value return tf.reshape(x_tensor, shape=(-1, flattened)) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_flatten(flatten) """ Explanation: Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function weights = tf.Variable(tf.truncated_normal([x_tensor.shape[1].value, num_outputs],stddev=stddev)) bias = tf.Variable(tf.zeros([num_outputs], dtype=tf.float32)) fc1 = tf.add(tf.matmul(x_tensor, weights), bias) out = tf.nn.relu(fc1) return out """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_fully_conn(fully_conn) """ Explanation: Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ weights = tf.Variable(tf.truncated_normal([x_tensor.shape[1].value, num_outputs],stddev=stddev)) bias = tf.Variable(tf.zeros([num_outputs], dtype=tf.float32)) return tf.add(tf.matmul(x_tensor, weights), bias) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_output(output) """ Explanation: Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. Note: Activation, softmax, or cross entropy should not be applied to this. End of explanation """ def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers # Play around with different number of outputs, kernel size and stride # Function Definition from Above: #def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): stddev=0.01 conv_strides = (2,2) # Getting out of mem errors with stride=1 pool_strides = (2,2) pool_ksize = (2,2) conv_num_outputs1 = 32 conv_ksize1 = (2,2) conv_num_outputs2 = 128 conv_ksize2 = (4,4) conv_num_outputs3 = 128 conv_ksize3 = (2,2) fully_conn_out1 = 1024 fully_conn_out2 = 512 fully_conn_out3 = 128 num_outputs = 10 x = conv2d_maxpool(x, conv_num_outputs1, conv_ksize1, conv_strides, pool_ksize, pool_strides) #x = tf.nn.dropout(x, keep_prob) x = conv2d_maxpool(x, conv_num_outputs2, conv_ksize2, conv_strides, pool_ksize, pool_strides) x = tf.nn.dropout(x, keep_prob) #x = conv2d_maxpool(x, conv_num_outputs3, conv_ksize3, conv_strides, pool_ksize, pool_strides) # TODO: Apply a Flatten Layer # Function Definition from Above: x = flatten(x) # TODO: Apply 1, 2, or 3 Fully Connected Layers # Play around with different number of outputs # Function Definition from Above: x = fully_conn(x,fully_conn_out1) x = tf.nn.dropout(x, keep_prob) x = fully_conn(x,fully_conn_out2) #x = tf.nn.dropout(x, keep_prob) #x = fully_conn(x,fully_conn_out3) # TODO: Apply an Output Layer # Set this to the number of classes # Function Definition from Above: x = output(x, num_outputs) return x """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ ############################## ## Build the Neural Network ## ############################## # Remove previous weights, bias, inputs, etc.. tf.reset_default_graph() # Inputs x = neural_net_image_input((32, 32, 3)) y = neural_net_label_input(10) keep_prob = neural_net_keep_prob_input() # Model logits = conv_net(x, keep_prob) # Name logits Tensor, so that is can be loaded from disk after training logits = tf.identity(logits, name='logits') # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') tests.test_conv_net(conv_net) """ Explanation: Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Fully Connected Layers Apply an Output Layer Return the output Apply TensorFlow's Dropout to one or more layers in the model using keep_prob. End of explanation """ def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data """ session.run(optimizer, feed_dict={ x: feature_batch, y: label_batch, keep_prob: keep_probability}) pass """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_train_nn(train_neural_network) """ Explanation: Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be called for each batch, so tf.global_variables_initializer() has already been called. Note: Nothing needs to be returned. This function is only optimizing the neural network. End of explanation """ def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy: TensorFlow accuracy function """ # TODO: Implement Function loss = session.run(cost, feed_dict={ x: feature_batch, y: label_batch, keep_prob: 1.}) valid_acc = sess.run(accuracy, feed_dict={ x: valid_features[:256], y: valid_labels[:256], keep_prob: 1.}) train_acc = session.run (accuracy, feed_dict = { x: feature_batch, y: label_batch, keep_prob: 1.}) print('Loss: {:>10.4f} Training: {:.6f} Validation: {:.6f}'.format( loss, train_acc, valid_acc)) pass """ Explanation: Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. End of explanation """ # TODO: Tune Parameters epochs = 100 batch_size = 1024 keep_probability = 0.4 """ Explanation: Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the probability of keeping a node using dropout End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): batch_i = 1 for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) """ Explanation: Train on a Single CIFAR-10 Batch Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batches = 5 for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) """ Explanation: Fully Train the Model Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_classification' n_samples = 4 top_n_predictions = 3 def test_model(): """ Test the saved model against the test dataset """ test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb')) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load model loader = tf.train.import_meta_graph(save_model_path + '.meta') loader.restore(sess, save_model_path) # Get Tensors from loaded model loaded_x = loaded_graph.get_tensor_by_name('x:0') loaded_y = loaded_graph.get_tensor_by_name('y:0') loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') loaded_logits = loaded_graph.get_tensor_by_name('logits:0') loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0') # Get accuracy in batches for memory limitations test_batch_acc_total = 0 test_batch_count = 0 for test_feature_batch, test_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size): test_batch_acc_total += sess.run( loaded_acc, feed_dict={loaded_x: test_feature_batch, loaded_y: test_label_batch, loaded_keep_prob: 1.0}) test_batch_count += 1 print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count)) # Print Random Samples random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples))) random_test_predictions = sess.run( tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions), feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0}) helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions) test_model() """ Explanation: Checkpoint The model has been saved to disk. Test Model Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters. End of explanation """
pyGrowler/Growler
examples/ExampleNotebook_1.ipynb
apache-2.0
import growler growler.__meta__.version_info """ Explanation: Growler Example in Jupyter End of explanation """ app = growler.App("NotebookServer") """ Explanation: Create growler application with name NotebookServer End of explanation """ @app.use def print_client_info(req, res): ip = req.ip reqpath = req.path print("[{ip}] {path}".format(ip=ip, path=reqpath)) print(" >", req.headers['USER-AGENT']) print(flush=True) """ Explanation: Add a general purpose method which prints ip address and the USER-AGENT header End of explanation """ i = 0 @app.get("/") def index(req, res): global i res.send_text("It Works! (%d)" % i) i += 1 """ Explanation: Next, add a route matching any GET requests for the root (/) of the site. This uses a simple global variable to count the number times this page has been accessed, and return text to the client End of explanation """ app.print_middleware_tree() """ Explanation: We can see the tree of middleware all requests will pass through - Notice the router object that was implicitly created which will match all requests. End of explanation """ app.create_server_and_run_forever(host='127.0.0.1', port=9000) """ Explanation: Use the helper method to create the asyncio server listening on port 9000. End of explanation """
grokkaine/biopycourse
day2/ML_DR.ipynb
cc0-1.0
%matplotlib inline """ Explanation: Dimension Reduction Feature selection Feature extraction PCA ICA FA Application: tSNE End of explanation """ from sklearn.svm import LinearSVC from sklearn.datasets import load_iris from sklearn.feature_selection import SelectFromModel iris = load_iris() X, y = iris.data, iris.target print(X.shape) # C controls the sparsity, try smaller for fewer features! lsvc = LinearSVC(C=0.01, penalty="l1", dual=False).fit(X, y) model = SelectFromModel(lsvc, prefit=True) X_new = model.transform(X) print(X_new.shape) """ Explanation: Feature selection Especially popular in SNP and gene expression studies, feature selection contains a miriad of choices for selecting variables of interest. The module sklearn.feature_selection contains several feature selection possibilities, such as univariate filter selection methods and the recursive feature elimination. Another class of feature selection, SelectFromModel is based on any estimator that can score features and order them by importance. Many sparse estimators such as Lasso, Logistic and Linear SVC can be used. End of explanation """ from sklearn.ensemble import ExtraTreesClassifier from sklearn.datasets import load_iris from sklearn.feature_selection import SelectFromModel iris = load_iris() X, y = iris.data, iris.target print(X.shape) clf = ExtraTreesClassifier() clf = clf.fit(X, y) print(clf.feature_importances_) model = SelectFromModel(clf, prefit=True) X_new = model.transform(X) print(X_new.shape) """ Explanation: Rather than zeroing out on features, tree based estimators would compute feature importance. End of explanation """ %matplotlib inline print(__doc__) import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_boston from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LassoCV # Load the boston dataset. boston = load_boston() X, y = boston['data'], boston['target'] # We use the base estimator LassoCV since the L1 norm promotes sparsity of features. clf = LassoCV() # Set a minimum threshold of 0.25 sfm = SelectFromModel(clf, threshold=0.25) sfm.fit(X, y) n_features = sfm.transform(X).shape[1] # Reset the threshold till the number of features equals two. # Note that the attribute can be set directly instead of repeatedly # fitting the metatransformer. while n_features > 2: sfm.threshold += 0.1 X_transform = sfm.transform(X) n_features = X_transform.shape[1] # Plot the selected two features from X. plt.title( "Features selected from Boston using SelectFromModel with " "threshold %0.3f." % sfm.threshold) feature1 = X_transform[:, 0] feature2 = X_transform[:, 1] plt.plot(feature1, feature2, 'r.') plt.xlabel("Feature number 1") plt.ylabel("Feature number 2") plt.ylim([np.min(feature2), np.max(feature2)]) plt.show() print(boston.keys()) print(boston['feature_names']) print(boston['DESCR']) """ Explanation: Task: Use the example below to fit a tree or a forest and compare results! (Tip: check the scikit learn documentation on feature selection) Evaluate your goodness of fit using the two feature selectors and compare! End of explanation """ %matplotlib inline import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition from sklearn import datasets np.random.seed(5) centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target print("Shape of Iris dataset", iris.data.shape) fig = plt.figure(1, figsize=(8, 6)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) #ax = Axes3D(fig, elev=-150, azim=110) # feature extraction plt.cla() pca = decomposition.PCA(n_components=3) pca.fit(X) X_reduced = pca.transform(X) # summarize components print("Explained Variance: ", pca.explained_variance_ratio_) print("Principal components", pca.components_) print("Shape of reduced dataset", X_reduced.shape) for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X_reduced[y == label, 0].mean(), X_reduced[y == label, 1].mean() + 1.5, X_reduced[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X_reduced[:, 0], X_reduced[:, 1], X_reduced[:, 2], c=y, edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_title("First three PCA directions") ax.set_xlabel("1st eigenvector") ax.w_xaxis.set_ticklabels([]) ax.set_ylabel("2nd eigenvector") ax.w_yaxis.set_ticklabels([]) ax.set_zlabel("3rd eigenvector") ax.w_zaxis.set_ticklabels([]) plt.show() import matplotlib.pyplot as plt plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=Y) """ Explanation: Having irrelevant features in your data can decrease the accuracy of many models, especially linear algorithms. This is partly because linear modeling doesn't work well with data where feature present multiple linear dependencies (seethis for more). Three benefits of performing feature selection before modeling your data are: - Reduces Overfitting: Less redundant data means less opportunity to make decisions based on noise. - Improves Accuracy: Less misleading data means modeling accuracy improves. - Reduces Training Time: Less data means that algorithms train faster. Feature extraction Rather than selecting features, FT creates an entirely new (transformed) feature space, having lower dimensionality. https://en.wikipedia.org/wiki/Feature_extraction PCA (Principal Component Analysis) Many times our data is not full rank, which means that some variables repeat as a linear combination or others. PCA will transform the dataset into a number of uncorelated components. The first principal component has the largest possible variance (that is, accounts for as much of the variability in the data as possible), and each succeeding component in turn has the highest variance possible under the constraint that it is orthogonal to (i.e., uncorrelated with) the preceding components. For a visual explanation look here. Mathematically, PCA is a linear transformation of a matrix $X(n,p)$ of $p$ features, defined by a set of $m$ $p$-dimensional vectors called loadings ${w}{(k)} = (w_1, \dots, w_p){(k)}$ mapping each row vector of $X$ into a set of $m$ principal component scores ${t}{(i)} = (t_1, \dots, t_m){(i)}$, given by $${t_{k}}{(i)} = {x}{(i)} \cdot {w}_{(k)} \qquad \mathrm{for} \qquad i = 1,\dots,n \qquad k = 1,\dots,m $$ in such a way that the individual variables $t_1, \dots, t_m$ of $t$ considered over the data set successively inherit the maximum possible variance from $x$, with each loading vector $w$ constrained to be a unit vector. Numerically, there is a direct connection between the loading vectors and the spectral decomposition of the empirical covariance matrix $X^TX$ in that the first loading vector is the eigenvector with the largest eigenvalue in the transformation of the covariance matrix into a diagonal form. With scikit-learn, PCA is part of the matrix decomposition module, and it is numerically solved via SVD decomposition. End of explanation """ import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.decomposition import PCA import pandas as pd from sklearn.preprocessing import StandardScaler iris = datasets.load_iris() X = iris.data y = iris.target #In general a good idea is to scale the data scaler = StandardScaler() scaler.fit(X) X=scaler.transform(X) pca = PCA() x_new = pca.fit_transform(X) def myplot(score,load,labels=None): xs = score[:,0] ys = score[:,1] n = load.shape[0] scalex = 1.0/(xs.max() - xs.min()) scaley = 1.0/(ys.max() - ys.min()) plt.scatter(xs * scalex,ys * scaley, c = y) for i in range(n): plt.arrow(0, 0, load[i,0], load[i,1],color = 'r',alpha = 0.5) if labels is None: plt.text(load[i,0]* 1.15, load[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center') else: plt.text(load[i,0]* 1.15, load[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center') plt.xlim(-1,1) plt.ylim(-1,1) plt.xlabel("PC{}".format(1)) plt.ylabel("PC{}".format(2)) plt.grid() #Call the function. Use only the 2 PCs. myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :])) plt.show() """ Explanation: Task: - How to make the score vs loadings biplots, similar to those in R? - How to compute the FA loadings/scores based on the principal components? First of all, PCA is not necessarily a factor analysis subject, and the habit of using scores vs loadings doesn't exist or is different elsewhere. Finish the code bellow to add proper labels for the loadings, and compute the actual loadings. Further read: - https://arxiv.org/pdf/1404.1100.pdf - https://stats.stackexchange.com/questions/119746/what-is-the-proper-association-measure-of-a-variable-with-a-pca-component-on-a/119758#119758 - https://stackoverflow.com/questions/21217710/factor-loadings-using-sklearn/28062715#28062715 End of explanation """ import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA, FastICA # two Student T tests with hight degrees of freedom rng = np.random.RandomState(42) # initialize the Mersenne Twister randomg number generator S = rng.standard_t(1.5, size=(20000, 2)) S[:, 0] *= 2. # Mix data A = np.array([[1, 1], [0, 2]]) # Mixing matrix X = np.dot(S, A.T) # Generate observations # Train PCA and Fast ICA pca = PCA() S_pca_ = pca.fit(X).transform(X) ica = FastICA(random_state=rng) S_ica_ = ica.fit(X).transform(X) # Estimate the sources S_ica_ /= S_ica_.std(axis=0) # Plot results def plot_samples(S, axis_list=None): plt.scatter(S[:, 0], S[:, 1], s=2, marker='o', zorder=10, color='steelblue', alpha=0.5) if axis_list is not None: colors = ['orange', 'red'] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work plt.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) plt.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color) plt.hlines(0, -3, 3) plt.vlines(0, -3, 3) plt.xlim(-3, 3) plt.ylim(-3, 3) plt.xlabel('x') plt.ylabel('y') plt.figure() plt.subplot(2, 2, 1) plot_samples(S / S.std()) plt.title('True Independent Sources') axis_list = [pca.components_.T, ica.mixing_] plt.subplot(2, 2, 2) plot_samples(X / np.std(X), axis_list=axis_list) legend = plt.legend(['PCA', 'ICA'], loc='upper right') legend.set_zorder(100) plt.title('Observations') plt.subplot(2, 2, 3) plot_samples(S_pca_ / np.std(S_pca_, axis=0)) plt.title('PCA recovered signals') plt.subplot(2, 2, 4) plot_samples(S_ica_ / np.std(S_ica_)) plt.title('ICA recovered signals') plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.36) plt.show() """ Explanation: ICA (Independent Component Analysis) ICA is an algorithm that finds directions in the feature space corresponding to projections with high non-Gaussianity. Why: - Many types of biological datasets are Gaussian rather then normally distributed. - Continuous biological or biomedical machine signals are typically Gaussian. - The question is not always related to dividing data based on the highest variance. Further read: - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3298499/ - http://scikit-learn.org/stable/auto_examples/decomposition/plot_ica_vs_pca.html#sphx-glr-auto-examples-decomposition-plot-ica-vs-pca-py End of explanation """ from sklearn.datasets import load_iris from sklearn.decomposition import FactorAnalysis iris = load_iris() X, y = iris.data, iris.target factor = FactorAnalysis(n_components=4, random_state=101).fit(X) import pandas as pd pd.DataFrame(factor.components_,columns=iris.feature_names) """ Explanation: FA Factor Analysis Unique variance: Some variance is unique to the variable under examination. It cannot be associated to what happens to any other variable. Shared variance: Some variance is shared with one or more other variables, creating redundancy in the data. Redundancy implies that you can find the same information, with slightly different values, in various features and across many observations. Bellow, the components_ attribute, returns an array containing measures of the relationship between the newly created factors, placed in rows, and the original features, placed in columns. Higher positive scores correspond with factors being positively associated with the features. In this case, although we fit the factor model based on four components, only two components seem to fit the dataset. Factor analysis uses an expectation maximization (EM) optimizer to find the best Gaussian distribution that can accurately model your data within a tolerance of n_tolerance. In simple terms n_components is the dimensionality of the Gaussian distribution. End of explanation """ import numpy as np from sklearn.datasets import fetch_mldata mnist = fetch_mldata("MNIST original") X = mnist.data / 255.0 y = mnist.target print(X.shape, y.shape) import pandas as pd feat_cols = [ 'pixel'+str(i) for i in range(X.shape[1]) ] df = pd.DataFrame(X,columns=feat_cols) df['label'] = y df['label'] = df['label'].apply(lambda i: str(i)) #X, y = None, None print('Size of the dataframe: {}'.format(df.shape)) %matplotlib inline import matplotlib.pyplot as plt rndperm = np.random.permutation(df.shape[0]) # Plot the graph plt.gray() fig = plt.figure( figsize=(16,7) ) for i in range(0,30): ax = fig.add_subplot(3,10,i+1, title='Digit: ' + str(df.loc[rndperm[i],'label']) ) ax.matshow(df.loc[rndperm[i],feat_cols].values.reshape((28,28)).astype(float)) plt.show() from sklearn.decomposition import PCA pca = PCA(n_components=3) pca_result = pca.fit_transform(df[feat_cols].values) df['pca-one'] = pca_result[:,0] df['pca-two'] = pca_result[:,1] df['pca-three'] = pca_result[:,2] print('Explained variation per principal component: {}'.format(pca.explained_variance_ratio_)) from ggplot import * chart = ggplot( df.loc[rndperm[:3000],:], aes(x='pca-one', y='pca-two', color='label') ) \ + geom_point(size=75,alpha=0.8) \ + ggtitle("First and Second Principal Components colored by digit") chart import time from sklearn.manifold import TSNE n_sne = 3000 time_start = time.time() tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=250) tsne_results = tsne.fit_transform(df.loc[rndperm[:n_sne],feat_cols].values) print('t-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start)) df_tsne = df.loc[rndperm[:n_sne],:].copy() df_tsne['x-tsne'] = tsne_results[:,0] df_tsne['y-tsne'] = tsne_results[:,1] chart = ggplot( df_tsne, aes(x='x-tsne', y='y-tsne', color='label') ) \ + geom_point(size=70,alpha=0.1) \ + ggtitle("tSNE dimensions colored by digit") chart """ Explanation: Further read: - https://en.wikipedia.org/wiki/Multiple_factor_analysis - https://en.wikipedia.org/wiki/Factor_analysis_of_mixed_data - https://blog.dominodatalab.com/how-to-do-factor-analysis/ tSNE It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results. While t-SNE can be useful for DR, it is considered more useful as a visualization technique in classification problems. One of the prize winning creators maintains a website with native calls to his implementation in multiple languages including python, but scikit-learn also has an implementation available. http://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html http://scikit-learn.org/stable/modules/manifold.html#t-sne One of the most popular demo is the classification of the MINST digit data. End of explanation """
zentonllo/tfg-tensorflow
cloud/datalab/notebooks_ejemplo/BigQuery+Magic+Commands+and+DML.ipynb
mit
%%bq query --name UniqueNames2013 WITH UniqueNames2013 AS (SELECT DISTINCT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE Year = 2013) SELECT * FROM UniqueNames2013 """ Explanation: BigQuery Magic Commands and DML The examples in this notebook introduce features of BigQuery Standard SQL and BigQuery SQL Data Manipulation Language (beta). BigQuery Standard SQL is compliant with the SQL 2011 standard. You've already seen the use of the magic command %%bq in the Hello BigQuery and BigQuery Commands notebooks. This command and others in the Google Cloud Datalab API support BigQuery Standard SQL. Using the BigQuery Magic command with Standard SQL First, we will cover some more uses of the %%bq magic command. Let's define a query to work with: End of explanation """ %%bq -h """ Explanation: Now let's list all available commands to work with %%bq End of explanation """ %%bq dryrun -q UniqueNames2013 """ Explanation: The dryrun argument in %%bq can be helpful to confirm the syntax of the SQL query. Instead of executing the query, it will only return some statistics: End of explanation """ %%bq sample -q UniqueNames2013 """ Explanation: Now, let's get a small sample of the results using the sample argument in %%bq: End of explanation """ %%bq execute -q UniqueNames2013 """ Explanation: Finally, We can use the execute command in %%bq to display the results of our query: End of explanation """ import google.datalab.bigquery as bq # Create a new dataset (this will be deleted later in the notebook) sample_dataset = bq.Dataset('sampleDML') if not sample_dataset.exists(): sample_dataset.create(friendly_name = 'Sample Dataset for testing DML', description = 'Created from Sample Notebook in Google Cloud Datalab') sample_dataset.exists() # To create a table, we need to create a schema for it. # Its easiest to create a schema from some existing data, so this # example demonstrates using an example object fruit_row = { 'name': 'string value', 'count': 0 } sample_table1 = bq.Table("sampleDML.fruit_basket").create(schema = bq.Schema.from_data([fruit_row]), overwrite = True) """ Explanation: Using Google BigQuery SQL Data Manipulation Language Below, we will demonstrate how to use Google BigQuery SQL Data Manipulation Language (DML) in Datalab. Preparation First, let's import the BigQuery module, and create a sample dataset and table to help demonstrate the features of Google BigQuery DML. End of explanation """ %%bq query INSERT sampleDML.fruit_basket (name, count) VALUES('banana', 5), ('orange', 10), ('apple', 15), ('mango', 20) """ Explanation: Inserting Data We can add rows to our newly created fruit_basket table by using an INSERT statement in our BigQuery Standard SQL query. End of explanation """ %%bq query INSERT sampleDML.fruit_basket (name, count) SELECT * FROM UNNEST([('peach', 25), ('watermelon', 30)]) """ Explanation: You may rewrite the previous query as: End of explanation """ %%bq query INSERT sampleDML.fruit_basket(name, count) WITH w AS ( SELECT ARRAY<STRUCT<name string, count int64>> [('cherry', 35), ('cranberry', 40), ('pear', 45)] col ) SELECT name, count FROM w, UNNEST(w.col) """ Explanation: You can also use a WITH clause with INSERT and SELECT. End of explanation """ fruit_row_detailed = { 'name': 'string value', 'count': 0, 'readytoeat': False } sample_table2 = bq.Table("sampleDML.fruit_basket_detailed").create(schema = bq.Schema.from_data([fruit_row_detailed]), overwrite = True) %%bq query INSERT sampleDML.fruit_basket_detailed (name, count, readytoeat) SELECT name, count, false FROM sampleDML.fruit_basket """ Explanation: Here is an example that copies one table's contents into another. First we will create a new table. End of explanation """ %%bq query UPDATE sampleDML.fruit_basket_detailed SET readytoeat = True WHERE name = 'banana' """ Explanation: Updating Data You can update rows in the fruit_basket table by using an UPDATE statement in the BigQuery Standard SQL query. We will try to do this using the Datalab BigQuery API. End of explanation """ %%bq tables view --name sampleDML.fruit_basket_detailed """ Explanation: To view the contents of a table in BigQuery, use %%bq tables view command: End of explanation """ %%bq query DELETE sampleDML.fruit_basket WHERE name in ('cherry', 'cranberry') """ Explanation: Deleting Data You can delete rows in the fruit_basket table by using a DELETE statement in the BigQuery Standard SQL query. End of explanation """ %%bq query DELETE sampleDML.fruit_basket_detailed WHERE NOT EXISTS (SELECT * FROM sampleDML.fruit_basket WHERE fruit_basket_detailed.name = fruit_basket.name) """ Explanation: Use the following query to delete the corresponding entries in sampleDML.fruit_basket_detailed End of explanation """ # Clear out sample resources sample_dataset.delete(delete_contents = True) """ Explanation: Deleting Resources End of explanation """
bashtage/statsmodels
examples/notebooks/formulas.ipynb
bsd-3-clause
import numpy as np # noqa:F401 needed in namespace for patsy import statsmodels.api as sm """ Explanation: Formulas: Fitting models using R-style formulas Since version 0.5.0, statsmodels allows users to fit statistical models using R-style formulas. Internally, statsmodels uses the patsy package to convert formulas and data to the matrices that are used in model fitting. The formula framework is quite powerful; this tutorial only scratches the surface. A full description of the formula language can be found in the patsy docs: Patsy formula language description Loading modules and functions End of explanation """ from statsmodels.formula.api import ols """ Explanation: Import convention You can import explicitly from statsmodels.formula.api End of explanation """ sm.formula.ols """ Explanation: Alternatively, you can just use the formula namespace of the main statsmodels.api. End of explanation """ import statsmodels.formula.api as smf """ Explanation: Or you can use the following convention End of explanation """ sm.OLS.from_formula """ Explanation: These names are just a convenient way to get access to each model's from_formula classmethod. See, for instance End of explanation """ dta = sm.datasets.get_rdataset("Guerry", "HistData", cache=True) df = dta.data[["Lottery", "Literacy", "Wealth", "Region"]].dropna() df.head() """ Explanation: All of the lower case models accept formula and data arguments, whereas upper case ones take endog and exog design matrices. formula accepts a string which describes the model in terms of a patsy formula. data takes a pandas data frame or any other data structure that defines a __getitem__ for variable names like a structured array or a dictionary of variables. dir(sm.formula) will print a list of available models. Formula-compatible models have the following generic call signature: (formula, data, subset=None, *args, **kwargs) OLS regression using formulas To begin, we fit the linear model described on the Getting Started page. Download the data, subset columns, and list-wise delete to remove missing observations: End of explanation """ mod = ols(formula="Lottery ~ Literacy + Wealth + Region", data=df) res = mod.fit() print(res.summary()) """ Explanation: Fit the model: End of explanation """ res = ols(formula="Lottery ~ Literacy + Wealth + C(Region)", data=df).fit() print(res.params) """ Explanation: Categorical variables Looking at the summary printed above, notice that patsy determined that elements of Region were text strings, so it treated Region as a categorical variable. patsy's default is also to include an intercept, so we automatically dropped one of the Region categories. If Region had been an integer variable that we wanted to treat explicitly as categorical, we could have done so by using the C() operator: End of explanation """ res = ols(formula="Lottery ~ Literacy + Wealth + C(Region) -1 ", data=df).fit() print(res.params) """ Explanation: Patsy's mode advanced features for categorical variables are discussed in: Patsy: Contrast Coding Systems for categorical variables Operators We have already seen that "~" separates the left-hand side of the model from the right-hand side, and that "+" adds new columns to the design matrix. Removing variables The "-" sign can be used to remove columns/variables. For instance, we can remove the intercept from a model by: End of explanation """ res1 = ols(formula="Lottery ~ Literacy : Wealth - 1", data=df).fit() res2 = ols(formula="Lottery ~ Literacy * Wealth - 1", data=df).fit() print(res1.params, "\n") print(res2.params) """ Explanation: Multiplicative interactions ":" adds a new column to the design matrix with the interaction of the other two columns. "*" will also include the individual columns that were multiplied together: End of explanation """ res = smf.ols(formula="Lottery ~ np.log(Literacy)", data=df).fit() print(res.params) """ Explanation: Many other things are possible with operators. Please consult the patsy docs to learn more. Functions You can apply vectorized functions to the variables in your model: End of explanation """ def log_plus_1(x): return np.log(x) + 1.0 res = smf.ols(formula="Lottery ~ log_plus_1(Literacy)", data=df).fit() print(res.params) """ Explanation: Define a custom function: End of explanation """ import patsy f = "Lottery ~ Literacy * Wealth" y, X = patsy.dmatrices(f, df, return_type="matrix") print(y[:5]) print(X[:5]) """ Explanation: Any function that is in the calling namespace is available to the formula. Using formulas with models that do not (yet) support them Even if a given statsmodels function does not support formulas, you can still use patsy's formula language to produce design matrices. Those matrices can then be fed to the fitting function as endog and exog arguments. To generate numpy arrays: End of explanation """ f = "Lottery ~ Literacy * Wealth" y, X = patsy.dmatrices(f, df, return_type="dataframe") print(y[:5]) print(X[:5]) print(sm.OLS(y, X).fit().summary()) """ Explanation: To generate pandas data frames: End of explanation """
NumCosmo/NumCosmo
notebooks/DataNCount/cmp_cluster_ccl_numcosmo.ipynb
gpl-3.0
#CCL cosmology cosmo_ccl = ccl.Cosmology(Omega_c = 0.30711 - 0.048254, Omega_b = 0.048254, h = 0.677, sigma8 = 0.8822714165197718, n_s=0.96, Omega_k = 0, transfer_function='eisenstein_hu') ccl_cosmo_set_high_prec (cosmo_ccl) cosmo, dist, ps_lin, ps_nln, hmfunc = create_nc_obj (cosmo_ccl) psf = hmfunc.peek_psf () """ Explanation: initialize the Cosmological models End of explanation """ #Numcosmo Cluster Abundance #First we need to define the multiplicity function here we will use the tinker mulf = nc.MultiplicityFuncTinker.new() mulf.set_linear_interp (True) mulf.set_mdef(nc.MultiplicityFuncMassDef.CRITICAL) mulf.set_Delta(200) #Second we need to construct a filtered power spectrum hmf = nc.HaloMassFunction.new(dist,psf,mulf) hmf.set_area((0.25)*4*np.pi) #Here we define the mass proxy in the first analysis is used the true mass and redshift of the clusters cluster_m = nc.ClusterMass.new_from_name("NcClusterMassNodist{'lnM-min':<%20.15e>, 'lnM-max':<%20.15e>}" % (math.log(10)*np.log10(1e14),math.log(10)*np.log10(1e16))) cluster_z = nc.ClusterRedshift.new_from_name("NcClusterRedshiftNodist{'z-min': <%20.15e>, 'z-max':<%20.15e>}" % (0.25,2)) ca = nc.ClusterAbundance.new(hmf,None) mset = ncm.MSet.new_array([cosmo,cluster_m,cluster_z]) mset.pretty_log() print('sigma8 = '+str(cosmo.sigma8(psf))) #CCL Cluster Abundance clc = cl_count.ClusterAbundance() #choose the halo mass function and mass definition massdef = ccl.halos.massdef.MassDef(200, 'critical', c_m_relation=None) hmd = ccl.halos.hmfunc.MassFuncTinker08(cosmo_ccl, mass_def=massdef) clc.set_cosmology(cosmo = cosmo_ccl, hmd = hmd, massdef = massdef) clc.sky_area = (0.25)*4*np.pi """ Explanation: initialize the ClusterAbundance object End of explanation """ t0 = time.time() #Bins definition z_nodes = np.linspace(0.25, 2, 8) log10M_nodes = np.linspace(14, 14.8, 11) lnM_nodes = log10M_nodes * math.log(10) #Numcosmo cluster counts in the bins Numcosmo_Abundance = [] ca.prepare (cosmo, cluster_z, cluster_m) for zl, zu in zip (z_nodes, z_nodes[1:]): nc_bin_mass = [] for lnMl, lnMu in zip (lnM_nodes, lnM_nodes[1:]): Pbin = ca.intp_bin_d2n(cosmo, cluster_z, cluster_m, [lnMl], [lnMu], None, [zl], [zu], None) nc_bin_mass.append(Pbin) Numcosmo_Abundance.append(nc_bin_mass) #Numcosmo_Abundance[i][j] is the number of clusters in i-th z_bin and j-th mass_bin t1 = time.time() print('time (seconds) = ' + str(t1-t0)) #CCL cluster count in the bins t0 = time.time() CCL_Abundance_exact = clc.Cluster_Abundance_MZ(zbin_edges = z_nodes, proxybin_edges = log10M_nodes, method = 'exact') t1 = time.time() print('time (seconds) = ' + str(t1-t0)) #CCL_Abundance_exact[i][j] is the number of clusters in i-th z_bin and j-th mass_bin for zl, zu, ccl_a_z, nc_a_z in zip(z_nodes, z_nodes[1:], CCL_Abundance_exact, Numcosmo_Abundance): for lnMl, lnMu, ccl_a, nc_a in zip (lnM_nodes, lnM_nodes[1:], ccl_a_z, nc_a_z): print("(% 16.9g % 16.9g) (% 16.9g % 16.9g) % 16.9g cmp %.2e" % (lnMl / math.log(10), lnMu / math.log(10), zl, zu, ccl_a, math.fabs (nc_a/ccl_a - 1.0))) diff = [] for i in range(len(CCL_Abundance_exact)): diff.append(100*abs((Numcosmo_Abundance[i]-CCL_Abundance_exact[i])/Numcosmo_Abundance[i])) plt.figure(figsize = (14,9)) plt.yscale('log') z_ = [np.mean([z_nodes[i],z_nodes[i+1]]) for i in np.arange(len(z_nodes)-1)] mass = [np.mean([10**log10M_nodes[i],10**log10M_nodes[i+1]]) for i in np.arange(len(log10M_nodes)-1)] plt.tick_params(axis='both', which="both", labelsize= 15) legend = [] for i in range(len(z_)): plt.scatter(mass, diff[:][i]) legend.append(str(round(z_nodes[i],3))+'< z <'+str(round(z_nodes[i+1],3))) plt.legend(legend,loc =4, fontsize = 10) plt.grid(True, which="both" ) plt.ylabel('|bias| CCL exact method to Numcosmo $(\%)$', fontsize = 20) plt.xlabel(r'$log_{10}(M)$', fontsize = 20) plt.ylim(1e-9,1e-1) plt.show() #diff[i][j] is the percentual difference between Numcosmo and CCL cluster abundance in i-th z_bin and j-th mass_bin """ Explanation: Binned approach Compute the 2D integral $$ N_{\alpha\beta}^{\rm predicted} = \Omega_s\int_{z_\alpha}^{z_{\alpha + 1}} dz\int_{\log_{10}M_\beta}^{\log_{10}M_{\beta + 1}}\frac{d^2V(z)}{dz d\Omega}\frac{dn(M,z)}{d\log_{10}M}d\log_{10}M $$ End of explanation """ #Generates cluster count catalog data ncdata = nc.DataClusterNCount.new(ca,'NcClusterRedshiftNodist','NcClusterMassNodist') rng = ncm.RNG.pool_get("example_ca_sampling"); ncdata.init_from_sampling(mset,(0.25)*4*np.pi,rng) ncdata.catalog_save("ca_nodist_unbinned_numcosmo.fits", True) ncdata_fits = fits.open('ca_nodist_unbinned_numcosmo.fits') #ncdata_fits.info() ncdata_data = ncdata_fits[1].data ncdata_Table = Table(ncdata_data) ncdata_Table.columns ncdata_Table.sort('Z_TRUE') display(ncdata_Table) #Using Numcosmo t0 = time.time() d2n = [] for i in ncdata_Table: d2n.append(ca.d2n(cosmo,cluster_z,cluster_m,i[1],i[0])) d2n = np.array(d2n) t1 = time.time() print('time (seconds) = ' + str(t1-t0)) d2n #Using CCL t0 = time.time() log10M = np.array(ncdata_Table[1][:]/np.log(10)) multiplicity_exact = clc.multiplicity_function_individual_MZ(z = np.array(ncdata_Table[0][:]), logm =log10M, method = 'exact') multiplicity_exact *= clc.sky_area/math.log(10) t1 = time.time() print('time (seconds) = ' + str(t1-t0)) print(multiplicity_exact) diff = abs(100*(multiplicity_exact-d2n)/d2n) plt.figure(figsize = (14,7)) plt.yscale('log') plt.tick_params(axis='both', which = 'major', labelsize= 15) plt.scatter(ncdata_Table[0][:], diff, s = 0.4, c = log10M) plt.colorbar() plt.grid(True, which='both') plt.xlabel(r'$redshift$', fontsize = 20) plt.ylabel('|bias| CCL exact method to Numcosmo $(\%)$', fontsize = 20) plt.ylim(10e-10,1) """ Explanation: Un-binned approach Compute $$\frac{d^2V(z_i)}{dz d\Omega}\frac{dn(M_i,z_i)}{d\log_{10}M_i}$$ for each masses and redshifts in a dark matter halo catalog End of explanation """
IanHawke/msc-or-python
02-loops-functions.ipynb
mit
def add(x, y): """ Add two numbers Parameters ---------- x : float First input y : float Second input Returns ------- x + y : float """ return x + y add(1, 2) """ Explanation: Functions Storing individual Python commands for re-use is one thing. Creating a function that can be repeatedly applied to different input data is quite another, and of huge importance in coding. In VBA there are two related concepts: subroutines and functions. Subroutines perform actions, functions return results (given inputs). In Python there is no distinction: any function can both return results and perform actions. In VBA there is a standard layout. For subroutines we have VB.NET Sub name() ' ' Comments ' Code End Sub For functions we have VB.NET Function name(arguments) ' ' Comments ' name = ... End Function A similar structure holds in Python. Here we have python def name(arguments): """ Comments """ return value The def keyword says that what follows is a function. Again, the name of the function follows the same rules and conventions as variables and files. The colon : at the end of the first line is essential: everything that follows that is indented will be the code to be executed when the function is called. The indentation is also essential. As soon as the indentation stops, the function stops (like End Function in VBA). Here is a simple example, that you can type directly into the console or into a file: End of explanation """ print(add(3, 4)) print(add(10.61, 5.99)) """ Explanation: We see that the line add(1, 2) is outside the function and so is executed. We can also call the function repeatedly: End of explanation """ help(add) """ Explanation: The lengthy comment at the start of the function is very useful to remind yourself later what the function should do. You can see this information by typing End of explanation """ import script2 script2.add(1, 2) """ Explanation: You can also view this in spyder by typing add in the Object window of the Help tab in the top right. We can save the function to a file and re-use the function by importing the file. Create a new file in the spyder editor containing ```python def add(x, y): """ Add two numbers Parameters ---------- x : float First input y : float Second input Returns ------- x + y : float """ return x + y ``` and save it as script2.py. Then in the console check that it works as expected: End of explanation """ count = 0 if count == 0: message = "There are no items." elif count == 1: message = "There is 1 item." else: message = "There are" + count + " items." print(message) """ Explanation: if statements and flow control We often need to make a decision whether to do something, or to do something else. In Visual Basic this uses an If statement: ```VB.Net Dim count As Integer = 0 Dim message As String If count = 0 Then message = "There are no items." ElseIf count = 1 Then message = "There is 1 item." Else message = "There are " & count & " items." End If ``` The equivalent Python code is similar: End of explanation """ def fibonacci(n): if n == 1 or n == 2: return 1 else: return fibonacci(n-1) + fibonacci(n-2) print('F_1 = ', fibonacci(1)) print('F_2 = ', fibonacci(2)) print('F_5 = ', fibonacci(5)) print('F_10 = ', fibonacci(10)) """ Explanation: We see that the Visual Basic If statement becomes the lower case if, and the ElseIf is contracted to elif. The condition (in this case!) compares a variable, count, to a number, using the equality comparison ==. Once again, as in the case of functions, the line containing the if definition is ended with a colon (:), and the commands to be executed are indented. We can include as many branches of the if statement as we like using multiple elif statements. We do not need to use any elif statements, nor an else, unless we want (or need) to. We can nest if statements inside each other. Exercise Write a function that, given an integer $n$, returns the $n^{\text{th}}$ Fibonacci number $F_n = F_{n-1} + F_{n-2}$, where $F_1 = 1 = F_2$. Check that it works for $n = 1, 2, 5, 10$ ($F_5 = 5$ and $F_{10} = 55$). End of explanation """ print(add(3, 1)) print(add(3, 2)) print(add(3, 3)) print(add(3, 4)) print(add(3, 5)) """ Explanation: Loops We will often want to run the same code many times on similar input. Let us suppose we want to add $n$ to $3$, where $n$ is every number between $1$ and $5$. We could do: End of explanation """ for n in 1, 2, 3, 4, 5: print(add(3, n)) print("Loop has ended") """ Explanation: This is tedious and there's a high chance of errors. In VBA you can define a loop that repeats commands as, for example VB.NET For n = 1 To 5 Z = 3 + n Next n In Python there is also a for loop: End of explanation """ for n in range(1, 6): print("n =", n) for m in range(3): print("m =", m) for k in range(2, 7, 2): print("k =", k) """ Explanation: The syntax has similarities to the syntax for functions. The line defining the loop starts with for, specifies the values that n takes, and ends with a colon. The code that is executed inside the loop is indented. As a short-hand for integer loops, we can use the range function: End of explanation """ for thing in 1, 2.5, "hello", add: print("thing is ", thing) """ Explanation: We see that if two numbers are given, range returns all integers from the first number up to but not including the second in steps of $1$; if one number is given, range starts from $0$; if three numbers are given, the third is the step. In fact Python will iterate over any collection of objects: they do not have to be integers: End of explanation """ t1 = (0, 1, 2, 3, 4, 5) print(t1[0]) print(t1[3]) """ Explanation: This is very often used in Python code: if you have some way of collecting things together, Python will happily iterate over them all. Containers, sequences, lists, arrays So what are the Python ways of collecting things together? In VBA, there are arrays: VB.NET Dim A(2) AS DOUBLE defines an array, or vector, of length $3$, starting from $0$, of double precision floating point numbers. VB.NET Dim B() AS DOUBLE defines an array, or vector, of arbitrary length, starting from $0$, of double precision floating point numbers. You can also start arrays from values other than $0$. The individual entries are accessed and modified using, for example, A(0). In Python there are many ways of collecting objects together. The closest to VBA are tuples and lists. Tuples A tuple is a sequence with fixed size, whose entries cannot be modified: End of explanation """ t1[0] = 1 """ Explanation: We see that to access individual entries we use square brackets and the number of the entry, starting from $0$. All Python tuples and lists start from $0$. To check that it cannot be modified: End of explanation """ print(t1[1:4]) """ Explanation: We can use slicing to access many entries at once: End of explanation """ print(t1[-1]) """ Explanation: As with the range function, the notation &lt;start&gt;:&lt;end&gt; returns the entries from (and including) &lt;start&gt; up to, but not including, &lt;end&gt;. We can use negative numbers to access from the right of the sequence: -1 is the last entry, -2 the next-to-last, and so on: End of explanation """ l1 = [0, 1, 2, 3, 4, 5] print(l1[3]) l1[3] = 7 print(l1[3]) l1.append(6) print(l1) """ Explanation: Lists A list is a sequence with a size that can change, and whose entries can be modified: End of explanation """ l1[0:2] = l1[4:6] print(l1) """ Explanation: The same slicing notation can be used, and now can be used to assignment: End of explanation """ l2 = [0, 1.2, "hello", ["a", 3, 4.5], (0, (1.1, 2.3, 4))] print(l2[1]) print(l2[3][0]) """ Explanation: Crucially, lists and tuples can contain anything. As with loops, there is no restriction on types, and things can be nested: End of explanation """ d1 = {"omega": 1.0, "Gamma": 5.7, "N": 100} print(d1["Gamma"]) """ Explanation: Dictionaries Both lists and tuples are ordered: there are accessed by an integer giving there location in the sequence. This doesn't always make sense. Consider an algorithm which depends on parameters $\omega, \Gamma, N$. We want to keep the parameters together, but there's no logical order to them. Instead we can use a dictionary, which is an unordered Python container: End of explanation """ for key in d1: print("Key is", key, "value is", d1[key]) """ Explanation: As there is no order we access dictionaries using the key. To loop over a dictionary, we take advantage of Python's loose iteration rules: End of explanation """ for key, value in d1.items(): print("Key is", key, "value is", value) """ Explanation: There is a shortcut to allow you to get both key and value in one go: End of explanation """ boaty = {'first name' : 'Boaty', 'last name' : 'McBoatface', 'student ID' : 123456, 'project' : 'Surveying the arctic ocean'} def f_name(d): print("My name is {} {}".format(d['first name'], d['last name'])) def f_project(d): print("Student {} is doing project {}".format(d['student ID'], d['project'])) f_name(boaty) f_project(boaty) """ Explanation: Exercise Write a dictionary with the structure: d = {'first name' : ..., 'last name' : ..., 'student ID' : ..., 'project' : ...} Fill it in with suitable values. Write two functions f_name and f_project. Each should take as input a dictionary. f_name should print "My name is <first name> <last name>" f_project should print "Student <student ID> is doing project <project>" where <X> should fill in the appropriate value from the dictionary. End of explanation """ import numpy # python list l = [[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]] a = numpy.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) print('list l = {}'.format(l)) print('numpy array a = {}'.format(a)) """ Explanation: Numpy arrays We've seen python's built-in lists for storing data, however for the numpy library contains the more powerful array datatype. Arrays are essentially a more powerful form of lists which make it easier to handle data. Most importantly, they allow us to apply operations to all elements of an array at once, rather than looping over the elements one-by-one. To see this, let's create a list and a numpy array, both containing the same data. End of explanation """ print(l[1][2]) print(a[1,2]) """ Explanation: Accessing elements of numpy arrays is very similar to accessing elements of lists, but with slightly less typing. To access elements from an n-dimensional list, we have to use multiple square brackets, e.g. l[0][4][7][8]. For a numpy array, we separate the indices using a comma: a[0, 4, 7, 8]. End of explanation """ import copy squared = copy.deepcopy(l) for i in range(3): for j in range(3): squared[i][j] = l[i][j]**2 print(squared) """ Explanation: Let's say we now want to square every element of the array. For this 2d list, we would need a for loop: End of explanation """ print(a**2) """ Explanation: Note that here we used the function deepcopy from the copy module the copy the list l. If we had simply used squared = l, when we the assigned the elements of squared new values, this would also have changed the values in l. This is in contrast to the simple variables we saw before, where changing the value of one will leave the values of others unchanged. For numpy arrays, applying operations across the entire array is much simpler: End of explanation """ # transpose a.T # reshape numpy.reshape(a, (1,9)) # stack arrays horizontally numpy.hstack((a,a,a)) """ Explanation: Numpy has a range of array manipulation routines for rearranging and manipulating elements, such as those below. End of explanation """ a[a > 5] """ Explanation: If you've used Matlab before, you may be familiar with logical indexing. This is a way of accessing elements of a array that satisfy some criteria, e.g. all the elements which are greater than 0. We can also do this with numpy arrays using boolean array indexing: End of explanation """
relopezbriega/mi-python-blog
content/notebooks/RegexPython.ipynb
gpl-2.0
# importando el modulo de regex de python import re """ Explanation: Expresiones Regulares con Python Esta notebook fue creada originalmente como un blog post por Raúl E. López Briega en Mi blog sobre Python. El contenido esta bajo la licencia BSD. <img alt="Expresiones regulares" title="Expresiones regulares" src="https://relopezbriega.github.io/images/regex.png" width="700"> Introducción Uno de los problemas más comunes con que nos solemos encontrar al desarrollar cualquier programa informático, es el de procesamiento de texto. Esta tarea puede resultar bastante trivial para el cerebro humano, ya que nosotros podemos detectar con facilidad que es un número y que una letra, o cuales son palabras que cumplen con un determinado patrón y cuales no; pero estas mismas tareas no son tan fáciles para una computadora. Es por esto, que el procesamiento de texto siempre ha sido uno de los temas más relevantes en las ciencias de la computación. Luego de varias décadas de investigación se logró desarrollar un poderoso y versátil lenguaje que cualquier computadora puede utilizar para reconocer patrones de texto; este lenguale es lo que hoy en día se conoce con el nombre de expresiones regulares; las operaciones de validación, búsqueda, extracción y sustitución de texto ahora son tareas mucho más sencillas para las computadoras gracias a las expresiones regulares. ¿Qué son las Expresiones Regulares? Las expresiones regulares, a menudo llamada también regex, son unas secuencias de caracteres que forma un patrón de búsqueda, las cuales son formalizadas por medio de una sintaxis específica. Los patrones se interpretan como un conjunto de instrucciones, que luego se ejecutan sobre un texto de entrada para producir un subconjunto o una versión modificada del texto original. Las expresiones regulares pueden incluir patrones de coincidencia literal, de repetición, de composición, de ramificación, y otras sofisticadas reglas de reconocimiento de texto . Las expresiones regulares deberían formar parte del arsenal de cualquier buen programador ya que un gran número de problemas de procesamiento de texto pueden ser fácilmente resueltos con ellas. Componentes de las Expresiones Regulares Las expresiones regulares son un mini lenguaje en sí mismo, por lo que para poder utilizarlas eficientemente primero debemos entender los componentes de su sintaxis; ellos son: Literales: Cualquier caracter se encuentra a sí mismo, a menos que se trate de un metacaracter con significado especial. Una serie de caracteres encuentra esa misma serie en el texto de entrada, por lo tanto la plantilla "raul" encontrará todas las apariciones de "raul" en el texto que procesamos. Secuencias de escape: La sintaxis de las expresiones regulares nos permite utilizar las secuencias de escape que ya conocemos de otros lenguajes de programación para esos casos especiales como ser finales de línea, tabs, barras diagonales, etc. Las principales secuencias de escape que podemos encontrar, son: Secuencia de escape | Significado ---|--- \n | Nueva línea (new line). El cursor pasa a la primera posición de la línea siguiente. \t | Tabulador. El cursor pasa a la siguiente posición de tabulación. \\ | Barra diagonal inversa \v | Tabulación vertical. \ooo | Carácter ASCII en notación octal. \xhh | Carácter ASCII en notación hexadecimal. \xhhhh | Carácter Unicode en notación hexadecimal. Clases de caracteres: Se pueden especificar clases de caracteres encerrando una lista de caracteres entre corchetes [], la que que encontrará uno cualquiera de los caracteres de la lista. Si el primer símbolo después del "[" es "^", la clase encuentra cualquier caracter que no está en la lista. Metacaracteres: Los metacaracteres son caracteres especiales que son la esencia de las expresiones regulares. Como son sumamente importantes para entender la sintaxis de las expresiones regulares y existen diferentes tipos, voy a dedicar una sección a explicarlos un poco más en detalle. Metacaracteres Metacaracteres - delimitadores Esta clase de metacaracteres nos permite delimitar dónde queremos buscar los patrones de búsqueda. Ellos son: Metacaracter | Descripción ---|--- ^ | inicio de línea. $ | fin de línea. \A | inicio de texto. \Z | fin de texto. . | cualquier caracter en la línea. \b | encuentra límite de palabra. \B | encuentra distinto a límite de palabra. Metacaracteres - clases predefinidas Estas son clases predefinidas que nos facilitan la utilización de las expresiones regulares. Ellos son: Metacaracter | Descripción ---|--- \w | un caracter alfanumérico (incluye "_"). \W | un caracter no alfanumérico. \d | un caracter numérico. \D | un caracter no numérico. \s | cualquier espacio (lo mismo que [ \t\n\r\f]). \S | un no espacio. Metacaracteres - iteradores Cualquier elemento de una expresion regular puede ser seguido por otro tipo de metacaracteres, los iteradores. Usando estos metacaracteres se puede especificar el número de ocurrencias del caracter previo, de un metacaracter o de una subexpresión. Ellos son: Metacaracter | Descripción ---|--- * | cero o más, similar a {0,}. + | una o más, similar a {1,}. ? | cero o una, similar a {0,1}. {n} | exactamente n veces. {n,} | por lo menos n veces. {n,m} | por lo menos n pero no más de m veces. *? | cero o más, similar a {0,}?. +? | una o más, similar a {1,}?. ?? | cero o una, similar a {0,1}?. {n}? | exactamente n veces. {n,}? |por lo menos n veces. {n,m}? |por lo menos n pero no más de m veces. En estos metacaracteres, los dígitos entre llaves de la forma {n,m}, especifican el mínimo número de ocurrencias en n y el máximo en m. Metacaracteres - alternativas Se puede especificar una serie de alternativas para una plantilla usando "|" para separarlas, entonces do|re|mi encontrará cualquier "do", "re", o "mi" en el texto de entrada.Las alternativas son evaluadas de izquierda a derecha, por lo tanto la primera alternativa que coincide plenamente con la expresión analizada es la que se selecciona. Por ejemplo: si se buscan foo|foot en "barefoot'', sólo la parte "foo" da resultado positivo, porque es la primera alternativa probada, y porque tiene éxito en la búsqueda de la cadena analizada. Ejemplo: foo(bar|foo) --> encuentra las cadenas 'foobar' o 'foofoo'. Metacaracteres - subexpresiones La construcción ( ... ) también puede ser empleada para definir subexpresiones de expresiones regulares. Ejemplos: (foobar){10} --> encuentra cadenas que contienen 8, 9 o 10 instancias de 'foobar' foob([0-9]|a+)r --> encuentra 'foob0r', 'foob1r' , 'foobar', 'foobaar', 'foobaar' etc. Metacaracteres - memorias (backreferences) Los metacaracteres \1 a \9 son interpretados como memorias. \<n> encuentra la subexpresión previamente encontrada #<n>. Ejemplos: (.)\1+ --> encuentra 'aaaa' y 'cc'. (.+)\1+ --> también encuentra 'abab' y '123123' (['"]?)(\d+)\1 --> encuentra '"13" (entre comillas dobles), o '4' (entre comillas simples) o 77 (sin comillas) etc. Expresiones Regulares con Python Luego de esta introducción, llegó el tiempo de empezar a jugar con las expresiones regulares y Python. Como no podría ser de otra forma tratandose de Python y su filosofía de todas las baterías incluídas; en la librería estandar de Python podemos encontrar el módulo re, el cual nos proporciona todas las operaciones necesarias para trabajar con las expresiones regulares. Por lo tanto, en primer lugar lo que debemos hacer es importar el modulo re. End of explanation """ # compilando la regex patron = re.compile(r'\bfoo\b') # busca la palabra foo """ Explanation: Buscando coincidencias Una vez que hemos importado el módulo, podemos empezar a tratar de buscar coincidencias con un determinado patrón de búsqueda. Para hacer esto, primero debemos compilar nuestra expresion regular en un objeto de patrones de Python, el cual posee métodos para diversas operaciones, tales como la búsqueda de coincidencias de patrones o realizar sustituciones de texto. End of explanation """ # texto de entrada texto = """ bar foo bar foo barbarfoo foofoo foo bar """ # match nos devuelve None porque no hubo coincidencia al comienzo del texto print(patron.match(texto)) # match encuentra una coindencia en el comienzo del texto m = patron.match('foo bar') m # search nos devuelve la coincidencia en cualquier ubicacion. s = patron.search(texto) s # findall nos devuelve una lista con todas las coincidencias fa = patron.findall(texto) fa # finditer nos devuelve un iterador fi = patron.finditer(texto) fi # iterando por las distintas coincidencias next(fi) next(fi) """ Explanation: Ahora que ya tenemos el objeto de expresión regular compilado podemos utilizar alguno de los siguientes métodos para buscar coincidencias con nuestro texto. match(): El cual determinada si la regex tiene coincidencias en el comienzo del texto. search(): El cual escanea todo el texto buscando cualquier ubicación donde haya una coincidencia. findall(): El cual encuentra todos los subtextos donde haya una coincidencia y nos devuelve estas coincidencias como una lista. finditer(): El cual es similar al anterior pero en lugar de devolvernos una lista nos devuelve un <a href="https://es.wikipedia.org/wiki/Iterador_(patr%C3%B3n_de_dise%C3%B1o)">iterador</a>. Veamoslos en acción. End of explanation """ # Métodos del objeto de coincidencia m.group(), m.start(), m.end(), m.span() s.group(), s.start(), s.end(), s.span() """ Explanation: Como podemos ver en estos ejemplos, cuando hay coincidencias, Python nos devuelve un Objeto de coincidencia (salvo por el método findall() que devuelve una lista). Este Objeto de coincidencia también tiene sus propios métodos que nos proporcionan información adicional sobre la coincidencia; éstos métodos son: group(): El cual devuelve el texto que coincide con la expresion regular. start(): El cual devuelve la posición inicial de la coincidencia. end(): El cual devuelve la posición final de la coincidencia. span(): El cual devuelve una tupla con la posición inicial y final de la coincidencia. End of explanation """ # texto de entrada becquer = """Podrá nublarse el sol eternamente; Podrá secarse en un instante el mar; Podrá romperse el eje de la tierra como un débil cristal. ¡todo sucederá! Podrá la muerte cubrirme con su fúnebre crespón; Pero jamás en mí podrá apagarse la llama de tu amor.""" # patron para dividir donde no encuentre un caracter alfanumerico patron = re.compile(r'\W+') palabras = patron.split(becquer) palabras[:10] # 10 primeras palabras # Utilizando la version no compilada de split. re.split(r'\n', becquer) # Dividiendo por linea. # Utilizando el tope de divisiones patron.split(becquer, 5) # Cambiando "Podrá" o "podra" por "Puede" podra = re.compile(r'\b(P|p)odrá\b') puede = podra.sub("Puede", becquer) print(puede) # Limitando el número de reemplazos puede = podra.sub("Puede", becquer, 2) print(puede) # Utilizando la version no compilada de subn re.subn(r'\b(P|p)odrá\b', "Puede", becquer) # se realizaron 5 reemplazos """ Explanation: Modificando el texto de entrada Además de buscar coincidencias de nuestro patrón de búsqueda en un texto, podemos utilizar ese mismo patrón para realizar modificaciones al texto de entrada. Para estos casos podemos utilizar los siguientes métodos: split(): El cual divide el texto en una lista, realizando las divisiones del texto en cada lugar donde se cumple con la expresion regular. sub(): El cual encuentra todos los subtextos donde existe una coincidencia con la expresion regular y luego los reemplaza con un nuevo texto. subn(): El cual es similar al anterior pero además de devolver el nuevo texto, también devuelve el numero de reemplazos que realizó. Veamoslos en acción. End of explanation """ # Ejemplo de findall con la funcion a nivel del modulo # findall nos devuelve una lista con todas las coincidencias re.findall(r'\bfoo\b', texto) """ Explanation: Funciones no compiladas En estos últimos ejemplos, pudimos ver casos donde utilizamos las funciones al nivel del módulo split() y subn(). Para cada uno de los ejemplos que vimos (match, search, findall, finditer, split, sub y subn) existe una versión al nivel del módulo que se puede utilizar sin necesidad de compilar primero el patrón de búsqueda; simplemente le pasamos como primer argumento la expresion regular y el resultado será el mismo. La ventaja que tiene la versión compila sobre las funciones no compiladas es que si vamos a utilizar la expresion regular dentro de un bucle nos vamos a ahorrar varias llamadas de funciones y por lo tanto mejorar la performance de nuestro programa. End of explanation """ # Ejemplo de IGNORECASE # Cambiando "Podrá" o "podra" por "Puede" podra = re.compile(r'podrá\b', re.I) # el patrón se vuelve más sencillo puede = podra.sub("puede", becquer) print(puede) # Ejemplo de VERBOSE mail = re.compile(r""" \b # comienzo de delimitador de palabra [\w.%+-] # usuario: Cualquier caracter alfanumerico mas los signos (.%+-) +@ # seguido de @ [\w.-] # dominio: Cualquier caracter alfanumerico mas los signos (.-) +\. # seguido de . [a-zA-Z]{2,6} # dominio de alto nivel: 2 a 6 letras en minúsculas o mayúsculas. \b # fin de delimitador de palabra """, re.X) mails = """raul.lopez@relopezbriega.com, Raul Lopez Briega, foo bar, relopezbriega@relopezbriega.com.ar, raul@github.io, https://relopezbriega.com.ar, https://relopezbriega.github.io, python@python, river@riverplate.com.ar, pythonAR@python.pythonAR """ # filtrando los mails con estructura válida mail.findall(mails) """ Explanation: Banderas de compilación Las banderas de compilación permiten modificar algunos aspectos de cómo funcionan las expresiones regulares. Todas ellas están disponibles en el módulo re bajo dos nombres, un nombre largo como IGNORECASE y una forma abreviada de una sola letra como I. Múltiples banderas pueden ser especificadas utilizando el operador "|" OR; Por ejemplo, re.I | RE.M establece las banderas de E y M. Algunas de las banderas de compilación que podemos encontrar son: IGNORECASE, I: Para realizar búsquedas sin tener en cuenta las minúsculas o mayúsculas. VERBOSE, X: Que habilita la modo verborrágico, el cual permite organizar el patrón de búsqueda de una forma que sea más sencilla de entender y leer. ASCII, A: Que hace que las secuencias de escape \w, \b, \s and \d funciones para coincidencias con los caracteres ASCII. DOTALL, S: La cual hace que el metacaracter . funcione para cualquier caracter, incluyendo el las líneas nuevas. LOCALE, L: Esta opción hace que \w, \W, \b, \B, \s, y \S dependientes de la localización actual. MULTILINE, M: Que habilita la coincidencia en múltiples líneas, afectando el funcionamiento de los metacaracteres ^ and $. End of explanation """ # Accediendo a los grupos por sus indices patron = re.compile(r"(\w+) (\w+)") s = patron.search("Raul Lopez") # grupo 1 s.group(1) # grupo 2 s.group(2) """ Explanation: Como podemos ver en este último ejemplo, la opción VERBOSE puede ser muy util para que cualquier persona que lea nuestra expresion regular pueda entenderla más fácilmente. Nombrando los grupos Otra de las funciones interesantes que nos ofrece el módulo re de Python; es la posibilidad de ponerle nombres a los grupos de nuestras expresiones regulares. Así por ejemplo, en lugar de acceder a los grupos por sus índices, como en este caso... End of explanation """ # Accediendo a los grupos por nombres patron = re.compile(r"(?P<nombre>\w+) (?P<apellido>\w+)") s = patron.search("Raul Lopez") # grupo nombre s.group("nombre") # grupo apellido s.group("apellido") """ Explanation: Podemos utilizar la sintaxis especial (?P&lt;nombre&gt;patron) que nos ofrece Python para nombrar estos grupos y que sea más fácil identificarlos. End of explanation """ # Validando una URL url = re.compile(r"^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$") # vemos que https://relopezbriega.com.ar lo acepta como una url válida. url.search("https://relopezbriega.com.ar") # pero https://google.com/un/archivo!.html no la acepta por el carcter ! print(url.search("https://google.com/un/archivo!.html")) """ Explanation: Otros ejemplos de expresiones regulares Por último, para ir cerrando esta introducción a las expresiones regulares, les dejo algunos ejemplos de las expresiones regulares más utilizadas. Validando mails Para validar que un mail tenga la estructura correcta, podemos utilizar la siguiente expresion regular: regex: \b[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,6}\b Este es el patrón que utilizamos en el ejemplo de la opción VERBOSE. Validando una URL Para validar que una URL tenga una estructura correcta, podemos utilizar esta expresion regular: regex: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ End of explanation """ # Validando una dirección IP patron = ('^(?:(?:25[0-5]|2[0-4][0-9]|' '[01]?[0-9][0-9]?)\.){3}' '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$') ip = re.compile(patron) # la ip 73.60.124.136 es valida ip.search("73.60.124.136") # pero la ip 256.60.124.136 no es valida print(ip.search("256.60.124.136")) """ Explanation: Validando una dirección IP Para validar que una dirección IP tenga una estructura correcta, podemos utilizar esta expresión regular: regex: ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ End of explanation """ # Validando una fecha fecha = re.compile(r'^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\d\d)$') # validando 13/02/1982 fecha.search("13/02/1982") # no valida 13-02-1982 print(fecha.search("13-02-1982")) # no valida 32/12/2015 print(fecha.search("32/12/2015")) # no valida 30/14/2015 print(fecha.search("30/14/2015")) """ Explanation: Validando una fecha Para validar que una fecha tenga una estructura dd/mm/yyyy, podemos utilizar esta expresión regular: regex: ^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\d\d)$ End of explanation """
phoebe-project/phoebe2-docs
2.3/tutorials/solver_times.ipynb
gpl-3.0
#!pip install -I "phoebe>=2.3,<2.4" """ Explanation: Advanced: solver_times Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). End of explanation """ import phoebe import numpy as np import matplotlib.pyplot as plt """ Explanation: Let's get started with some basic imports End of explanation """ b = phoebe.default_binary() b.add_dataset('lc', times=phoebe.linspace(0,5,1001)) b.add_compute('ellc', compute='ellc01') b.set_value_all('ld_mode', 'lookup') b.run_compute('ellc01') times = b.get_value('times@model') fluxes = b.get_value('fluxes@model') sigmas = np.ones_like(times) * 0.01 b = phoebe.default_binary() b.add_dataset('lc', compute_phases=phoebe.linspace(0,1,101), times=times, fluxes=fluxes, sigmas=sigmas) b.add_compute('ellc', compute='ellc01') b.set_value_all('ld_mode', 'lookup') b.add_solver('optimizer.nelder_mead', compute='ellc01', fit_parameters=['teff'], solver='nm_solver') """ Explanation: And then we'll build a synthetic "dataset" and initialize a new bundle with those data End of explanation """ print(b.filter(qualifier='solver_times')) print(b.get_parameter(qualifier='solver_times', dataset='lc01').choices) """ Explanation: solver_times parameter and options End of explanation """ help(b.parse_solver_times) """ Explanation: The logic for solver times is generally only used internally within b.run_solver (for optimizers and samplers which require a forward-model to be computed). However, it is useful (in order to diagnose any issues, for example) to be able to see how the combination of solver_times, times, compute_times/compute_phases, mask_enabled, and mask_phases will be interpretted within PHOEBE during b.run_solver. See also: * Advanced: mask_phases * Advanced: Compute Times & Phases To access the underlying times that would be used, we can call b.parse_solver_times. Let's first look at the docstring (also available from the link above): End of explanation """ #logger = phoebe.logger('info') """ Explanation: Additionally, we can pass solver to b.run_compute to have the forward-model computed as it would be within the solver itself (this just calls run_compute with the compute option referenced by the solver and with the parsed solver_times). Below we'll go through each of the scenarios listed above and demonstrate how that logic changes the times at which the forward model will be computed within b.run_solver (with the cost-function interpolating between the resulting forward-model and the observations as necessary). The messages regarding the internal choice of logic for solver_times will be exposed at the 'info' level of the logger. We'll leave that off here to avoid the noise of the logger messages from run_compute calls, but you can uncomment the following line to see those messages. End of explanation """ b.set_value('solver_times', 'times') b.set_value('compute_phases', phoebe.linspace(0,1,101)) b.set_value('mask_enabled', False) b.set_value('dperdt', 0.0) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() print(solver_times) _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: solver_times = 'times' without phase_mask enabled End of explanation """ b.set_value('solver_times', 'times') b.set_value('compute_phases', phoebe.linspace(0,1,101)) b.set_value('mask_enabled', True) b.set_value('mask_phases', [(-0.1, 0.1), (0.45,0.55)]) b.set_value('dperdt', 0.0) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: with phase_mask enabled End of explanation """ b.set_value('solver_times', 'compute_times') b.set_value('compute_phases', phoebe.linspace(0,1,101)) b.set_value('mask_enabled', False) b.set_value('dperdt', 0.0) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: solver_times = 'compute_times' without phase_mask enabled End of explanation """ b.set_value('solver_times', 'compute_times') b.set_value('compute_phases', phoebe.linspace(0,1,101)) b.set_value('mask_enabled', True) b.set_value('mask_phases', [(-0.1, 0.1), (0.45,0.55)]) b.set_value('dperdt', 0.0) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: with phase_mask enabled and time-independent hierarchy End of explanation """ b.set_value('solver_times', 'compute_times') b.set_value('compute_phases', phoebe.linspace(0,1,101)) b.set_value('mask_enabled', True) b.set_value('mask_phases', [(-0.1, 0.1), (0.45,0.55)]) b.set_value('dperdt', 0.1) print(b.hierarchy.is_time_dependent()) """ Explanation: with phase_mask enabled and time-dependent hierarchy End of explanation """ print(b.run_checks_solver()) """ Explanation: In the case where we have a time-dependent system b.run_solver will fail with an error from b.run_checks_solver if compute_times does not fully encompass the dataset times. End of explanation """ b.flip_constraint('compute_times', solve_for='compute_phases') b.set_value('compute_times', phoebe.linspace(0,5,501)) print(b.run_checks_solver()) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: This will always be the case when providing compute_phases when the dataset times cover more than a single cycle. Here we'll follow the advice from the error and provide compute_times instead. End of explanation """ _ = b.flip_constraint('compute_phases', solve_for='compute_times') """ Explanation: Now we'll just flip the constraint back for the remaining examples End of explanation """ b.set_value('solver_times', 'auto') b.set_value('compute_phases', phoebe.linspace(0,1,101)) b.set_value('mask_enabled', False) b.set_value('dperdt', 0.0) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: solver_times = 'auto' solver_times='auto' determines the times array under both conditions (solver_times='times' and solver_times='compute_times') and ultimately chooses whichever of the two is shorter. To see this, we'll stick with the no-mask, time-independent case and change the length of compute_phases to show the switch to the shorter of the available options. compute_times shorter End of explanation """ b.set_value('solver_times', 'auto') b.set_value('compute_phases', phoebe.linspace(0,1,2001)) b.set_value('mask_enabled', False) b.set_value('dperdt', 0.0) dataset_times = b.get_value('times', context='dataset') _ = plt.plot(times, np.ones_like(times)*1, 'k.') compute_times = b.get_value('compute_times', context='dataset') _ = plt.plot(compute_times, np.ones_like(compute_times)*2, 'b.') solver_times = b.parse_solver_times() _ = plt.plot(solver_times['lc01'], np.ones_like(solver_times['lc01'])*3, 'g.') b.run_compute(solver='nm_solver') _ = b.plot(show=True) """ Explanation: times shorter End of explanation """
tensorflow/tensorflow
tensorflow/lite/g3doc/models/modify/model_maker/image_classification.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 The TensorFlow Authors. End of explanation """ !sudo apt -y install libportaudio2 !pip install -q tflite-model-maker """ Explanation: Image classification with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lite/models/modify/model_maker/image_classification"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/models/modify/model_maker/image_classification.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/models/modify/model_maker/image_classification.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/tensorflow/tensorflow/lite/g3doc/models/modify/model_maker/image_classification.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> <td> <a href="https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1"><img src="https://www.tensorflow.org/images/hub_logo_32px.png" />See TF Hub model</a> </td> </table> The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow neural-network model to particular input data when deploying this model for on-device ML applications. This notebook shows an end-to-end example that utilizes this Model Maker library to illustrate the adaption and conversion of a commonly-used image classification model to classify flowers on a mobile device. Prerequisites To run this example, we first need to install several required packages, including Model Maker package that in GitHub repo. End of explanation """ import os import numpy as np import tensorflow as tf assert tf.__version__.startswith('2') from tflite_model_maker import model_spec from tflite_model_maker import image_classifier from tflite_model_maker.config import ExportFormat from tflite_model_maker.config import QuantizationConfig from tflite_model_maker.image_classifier import DataLoader import matplotlib.pyplot as plt """ Explanation: Import the required packages. End of explanation """ image_path = tf.keras.utils.get_file( 'flower_photos.tgz', 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz', extract=True) image_path = os.path.join(os.path.dirname(image_path), 'flower_photos') """ Explanation: Simple End-to-End Example Get the data path Let's get some images to play with this simple end-to-end example. Hundreds of images is a good start for Model Maker while more data could achieve better accuracy. End of explanation """ data = DataLoader.from_folder(image_path) train_data, test_data = data.split(0.9) """ Explanation: You could replace image_path with your own image folders. As for uploading data to colab, you could find the upload button in the left sidebar shown in the image below with the red rectangle. Just have a try to upload a zip file and unzip it. The root file path is the current path. <img src="https://storage.googleapis.com/download.tensorflow.org/models/tflite/screenshots/model_maker_image_classification.png" alt="Upload File" width="800" hspace="100"> If you prefer not to upload your images to the cloud, you could try to run the library locally following the guide in GitHub. Run the example The example just consists of 4 lines of code as shown below, each of which representing one step of the overall process. Step 1. Load input data specific to an on-device ML app. Split it into training data and testing data. End of explanation """ model = image_classifier.create(train_data) """ Explanation: Step 2. Customize the TensorFlow model. End of explanation """ loss, accuracy = model.evaluate(test_data) """ Explanation: Step 3. Evaluate the model. End of explanation """ model.export(export_dir='.') """ Explanation: Step 4. Export to TensorFlow Lite model. Here, we export TensorFlow Lite model with metadata which provides a standard for model descriptions. The label file is embedded in metadata. The default post-training quantization technique is full integer quantization for the image classification task. You could download it in the left sidebar same as the uploading part for your own use. End of explanation """ image_path = tf.keras.utils.get_file( 'flower_photos.tgz', 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz', extract=True) image_path = os.path.join(os.path.dirname(image_path), 'flower_photos') """ Explanation: After these simple 4 steps, we could further use TensorFlow Lite model file in on-device applications like in image classification reference app. Detailed Process Currently, we support several models such as EfficientNet-Lite* models, MobileNetV2, ResNet50 as pre-trained models for image classification. But it is very flexible to add new pre-trained models to this library with just a few lines of code. The following walks through this end-to-end example step by step to show more detail. Step 1: Load Input Data Specific to an On-device ML App The flower dataset contains 3670 images belonging to 5 classes. Download the archive version of the dataset and untar it. The dataset has the following directory structure: <pre> <b>flower_photos</b> |__ <b>daisy</b> |______ 100080576_f52e8ee070_n.jpg |______ 14167534527_781ceb1b7a_n.jpg |______ ... |__ <b>dandelion</b> |______ 10043234166_e6dd915111_n.jpg |______ 1426682852_e62169221f_m.jpg |______ ... |__ <b>roses</b> |______ 102501987_3cdb8e5394_n.jpg |______ 14982802401_a3dfb22afb.jpg |______ ... |__ <b>sunflowers</b> |______ 12471791574_bb1be83df4.jpg |______ 15122112402_cafa41934f.jpg |______ ... |__ <b>tulips</b> |______ 13976522214_ccec508fe7.jpg |______ 14487943607_651e8062a1_m.jpg |______ ... </pre> End of explanation """ data = DataLoader.from_folder(image_path) """ Explanation: Use DataLoader class to load data. As for from_folder() method, it could load data from the folder. It assumes that the image data of the same class are in the same subdirectory and the subfolder name is the class name. Currently, JPEG-encoded images and PNG-encoded images are supported. End of explanation """ train_data, rest_data = data.split(0.8) validation_data, test_data = rest_data.split(0.5) """ Explanation: Split it to training data (80%), validation data (10%, optional) and testing data (10%). End of explanation """ plt.figure(figsize=(10,10)) for i, (image, label) in enumerate(data.gen_dataset().unbatch().take(25)): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(image.numpy(), cmap=plt.cm.gray) plt.xlabel(data.index_to_label[label.numpy()]) plt.show() """ Explanation: Show 25 image examples with labels. End of explanation """ model = image_classifier.create(train_data, validation_data=validation_data) """ Explanation: Step 2: Customize the TensorFlow Model Create a custom image classifier model based on the loaded data. The default model is EfficientNet-Lite0. End of explanation """ model.summary() """ Explanation: Have a look at the detailed model structure. End of explanation """ loss, accuracy = model.evaluate(test_data) """ Explanation: Step 3: Evaluate the Customized Model Evaluate the result of the model, get the loss and accuracy of the model. End of explanation """ # A helper function that returns 'red'/'black' depending on if its two input # parameter matches or not. def get_label_color(val1, val2): if val1 == val2: return 'black' else: return 'red' # Then plot 100 test images and their predicted labels. # If a prediction result is different from the label provided label in "test" # dataset, we will highlight it in red color. plt.figure(figsize=(20, 20)) predicts = model.predict_top_k(test_data) for i, (image, label) in enumerate(test_data.gen_dataset().unbatch().take(100)): ax = plt.subplot(10, 10, i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(image.numpy(), cmap=plt.cm.gray) predict_label = predicts[i][0][0] color = get_label_color(predict_label, test_data.index_to_label[label.numpy()]) ax.xaxis.label.set_color(color) plt.xlabel('Predicted: %s' % predict_label) plt.show() """ Explanation: We could plot the predicted results in 100 test images. Predicted labels with red color are the wrong predicted results while others are correct. End of explanation """ model.export(export_dir='.') """ Explanation: If the accuracy doesn't meet the app requirement, one could refer to Advanced Usage to explore alternatives such as changing to a larger model, adjusting re-training parameters etc. Step 4: Export to TensorFlow Lite Model Convert the trained model to TensorFlow Lite model format with metadata so that you can later use in an on-device ML application. The label file and the vocab file are embedded in metadata. The default TFLite filename is model.tflite. In many on-device ML application, the model size is an important factor. Therefore, it is recommended that you apply quantize the model to make it smaller and potentially run faster. The default post-training quantization technique is full integer quantization for the image classification task. End of explanation """ model.export(export_dir='.', export_format=ExportFormat.LABEL) """ Explanation: See the image classification examples guide for more details about how to integrate the TensorFlow Lite model into mobile apps. This model can be integrated into an Android or an iOS app using the ImageClassifier API of the TensorFlow Lite Task Library. The allowed export formats can be one or a list of the following: ExportFormat.TFLITE ExportFormat.LABEL ExportFormat.SAVED_MODEL By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the label file as follows: End of explanation """ model.evaluate_tflite('model.tflite', test_data) """ Explanation: You can also evaluate the tflite model with the evaluate_tflite method. End of explanation """ config = QuantizationConfig.for_float16() """ Explanation: Advanced Usage The create function is the critical part of this library. It uses transfer learning with a pretrained model similar to the tutorial. The create function contains the following steps: Split the data into training, validation, testing data according to parameter validation_ratio and test_ratio. The default value of validation_ratio and test_ratio are 0.1 and 0.1. Download a Image Feature Vector as the base model from TensorFlow Hub. The default pre-trained model is EfficientNet-Lite0. Add a classifier head with a Dropout Layer with dropout_rate between head layer and pre-trained model. The default dropout_rate is the default dropout_rate value from make_image_classifier_lib by TensorFlow Hub. Preprocess the raw input data. Currently, preprocessing steps including normalizing the value of each image pixel to model input scale and resizing it to model input size. EfficientNet-Lite0 have the input scale [0, 1] and the input image size [224, 224, 3]. Feed the data into the classifier model. By default, the training parameters such as training epochs, batch size, learning rate, momentum are the default values from make_image_classifier_lib by TensorFlow Hub. Only the classifier head is trained. In this section, we describe several advanced topics, including switching to a different image classification model, changing the training hyperparameters etc. Customize Post-training quantization on the TensorFLow Lite model Post-training quantization is a conversion technique that can reduce model size and inference latency, while also improving CPU and hardware accelerator inference speed, with a little degradation in model accuracy. Thus, it's widely used to optimize the model. Model Maker library applies a default post-training quantization techique when exporting the model. If you want to customize post-training quantization, Model Maker supports multiple post-training quantization options using QuantizationConfig as well. Let's take float16 quantization as an instance. First, define the quantization config. End of explanation """ model.export(export_dir='.', tflite_filename='model_fp16.tflite', quantization_config=config) """ Explanation: Then we export the TensorFlow Lite model with such configuration. End of explanation """ model = image_classifier.create(train_data, model_spec=model_spec.get('mobilenet_v2'), validation_data=validation_data) """ Explanation: In Colab, you can download the model named model_fp16.tflite from the left sidebar, same as the uploading part mentioned above. Change the model Change to the model that's supported in this library. This library supports EfficientNet-Lite models, MobileNetV2, ResNet50 by now. EfficientNet-Lite are a family of image classification models that could achieve state-of-art accuracy and suitable for Edge devices. The default model is EfficientNet-Lite0. We could switch model to MobileNetV2 by just setting parameter model_spec to the MobileNetV2 model specification in create method. End of explanation """ loss, accuracy = model.evaluate(test_data) """ Explanation: Evaluate the newly retrained MobileNetV2 model to see the accuracy and loss in testing data. End of explanation """ inception_v3_spec = image_classifier.ModelSpec( uri='https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1') inception_v3_spec.input_image_shape = [299, 299] """ Explanation: Change to the model in TensorFlow Hub Moreover, we could also switch to other new models that inputs an image and outputs a feature vector with TensorFlow Hub format. As Inception V3 model as an example, we could define inception_v3_spec which is an object of image_classifier.ModelSpec and contains the specification of the Inception V3 model. We need to specify the model name name, the url of the TensorFlow Hub model uri. Meanwhile, the default value of input_image_shape is [224, 224]. We need to change it to [299, 299] for Inception V3 model. End of explanation """ model = image_classifier.create(train_data, validation_data=validation_data, epochs=10) """ Explanation: Then, by setting parameter model_spec to inception_v3_spec in create method, we could retrain the Inception V3 model. The remaining steps are exactly same and we could get a customized InceptionV3 TensorFlow Lite model in the end. Change your own custom model If we'd like to use the custom model that's not in TensorFlow Hub, we should create and export ModelSpec in TensorFlow Hub. Then start to define ModelSpec object like the process above. Change the training hyperparameters We could also change the training hyperparameters like epochs, dropout_rate and batch_size that could affect the model accuracy. The model parameters you can adjust are: epochs: more epochs could achieve better accuracy until it converges but training for too many epochs may lead to overfitting. dropout_rate: The rate for dropout, avoid overfitting. None by default. batch_size: number of samples to use in one training step. None by default. validation_data: Validation data. If None, skips validation process. None by default. train_whole_model: If true, the Hub module is trained together with the classification layer on top. Otherwise, only train the top classification layer. None by default. learning_rate: Base learning rate. None by default. momentum: a Python float forwarded to the optimizer. Only used when use_hub_library is True. None by default. shuffle: Boolean, whether the data should be shuffled. False by default. use_augmentation: Boolean, use data augmentation for preprocessing. False by default. use_hub_library: Boolean, use make_image_classifier_lib from tensorflow hub to retrain the model. This training pipeline could achieve better performance for complicated dataset with many categories. True by default. warmup_steps: Number of warmup steps for warmup schedule on learning rate. If None, the default warmup_steps is used which is the total training steps in two epochs. Only used when use_hub_library is False. None by default. model_dir: Optional, the location of the model checkpoint files. Only used when use_hub_library is False. None by default. Parameters which are None by default like epochs will get the concrete default parameters in make_image_classifier_lib from TensorFlow Hub library or train_image_classifier_lib. For example, we could train with more epochs. End of explanation """ loss, accuracy = model.evaluate(test_data) """ Explanation: Evaluate the newly retrained model with 10 training epochs. End of explanation """
Olsthoorn/TransientGroundwaterFlow
readthedocs/Course2016_jupyter/docs/source/PartialPenetration.ipynb
gpl-3.0
from scipy.special import k0 # bessel function K0 import numpy as np def dWpp(r, z, a, b, D): """Returns additional drawdown caused by partial penetration Solution by Hantush. See Kruseman and De Ridder (1994), p159. The real extra drawdown is Q/(2 pi kD) * dW Parmeters: ---------- r : distance from the well z : distance from the bottom of the aquifer a : distance of top of screen to bottom of aquifer b : distance of bottom of creen to bottom of aquifer Returns: -------- dW : ndarray size (Nz, Nr) containing all combinations of z and r Extra drawdown in terms of well function, which has still to be multiplied by Q/(2 pi kD). """ tol = 1e-3 pi = np.pi d = a - b r = np.array(r.ravel(), dtype = float)[np.newaxis,:] z = np.array(z.ravel(), dtype = float)[:,np.newaxis] alpha= pi * a/D beta = pi * b/D zeta = pi * z/D rho = pi * r/D delta= pi * d/D maxiter = 500 Dw = (z * r) * 0. dw0 = np.ones(Dw.shape) for n in np.arange(1.,maxiter+1.): dw1 = dw0 dw0 = (np.sin(n * alpha) - np.sin(n * beta)) * np.cos(n * zeta) * k0( n * rho) / n Dw += dw0 #print(np.sum(np.abs(dw1 + dw0))) if np.sum(np.abs(dw1 + dw0))< tol: break print("Iterations: {}".format(n)) return (2./delta) * Dw """ Explanation: Partial penetration Thicker aquifers are mostly only partially penetrated by well screens. This is to save drilling and installation expences. When the aim of wells is to pump dry an excavation, shorter well screens may even reduce the amount of water to be pumped while enhancing the required shallow drawdown at the bottom of the excavation; this also saves water and energy. With a fully penetrating well screen, the flow lines towards the well are essentially all virtually parallel and horizontal. This is also the case with partially penetrating well at distances larger than about 1.5 times the aquifer thickness. But at closer distances, the streamlines must converge towards the smaller screen. This causes vertical velocity components and larger velocities near the screen and, therefore, an extra loss of head. This head loss due to converging streamlines is the extra drawdown due to partial penetration. If one compares the flow in the situation with a fully penetrating well screen with that of a partially penetrating screen at the same spot, one imagins that to obtain the flow in the case of the partially penetrating screen, one can take the case of the fully penetrating screen and superimpose above and below the partially penetrating screen an injection that makes the combined flow at r=0 above and below the screen equal zero. At the same time, this injection is extra extracted from the partially penetrating screen itself. Hantush has developed an analytical solution for this additional flow, which can be superimposed on that of the case with a fully penetrating screen. This extra drawdown has to be added to the solution for the fully penetrating screen, no matter if this the flow is steady or transient. Of course, there is always a transient phase in the vicinity of the screen but because its effect is only felt within a short distancefrom the well, this transient phase so short that it can be ignored relative to the transients of the drawdown at larger distances, and especially also with respect to the transients in the case of water table aquifers where drawdown is determined by specific yield which is about two oerders slower than transiens determined by the elastic storage. Elastic storage works simultaneously with specific yield in water table aquifers, but is completely masked by the slow transients that the much larger specific yield causes. The situation envisioned by Hantush (1955) is shown in the figure. The parameters are used in his formula below. For the outcome it does not matter whether distances are measured from the top of from the bottom of the aquifer, but one has to be consistent. Hantush's solution for the efect of partial penetration is as follows: $$ s_{partialy} - s_{fully} = \frac Q {2 \pi kD} \times \frac {2 D} {\pi d } \sum_{n=1}^{\infty} \frac 1 n \left( \sin \left( \frac {n \pi a} D \right) - \sin \left( \frac {n \pi b} D \right) \right) \cos \left( \frac {n \pi z} D \right) K_0 \left( \frac {n \pi r} D \right) $$ This solution can be readily implemented in Python, as is shown below: End of explanation """ import matplotlib.pylab as plt kD = 600. S = 0.001 D = 50. a = 40. b = 30. r0 = 0.3 r = np.logspace(np.log10(r0), 2., 41) z = np.linspace(0., D, 51) dw = dWpp(r, z, a, b, D) fig =plt.figure() ax = fig.add_subplot(111) ax.set(xlabel='r [m]', ylabel='z [m]', title='Additional drawdown due to partial screen penetraton') ax.contour(r, z, dw, 50) plt.show() """ Explanation: Let's apply this solution and see if it works. First we show the solution itself. This is the flow (head) that has to be superimposed to the situation with a fully penetrating screen. The head contours show 1. There is not only extraction from the screen but also injection above and below the screen, which, if superimposed to the case of the fully penetrating screen should yield no flow there. 2. There is not flow at some distance from the screen. In practice, one takes 1.5 times the aquifer thickness for this distance. If vertical anisotropy is large, this should be taken into account, then $r>1.5 D \sqrt{k_r / k_z }$ The code below shows an example in which the solution is used: It is important to remark that a large number of terms (namely 220) was necessary to obtain the required accuracy. This implies that it is not easy to get the correct results by adding just a few terms by hand. End of explanation """ from scipy.special import expi def W(u): return -expi(-u) # Theis well function as was done earlier u = lambda r, t : r**2 * S / (4 * kD * t) # the argument u """ Explanation: As was said, it is difficult to see wether this result is correct. Therefore we'll add the drawdown due to a fully penetrating well to see whether the contours fo the drawdown near the screen concentrates around it and whether the flow above and below the partially penetrating screen is indeed zero. To add the drawdown due to a fully penetrating well, we'll use that computed by the Theis formula, which we have at our disposition. First define the Theis well function (once more) and also $u$ as a function of $r$ and $t$ End of explanation """ Q = 1200 t = 1.0 s = Q / (4 * np.pi * kD) * W(u(r,t)) + Q/(2 * np.pi * kD) * dWpp(r, z, a, b, D) fig1 =plt.figure() ax1 = fig1.add_subplot(111) ax1.set(xlabel='r [m]', ylabel='z [m]', title='Additional drawdown due to partial screen penetraton') ax1.contour(r, z, s, 50) plt.show() """ Explanation: We now superimpose the Theis drawdown and the extra drawdown due to partial penetration. Note: In the addition below, we implicitly make use of Python's broadcasting when we add the vector obtained for the fully penetrating drawdown to the array obtained from the extra partially penetrating drawdown. Numpy matches the different shapes for us and carries out the addition without complaints. (You can check the shapes by executing s.shape, dWpp($\cdots$).shape etc). End of explanation """ import pdb r = np.array([r0]) # distance to the well z = np.linspace(b, a, 21) # elevation ds = Q/(2 * np.pi * kD) * dWpp(r, z, a, b, D) # partial penetration print('mean of dpp along the screen: {:.2f} m'.format(np.mean(ds))) print('max of dpp along the screen : {:.2f} m'.format(np.max(ds))) print('dpp along for 21 points the screen:') print(' z dpp(z)') for zz, dds in zip(z, ds): print("{:10.2f} {:10.3f}".format(zz, dds[0])) print("Drawdown by fully penetrating schreen {:.2f} m".format(Q / (4 * np.pi * kD) * W(u(r0,t)))) """ Explanation: This result shows that the contours indeed concentrate around the screen and only around the screen. The figure also shows that the head contours are perpendicular to the impervious top and bottom of the aquifer, as well as to the center of the well below and above the partially penetrating screen, as expected. The extra drawdown in the screen itself may be computed by using a value of $z$ an $r$ that corresponds to the center of the screen. That is $z = (b+a)/2$ and $r=r0$, or take the average for a number of points along the screen. The latter is better, because Hantush derived his formula for a uniform extraction along the screen. This implies that the head varies along the screen, at least somewhat, which does not correspond with a reality, where the head rather than the inflow is constant along the screen. Therefore an average for points along the screen is preferable. But the difference is expected to be negligeable in practice. We an investigate this claim right away, using the available code. End of explanation """
gabicfa/RedesSociais
encontro02/3-bellman.ipynb
gpl-3.0
import sys sys.path.append('..') import socnet as sn """ Explanation: Encontro 02, Parte 3: Algoritmo de Bellman-Ford Este guia foi escrito para ajudar você a atingir os seguintes objetivos: implementar o algoritmo de Bellman-Ford; praticar o uso da biblioteca da disciplina. Primeiramente, vamos importar a biblioteca: End of explanation """ sn.graph_width = 320 sn.graph_height = 180 """ Explanation: A seguir, vamos configurar as propriedades visuais: End of explanation """ g = sn.load_graph('3-bellman.gml', has_pos=True) for n, m in g.edges(): g.edge[n][m]['label'] = g.edge[n][m]['c'] sn.show_graph(g, elab=True) """ Explanation: Por fim, vamos carregar e visualizar um grafo: End of explanation """ from math import inf, isinf s = 0 for n in g.nodes(): g.node[n]['d'] = inf g.node[s]['d'] = 0 for i in range(g.number_of_nodes() - 1): for n, m in g.edges(): d = g.node[n]['d'] + g.edge[n][m]['c'] if g.node[m]['d'] > d: g.node[m]['d'] = d for n in g.nodes(): print('distância de {}: {}'.format(n, g.node[n]['d'])) """ Explanation: Passeios de custo mínimo O arquivo atribui c às arestas. Formalmente, esse atributo é uma função que mapeia pares de nós a reais: $c \colon N \times N \rightarrow \mathbb{R}$. O custo de um passeio $\langle n_0, n_1, \ldots, n_{k-1} \rangle$ é $\sum^{k-2}{i=0} c(n_i, n{i+1})$. Um passeio de origem $s$ e destino $t$ tem custo mínimo se não existe outro passeio de origem $s$ e destino $t$ de custo menor. Note que podem existir múltiplos passeios de custo mínimo. A distância ponderada de $s$ a $t$ é o custo mínimo de um passeio de origem $s$ e destino $t$. Por completude, dizemos que a distância ponderada de $s$ a $t$ é $\infty$ se não existe passeio de origem $s$ e destino $t$. Algoritmo de Bellman-Ford Dado um nó $s$, podemos eficientemente calcular as distâncias ponderadas desse a todos os outros nós do grafo usando o algoritmo de Bellman-Ford. A ideia desse algoritmo é diferente da ideia do algoritmo de busca em largura, mas também é simples: inicializamos a distância de $s$ como $0$, inicializamos a distância dos outros nós como $\infty$ e verificamos todas as arestas. Para cada aresta $(n, m)$, se a distância de $m$ for maior que a distância de $n$ mais o custo de $(n, m)$, essa soma passa a ser a nova distância de $m$. É possível demonstrar matematicamente esse laço precisa ser repetido não mais que $|N|-1$ vezes, onde $|N|$ é a quantidade de nós. End of explanation """ from math import inf, isinf def snapshot(g, frames): for n in g.nodes(): if isinf(g.node[n]['d']): g.node[n]['label'] = '∞' else: g.node[n]['label'] = str(g.node[n]['d']) frame = sn.generate_frame(g, nlab=True) frames.append(frame) red = (255, 0, 0) blue = (0, 0, 255) frames = [] s = 0 for n in g.nodes(): g.node[n]['d'] = inf g.node[s]['d'] = 0 sn.reset_node_colors(g) sn.reset_edge_colors(g) snapshot(g, frames) for i in range(g.number_of_nodes() - 1): for n, m in g.edges(): d = g.node[n]['d'] + g.edge[n][m]['c'] g.edge[n][m]['color'] = red # snapshot(g, frames) if g.node[m]['d'] > d: g.node[m]['d'] = d g.edge[n][m]['color'] = blue snapshot(g, frames) g.edge[n][m]['color'] = sn.edge_color snapshot(g, frames) sn.reset_edge_colors(g) sn.show_animation(frames) """ Explanation: No entanto, essa demonstração depende de certas hipóteses em relação ao grafo. Tenho uma má e uma boa notícia: a má é que existem grafos em que o algoritmo não funciona, ou seja, devolve uma resposta incorreta; a boa é que, nos grafos em que ele funciona, os passeios de custo mínimo são caminhos de custo mínimo. Exercício 1 Que grafos são esses? Os gráficoso nos quais o algoritmo não funciona são os grafos fechados cujas arestas possuem apenas valores negativos. Isso acontece pois, nesse caso, o código ficaria em loop infinito ja que esse caminho seria sempre o menor de todos (o mais negativo). Exercício 2 Monte uma visualização do algoritmo de Bellman-Ford. End of explanation """
UCSD-E4E/radio_collar_tracker_drone
doc/Precision Analysis.ipynb
gpl-3.0
import numpy as np import matplotlib.pyplot as plt; plt.ion() from scipy.optimize import least_squares from scipy import stats as st """ Explanation: This notebook presents the techniques of displaying the precision of the Radio Telemetry Tracker system. End of explanation """ def receivePowerModel(d, k, n): return k - 10 * n * np.log10(d) """ Explanation: Model Estimation To determine the location of the radio transmitter, we need to find a relationship between the measurement location and the radio amplitude measurement. We use the radio signal path loss model: $L = 10nlog_{10}(d)$. We can then rewrite this in terms of receive and transmit power, $R$ and $P$: $R = P - 10nlog_{10}(d) + C$, where $C$ represents receive losses not due to path loss. In theory, $n$ is 2 for path loss in a vacuum, but in practice, we see $n$ range from $2$ to $6$. However, we cannot in principle differentiate between P and C, as they are summed together, so we can simply combine them into a single parameter $k$: $R = k - 10nlog_{10}(d)$ End of explanation """ vx = np.array([[5, 1, 0], [-1, 5, 0], [-5, -1, 0], [1, -5, 0]]) tx = (477954, 3638577, 11, 'S') txp = 100 n = 4 C = 1 d = 1000 tx_loc = np.array([tx[0], tx[1], 0]) dx_loc = np.array([tx[0] - 100, tx[1], 30]) s_per_leg = 30 c_loc = dx_loc D_p = [] for leg in range(4): for s in range(s_per_leg): c_loc += vx[leg,:] dist = np.linalg.norm(tx_loc - c_loc) R = receivePowerModel(dist, txp - C, n) D_p.append([c_loc[0], c_loc[1], c_loc[2], R]) simulated_D = np.array(D_p) plt.scatter(simulated_D[:,0], simulated_D[:,1], c = simulated_D[:,3]) plt.colorbar(label="Ping Power") plt.xlabel("Easting (m)") plt.ylabel("Northing (m)") plt.title("Simulated Data with No Noise") plt.show() """ Explanation: When we receive data, we can extract the following information: drone location in x, y, and z, and transmitter receive power. We can then put this information into a matrix $D = \begin{bmatrix}x_d & y_d & z_d & R\end{bmatrix}$, where $x_d$ is the column vector of drone x coordinates, $y_d$ is the column vector of drone y coordinates, $z_d$ is the column vector of drone z coordinates, and $R$ is the column vector of receive powers. We generate a simulated dataset below: End of explanation """ def residuals(params, data): tx = params[0] ty = params[1] t_loc = np.array([tx, ty, 0]) k = params[2] n = params[3] R = data[:,3] d_loc = data[:,0:3] residuals = np.zeros(len(R)) for i in range(len(R)): residuals[i] = R[i] - receivePowerModel(np.linalg.norm(t_loc - d_loc[i,:]), k, n) return residuals initialGuess = np.array([np.mean(simulated_D[:,0]), np.mean(simulated_D[:,1]), np.max(simulated_D[:,3]), 4]) results = least_squares(residuals, initialGuess, kwargs={'data':simulated_D}) print(results.x) print("Lateral error: %f" % np.linalg.norm(tx_loc - np.array([results.x[0], results.x[1], 0]))) print("k error: %f" % (txp - C - results.x[2])) print("n error: %f" % (n - results.x[3])) """ Explanation: To localize the transmitter, we simply take the measurements in $D$ and fit them to the model in receivePowerModel End of explanation """ c_loc = dx_loc D_p = [] s_xy = np.sqrt(3) s_z = np.sqrt(0.5) s_R = np.sqrt(5) for leg in range(4): for s in range(s_per_leg): c_loc += vx[leg,:] dist = np.linalg.norm(tx_loc - c_loc) R = receivePowerModel(dist, txp - C, n) D_p.append([c_loc[0] + np.random.normal(0,s_xy), c_loc[1] + np.random.normal(0,s_xy), c_loc[2] + np.random.normal(0,s_z), R + np.random.normal(0,s_R)]) simulated_D_error = np.array(D_p) plt.scatter(simulated_D_error[:,0], simulated_D_error[:,1], c = simulated_D_error[:,3]) plt.colorbar(label="Ping Power") plt.xlabel("Easting (m)") plt.ylabel("Northing (m)") plt.title("Simulated Data with Noise") plt.show() initialGuess = np.array([np.mean(simulated_D_error[:,0]), np.mean(simulated_D_error[:,1]), np.max(simulated_D_error[:,3]), 4]) results = least_squares(residuals, initialGuess, kwargs={'data':simulated_D_error}) print(results.x) print("Lateral error: %f" % np.linalg.norm(tx_loc - np.array([results.x[0], results.x[1], 0]))) print("k error: %f" % (txp - C - results.x[2])) print("n error: %f" % (n - results.x[3])) """ Explanation: As shown above, the estimated result is nearly identical to the simulated parameters, which should be the case, as the only source of noise here is from quantization error. In order to accurately simulate the data from the drone, we need to add some error to the measurements. In this case, we will add Gaussian noise to each measurement. For the $x$ and $y$ coordinates, we will add Gaussian noise with $\mu = 0$ and $\sigma^2 = 3$. For the $z$ coordinate, we will add Gaussian noise with $\mu = 0$ and $\sigma^2 = 0.5$. For the $R$ measurement, we will add Gaussian noise with $\mu = 0$ and $\sigma^2 = 5$. End of explanation """ width = 100 dist = 50 field = np.zeros((2 * width, 2 * width)) origin = np.array([width, width]) stddev = 0.4 * dist mean = dist rv = st.norm(loc = mean, scale = stddev) for x in range(field.shape[0]): for y in range(field.shape[1]): r = np.linalg.norm(np.array([x, y]) - origin) field[x, y] = rv.pdf(r) fig = plt.figure() plt.imshow(field, extent=(-width, width, -width, width), origin='lower') plt.colorbar() plt.scatter(0, 0, marker='^', color='red') cir = plt.Circle((0, 0), radius=dist, fill=False, edgecolor='red') fig.gca().add_artist(cir) plt.xlabel('Easting (m)') plt.ylabel('Northing (m)') plt.title('Certainty Distribution for a Single Ping') plt.show() """ Explanation: Precision Visualization In order to provide a metric of how certain our estimate is, we need to provide a way to visualize the precision of our estimate. Naive Visualization The easiest way to do this is to assume a distribution over the distance from each ping to the transmitter. We assume that the distance calculated for each ping has additive Gaussian noise with a standard deviation of 40% of the calculated range. Because the location of the transmitter is calculated from multiple independent measurements, the probability of the transmitter being at a particular location is equal to the product of the probability of each distance calculation. We can then use log probability to simplify the calculations. For a single ping, we demonstrate the probability heatmap below. This is a simulated ping at $(0, 0)$, with a calculated distance of 50 meters. The calculated distance is represented by the red circle, and the ping location is represented by the red triangle. End of explanation """ width = 120 dist = 50 pings = [np.array([-dist, 0]), np.array([0, -dist]), np.array([.7*dist, .7*dist])] field = np.zeros((2 * width, 2 * width)) origin = np.array([width, width]) stddev = 0.4 * dist mean = dist rv = st.norm(loc = mean, scale = stddev) for x in range(field.shape[0]): for y in range(field.shape[1]): for ping in pings: r = np.linalg.norm(np.array([x, y]) - origin - ping) field[x, y] += np.log10(rv.pdf(r)) fig1 = plt.figure() plt.imshow(np.power(10, field), extent=(-width, width, -width, width), origin='lower') plt.colorbar() for ping in pings: plt.scatter(ping[0], ping[1], marker='^', color='red') cir = plt.Circle(ping, radius=dist, fill=False, edgecolor='red') fig1.gca().add_artist(cir) plt.xlabel('Easting (m)') plt.ylabel('Northing (m)') plt.title('Certainty Distribution for a Three Pings') plt.show() """ Explanation: For multiple pings, we simply sum the log probability together. The below code simulates three pings, one at $(-50, 0)$, one at $(0, -50)$, and one at $(35, 35)$. Each has a calculated distance of 50 meters, with the distance again represented by the red circles, and ping locations represented by the red triangles. End of explanation """ def distancePowerModel(R, k, n): return np.power(10, (k - R) / (10 * n)) simulated_D_error new_D = simulated_D_error[simulated_D_error[:,3] > 20,:] tx_loc = results.x[0:2] n = results.x[3] k = results.x[2] resolution = 0.25 #px per meter border = 20 # meter max_x = max(np.max(simulated_D_error[:,0]), tx_loc[0]) + border min_x = min(np.min(simulated_D_error[:,0]), tx_loc[0]) - border max_y = max(np.max(simulated_D_error[:,1]), tx_loc[1]) + border min_y = min(np.min(simulated_D_error[:,1]), tx_loc[1]) - border # origin is top left, 0.5 px / m resolution field = np.zeros((int((max_x - min_x) * resolution), int((max_y - min_y) * resolution))) origin = np.array([max_x, min_y]) means = [distancePowerModel(R, k, n) for R in new_D[:,3]] rv = [st.norm(loc = d, scale = 0.4 * d) for d in means] for x in range(field.shape[0]): for y in range(field.shape[1]): px_loc = origin + np.array([-x, y]) / resolution for ping_idx in range(len(rv)): distance = np.linalg.norm(px_loc - new_D[ping_idx,0:2]) if distance < 2 * means[ping_idx]: field[x, y] += np.log10(rv[ping_idx].pdf(distance)) plt.imshow(np.power(10, field), extent=(min_x, max_x, min_y, max_y), origin="lower") tx_loc tx_loc """ Explanation: In order to generate a heatmap for a dataset, we need to first determine the appropriate heatmap area. As a prerequisite, we must know the estimated transmitter location and ping locations. Because the transmitter location might not be within the polygon that encloses all the ping locations, it is essential to take the transmitter location into account when generating the heatmap area. A simple way to do this would be to take the maximum extents of both estimated transmitter and ping locations. We can then use the same technique as above to generate the heatmap. In order to generate the distances from the data, we need to invert the receive power model, which becomes $d = 10^\frac{k - R}{10n}$ End of explanation """
nikodtbVf/aima-si
search.ipynb
mit
from search import * """ Explanation: Solving problems by Searching This notebook serves as supporting material for topics covered in Chapter 3 - Solving Problems by Searching and Chapter 4 - Beyond Classical Search from the book Artificial Intelligence: A Modern Approach. This notebook uses implementations from search.py module. Let's start by importing everything from search module. End of explanation """ %psource Problem """ Explanation: Review Here, we learn about problem solving. Building goal-based agents that can plan ahead to solve problems, in particular navigation problem / route finding problem. First, we will start the problem solving by precicly defining problems and their solutions. We will look at several general-purpose search algorithms. Broadly, search algorithms are classified into two types: Uninformed search algorithms: Search algorithms which explores the search space without having any information aboout the problem other than its definition. Examples: Breadth First Search Depth First Search Depth Limited Search Iterative Deepening Search Informed search algorithms: These type of algorithms leverage any information (hueristics, path cost) on the problem to search through the search space to find the solution efficiently. Examples: Best First Search Uniform Cost Search A* Search Recursive Best First Search Don't miss the visualisations of these algorithms solving route-finding problem defined on romania map at the end of this notebook. Problem Let's see how we define a Problem. Run the next cell to see how abstract class Problem is defined in the search module. End of explanation """ %psource GraphProblem """ Explanation: The Problem class has six methods. __init__(self, initial, goal) : This is what is called a constructor and is the first method called when you create an instance of class. initial specifies the initial state of our search problem. It represents the start state from where our agent begins its task of exploration to find the goal state(s) which is given in the goal parameter. actions(self, state) : This method returns all the possible actions agent can execute in the given state state. result(self, state, action) : This returns the resulting state if action action is taken in the state state. This Problem class only deals with deterministic outcomes. So we know for sure what every action in a state would result to. goal_test(self, state) : Given a graph state, it checks if it is a terminal state. If the state is indeed a goal state, value of True is returned. Else, of course, False is returned. path_cost(self, c, state1, action, state2) : Return the cost of the path that arrives at state2 as a result of taking action from state1, assuming total cost of c to get up to state1. value(self, state) : This acts as a bit of extra information in problems where we try to optimize a value when we cannot do a goal test. We will use the abstract class Problem to define out real problem named GraphProblem. You can see how we defing GraphProblem by running the next cell. End of explanation """ romania_map = UndirectedGraph(dict( Arad=dict(Zerind=75, Sibiu=140, Timisoara=118), Bucharest=dict(Urziceni=85, Pitesti=101, Giurgiu=90, Fagaras=211), Craiova=dict(Drobeta=120, Rimnicu=146, Pitesti=138), Drobeta=dict(Mehadia=75), Eforie=dict(Hirsova=86), Fagaras=dict(Sibiu=99), Hirsova=dict(Urziceni=98), Iasi=dict(Vaslui=92, Neamt=87), Lugoj=dict(Timisoara=111, Mehadia=70), Oradea=dict(Zerind=71, Sibiu=151), Pitesti=dict(Rimnicu=97), Rimnicu=dict(Sibiu=80), Urziceni=dict(Vaslui=142))) romania_map.locations = dict( Arad=(91, 492), Bucharest=(400, 327), Craiova=(253, 288), Drobeta=(165, 299), Eforie=(562, 293), Fagaras=(305, 449), Giurgiu=(375, 270), Hirsova=(534, 350), Iasi=(473, 506), Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537), Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410), Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350), Vaslui=(509, 444), Zerind=(108, 531)) """ Explanation: Now it's time to define our problem. We will define it by passing initial, goal, graph to GraphProblem. So, our problem is to find the goal state starting from the given initial state on the provided graph. Have a look at our romania_map, which is an Undirected Graph containing a dict of nodes as keys and neighbours as values. End of explanation """ romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) """ Explanation: It is pretty straight forward to understand this romania_map. The first node Arad has three neighbours named Zerind, Sibiu, Timisoara. Each of these nodes are 75, 140, 118 units apart from Arad respectively. And the same goes with other nodes. And romania_map.locations contains the positions of each of the nodes. We will use the straight line distance (which is different from the one provided in romania_map) between two cities in algorithms like A*-search and Recursive Best First Search. Define a problem: Hmm... say we want to start exploring from Arad and try to find Bucharest in our romania_map. So, this is how we do it. End of explanation """ romania_locations = romania_map.locations print(romania_locations) """ Explanation: Romania map visualisation Let's have a visualisation of Romania map [Figure 3.2] from the book and see how different searching algorithms perform / how frontier expands in each search algorithm for a simple problem named romania_problem. Have a look at romania_locations. It is a dictionary defined in search module. We will use these location values to draw the romania graph using networkx. End of explanation """ %matplotlib inline import networkx as nx import matplotlib.pyplot as plt from matplotlib import lines from ipywidgets import interact import ipywidgets as widgets from IPython.display import display import time """ Explanation: Let's start the visualisations by importing necessary modules. We use networkx and matplotlib to show the map in notebook and we use ipywidgets to interact with the map to see how the searching algorithm works. End of explanation """ # initialise a graph G = nx.Graph() # use this while labeling nodes in the map node_labels = dict() # use this to modify colors of nodes while exploring the graph. # This is the only dict we send to `show_map(node_colors)` while drawing the map node_colors = dict() for n, p in romania_locations.items(): # add nodes from romania_locations G.add_node(n) # add nodes to node_labels node_labels[n] = n # node_colors to color nodes while exploring romania map node_colors[n] = "white" # we'll save the initial node colors to a dict to use later initial_node_colors = dict(node_colors) # positions for node labels node_label_pos = {k:[v[0],v[1]-10] for k,v in romania_locations.items()} # use thi whiel labeling edges edge_labels = dict() # add edges between cities in romania map - UndirectedGraph defined in search.py for node in romania_map.nodes(): connections = romania_map.get(node) for connection in connections.keys(): distance = connections[connection] # add edges to the graph G.add_edge(node, connection) # add distances to edge_labels edge_labels[(node, connection)] = distance """ Explanation: Let's get started by initializing an empty graph. We will add nodes, place the nodes in their location as shown in the book, add edges to the graph. End of explanation """ def show_map(node_colors): # set the size of the plot plt.figure(figsize=(18,13)) # draw the graph (both nodes and edges) with locations from romania_locations nx.draw(G, pos = romania_locations, node_color = [node_colors[node] for node in G.nodes()]) # draw labels for nodes node_label_handles = nx.draw_networkx_labels(G, pos = node_label_pos, labels = node_labels, font_size = 14) # add a white bounding box behind the node labels [label.set_bbox(dict(facecolor='white', edgecolor='none')) for label in node_label_handles.values()] # add edge lables to the graph nx.draw_networkx_edge_labels(G, pos = romania_locations, edge_labels=edge_labels, font_size = 14) # add a legend white_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="white") orange_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="orange") red_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="red") gray_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="gray") plt.legend((white_circle, orange_circle, red_circle, gray_circle), ('Un-explored', 'Frontier', 'Currently exploring', 'Explored'), numpoints=1,prop={'size':16}, loc=(.8,.75)) # show the plot. No need to use in notebooks. nx.draw will show the graph itself. plt.show() """ Explanation: We have completed building our graph based on romania_map and its locations. It's time to display it here in the notebook. This function show_map(node_colors) helps us do that. We will be calling this function later on to display the map at each and every interval step while searching using variety of algorithms from the book. End of explanation """ show_map(node_colors) """ Explanation: We can simply call the function with node_colors dictionary object to display it. End of explanation """ def final_path_colors(problem, solution): "returns a node_colors dict of the final path provided the problem and solution" # get initial node colors final_colors = dict(initial_node_colors) # color all the nodes in solution and starting node to green final_colors[problem.initial] = "green" for node in solution: final_colors[node] = "green" return final_colors def display_visual(user_input, algorithm=None, problem=None): if user_input == False: def slider_callback(iteration): # don't show graph for the first time running the cell calling this function try: show_map(all_node_colors[iteration]) except: pass def visualize_callback(Visualize): if Visualize is True: button.value = False global all_node_colors iterations, all_node_colors, node = algorithm(problem) solution = node.solution() all_node_colors.append(final_path_colors(problem, solution)) slider.max = len(all_node_colors) - 1 for i in range(slider.max + 1): slider.value = i # time.sleep(.5) slider = widgets.IntSlider(min=0, max=1, step=1, value=0) slider_visual = widgets.interactive(slider_callback, iteration = slider) display(slider_visual) button = widgets.ToggleButton(value = False) button_visual = widgets.interactive(visualize_callback, Visualize = button) display(button_visual) if user_input == True: node_colors = dict(initial_node_colors) if algorithm == None: algorithms = {"Breadth First Tree Search": breadth_first_tree_search, "Breadth First Search": breadth_first_search, "Uniform Cost Search": uniform_cost_search, "A-star Search": astar_search} algo_dropdown = widgets.Dropdown(description = "Search algorithm: ", options = sorted(list(algorithms.keys())), value = "Breadth First Tree Search") display(algo_dropdown) def slider_callback(iteration): # don't show graph for the first time running the cell calling this function try: show_map(all_node_colors[iteration]) except: pass def visualize_callback(Visualize): if Visualize is True: button.value = False problem = GraphProblem(start_dropdown.value, end_dropdown.value, romania_map) global all_node_colors if algorithm == None: user_algorithm = algorithms[algo_dropdown.value] # print(user_algorithm) # print(problem) iterations, all_node_colors, node = user_algorithm(problem) solution = node.solution() all_node_colors.append(final_path_colors(problem, solution)) slider.max = len(all_node_colors) - 1 for i in range(slider.max + 1): slider.value = i # time.sleep(.5) start_dropdown = widgets.Dropdown(description = "Start city: ", options = sorted(list(node_colors.keys())), value = "Arad") display(start_dropdown) end_dropdown = widgets.Dropdown(description = "Goal city: ", options = sorted(list(node_colors.keys())), value = "Fagaras") display(end_dropdown) button = widgets.ToggleButton(value = False) button_visual = widgets.interactive(visualize_callback, Visualize = button) display(button_visual) slider = widgets.IntSlider(min=0, max=1, step=1, value=0) slider_visual = widgets.interactive(slider_callback, iteration = slider) display(slider_visual) """ Explanation: Voila! You see, the romania map as shown in the Figure[3.2] in the book. Now, see how different searching algorithms perform with our problem statements. Searching algorithms visualisations In this section, we have visualisations of the following searching algorithms: Breadth First Tree Search - Implemented Depth First Tree Search Depth First Graph Search Breadth First Search - Implemented Best First Graph Search Uniform Cost Search - Implemented Depth Limited Search Iterative Deepening Search A*-Search - Implemented Recursive Best First Search We add the colors to the nodes to have a nice visualisation when displaying. So, these are the different colors we are using in these visuals: * Un-explored nodes - <font color='black'>white</font> * Frontier nodes - <font color='orange'>orange</font> * Currently exploring node - <font color='red'>red</font> * Already explored nodes - <font color='gray'>gray</font> Now, we will define some helper methods to display interactive buttons ans sliders when visualising search algorithms. End of explanation """ def tree_search(problem, frontier): """Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Don't worry about repeated paths to a state. [Figure 3.7]""" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] node_colors = dict(initial_node_colors) frontier.append(Node(problem.initial)) node_colors[Node(problem.initial).state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) while frontier: node = frontier.pop() # modify the currently searching node to red node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test(node.state): # modify goal node to green after reaching the goal node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, node) frontier.extend(node.expand(problem)) for n in node.expand(problem): node_colors[n.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) # modify the color of explored nodes to gray node_colors[node.state] = "gray" iterations += 1 all_node_colors.append(dict(node_colors)) return None def breadth_first_tree_search(problem): "Search the shallowest nodes in the search tree first." iterations, all_node_colors, node = tree_search(problem, FIFOQueue()) return(iterations, all_node_colors, node) """ Explanation: Breadth first tree search We have a working implementation in search module. But as we want to interact with the graph while it is searching, we need to modify the implementation. Here's the modified breadth first tree search. End of explanation """ all_node_colors = [] romania_problem = GraphProblem('Arad', 'Fagaras', romania_map) display_visual(user_input = False, algorithm = breadth_first_tree_search, problem = romania_problem) """ Explanation: Now, we use ipywidgets to display a slider, a button and our romania map. By sliding the slider we can have a look at all the intermediate steps of a particular search algorithm. By pressing the button Visualize, you can see all the steps without interacting with the slider. These two helper functions are the callback function which are called when we interact with slider and the button. End of explanation """ def breadth_first_search(problem): "[Figure 3.11]" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] node_colors = dict(initial_node_colors) node = Node(problem.initial) node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test(node.state): node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, node) frontier = FIFOQueue() frontier.append(node) # modify the color of frontier nodes to blue node_colors[node.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) explored = set() while frontier: node = frontier.pop() node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: if problem.goal_test(child.state): node_colors[child.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, child) frontier.append(child) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) node_colors[node.state] = "gray" iterations += 1 all_node_colors.append(dict(node_colors)) return None all_node_colors = [] romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) display_visual(user_input = False, algorithm = breadth_first_search, problem = romania_problem) """ Explanation: Breadth first search Let's change all the node_colors to starting position and define a different problem statement. End of explanation """ def best_first_graph_search(problem, f): """Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have breadth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned.""" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] node_colors = dict(initial_node_colors) f = memoize(f, 'f') node = Node(problem.initial) node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test(node.state): node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, node) frontier = PriorityQueue(min, f) frontier.append(node) node_colors[node.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) explored = set() while frontier: node = frontier.pop() node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test(node.state): node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, node) explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: frontier.append(child) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) elif child in frontier: incumbent = frontier[child] if f(child) < f(incumbent): del frontier[incumbent] frontier.append(child) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) node_colors[node.state] = "gray" iterations += 1 all_node_colors.append(dict(node_colors)) return None def uniform_cost_search(problem): "[Figure 3.14]" iterations, all_node_colors, node = best_first_graph_search(problem, lambda node: node.path_cost) return(iterations, all_node_colors, node) all_node_colors = [] romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) display_visual(user_input = False, algorithm = uniform_cost_search, problem = romania_problem) """ Explanation: Uniform cost search Let's change all the node_colors to starting position and define a different problem statement. End of explanation """ def best_first_graph_search(problem, f): """Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have breadth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned.""" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] node_colors = dict(initial_node_colors) f = memoize(f, 'f') node = Node(problem.initial) node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test(node.state): node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, node) frontier = PriorityQueue(min, f) frontier.append(node) node_colors[node.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) explored = set() while frontier: node = frontier.pop() node_colors[node.state] = "red" iterations += 1 all_node_colors.append(dict(node_colors)) if problem.goal_test(node.state): node_colors[node.state] = "green" iterations += 1 all_node_colors.append(dict(node_colors)) return(iterations, all_node_colors, node) explored.add(node.state) for child in node.expand(problem): if child.state not in explored and child not in frontier: frontier.append(child) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) elif child in frontier: incumbent = frontier[child] if f(child) < f(incumbent): del frontier[incumbent] frontier.append(child) node_colors[child.state] = "orange" iterations += 1 all_node_colors.append(dict(node_colors)) node_colors[node.state] = "gray" iterations += 1 all_node_colors.append(dict(node_colors)) return None def astar_search(problem, h=None): """A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search, or else in your Problem subclass.""" h = memoize(h or problem.h, 'h') iterations, all_node_colors, node = best_first_graph_search(problem, lambda n: n.path_cost + h(n)) return(iterations, all_node_colors, node) all_node_colors = [] romania_problem = GraphProblem('Arad', 'Bucharest', romania_map) display_visual(user_input = False, algorithm = astar_search, problem = romania_problem) all_node_colors = [] # display_visual(user_input = True, algorithm = breadth_first_tree_search) display_visual(user_input = True) """ Explanation: A* search Let's change all the node_colors to starting position and define a different problem statement. End of explanation """
retnuh/deep-learning
autoencoder/Simple_Autoencoder.ipynb
mit
%matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) """ Explanation: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed representation of the input. Then, this representation is passed through a decoder to reconstruct the input data. Generally the encoder and decoder will be built with neural networks, then trained on example data. In this notebook, we'll be build a simple network architecture for the encoder and decoder. Let's get started by importing our libraries and getting the dataset. End of explanation """ img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r') """ Explanation: Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits. End of explanation """ # Size of the encoding layer (the hidden layer) encoding_dim = 32 # feel free to change this value inputs_ = tf.placeholder(tf.float32, [None, 784], name='inputs') targets_ = tf.placeholder(tf.float32, [None, 784], name='targets') # Output of hidden layer encoded = tf.layers.dense(inputs_, encoding_dim) # Output layer logits logits = tf.layers.dense(inputs_, 784, activation=None) # Sigmoid output from logits decoded = tf.sigmoid(logits) # Sigmoid cross-entropy loss loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=targets_, logits=logits) # Mean of the loss cost = tf.reduce_mean(loss) # Adam optimizer opt = tf.train.AdamOptimizer(0.01).minimize(cost) """ Explanation: We'll train an autoencoder with these images by flattening them into 784 length vectors. The images from this dataset are already normalized such that the values are between 0 and 1. Let's start by building basically the simplest autoencoder with a single ReLU hidden layer. This layer will be used as the compressed representation. Then, the encoder is the input layer and the hidden layer. The decoder is the hidden layer and the output layer. Since the images are normalized between 0 and 1, we need to use a sigmoid activation on the output layer to get values matching the input. Exercise: Build the graph for the autoencoder in the cell below. The input images will be flattened into 784 length vectors. The targets are the same as the inputs. And there should be one hidden layer with a ReLU activation and an output layer with a sigmoid activation. The loss should be calculated with the cross-entropy loss, there is a convenient TensorFlow function for this tf.nn.sigmoid_cross_entropy_with_logits (documentation). You should note that tf.nn.sigmoid_cross_entropy_with_logits takes the logits, but to get the reconstructed images you'll need to pass the logits through the sigmoid function. End of explanation """ # Create the session sess = tf.Session() """ Explanation: Training End of explanation """ epochs = 20 batch_size = 200 sess.run(tf.global_variables_initializer()) for e in range(epochs): for ii in range(mnist.train.num_examples//batch_size): batch = mnist.train.next_batch(batch_size) feed = {inputs_: batch[0], targets_: batch[0]} batch_cost, _ = sess.run([cost, opt], feed_dict=feed) print("Epoch: {}/{}...".format(e+1, epochs), "Training loss: {:.4f}\r".format(batch_cost), end='') print() """ Explanation: Here I'll write a bit of code to train the network. I'm not too interested in validation here, so I'll just monitor the training loss. Calling mnist.train.next_batch(batch_size) will return a tuple of (images, labels). We're not concerned with the labels here, we just need the images. Otherwise this is pretty straightfoward training with TensorFlow. We initialize the variables with sess.run(tf.global_variables_initializer()). Then, run the optimizer and get the loss with batch_cost, _ = sess.run([cost, opt], feed_dict=feed). End of explanation """ fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4)) in_imgs = mnist.test.images[:10] reconstructed, compressed = sess.run([decoded, encoded], feed_dict={inputs_: in_imgs}) for images, row in zip([in_imgs, reconstructed], axes): for img, ax in zip(images, row): ax.imshow(img.reshape((28, 28)), cmap='Greys_r') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) fig.tight_layout(pad=0.1) sess.close() """ Explanation: Checking out the results Below I've plotted some of the test images along with their reconstructions. For the most part these look pretty good except for some blurriness in some parts. End of explanation """
kingb12/languagemodelRNN
report_notebooks/encdec_noing15_bow_200_512_04drb.ipynb
mit
report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing15_bow_200_512_04drb/encdec_noing15_bow_200_512_04drb.json' log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing15_bow_200_512_04drb/encdec_noing15_bow_200_512_04drb_logs.json' import json import matplotlib.pyplot as plt with open(report_file) as f: report = json.loads(f.read()) with open(log_file) as f: logs = json.loads(f.read()) print'Encoder: \n\n', report['architecture']['encoder'] print'Decoder: \n\n', report['architecture']['decoder'] """ Explanation: Encoder-Decoder Analysis Model Architecture End of explanation """ print('Train Perplexity: ', report['train_perplexity']) print('Valid Perplexity: ', report['valid_perplexity']) print('Test Perplexity: ', report['test_perplexity']) """ Explanation: Perplexity on Each Dataset End of explanation """ %matplotlib inline for k in logs.keys(): plt.plot(logs[k][0], logs[k][1], label=str(k) + ' (train)') plt.plot(logs[k][0], logs[k][2], label=str(k) + ' (valid)') plt.title('Loss v. Epoch') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.show() """ Explanation: Loss vs. Epoch End of explanation """ %matplotlib inline for k in logs.keys(): plt.plot(logs[k][0], logs[k][3], label=str(k) + ' (train)') plt.plot(logs[k][0], logs[k][4], label=str(k) + ' (valid)') plt.title('Perplexity v. Epoch') plt.xlabel('Epoch') plt.ylabel('Perplexity') plt.legend() plt.show() """ Explanation: Perplexity vs. Epoch End of explanation """ def print_sample(sample, best_bleu=None): enc_input = ' '.join([w for w in sample['encoder_input'].split(' ') if w != '<pad>']) gold = ' '.join([w for w in sample['gold'].split(' ') if w != '<mask>']) print('Input: '+ enc_input + '\n') print('Gend: ' + sample['generated'] + '\n') print('True: ' + gold + '\n') if best_bleu is not None: cbm = ' '.join([w for w in best_bleu['best_match'].split(' ') if w != '<mask>']) print('Closest BLEU Match: ' + cbm + '\n') print('Closest BLEU Score: ' + str(best_bleu['best_score']) + '\n') print('\n') for i, sample in enumerate(report['train_samples']): print_sample(sample, report['best_bleu_matches_train'][i] if 'best_bleu_matches_train' in report else None) for i, sample in enumerate(report['valid_samples']): print_sample(sample, report['best_bleu_matches_valid'][i] if 'best_bleu_matches_valid' in report else None) for i, sample in enumerate(report['test_samples']): print_sample(sample, report['best_bleu_matches_test'][i] if 'best_bleu_matches_test' in report else None) """ Explanation: Generations End of explanation """ def print_bleu(blue_struct): print 'Overall Score: ', blue_struct['score'], '\n' print '1-gram Score: ', blue_struct['components']['1'] print '2-gram Score: ', blue_struct['components']['2'] print '3-gram Score: ', blue_struct['components']['3'] print '4-gram Score: ', blue_struct['components']['4'] # Training Set BLEU Scores print_bleu(report['train_bleu']) # Validation Set BLEU Scores print_bleu(report['valid_bleu']) # Test Set BLEU Scores print_bleu(report['test_bleu']) # All Data BLEU Scores print_bleu(report['combined_bleu']) """ Explanation: BLEU Analysis End of explanation """ # Training Set BLEU n-pairs Scores print_bleu(report['n_pairs_bleu_train']) # Validation Set n-pairs BLEU Scores print_bleu(report['n_pairs_bleu_valid']) # Test Set n-pairs BLEU Scores print_bleu(report['n_pairs_bleu_test']) # Combined n-pairs BLEU Scores print_bleu(report['n_pairs_bleu_all']) # Ground Truth n-pairs BLEU Scores print_bleu(report['n_pairs_bleu_gold']) """ Explanation: N-pairs BLEU Analysis This analysis randomly samples 1000 pairs of generations/ground truths and treats them as translations, giving their BLEU score. We can expect very low scores in the ground truth and high scores can expose hyper-common generations End of explanation """ print 'Average (Train) Generated Score: ', report['average_alignment_train'] print 'Average (Valid) Generated Score: ', report['average_alignment_valid'] print 'Average (Test) Generated Score: ', report['average_alignment_test'] print 'Average (All) Generated Score: ', report['average_alignment_all'] print 'Average Gold Score: ', report['average_alignment_gold'] """ Explanation: Alignment Analysis This analysis computs the average Smith-Waterman alignment score for generations, with the same intuition as N-pairs BLEU, in that we expect low scores in the ground truth and hyper-common generations to raise the scores End of explanation """
tensorflow/examples
lite/examples/digit_classifier/ml/mnist_tflite.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 The TensorFlow Authors. End of explanation """ # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotlib.pyplot as plt import math print(tf.__version__) # Helper function to display digit images def show_sample(images, labels, sample_count=25): # Create a square with can fit {sample_count} images grid_count = math.ceil(math.ceil(math.sqrt(sample_count))) grid_count = min(grid_count, len(images), len(labels)) plt.figure(figsize=(2*grid_count, 2*grid_count)) for i in range(sample_count): plt.subplot(grid_count, grid_count, i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(images[i], cmap=plt.cm.gray) plt.xlabel(labels[i]) plt.show() """ Explanation: Build a digit classifier app with TensorFlow Lite <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/lite/examples/digit_classifier/ml/mnist_tflite.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/examples/blob/master/lite/examples/digit_classifier/ml/mnist_tflite.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> Overview This notebook shows an end-to-end example of training a TensorFlow model using Keras and Python, then export it to TensorFlow Lite format to use in mobile apps. Here we will train a handwritten digit classifier using MNIST dataset. Setup End of explanation """ # Download MNIST dataset. mnist = keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # If you can't download the MNIST dataset from Keras, please try again with an alternative method below # path = keras.utils.get_file('mnist.npz', # origin='https://s3.amazonaws.com/img-datasets/mnist.npz', # file_hash='8a61469f7ea1b51cbae51d4f78837e45') # with np.load(path, allow_pickle=True) as f: # train_images, train_labels = f['x_train'], f['y_train'] # test_images, test_labels = f['x_test'], f['y_test'] # Normalize the input image so that each pixel value is between 0 to 1. train_images = train_images / 255.0 test_images = test_images / 255.0 # Show the first 25 images in the training dataset. show_sample(train_images, ['Label: %s' % label for label in train_labels]) """ Explanation: Download and explore the MNIST dataset The MNIST database contains 60,000 training images and 10,000 testing images of handwritten digits. We will use the dataset to demonstrate how to train a image classification model and convert it to TensorFlow Lite format. Each image in the MNIST dataset is a 28x28 grayscale image containing a digit. End of explanation """ # Define the model architecture model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), # Optional: You can replace the dense layer above with the convolution layers below to get higher accuracy. # keras.layers.Reshape(target_shape=(28, 28, 1)), # keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=tf.nn.relu), # keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=tf.nn.relu), # keras.layers.MaxPooling2D(pool_size=(2, 2)), # keras.layers.Dropout(0.25), # keras.layers.Flatten(input_shape=(28, 28)), # keras.layers.Dense(128, activation=tf.nn.relu), # keras.layers.Dropout(0.5), keras.layers.Dense(10) ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # Train the digit classification model model.fit(train_images, train_labels, epochs=5) """ Explanation: Train a TensorFlow model to classify digit images We use Keras API to build a TensorFlow model that can classify the digit images. Please see this tutorial if you are interested to learn more about how to build machine learning model with Keras and TensorFlow. End of explanation """ # Evaluate the model using test dataset. test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) # Predict the labels of digit images in our test dataset. predictions = model.predict(test_images) # Then plot the first 25 test images and their predicted labels. show_sample(test_images, ['Predicted: %d' % np.argmax(result) for result in predictions]) """ Explanation: Evaluate our model We run our digit classification model against our test dataset that the model hasn't seen during its training process. We want to confirm that the model didn't just remember the digits it saw but also generalize well to new images. End of explanation """ # Convert Keras model to TF Lite format. converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # Save the TF Lite model as file f = open('mnist.tflite', "wb") f.write(tflite_model) f.close() # Download the digit classification model if you're using Colab, # or print the model's local path if you're not using Colab. try: from google.colab import files files.download('mnist.tflite') except ImportError: import os print('TF Lite model:', os.path.join(os.getcwd(), 'mnist.tflite')) """ Explanation: Convert the Keras model to TensorFlow Lite End of explanation """ # Download a test image zero_img_path = keras.utils.get_file( 'zero.png', 'https://storage.googleapis.com/khanhlvg-public.appspot.com/digit-classifier/zero.png' ) image = keras.preprocessing.image.load_img( zero_img_path, color_mode = 'grayscale', target_size=(28, 28), interpolation='bilinear' ) # Pre-process the image: Adding batch dimension and normalize the pixel value to [0..1] # In training, we feed images in a batch to the model to improve training speed, making the model input shape to be (BATCH_SIZE, 28, 28). # For inference, we still need to match the input shape with training, so we expand the input dimensions to (1, 28, 28) using np.expand_dims input_image = np.expand_dims(np.array(image, dtype=np.float32) / 255.0, 0) # Show the pre-processed input image show_sample(input_image, ['Input Image'], 1) # Run inference with TensorFlow Lite interpreter = tf.lite.Interpreter(model_content=tflite_model) interpreter.allocate_tensors() interpreter.set_tensor(interpreter.get_input_details()[0]["index"], input_image) interpreter.invoke() output = interpreter.tensor(interpreter.get_output_details()[0]["index"])()[0] # Print the model's classification result digit = np.argmax(output) print('Predicted Digit: %d\nConfidence: %f' % (digit, output[digit])) """ Explanation: Verify the TensorFlow Lite model End of explanation """
DJCordhose/ai
notebooks/tf2/time-series-advanced.ipynb
mit
!pip install -q tf-nightly-gpu-2.0-preview import tensorflow as tf print(tf.__version__) # univariate data preparation import numpy as np # split a univariate sequence into samples def split_sequence(sequence, n_steps): X, y = list(), list() for i in range(len(sequence)): # find the end of this pattern end_ix = i + n_steps # check if we are beyond the sequence if end_ix > len(sequence)-1: break # gather input and output parts of the pattern seq_x, seq_y = sequence[i:end_ix], sequence[end_ix] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y) # define input sequence raw_seq = [10, 20, 30, 40, 50, 60, 70, 80, 90] # choose a number of time steps n_steps = 3 # split into samples X, y = split_sequence(raw_seq, n_steps) # summarize the data list(zip(X, y)) n_features = 1 X = X.reshape((X.shape[0], X.shape[1], n_features)) """ Explanation: <a href="https://colab.research.google.com/github/DJCordhose/ai/blob/master/notebooks/tf2/time-series-advanced.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Advanced Time Series / Sequences Example, some code and a lot of inspiration taken from: https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/ End of explanation """ # one output for each input timestep # ideal for feeding into something that *expects* timesteps rnn_units = 1 from tensorflow.keras.layers import Dense, LSTM, GRU, SimpleRNN, Bidirectional from tensorflow.keras.models import Sequential, Model model = Sequential([ SimpleRNN(units=rnn_units, activation='relu', input_shape=(n_steps, n_features), return_sequences=True) ]) # https://keras.io/layers/recurrent/ # input: (samples, timesteps, input_dim) # output with return_sequences: (samples, timesteps, units) predict(model, [[10, 20, 30]]) rnn_units = 50 model = Sequential([ SimpleRNN(units=rnn_units, activation='relu', input_shape=(n_steps, n_features), return_sequences=True, name="RNN_Input"), SimpleRNN(units=rnn_units, activation='relu', name="RNN_Latent"), Dense(units=1, name="Linear_Output") ]) model.compile(optimizer='adam', loss='mse') model.summary() %time history = model.fit(X, y, epochs=500, verbose=0) import matplotlib.pyplot as plt plt.yscale('log') plt.ylabel("loss") plt.xlabel("epochs") plt.plot(history.history['loss']) predict(model, [[10, 20, 30], [70, 80, 90], [100, 110, 120], [200, 210, 220], [200, 300, 400]]) """ Explanation: Multi Layer RNNs End of explanation """ rnn_units = 50 model = Sequential([ LSTM(units=rnn_units, activation='relu', input_shape=(n_steps, n_features), name="RNN_Input"), Dense(units=1, name="Linear_Output") ]) model.compile(optimizer='adam', loss='mse') model.summary() # https://arxiv.org/ftp/arxiv/papers/1701/1701.05923.pdf # n = output dimension # m = input dimension # Total number of parameters for # Simple RNN = n**2 + nm + n # GRU = 3 × (n**2 + nm + n) # LSTM = 4 × (n**2 + nm + n) output_dimension = rnn_units input_dimension = n_features parameters = 4 * (output_dimension ** 2 + output_dimension * input_dimension + output_dimension) parameters %time history = model.fit(X, y, epochs=500, verbose=0) plt.yscale('log') plt.ylabel("loss") plt.xlabel("epochs") plt.plot(history.history['loss']) predict(model, [[10, 20, 30], [70, 80, 90], [100, 110, 120], [200, 210, 220], [200, 300, 400]]) rnn_units = 50 model = Sequential([ GRU(units=rnn_units, activation='relu', input_shape=(n_steps, n_features), name="RNN_Input"), Dense(units=1, name="Linear_Output") ]) model.compile(optimizer='adam', loss='mse') model.summary() output_dimension = rnn_units input_dimension = n_features parameters = 3 * (output_dimension ** 2 + output_dimension * input_dimension + output_dimension) parameters %time history = model.fit(X, y, epochs=500, verbose=0) plt.yscale('log') plt.ylabel("loss") plt.xlabel("epochs") plt.plot(history.history['loss']) predict(model, [[10, 20, 30], [70, 80, 90], [100, 110, 120], [200, 210, 220], [200, 300, 400]]) """ Explanation: LSMTs / GRUs mainly beneficial for long sequences but also 3-4 times more expensive might not have better results for short sequences like these End of explanation """ in_seq1 = [10, 20, 30, 40, 50, 60, 70, 80, 90] in_seq2 = [15, 25, 35, 45, 55, 65, 75, 85, 95] out_seq = [in1 + in2 for in1, in2 in zip(in_seq1, in_seq2)] out_seq # convert to [rows, columns] structure in_seq1 = np.array(in_seq1).reshape((len(in_seq1), 1)) in_seq2 = np.array(in_seq2).reshape((len(in_seq2), 1)) out_seq = np.array(out_seq).reshape((len(out_seq), 1)) out_seq # horizontally stack columns dataset = np.hstack((in_seq1, in_seq2, out_seq)) dataset # split a multivariate sequence into samples def split_sequences(sequences, n_steps): X, y = list(), list() for i in range(len(sequences)): # find the end of this pattern end_ix = i + n_steps # check if we are beyond the dataset if end_ix > len(sequences): break # gather input and output parts of the pattern seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y) # choose a number of time steps n_steps = 3 # convert into input/output X, y = split_sequences(dataset, n_steps) # summarize the data list(zip(X, y)) # the dataset knows the number of features, e.g. 2 n_features = X.shape[2] # define model model = Sequential() model.add(GRU(units=50, activation='relu', input_shape=(n_steps, n_features), name="RNN_Input")) model.add(Dense(units=1, name="Linear_Output")) model.compile(optimizer='adam', loss='mse') # fit model %time history = model.fit(X, y, epochs=500, verbose=0) import matplotlib.pyplot as plt plt.yscale('log') plt.plot(history.history['loss']) def predict_multi(model, samples): input = np.array(samples) input = input.reshape(1, input.shape[0], input.shape[1]) y_pred = model.predict(input) return y_pred predict_multi(model, [[80, 85], [90, 95], [100, 105]]) predict_multi(model, [[10, 15], [20, 25], [30, 35]]) predict_multi(model, [[180, 185], [190, 195], [200, 205]]) """ Explanation: Multivariate LSTM Models Multiple Input Series End of explanation """ y += 20 list(zip(X, y)) model = Sequential() model.add(GRU(units=50, activation='relu', input_shape=(n_steps, n_features), name="RNN_Input")) model.add(Dense(units=1, name="Linear_Output")) model.compile(optimizer='adam', loss='mse') # train a little bit longer, as this should be harder now %time history = model.fit(X, y, epochs=2000, verbose=0) import matplotlib.pyplot as plt plt.yscale('log') plt.plot(history.history['loss']) predict_multi(model, [[80, 85], [90, 95], [100, 105]]) predict_multi(model, [[10, 15], [20, 25], [30, 35]]) predict_multi(model, [[180, 185], [190, 195], [200, 205]]) """ Explanation: Let's make this a little bit harder output y can be inferred from final timestep now we try to infer following ouput End of explanation """ # split a univariate sequence into samples def split_sequence(sequence, n_steps_in, n_steps_out): X, y = list(), list() for i in range(len(sequence)): # find the end of this pattern end_ix = i + n_steps_in out_end_ix = end_ix + n_steps_out # check if we are beyond the sequence if out_end_ix > len(sequence): break # gather input and output parts of the pattern seq_x, seq_y = sequence[i:end_ix], sequence[end_ix:out_end_ix] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y) # define input sequence raw_seq = [10, 20, 30, 40, 50, 60, 70, 80, 90] # choose a number of time steps n_steps_in, n_steps_out = 3, 2 # split into samples X, y = split_sequence(raw_seq, n_steps_in, n_steps_out) # summarize the data for input, output in zip(X, y): print (input, output) # reshape from [samples, timesteps] into [samples, timesteps, features] n_features = 1 X = X.reshape((X.shape[0], X.shape[1], n_features)) # define model model = Sequential() model.add(GRU(100, activation='relu', input_shape=(n_steps_in, n_features))) # model.add(GRU(100, activation='relu', return_sequences=True, input_shape=(n_steps_in, n_features))) # model.add(GRU(100, activation='relu')) model.add(Dense(n_steps_out)) model.compile(optimizer='adam', loss='mse') # fit model %time history = model.fit(X, y, epochs=500, verbose=0) import matplotlib.pyplot as plt plt.yscale('log') plt.plot(history.history['loss']) X_sample = np.array([70, 80, 90]).reshape((1, n_steps_in, n_features)) y_pred = model.predict(X_sample) print(y_pred) X_sample = np.array([10, 20, 30]).reshape((1, n_steps_in, n_features)) y_pred = model.predict(X_sample) print(y_pred) """ Explanation: Multi-Step LSTM Models this might just as well be an encoder / decoder approach End of explanation """
Santana9937/Regression_ML_Specialization
Week_4_Ridge_Regression/assign_2_ridge-regression.ipynb
mit
import graphlab import numpy as np import pandas as pd from sklearn import linear_model import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') %matplotlib inline """ Explanation: Regression Week 4: Ridge Regression (gradient descent) In this notebook, we will implement ridge regression via gradient descent. You will: * Convert an SFrame into a Numpy array * Write a Numpy function to compute the derivative of the regression weights with respect to a single feature * Write gradient descent function to compute the regression weights given an initial weight vector, step size, tolerance, and L2 penalty Importing Libraries End of explanation """ sales = graphlab.SFrame('kc_house_data.gl/') plt.figure(figsize=(8,6)) plt.plot(sales['sqft_living'], sales['price'],'.') plt.xlabel('Living Area (ft^2)', fontsize=16) plt.ylabel('House Price ($)', fontsize=16) plt.title('King County, Seattle House Price Data', fontsize=18) plt.axis([0.0, 14000.0, 0.0, 8000000.0]) plt.show() """ Explanation: If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do this directly using the SFrames as seen in the first notebook of Week 2. For this notebook, however, we will work with the existing features. Loading and Plotting the house sales data End of explanation """ def get_numpy_data(input_sframe, features, output): input_sframe['constant'] = 1 # Adding column 'constant' to input SFrame with all values = 1.0 features = ['constant'] + features # Adding 'constant' to List of features # Selecting the columns for the feature_matrux and output_array features_sframe = input_sframe[features] output_sarray = input_sframe[output] # Converting sframes to numpy.ndarrays feature_matrix = features_sframe.to_numpy() output_array = output_sarray.to_numpy() return(feature_matrix, output_array) """ Explanation: Import useful functions from previous notebook As in Week 2, we convert the SFrame into a 2D Numpy array. Copy and paste get_num_data() from the second notebook of Week 2. End of explanation """ def predict_output(feature_matrix, weights): predictions = np.dot(feature_matrix, weights) return predictions """ Explanation: Also, copy and paste the predict_output() function to compute the predictions for an entire matrix of features given the matrix and the weights: End of explanation """ def feature_derivative_ridge(errors, feature, weight, l2_penalty, feature_is_constant): # If feature_is_constant is True, derivative is twice the dot product of errors and feature if feature_is_constant==True: derivative = 2.0*np.dot(errors, feature) # Otherwise, derivative is twice the dot product plus 2*l2_penalty*weight else: derivative = 2.0*np.dot(errors, feature) + 2.0*l2_penalty*weight return derivative """ Explanation: Computing the Derivative We are now going to move to computing the derivative of the regression cost function. Recall that the cost function is the sum over the data points of the squared difference between an observed output and a predicted output, plus the L2 penalty term. Cost(w) = SUM[ (prediction - output)^2 ] + l2_penalty*(w[0]^2 + w[1]^2 + ... + w[k]^2). Since the derivative of a sum is the sum of the derivatives, we can take the derivative of the first part (the RSS) as we did in the notebook for the unregularized case in Week 2 and add the derivative of the regularization part. As we saw, the derivative of the RSS with respect to w[i] can be written as: 2*SUM[ error*[feature_i] ]. The derivative of the regularization term with respect to w[i] is: 2*l2_penalty*w[i]. Summing both, we get 2*SUM[ error*[feature_i] ] + 2*l2_penalty*w[i]. That is, the derivative for the weight for feature i is the sum (over data points) of 2 times the product of the error and the feature itself, plus 2*l2_penalty*w[i]. We will not regularize the constant. Thus, in the case of the constant, the derivative is just twice the sum of the errors (without the 2*l2_penalty*w[0] term). Recall that twice the sum of the product of two vectors is just twice the dot product of the two vectors. Therefore the derivative for the weight for feature_i is just two times the dot product between the values of feature_i and the current errors, plus 2*l2_penalty*w[i]. With this in mind complete the following derivative function which computes the derivative of the weight given the value of the feature (over all data points) and the errors (over all data points). To decide when to we are dealing with the constant (so we don't regularize it) we added the extra parameter to the call feature_is_constant which you should set to True when computing the derivative of the constant and False otherwise. End of explanation """ (example_features, example_output) = get_numpy_data(sales, ['sqft_living'], 'price') my_weights = np.array([1., 10.]) test_predictions = predict_output(example_features, my_weights) errors = test_predictions - example_output # prediction errors # next two lines should print the same values print feature_derivative_ridge(errors, example_features[:,1], my_weights[1], 1, False) print np.sum(errors*example_features[:,1])*2+20. print '' # next two lines should print the same values print feature_derivative_ridge(errors, example_features[:,0], my_weights[0], 1, True) print np.sum(errors)*2. """ Explanation: To test your feature derivartive run the following: End of explanation """ def ridge_regression_gradient_descent(feature_matrix, output, initial_weights, step_size, l2_penalty, max_iterations): weights = np.array(initial_weights) # make sure it's a numpy array iteration_count = 0 #while not reached maximum number of iterations: while iteration_count < max_iterations: predictions = predict_output(feature_matrix, weights) # computing predictions w/ feature_matrix and weights errors = predictions - output # compute the errors as predictions - output # loop over each weight for i in xrange(len(weights)): # Recall that feature_matrix[:,i] is the feature column associated with weights[i] # compute the derivative for weight[i]. #(Remember: when i=0, you are computing the derivative of the constant!) if i == 0: derivative = feature_derivative_ridge(errors, feature_matrix[:,0], weights[0], l2_penalty, True) else: derivative = feature_derivative_ridge(errors, feature_matrix[:,i], weights[i], l2_penalty, False) weights[i] = weights[i] - step_size*derivative # Incrementing the iteration count iteration_count += 1 return weights """ Explanation: Gradient Descent Now we will write a function that performs a gradient descent. The basic premise is simple. Given a starting point we update the current weights by moving in the negative gradient direction. Recall that the gradient is the direction of increase and therefore the negative gradient is the direction of decrease and we're trying to minimize a cost function. The amount by which we move in the negative gradient direction is called the 'step size'. We stop when we are 'sufficiently close' to the optimum. Unlike in Week 2, this time we will set a maximum number of iterations and take gradient steps until we reach this maximum number. If no maximum number is supplied, the maximum should be set 100 by default. (Use default parameter values in Python.) With this in mind, complete the following gradient descent function below using your derivative function above. For each step in the gradient descent, we update the weight for each feature before computing our stopping criteria. End of explanation """ simple_features = ['sqft_living'] my_output = 'price' """ Explanation: Visualizing effect of L2 penalty The L2 penalty gets its name because it causes weights to have small L2 norms than otherwise. Let's see how large weights get penalized. Let us consider a simple model with 1 feature: End of explanation """ train_data,test_data = sales.random_split(.8,seed=0) """ Explanation: Load the training set and test set. End of explanation """ (simple_feature_matrix, output) = get_numpy_data(train_data, simple_features, my_output) (simple_test_feature_matrix, test_output) = get_numpy_data(test_data, simple_features, my_output) """ Explanation: In this part, we will only use 'sqft_living' to predict 'price'. Use the get_numpy_data function to get a Numpy versions of your data with only this feature, for both the train_data and the test_data. End of explanation """ initial_weights = np.array([0.0, 0.0]) step_size = 1e-12 max_iterations=1000 """ Explanation: Let's set the parameters for our optimization: End of explanation """ l2_penalty = 0.0 simple_weights_0_penalty = ridge_regression_gradient_descent(simple_feature_matrix, output, initial_weights, step_size, l2_penalty, max_iterations) """ Explanation: First, let's consider no regularization. Set the l2_penalty to 0.0 and run your ridge regression algorithm to learn the weights of your model. Call your weights: simple_weights_0_penalty we'll use them later. End of explanation """ l2_penalty = 1.0e11 simple_weights_high_penalty = ridge_regression_gradient_descent(simple_feature_matrix, output, initial_weights, step_size, l2_penalty, max_iterations) """ Explanation: Next, let's consider high regularization. Set the l2_penalty to 1e11 and run your ridge regression algorithm to learn the weights of your model. Call your weights: simple_weights_high_penalty we'll use them later. End of explanation """ plt.figure(figsize=(8,6)) plt.plot(simple_feature_matrix[:,1],output,'.', label= 'House Price Data') plt.hold(True) plt.plot(simple_feature_matrix[:,1], predict_output(simple_feature_matrix, simple_weights_0_penalty),'-', label= 'No L2 Penalty') plt.plot(simple_feature_matrix[:,1], predict_output(simple_feature_matrix, simple_weights_high_penalty),'-', label= 'Large L2 Penalty') plt.hold(False) plt.legend(loc='upper left', fontsize=16) plt.xlabel('Living Area (ft^2)', fontsize=16) plt.ylabel('House Price ($)', fontsize=16) plt.title('King County, Seattle House Price Data', fontsize=18) plt.axis([0.0, 14000.0, 0.0, 8000000.0]) plt.show() """ Explanation: This code will plot the two learned models. (The green line is for the model with no regularization and the red line is for the one with high regularization.) End of explanation """ test_pred_weights_0 = predict_output(simple_test_feature_matrix, initial_weights) RSS_test_weights_0 = sum( (test_output - test_pred_weights_0)**2.0 ) test_pred_no_reg = predict_output(simple_test_feature_matrix, simple_weights_0_penalty) RSS_test_no_reg = sum( (test_output - test_pred_no_reg)**2.0 ) test_pred_high_reg = predict_output(simple_test_feature_matrix, simple_weights_high_penalty) RSS_test_high_reg = sum( (test_output - test_pred_high_reg)**2.0 ) """ Explanation: Compute the RSS on the TEST data for the following three sets of weights: 1. The initial weights (all zeros) 2. The weights learned with no regularization 3. The weights learned with high regularization Which weights perform best? End of explanation """ print 'No Regulatization sqft_living weight: %.1f' %(simple_weights_0_penalty[1]) print 'High Regulatization sqft_living weight: %.1f' %(simple_weights_high_penalty[1]) """ Explanation: QUIZ QUESTIONS Q1: What is the value of the coefficient for sqft_living that you learned with no regularization, rounded to 1 decimal place? What about the one with high regularization? End of explanation """ print 'Line with No Regularization is steeper' """ Explanation: Q2: Comparing the lines you fit with the with no regularization versus high regularization, which one is steeper? End of explanation """ print 'Test set RSS with initial weights all set to 0.0: %.1e' %(RSS_test_weights_0) print 'Test set RSS with initial weights set to weights learned with no regularization: %.1e' %(RSS_test_no_reg) print 'Test set RSS with initial weights set to weights learned with high regularization: %.1e' %(RSS_test_high_reg) """ Explanation: Q3: What are the RSS on the test data for each of the set of weights above (initial, no regularization, high regularization)? End of explanation """ model_features = ['sqft_living', 'sqft_living15'] # sqft_living15 is the average squarefeet for the nearest 15 neighbors. my_output = 'price' (feature_matrix, output) = get_numpy_data(train_data, model_features, my_output) (test_feature_matrix, test_output) = get_numpy_data(test_data, model_features, my_output) """ Explanation: Initial weights learned with no regularization performed best on the Test Set (lowest RSS value) Running a multiple regression with L2 penalty Let us now consider a model with 2 features: ['sqft_living', 'sqft_living15']. First, create Numpy versions of your training and test data with these two features. End of explanation """ initial_weights = np.array([0.0,0.0,0.0]) step_size = 1e-12 max_iterations = 1000 """ Explanation: We need to re-inialize the weights, since we have one extra parameter. Let us also set the step size and maximum number of iterations. End of explanation """ l2_penalty = 0.0 multiple_weights_0_penalty = ridge_regression_gradient_descent(feature_matrix, output, initial_weights, step_size, l2_penalty, max_iterations) """ Explanation: First, let's consider no regularization. Set the l2_penalty to 0.0 and run your ridge regression algorithm to learn the weights of your model. Call your weights: multiple_weights_0_penalty End of explanation """ l2_penalty = 1.0e11 multiple_weights_high_penalty = ridge_regression_gradient_descent(feature_matrix, output, initial_weights, step_size, l2_penalty, max_iterations) """ Explanation: Next, let's consider high regularization. Set the l2_penalty to 1e11 and run your ridge regression algorithm to learn the weights of your model. Call your weights: multiple_weights_high_penalty End of explanation """ test_pred_mul_feat_weights_0 = predict_output(test_feature_matrix, initial_weights) RSS_test_mul_feat_weights_0 = sum( (test_output - test_pred_mul_feat_weights_0)**2.0 ) test_pred_mul_feat_no_reg = predict_output(test_feature_matrix, multiple_weights_0_penalty) RSS_test_mul_feat_no_reg = sum( (test_output - test_pred_mul_feat_no_reg)**2.0 ) test_pred_mul_feat_high_reg = predict_output(test_feature_matrix, multiple_weights_high_penalty) RSS_test_mul_feat_high_reg = sum( (test_output - test_pred_mul_feat_high_reg)**2.0 ) """ Explanation: Compute the RSS on the TEST data for the following three sets of weights: 1. The initial weights (all zeros) 2. The weights learned with no regularization 3. The weights learned with high regularization Which weights perform best? End of explanation """ print 'Pred. price of 1st house in Test Set with weights learned with no reg.: %.2f' %(test_pred_mul_feat_no_reg[0]) print 'Pred. price of 1st house in Test Set with weights learned with high reg.: %.2f' %(test_pred_mul_feat_high_reg[0]) print 'Pred. price - actual prize of 1st house in Test Set, using weights w/ no reg.: %.2f' %(abs(test_output[0] - test_pred_mul_feat_no_reg[0])) print 'Pred. price - actual prize of 1st house in Test Set, using weights w/ high reg.: %.2f' %(abs(test_output[0] - test_pred_mul_feat_high_reg[0])) """ Explanation: Predict the house price for the 1st house in the test set using the no regularization and high regularization models. (Remember that python starts indexing from 0.) How far is the prediction from the actual price? Which weights perform best for the 1st house? End of explanation """ print 'No Regulatization sqft_living weight: %.1f' %(multiple_weights_0_penalty[1]) print 'High Regulatization sqft_living weight: %.1f' %(multiple_weights_high_penalty[1]) """ Explanation: Weights with high regularization perform best on 1st house in Test Set QUIZ QUESTIONS Q1: What is the value of the coefficient for sqft_living that you learned with no regularization, rounded to 1 decimal place? What about the one with high regularization? End of explanation """ print 'Test set RSS with initial weights all set to 0.0: %.1e' %(RSS_test_mul_feat_weights_0) print 'Test set RSS with initial weights set to weights learned with no regularization: %.1e' %(RSS_test_mul_feat_no_reg) print 'Test set RSS with initial weights set to weights learned with high regularization: %.1e' %(RSS_test_mul_feat_high_reg) """ Explanation: Q2: What are the RSS on the test data for each of the set of weights above (initial, no regularization, high regularization)? End of explanation """
tensorflow/probability
tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2018 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ #@title Install { display-mode: "form" } TF_Installation = 'System' #@param ['TF Nightly', 'TF Stable', 'System'] if TF_Installation == 'TF Nightly': !pip install -q --upgrade tf-nightly print('Installation of `tf-nightly` complete.') elif TF_Installation == 'TF Stable': !pip install -q --upgrade tensorflow print('Installation of `tensorflow` complete.') elif TF_Installation == 'System': pass else: raise ValueError('Selection Error: Please select a valid ' 'installation option.') #@title Install { display-mode: "form" } TFP_Installation = "System" #@param ["Nightly", "Stable", "System"] if TFP_Installation == "Nightly": !pip install -q tfp-nightly print("Installation of `tfp-nightly` complete.") elif TFP_Installation == "Stable": !pip install -q --upgrade tensorflow-probability print("Installation of `tensorflow-probability` complete.") elif TFP_Installation == "System": pass else: raise ValueError("Selection Error: Please select a valid " "installation option.") """ Explanation: Fitting Generalized Linear Mixed-effects Models Using Variational Inference <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/probability/examples/Linear_Mixed_Effects_Model_Variational_Inference"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/probability/examples/jupyter_notebooks/Linear_Mixed_Effects_Model_Variational_Inference.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import os from six.moves import urllib import matplotlib.pyplot as plt; plt.style.use('ggplot') import numpy as np import pandas as pd import seaborn as sns; sns.set_context('notebook') import tensorflow_datasets as tfds import tensorflow.compat.v2 as tf tf.enable_v2_behavior() import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors """ Explanation: Abstract In this colab we demonstrate how to fit a generalized linear mixed-effects model using variational inference in TensorFlow Probability. Model Family Generalized linear mixed-effect models (GLMM) are similar to generalized linear models (GLM) except that they incorporate a sample specific noise into the predicted linear response. This is useful in part because it allows rarely seen features to share information with more commonly seen features. As a generative process, a Generalized Linear Mixed-effects Model (GLMM) is characterized by: $$ \begin{align} \text{for } & r = 1\ldots R: \hspace{2.45cm}\text{# for each random-effect group}\ &\begin{aligned} \text{for } &c = 1\ldots |C_r|: \hspace{1.3cm}\text{# for each category ("level") of group $r$}\ &\begin{aligned} \beta_{rc} &\sim \text{MultivariateNormal}(\text{loc}=0_{D_r}, \text{scale}=\Sigma_r^{1/2}) \end{aligned} \end{aligned}\\ \text{for } & i = 1 \ldots N: \hspace{2.45cm}\text{# for each sample}\ &\begin{aligned} &\eta_i = \underbrace{\vphantom{\sum_{r=1}^R}x_i^\top\omega}\text{fixed-effects} + \underbrace{\sum{r=1}^R z_{r,i}^\top \beta_{r,C_r(i) }}\text{random-effects} \ &Y_i|x_i,\omega,{z{r,i} , \beta_r}_{r=1}^R \sim \text{Distribution}(\text{mean}= g^{-1}(\eta_i)) \end{aligned} \end{align} $$ where: $$ \begin{align} R &= \text{number of random-effect groups}\ |C_r| &= \text{number of categories for group $r$}\ N &= \text{number of training samples}\ x_i,\omega &\in \mathbb{R}^{D_0}\ D_0 &= \text{number of fixed-effects}\ C_r(i) &= \text{category (under group $r$) of the $i$th sample}\ z_{r,i} &\in \mathbb{R}^{D_r}\ D_r &= \text{number of random-effects associated with group $r$}\ \Sigma_{r} &\in {S\in\mathbb{R}^{D_r \times D_r} : S \succ 0 }\ \eta_i\mapsto g^{-1}(\eta_i) &= \mu_i, \text{inverse link function}\ \text{Distribution} &=\text{some distribution parameterizable solely by its mean} \end{align} $$ In other words, this says that every category of each group is associated with a sample, $\beta_{rc}$, from a multivariate normal. Although the $\beta_{rc}$ draws are always independent, they are only indentically distributed for a group $r$: notice there is exactly one $\Sigma_r$ for each $r\in{1,\ldots,R}$. When affinely combined with a sample's group's features ($z_{r,i}$), the result is sample-specific noise on the $i$-th predicted linear response (which is otherwise $x_i^\top\omega$). When we estimate ${\Sigma_r:r\in{1,\ldots,R}}$ we're essentially estimating the amount of noise a random-effect group carries which would otherwise drown out the signal present in $x_i^\top\omega$. There are a variety of options for the $\text{Distribution}$ and inverse link function, $g^{-1}$. Common choices are: - $Y_i\sim\text{Normal}(\text{mean}=\eta_i, \text{scale}=\sigma)$, - $Y_i\sim\text{Binomial}(\text{mean}=n_i \cdot \text{sigmoid}(\eta_i), \text{total_count}=n_i)$, and, - $Y_i\sim\text{Poisson}(\text{mean}=\exp(\eta_i))$. For more possibilities, see the tfp.glm module. Variational Inference Unfortunately, finding the maximum likelihood estimates of the parameters $\beta,{\Sigma_r}r^R$ entails a non-analytical integral. To circumvent this problem, we instead 1. Define a parameterized family of distributions (the "surrogate density"), denoted $q{\lambda}$ in the appendix. 2. Find parameters $\lambda$ so that $q_{\lambda}$ is close to our true target denstiy. The family of distributions will be independent Gaussians of the proper dimensions, and by "close to our target density", we will mean "minimizing the Kullback-Leibler divergence". See, for example Section 2.2 of "Variational Inference: A Review for Statisticians" for a well-written derivation and motivation. In particular, it shows that minimizing the K-L divergence is equivalent to minimizing the negative evidence lower bound (ELBO). Toy Problem Gelman et al.'s (2007) "radon dataset" is a dataset sometimes used to demonstrate approaches for regression. (E.g., this closely related PyMC3 blog post.) The radon dataset contains indoor measurements of Radon taken throughout the United States. Radon is naturally ocurring radioactive gas which is toxic in high concentrations. For our demonstration, let's suppose we're interested in validating the hypothesis that Radon levels are higher in households containing a basement. We also suspect Radon concentration is related to soil-type, i.e., geography matters. To frame this as an ML problem, we'll try to predict log-radon levels based on a linear function of the floor on which the reading was taken. We'll also use the county as a random-effect and in so doing account for variances due to geography. In other words, we'll use a generalized linear mixed-effect model. End of explanation """ if tf.test.gpu_device_name() != '/device:GPU:0': print("We'll just use the CPU for this run.") else: print('Huzzah! Found GPU: {}'.format(tf.test.gpu_device_name())) """ Explanation: We will also do a quick check for availablility of a GPU: End of explanation """ def load_and_preprocess_radon_dataset(state='MN'): """Load the Radon dataset from TensorFlow Datasets and preprocess it. Following the examples in "Bayesian Data Analysis" (Gelman, 2007), we filter to Minnesota data and preprocess to obtain the following features: - `county`: Name of county in which the measurement was taken. - `floor`: Floor of house (0 for basement, 1 for first floor) on which the measurement was taken. The target variable is `log_radon`, the log of the Radon measurement in the house. """ ds = tfds.load('radon', split='train') radon_data = tfds.as_dataframe(ds) radon_data.rename(lambda s: s[9:] if s.startswith('feat') else s, axis=1, inplace=True) df = radon_data[radon_data.state==state.encode()].copy() df['radon'] = df.activity.apply(lambda x: x if x > 0. else 0.1) # Make county names look nice. df['county'] = df.county.apply(lambda s: s.decode()).str.strip().str.title() # Remap categories to start from 0 and end at max(category). df['county'] = df.county.astype(pd.api.types.CategoricalDtype()) df['county_code'] = df.county.cat.codes # Radon levels are all positive, but log levels are unconstrained df['log_radon'] = df['radon'].apply(np.log) # Drop columns we won't use and tidy the index columns_to_keep = ['log_radon', 'floor', 'county', 'county_code'] df = df[columns_to_keep].reset_index(drop=True) return df df = load_and_preprocess_radon_dataset() df.head() """ Explanation: Obtain Dataset: We load the dataset from TensorFlow datasets and do some light preprocessing. End of explanation """ fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4)) df.groupby('floor')['log_radon'].plot(kind='density', ax=ax1); ax1.set_xlabel('Measured log(radon)') ax1.legend(title='Floor') df['floor'].value_counts().plot(kind='bar', ax=ax2) ax2.set_xlabel('Floor where radon was measured') ax2.set_ylabel('Count') fig.suptitle("Distribution of log radon and floors in the dataset"); """ Explanation: Specializing the GLMM Family In this section, we specialize the GLMM family to the task of predicting radon levels. To do this, we first consider the fixed-effect special case of a GLMM: $$ \mathbb{E}[\log(\text{radon}_j)] = c + \text{floor_effect}_j $$ This model posits that the log radon in observation $j$ is (in expectation) governed by the floor the $j$th reading is taken on, plus some constant intercept. In pseudocode, we might write def estimate_log_radon(floor): return intercept + floor_effect[floor] there's a weight learned for every floor and a universal intercept term. Looking at the radon measurements from floor 0 and 1, it looks like this might be a good start: End of explanation """ fig, ax = plt.subplots(figsize=(22, 5)); county_freq = df['county'].value_counts() county_freq.plot(kind='bar', ax=ax) ax.set_xlabel('County') ax.set_ylabel('Number of readings'); """ Explanation: To make the model a little more sophisticated, including something about geography is probably even better: radon is part of the decay chain of uranium, which may be present in the ground, so geography seems key to account for. $$ \mathbb{E}[\log(\text{radon}_j)] = c + \text{floor_effect}_j + \text{county_effect}_j $$ Again, in pseudocode, we have def estimate_log_radon(floor, county): return intercept + floor_effect[floor] + county_effect[county] the same as before except with a county-specific weight. Given a sufficiently large training set, this is a reasonable model. However, given our data from Minnesota, we see that there's there's a large number of counties with a small number of measurements. For example, 39 out of 85 counties have fewer than five observations. This motivates sharing statistical strength between all our observations, in a way that converges to the above model as the number of observations per county increases. End of explanation """ features = df[['county_code', 'floor']].astype(int) labels = df[['log_radon']].astype(np.float32).values.flatten() """ Explanation: If we fit this model, the county_effect vector would likely end up memorizing the results for counties which had only a few training samples, perhaps overfitting and leading to poor generalization. GLMM's offer a happy middle to the above two GLMs. We might consider fitting $$ \log(\text{radon}_j) \sim c + \text{floor_effect}_j + \mathcal{N}(\text{county_effect}_j, \text{county_scale}) $$ This model is the same as the first, but we have fixed our likelihood to be a normal distribution, and will share the variance across all counties through the (single) variable county_scale. In pseudocode, def estimate_log_radon(floor, county): county_mean = county_effect[county] random_effect = np.random.normal() * county_scale + county_mean return intercept + floor_effect[floor] + random_effect We will infer the joint distribution over county_scale, county_mean, and the random_effect using our observed data. The global county_scale allows us to share statistical strength across counties: those with many observations provide a hit at the variance of counties with few observations. Furthermore, as we gather more data, this model will converge to the model without a pooled scale variable - even with this dataset, we will come to similar conclusions about the most observed counties with either model. Experiment We'll now try to fit the above GLMM using variational inference in TensorFlow. First we'll split the data into features and labels. End of explanation """ def make_joint_distribution_coroutine(floor, county, n_counties, n_floors): def model(): county_scale = yield tfd.HalfNormal(scale=1., name='scale_prior') intercept = yield tfd.Normal(loc=0., scale=1., name='intercept') floor_weight = yield tfd.Normal(loc=0., scale=1., name='floor_weight') county_prior = yield tfd.Normal(loc=tf.zeros(n_counties), scale=county_scale, name='county_prior') random_effect = tf.gather(county_prior, county, axis=-1) fixed_effect = intercept + floor_weight * floor linear_response = fixed_effect + random_effect yield tfd.Normal(loc=linear_response, scale=1., name='likelihood') return tfd.JointDistributionCoroutineAutoBatched(model) joint = make_joint_distribution_coroutine( features.floor.values, features.county_code.values, df.county.nunique(), df.floor.nunique()) # Define a closure over the joint distribution # to condition on the observed labels. def target_log_prob_fn(*args): return joint.log_prob(*args, likelihood=labels) """ Explanation: Specify Model End of explanation """ # Initialize locations and scales randomly with `tf.Variable`s and # `tfp.util.TransformedVariable`s. _init_loc = lambda shape=(): tf.Variable( tf.random.uniform(shape, minval=-2., maxval=2.)) _init_scale = lambda shape=(): tfp.util.TransformedVariable( initial_value=tf.random.uniform(shape, minval=0.01, maxval=1.), bijector=tfb.Softplus()) n_counties = df.county.nunique() surrogate_posterior = tfd.JointDistributionSequentialAutoBatched([ tfb.Softplus()(tfd.Normal(_init_loc(), _init_scale())), # scale_prior tfd.Normal(_init_loc(), _init_scale()), # intercept tfd.Normal(_init_loc(), _init_scale()), # floor_weight tfd.Normal(_init_loc([n_counties]), _init_scale([n_counties]))]) # county_prior """ Explanation: Specify surrogate posterior We now put together a surrogate family $q_{\lambda}$, where the parameters $\lambda$ are trainable. In this case, our family is independent multivariate normal distributions, one for each parameter, and $\lambda = {(\mu_j, \sigma_j)}$, where $j$ indexes the four parameters. The method we use to fit the surrogate family uses tf.Variables. We also use tfp.util.TransformedVariable along with Softplus to constrain the (trainable) scale parameters to be positive. Additionally, we apply Softplus to the entire scale_prior, which is a positive parameter. We initialize these trainable variables with a bit of jitter to aid in optimization. End of explanation """ optimizer = tf.optimizers.Adam(learning_rate=1e-2) losses = tfp.vi.fit_surrogate_posterior( target_log_prob_fn, surrogate_posterior, optimizer=optimizer, num_steps=3000, seed=42, sample_size=2) (scale_prior_, intercept_, floor_weight_, county_weights_), _ = surrogate_posterior.sample_distributions() print(' intercept (mean): ', intercept_.mean()) print(' floor_weight (mean): ', floor_weight_.mean()) print(' scale_prior (approx. mean): ', tf.reduce_mean(scale_prior_.sample(10000))) fig, ax = plt.subplots(figsize=(10, 3)) ax.plot(losses, 'k-') ax.set(xlabel="Iteration", ylabel="Loss (ELBO)", title="Loss during training", ylim=0); """ Explanation: Note that this cell can be replaced with tfp.experimental.vi.build_factored_surrogate_posterior, as in: python surrogate_posterior = tfp.experimental.vi.build_factored_surrogate_posterior( event_shape=joint.event_shape_tensor()[:-1], constraining_bijectors=[tfb.Softplus(), None, None, None]) Results Recall that our goal is to define a tractable parameterized family of distributions, and then select parameters so that we have a tractable distribution that is close to our target distribution. We have built the surrogate distribution above, and can use tfp.vi.fit_surrogate_posterior, which accepts an optimizer and a given number of steps to find the parameters for the surrogate model minimizing the negative ELBO (which corresonds to minimizing the Kullback-Liebler divergence between the surrogate and the target distribution). The return value is the negative ELBO at each step, and the distributions in surrogate_posterior will have been updated with the parameters found by the optimizer. End of explanation """ county_counts = (df.groupby(by=['county', 'county_code'], observed=True) .agg('size') .sort_values(ascending=False) .reset_index(name='count')) means = county_weights_.mean() stds = county_weights_.stddev() fig, ax = plt.subplots(figsize=(20, 5)) for idx, row in county_counts.iterrows(): mid = means[row.county_code] std = stds[row.county_code] ax.vlines(idx, mid - std, mid + std, linewidth=3) ax.plot(idx, means[row.county_code], 'ko', mfc='w', mew=2, ms=7) ax.set( xticks=np.arange(len(county_counts)), xlim=(-1, len(county_counts)), ylabel="County effect", title=r"Estimates of county effects on log radon levels. (mean $\pm$ 1 std. dev.)", ) ax.set_xticklabels(county_counts.county, rotation=90); """ Explanation: We can plot the estimated mean county effects, along with the uncertainty of that mean. We have ordered this by number of observations, with the largest on the left. Notice that the uncertainty is small for the counties with many observations, but is larger for the counties that have only one or two observations. End of explanation """ fig, ax = plt.subplots(figsize=(10, 7)) ax.plot(np.log1p(county_counts['count']), stds.numpy()[county_counts.county_code], 'o') ax.set( ylabel='Posterior std. deviation', xlabel='County log-count', title='Having more observations generally\nlowers estimation uncertainty' ); """ Explanation: Indeed, we can see this more directly by plotting the log-number of observations against the estimated standard deviation, and see the relationship is approximately linear. End of explanation """ %%shell exit # Trick to make this block not execute. radon = read.csv('srrs2.dat', header = TRUE) radon = radon[radon$state=='MN',] radon$radon = ifelse(radon$activity==0., 0.1, radon$activity) radon$log_radon = log(radon$radon) # install.packages('lme4') library(lme4) fit <- lmer(log_radon ~ 1 + floor + (1 | county), data=radon) fit # Linear mixed model fit by REML ['lmerMod'] # Formula: log_radon ~ 1 + floor + (1 | county) # Data: radon # REML criterion at convergence: 2171.305 # Random effects: # Groups Name Std.Dev. # county (Intercept) 0.3282 # Residual 0.7556 # Number of obs: 919, groups: county, 85 # Fixed Effects: # (Intercept) floor # 1.462 -0.693 """ Explanation: Comparing to lme4 in R End of explanation """ print(pd.DataFrame(data=dict(intercept=[1.462, tf.reduce_mean(intercept_.mean()).numpy()], floor=[-0.693, tf.reduce_mean(floor_weight_.mean()).numpy()], scale=[0.3282, tf.reduce_mean(scale_prior_.sample(10000)).numpy()]), index=['lme4', 'vi'])) """ Explanation: The following table summarizes the results. End of explanation """
widdowquinn/SI_Holmes_etal_2017
notebooks/02-full_model_fit.ipynb
mit
%pylab inline import os import pickle import warnings; warnings.filterwarnings('ignore') import numpy as np import pandas as pd import pystan import scipy import seaborn as sns; sns.set_context('notebook') from Bio import SeqIO import tools """ Explanation: <img src="images/JHI_STRAP_Web.png" style="width: 150px; float: right;"> Supplementary Information: Holmes et al. 2020 2. Full model fitting This notebook describes fitting of a Bayesian hierarchical model of the effects of control (growth) and treatment (passage) on individual genes from E. coli DH10B (carrier) and Sakai (BAC load), to data obtained using a multi-E. coli microarray. Much of the code for the visualisation, analysis and data manipulation of the fitting results is found in the associated Python module tools.py, which should also be present in this directory. The model fit can be downloaded directly from the Zenodo repository, for use in this notebook: A code cell in the notebook below will attempt to make this download for you if the file does not already exist. Table of Contents Experiment summary and interpretation Building the model Stan model construction Define and fit the Stan model Extract the fit Inspecting the fit Median parameter estimates Identifying locus tags that confer an advantage under treatment Plotting distribution of effects Identifying candidates Manuscript Figure 1 Experiment summary and interpretation <a id="summary"></a> The experiment involves measuring changes in microarray probe intensity before and after a pool of bacteria is subjected to one of two processes: a sample from the pool is grown in media to a defined OD, then subsampled. This growth/subsample process is repeated n times. [control] a sample from the pool is applied to plant leaves, subsampled, and that subsample grown in media to a defined OD, then subsampled. This passage/subsample/growth/subsample process is repeated n times. [treatment] In a single replicate, the microarray is exposed to genomic DNA extracted from the pool (i) before the experiment begins, and (ii) after the experiment concludes. Three replicates are performed. <br /><div class="alert-success"> <b>All genes in all samples go through the growth and subsampling part of the experiment, and we wish to estimate the effect of passage and subsampling on individual genes.</b> </div> The pool of bacteria comprises E. coli DH10B as a carrier organism. The pool is heterogeneous, in that individual cells also contain BACs encoding random stretches of the E. coli Sakai chromosome. We therefore expect carrier organism genes to be unaffected by passage (treatment), and for any effects to be detectable only for genes that originate from E. coli Sakai. <br /><div class="alert-success"> <b>We expect that genes conferring a phenotypic/selective advantage only for association with the plant should be enriched at the end of the treatment experiment, but not at the end of the control experiment. Sakai genes that are enriched in both treatment and control experiments may be generally advantageous for growth, but those giving a selective advantage on passage through the plant could be specifically adaptive in an environmental context.</b> </div> <br /><div class="alert-danger"> <b>As the BACs describe contiguous regions of the E. coli Sakai genome, there is the possibility that linkage disequilibrium could result in some genes that do not confer an advantage by themselves apparently displaying enrichment after treatment.</b> </div> If the biological function conferring an advantage during passage is encoded by a suite of coregulated genes in an operon, we might expect all members of this suite to show evidence of enrichment after passage. It is likely that clusters of enrichment for operons or regulons post-passage will be seen in the results. Although we are not accounting for this clustering or association by operon directly in this model, it is a possible additional hierarchical term in future iterations of the model. We should expect there to be a selective burden to the carriage of additional non-functional gDNA as BACs, so we might also anticipate a slightly negative effect on recovery under control conditions. Python imports End of explanation """ # load clean, normalised, indexed data data = pd.read_csv(os.path.join("datasets", "normalised_array_data.tab"), sep="\t") # full dataset #data = pd.read_csv("datasets/reduced_locus_data.tab", sep="\t") # reduced dataset #data = data[:100] # uncomment this for debugging # useful values locus_tags = data['locus_tag'].unique() ntags = len(locus_tags) arrays = data['repXtrt'].unique() narrays = len(arrays) # Create output directory and filename to hold the fitted model outdir = "model_fits" os.makedirs(outdir, exist_ok=True) outfile = os.path.join(outdir, 'full_model_fit.pkl') """ Explanation: Building the model <a id="building"></a> We assume that each array probe $i$ (array probes take a unique values of $i$ in the context of the entire experiment; that is, $i$ is unique for probe X replicate X treatment) measures hybridisation of genomic DNA (gDNA) in the sample that corresponds to a single gene $j[i]$, and that the measured intensity of probe $i$ relates directly to the corresponding amount of gDNA in the sample. There may be multiple probes relating to a single gene, so it is possible that $j[p] = j[q], p \neq q$. <div class="alert-success"> <b>This establishes a basis for pooling probe-level effects as samples of the gene-level effect.</b> </div> We define the (input) measurement of a probe before an experiment as $x_i$, and the (output) measurement of that probe after the experiment as $y_i$. We assume that the measurement of each probe is subject to random experimental/measurement error that is normally-distributed with mean zero and variance $\sigma_y^2$. The actual quantity of DNA measured after the experiment can then be represented as $\hat{y}$, and the irreducible error in this experiment as $\epsilon$ ($\epsilon_i$ serves to include the irreducible errors in measuring both $x_i$ and $y_i$; all errors are assumed to be Normal, so their linear combinations are also Normal). $$y_i = \hat{y_i} + \epsilon_i$$ $$\epsilon_i \sim N(0, \sigma_y^2) \implies y_i \sim N(\hat{y_i}, \sigma_y^2)$$ The relationship between the input and output DNA quantities measured by a single probe can be represented as $\hat{y_i} = f(x_i)$. That is to say, that the measured input DNA quantity $x_i$ is a predictor of the output quantity. This relationship will be modelled as the sum of two linear effects: $$\textrm{control effect} = \alpha + \beta x$$ $$\textrm{treatment effect} = \gamma + \delta x$$ $$\hat{y_i} = \textrm{control effect}(x_i) + \textrm{treatment effect}(x_i) = \alpha + \beta x_i + \gamma + \delta x_i$$ As these are linear effects, we have intercept/offset parameters ($\alpha$, $\gamma$) and gradient/slope parameters ($\beta$, $\delta$). <div class="alert-success"> <b>Where $\beta$ or $\delta$ are large, they would indicate large $x_i$-dependent effects of the control (growth) and treatment (passage) parts of the experiment respectively.</b> </div> As formulated above, the four parameters would be identical for all probes, but we are interested in estimating the control and treatment effects for individual genes, so we require a set of parameters for each gene (as it corresponds to probe $i$): $j[i]$. This is appropriate for the effects of growth/treatment that are specific to the levels of a single gene: $\beta$ and $\delta$. The remaining parameters $\alpha$ and $\gamma$, the offsets from zero for each probe, could be considered to be constant across each replicate of both control and treatment experiments. They are possibly more realistically considered to be different for each array (i.e. each combination of replicate and treatment). <div class="alert-success"> <b>The offset for any particular array can be hierarchically modelled as being drawn from a distribution representing all arrays, and we require one parameter for each of the arrays, so that for probe $i$ the corresponding array for that experiment is $k[i]$.</b> </div> As a result, we estimate $\alpha_{k[i]}$, $\beta_{j[i]}$, $\gamma_{k[i]}$, $\delta_{j[i]}$, and the relationship for each probe is modelled as: $$\hat{y_i} = \textrm{control effect}{j[i]}(x_i) + \textrm{treatment effect}{j[i]}(x_i) = \alpha_{k[i]} + \beta_{j[i]} x_i + \gamma_{k[i]} + \delta_{j[i]} x_i$$ The parameters $\alpha_{k[i]}$, $\beta_{j[i]}$, $\gamma_{k[i]}$, $\delta_{j[i]}$ (and $\epsilon_i$) are to be estimated by the model fit. <br /><div class="alert-success"> <b>We assume that the values of each parameter, e.g. $\alpha_{k[i]}$, are drawn from a single pooled distribution for that parameter, $\alpha \sim \textrm{some distribution}$.</b> </div> This pooling ensures that our fits are not completely pooled as a single estimate $\alpha_{k[i]} = \alpha$, which would imply that all parameter estimates are constant for all genes/arrays, a situation that would be completely uninformative for our goal to identify gene-level effects, and which would underfit our model. It also means that our estimates are not completely unpooled, which would allow all parameter estimates to vary independently. That situation would be equivalent to simultaneously fitting independent linear relationships to each gene, and so risk overfitting our model to the measured data. <br /><div class="alert-warning"> <b>NOTE: By using a pooled distribution, we allow a parameter estimate for each gene to influence the estimates of that parameter for all other genes in the experiment, constrained by an expected distribution of that parameter's values. To do this, we define a prior distribution for each parameter, but we do not specify its mean or variance, allowing the parameters of these pooled distributions also to be estimated when fitting our model.</b> </div> For each parameter's prior we choose a Cauchy distribution, because it has fat tails and infinite variance. This does not constrain outlying and extreme values (those we are interested in) so much as other distributions (e.g. Normal or Student's t): $$\alpha_{k[i]} \sim Cauchy(\mu_{\alpha}, \sigma_{\alpha}^2)$$ $$\beta_{j[i]} \sim Cauchy(\mu_{\beta}, \sigma_{\beta}^2)$$ $$\gamma_{k[i]} \sim Cauchy(\mu_{\gamma}, \sigma_{\gamma}^2)$$ $$\delta_{j[i]} \sim Cauchy(\mu_{\delta}, \sigma_{\delta}^2)$$ Each parameter's prior distribution requires a fit of both its mean and variance, and these also become parameters in our model. The means are free to vary, but we assume that the variance of each parameter's prior can be drawn from a Uniform distribution on the range (0, 100): $$\sigma_{\alpha} \sim U(0, 100)$$ $$\sigma_{\beta} \sim U(0, 100)$$ $$\sigma_{\gamma} \sim U(0, 100)$$ $$\sigma_{\delta} \sim U(0, 100)$$ <div class="alert-success"> <b>We therefore construct the following model of the experiment:</b> $$\hat{y_i} = \alpha_{k[i]} + \beta_{j[i]} x_i + \gamma_{k[i]} t_i + \delta_{j[i]} t_i x_i$$ $$y_i \sim N(\hat{y_i}, \sigma_y^2)$$ $$\alpha_{k[i]} \sim Cauchy(\mu_{\alpha}, \sigma_{\alpha}^2)$$ $$\beta_{j[i]} \sim Cauchy(\mu_{\beta}, \sigma_{\beta}^2)$$ $$\gamma_{k[i]} \sim Cauchy(\mu_{\gamma}, \sigma_{\gamma}^2)$$ $$\delta_{j[i]} \sim Cauchy(\mu_{\delta}, \sigma_{\delta}^2)$$ $$\sigma_{\alpha} \sim U(0, 100)$$ $$\sigma_{\beta} \sim U(0, 100)$$ $$\sigma_{\gamma} \sim U(0, 100)$$ $$\sigma_{\delta} \sim U(0, 100)$$ $$\sigma_y \sim U(0, \infty)$$ <ul> <li> $y_i$: measured intensity output on the array for probe $i$ (specific to each replicate) <li> $\hat{y_i}$: actual probe intensity for probe $i$ (specific to each replicate) <li> $x_i$: measured intensity input on the array for probe $i$ (specific to each replicate) <li> $t_i$: 0/1 pseudovariable indicating whether the probe $i$ was measured in a control (0) or treatment (1) experiment <li> $\alpha_{k[i]}$: control effect offset for treatment X replicate $k$ (used for probe $i$) <li> $\mu_{\alpha}$: mean control effect offset for all arrays <li> $\sigma_{\alpha}$: control effect offset variance for all arrays <li> $\beta_{j[i]}$: control effect slope for gene $[j[i]$ <li> $\mu_{\beta}$: mean control effect slope for all genes <li> $\sigma_{\beta}$: control effect slope variance for all genes <li> $\gamma_{k[i]}$: treatment effect offset for treatment X replicate $k$ (used for probe $i$) <li> $\mu_{\gamma}$: mean treatment effect offset for all arrays <li> $\sigma_{\gamma}$: treatment effect offset variance for all arrays <li> $\delta_{j[i]}$: treatment effect slope for gene $j[i]$ <li> $\mu_{\delta}$: mean treatment effect slope for all genes <li> $\sigma_{\delta}$: treatment effect slope variance for all genes <li> $\sigma_y$: variance in measurement due to irreducible error </ul> </div> Load input data for fit In the cells below we load in the data to be fit, and define useful variables for inspecting/analysing the data later: locus_tags: the unique locus tags represented in the dataset ntags: the number of unique locus tags arrays: the arrays (combinations of replicate X treatment) used in the experiment narrays: the number of arrays used outdir: path to the directory in which to place model fit output outfile: path to the model fit output file (pickled dataframe) End of explanation """ # define unpooled stan model treatment_model = """ data { int<lower=0> N; int<lower=0> J; int<lower=0> K; int<lower=1, upper=J> tag[N]; int<lower=1, upper=K> array[N]; vector[N] t; vector[N] x; vector[N] y; } parameters { vector[K] a; vector[J] b; vector[K] g; vector[J] d; real mu_a; real mu_b; real mu_g; real mu_d; real<lower=0> sigma; real<lower=0,upper=100> sigma_a; real<lower=0,upper=100> sigma_b; real<lower=0,upper=100> sigma_g; real<lower=0,upper=100> sigma_d; } transformed parameters{ vector[N] y_hat; for (i in 1:N) y_hat[i] = a[array[i]] + b[tag[i]] * x[i] + g[array[i]] * t[i] + d[tag[i]] * t[i] * x[i]; } model { sigma_a ~ uniform(0, 100); a ~ cauchy(mu_a, sigma_a); sigma_b ~ uniform(0, 100); b ~ cauchy(mu_b, sigma_b); sigma_g ~ uniform(0, 100); g ~ cauchy(mu_g, sigma_g); sigma_d ~ uniform(0, 100); d ~ cauchy(mu_d, sigma_d); y ~ normal(y_hat, sigma); } """ # relate python variables to stan variables treatment_data_dict = {'N': len(data), 'J': ntags, 'K': narrays, 'tag': data['locus_tag_index'] + 1, 'array': data['repXtrt_index'] + 1, 't': data['treatment'], 'x': data['log_input'], 'y': data['log_output']} """ Explanation: Stan model construction <a id="build_stan"></a> We need to define data, parameters and our model for Stan. <div class="alert-success"> In the `data` block, we have: <ul> <li> `N`: `int`, the number of data points <li> `J`: `int`, the number of unique locus tags (`J` < `N`) <li> `K`: `int`, the number of unique treatment X replicate combinations (arrays) <li> `array`: `int[N]`, an index list of arrays <li> `tag`: `int[N]`, an index list of locus tags <li> `t`: `vector[N]`, 0/1 control/treatment values for each probe <li> `x`: `vector[N]`, the input log(intensity) values <li> `y`: `vector[N]`, the output log(intensity) values </ul> In the `parameter` block, we have: <ul> <li> `a`: `real vector[K]`, estimated offset effect on log(intensity) of the *control* for each array <li> `mu_a`: `real`, an unconstrained value to be fit that represents the mean of the Cauchy distribution for the *control* effect offset, for all arrays <li> `sigma_a`: `real<lower=0,upper=100>`, standard deviation of the Cauchy distribution for the *control* effect offset, for all arrays <li> `b`: `real vector[J]`, estimated slope effect on log(intensity) of the *control* for each locus tag/gene <li> `mu_b`: `real`, an unconstrained value to be fit that represents the mean of the Cauchy distribution for the *control* effect slope, for all locus tags <li> `sigma_b`: `real<lower=0,upper=100>`, standard deviation of the Cauchy distribution for the *control* effect slope, for all locus tags <li> `g`: `real vector[K]`, estimate of the influence of treatment on the output measured intensity (offset) for array <li> `mu_g`: `real`, an unconstrained value to be fit that represents the mean of the Cauchy distribution for the offset for all arrays due to *treatment* <li> `sigma_g`: `real<lower=0,upper=100>`, standard deviation of the Cauchy distribution for the offset for all arrays due to *treatment* <li> `d`: `real vector[J]`, estimate of the influence of treatment on the output measured intensity (slope) for each locus tag/gene <li> `mu_d`: `real`, an unconstrained value to be fit that represents the mean of the Cauchy distribution for the slope for all locus tags due to *treatment* <li> `sigma_d`: `real<lower=0,upper=100>`, standard deviation of the Cauchy distribution for the slope for all locus tags due to *treatment* <li> `sigma`: `real<lower=0>`, the irreducible error in the experiment/model </ul> We also define a `transformed parameter`: <ul> <li> `y_hat[i] <- b[tag[i]] * x[i] + a[array[i]] + g[tag[i]] * t[i] + d[array[i]] * t[i] * x[i]`: the linear relationship describing $\hat{y}$, our estimate of experimental output intensity, which is subject to variance `sigma`. </ul> </div> Define and fit the Stan model <a id="fit_stan"></a> In the cells below we define the model to be fit, in the Stan language, conduct the fit, and save the fit out to a pickled dataframe (or load it in from one, depending on which code is commented out). End of explanation """ # (1) USE THIS CELL TO RUN THE STAN FIT - takes a few hours on my laptop #treatment_fit = pystan.stan(model_code=treatment_model, # data=treatment_data_dict, # iter=1000, chains=2, # seed=tools.SEED) # (2) USE THIS CELL TO SAVE THE STAN FIT TO A PICKLE FILE #unpermutedChains = treatment_fit.extract() #unpermutedChains_df = pd.DataFrame([dict(unpermutedChains)]) #pickle.dump(unpermutedChains_df, open(outfile, 'wb')) # (3) USE THIS CELL TO DOWNLOAD THE STAN FIT FROM ZENODO: DOI:10.5281/zenodo.269638 # The file will not be downloaded if it already exists locally. # The file is 0.5GB in size, so may take some time to download import urllib.request if not os.path.isfile(outfile): zenodo_url = "https://zenodo.org/record/269638/files/full_model_fit.pkl" response = urllib.request.urlretrieve(zenodo_url, outfile) # (4) USE THIS CELL TO LOAD THE STAN FIT FROM A PICKLE FILE # Import the previously-fit model treatment_fit = pd.read_pickle(open(outfile, 'rb')) """ Explanation: <div class="alert-danger"> <b>At this point, you have two options to obtain the model fit data</b> </div> Run the model fit 'live' in the notebook. This may take several hours. USE CELL (1) (optionally) save the newly-generated model fit to a local file. USE CELL (2) Load the model fit from a local file. USE CELL (4) If you have not generated the data locally, then you can download it from Zenodo USE CELL (3) FIRST. It may be quicker to download the data from Zenodo using the button below, than to use cell (3), but be sure to place the downloaded file in the correct location as specified in the variable outfile. End of explanation """ # Get summary data for parameter estimates # use 'fit' for the model fit directly, and 'df'for loaded pickled data (estimates_by_probe, estimates) = tools.extract_variable_summaries(treatment_fit, 'df', ['a', 'b', 'g', 'd'], [arrays, locus_tags, arrays, locus_tags], data) # Inspect the data, one row per experiment probe estimates_by_probe.head() # Inspect the data, one row per locus tag estimates.head() # Separate estimates for Sakai and DH10B into two different dataframes sakai_estimates = tools.split_estimates(estimates, 'sakai') dh10b_estimates = tools.split_estimates(estimates, 'dh10b') """ Explanation: Extract the fit <a id="extract_stan"></a> <br /><div class="alert-warning"> <b>In the cells below we load in the contents of the pickled output (if the fit has already been run), and then extract useful summary information about mean, median, variance, and credibility intervals for the parameter estimates.</b> </div> <div class="alert-success"> <ul> <li> parameters $\alpha$, $\beta$, $\gamma$ and $\delta$ are represented by their Roman letter equivalents `a`, `b`, `g` and `d`. <li> `*_mean` and `*_median` are the mean and median estimates for the parameter over the ensemble <li> `*_sem` is the standard deviation for the parameter estimate over the ensemble <li> `*_Npc` is the *N*th percentile for the parameter estimate, over the ensemble. These can be combined to obtain credibility intervals (e.g. the range `a_25pc`..`a_75pc` constitutes the 50% CI for $\alpha_{j[i]}$. </div> End of explanation """ # Visualise median values for parameter estimates of alpha and gamma tools.boxplot_medians(estimates_by_probe, ['a', 'g']) # Visualise median values for parameter estimates of beta and delta tools.boxplot_medians(estimates, ['b', 'd']) """ Explanation: Inspecting the fit <a id="inspect_fit"></a> In the cells below, we visualise the fitted estimates for each of the parameters $\alpha$, $\beta$, $\gamma$, and $\delta$ as: box plots of median estimates for each locus tag relationship between control and treatment effects in Sakai plots of 50% credibility interval range and median estimate for each locus tag to identify locus tags with a possible selective advantage Median parameter estimates <a id="median_estimates"></a> We first inspect the range of fitted estimates to get an overview of the relationships for the data as a whole, and then examine whether this relationship varies by E. coli isolate. Making boxplots for the full set of fitted parameter estimates, for both isolates: End of explanation """ # Visualise median values for Sakai parameter estimates tools.boxplot_medians(dh10b_estimates, ['b', 'd']) """ Explanation: <div class="alert-success"> For this fit we can see that the estimates are all, in the main, tightly-distributed. Most estimated (median) values of $\alpha$ (control intercept), $\gamma$ (treatment intercept), and $\delta$ (treatment slope) are close to zero. Most estimated values of $\beta$ are close to (but slightly less than) unity. <b>This implies that:</b> <ul> <li> <b>The linear relationship between input and output intensity due to the control effects (growth only) is, for most genes in the experiment, a slight reduction of output intensity with respect to input intensity value, and on the whole the effect of the control/growth is neutral [median $\alpha$ ≈ 0, median $\beta$ ≈ 1]</b> <li> <b>For most genes in the experiment there is no treatment effect due to exposure to the plant [median $\gamma$ ≈ 0, median $\delta$ ≈ 0]</b> </ul> </div> <br /><div class="alert-warning"> <b>There are, however, a considerable number of outlying median values for each parameter, which suggests that a number of genes have associated parameter values that are affected by either control (growth) or treatment (passage).</b> </div> DH10B Considering boxplots of estimated $\beta_{j[i]}$ and $\delta_{j[i]}$ for the DH10B (carrier) isolate only: End of explanation """ # Visualise median values for Sakai parameter estimates tools.boxplot_medians(sakai_estimates, ['b', 'd']) """ Explanation: it is clear that the median parameter estimates for DH10B are extremely restricted in their range: $0.93 < \beta < 0.98$ $-0.065 < \delta < 0.045$ <div class="alert-success"> The control effect appears to be essentially *neutral*, in that the output intensity is almost a 1:1 linear relationship with the input intensity, but it is striking that the median estimates of $\gamma$ and $\delta$ are very close to zero, suggesting that passage (treatment) has almost no effect on this relationship, for any DH10B locus tag. <b>This is exactly what would be expected for DH10B as the carrier isolate.</b> </div> Sakai Considering the Sakai isolate parameter estimates for $\beta_{j[i]}$ and $\gamma_{j[i]}$ only: End of explanation """ # Plot estimated parameters for treatment effects against control effects for Sakai fig, ax = plt.subplots(1, 1, figsize=(6,6)) ax.scatter(sakai_estimates['d_median'], sakai_estimates['b_median'], alpha=0.2) ax.set_xlabel('delta (median)') ax.set_ylabel('beta (median)'); """ Explanation: By contrast to the results for DH10B, the median parameter estimates for Sakai have many large value outliers, though the bulk of estimates are close to the values seen for DH10B: $0.2 < \beta < 1.4$ $-1.5 < \delta < 0.5$ <div class="alert-success"> This indicates that we see the expected result, that strong variability of control and treatment effects are effectively confined to the Sakai BAC fragments. <b>It is expected that some genes/operons may be relatively advantageous in either growth (control) or passage (treatment) conditions, or both.</b> </div> We can visualise the relationships between parameter estimates for control and treatment effects in a scatterplot of control effect ($\beta$) against treatment effect ($\delta) for each locus tag. This plot can be considered in four quadrants, which are delineated by the bulk of the data which describes orthogonal effects of locus tags on growth and treatment: <br /><div class="alert-success"> <b>(i.e. for most locus tags, there is either an effect on treatment or control, but not both)</b> </div> (upper left) positive effect on growth, negative effect for treatment: may be related to ability to use growth medium more efficiently (upper right) positive effect on both growth and treatment: no locus tags display this characteristic (lower right) positive effect on treatment, negative effect for control: may be related to ability to use/exploit the plant, that is suppressive in the medium (lower left) negative effect on both growth and treatment: most locus tags that display an interaction lie in this group End of explanation """ # Label locus tags with positive effects for control and treatment sakai_estimates = tools.label_positive_effects(sakai_estimates) """ Explanation: <br /><div class="alert-warning"> The strong cross-like distribution indicates that most parameter estimates of $\beta$ or $\delta$ that vary from those of the bulk do so orthogonally in either treatment or control conditions, but not both. <br /><br /> <b>Where Sakai genes have an estimated effect under both conditions, this is typically negative for both treatment and control (lower left quadrant).</b> </div> Identifying locus tags that confer an advantage under treatment and/or control <a id="locus_tags"></a> We use a 50% credibility interval to determine whether the effect of a gene on passage is likely to be positive. Under this assumption, we identify locus tags for which the median estimate of $\delta$ is positive, and the central 50% of the parameter estimates for $\delta$ (the 50% credibility interval) does not include zero. We label these locus tags as trt_pos in the dataframe. <br /><div class="alert-success"> These locus tags correspond to the genes that we should believe confer a selective advantage in passage/treatment (i.e. we require our estimate to be credibly positive). </div> Likewise, we use a 50% credibility interval to determine whether the effect of a gene on surviving growth (control) is positive. If the 50% CI for $\beta$ does not include the 97.5 percentile for all estimates of $\beta$ (as an upper estimate of overall dataset centrality for this dataset), and the median value of $\beta$ is greater than this value, we consider that the effect of the gene on surviving growth conditions is positive. We label these locus tags as ctl_pos in the dataframe. End of explanation """ # Count locus tags in each of the positive groups counts = [sum(sakai_estimates[col]) for col in ('trt_pos', 'ctl_pos', 'combined')] print("treatment positive: {0}\ncontrol positive: {1}\nboth: {2}".format(*counts)) """ Explanation: We can count the number of locus_tags in each of the groups: End of explanation """ sakai_chromosome = sakai_estimates.loc[sakai_estimates['locus_tag'].str.startswith('ECs')] sakai_pOSAK = sakai_estimates.loc[sakai_estimates['locus_tag'].str.startswith('pOSAK1')] sakai_pO157 = sakai_estimates.loc[(sakai_estimates['locus_tag'].str.startswith('pO157')) | (sakai_estimates['locus_tag'].str.startswith('ECp'))] # Sakai chromosome sakai_chromosome_annotated = tools.annotate_locus_tags(sakai_chromosome, os.path.join('..', 'data', 'Sakai', 'GCF_000008865.1_ASM886v1_genomic.gbff')) sakai_chromosome_annotated.sort_values('startpos', inplace=True) #sakai_chromosome_annotated.head(15) # pOSAK1 sakai_pOSAK_annotated = tools.annotate_locus_tags(sakai_pOSAK, os.path.join('..', 'data', 'Sakai', 'GCF_000008865.1_ASM886v1_genomic.gbff')) sakai_pOSAK_annotated.sort_values('startpos', inplace=True) #sakai_pOSAK_annotated.head(15) # pECp sakai_pO157_annotated = tools.annotate_locus_tags(sakai_pO157, os.path.join('..', 'data', 'Sakai', 'GCF_000008865.1_ASM886v1_genomic.gbff')) sakai_pO157_annotated.sort_values('startpos', inplace=True) #sakai_pO157_annotated.head(15) # Regions of interest regions = [('S-loop 71', 'ECs1276', 'ECs1288', 1.3), ('SpLE1', 'ECs1299', 'ECs1410', 1.5), ('S-loop 225', 'ECs4325', 'ECs4341', 1.5), ('S-loop 231', 'ECs4379', 'ECs4387', 1.3)] annotations = {k:(tools.get_lt_index(v0, sakai_chromosome_annotated), tools.get_lt_index(v1, sakai_chromosome_annotated), v2) for k, v0, v1, v2 in regions} # Plot genome-wide estimates of beta for Sakai and mark values that don't include the median beta in 50% CI beta_thresh = np.median(sakai_chromosome_annotated['b_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of beta for Sakai chromosome' plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) # Plot on the figure axes tools.plot_parameter(sakai_chromosome_annotated, ax, 'b', beta_thresh, annotations=annotations); # Regions of interest regions = [('S-loop 71', 'ECs1276', 'ECs1288', 1), ('SpLE1', 'ECs1299', 'ECs1410', 1.8), ('S-loop 225', 'ECs4325', 'ECs4341', 1.8), ('S-loop 231', 'ECs4379', 'ECs4387', 1)] annotations = {k:(tools.get_lt_index(v0, sakai_chromosome_annotated), tools.get_lt_index(v1, sakai_chromosome_annotated), v2) for k, v0, v1, v2 in regions} # Plot genome-wide estimates of delta for Sakai and mark values that don't include zero in 50%CI delta_thresh = np.median(sakai_chromosome_annotated['d_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of delta for Sakai chromosome' plt.title("{0} [threshold: {1:.2f}]".format(title, delta_thresh)) tools.plot_parameter(sakai_chromosome_annotated, ax, 'd', delta_thresh, annotations=annotations) # Plot genome-wide estimates of beta for Sakai and mark values that don't include the median beta in 50% CI beta_thresh = np.median(sakai_pOSAK_annotated['b_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of beta for Sakai plasmid pOSAK' plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) tools.plot_parameter(sakai_pOSAK_annotated, ax, 'b', beta_thresh) # Plot genome-wide estimates of delta for Sakai and mark values that don't include zero in 50% CI delta_thresh = np.median(sakai_pOSAK_annotated['d_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of delta for Sakai plasmid pOSAK' plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) tools.plot_parameter(sakai_pOSAK_annotated, ax, 'd', delta_thresh) # Regions of interest regions = [('StcE', 'pO157p01', 'pO157p01', 0.98), ('etp T2SS', 'pO157p02', 'pO157p14', 1)] annotations = {k:(tools.get_lt_index(v0, sakai_pO157_annotated), tools.get_lt_index(v1, sakai_pO157_annotated), v2) for k, v0, v1, v2 in regions} # Plot genome-wide estimates of beta for Sakai and mark values that don't include the median beta in 50% CI beta_thresh = np.median(sakai_pO157_annotated['b_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of beta for Sakai plasmid p0157' plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) tools.plot_parameter(sakai_pO157_annotated, ax, 'b', beta_thresh, annotations=annotations) # Regions of interest regions = [('StcE', 'pO157p01', 'pO157p01', 0.13), ('etp T2SS', 'pO157p02', 'pO157p14', 0.19)] annotations = {k:(tools.get_lt_index(v0, sakai_pO157_annotated), tools.get_lt_index(v1, sakai_pO157_annotated), v2) for k, v0, v1, v2 in regions} # Plot genome-wide estimates of delta for Sakai and mark values that don't include zero in 50% CI delta_thresh = np.median(sakai_pO157_annotated['d_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of delta for Sakai plasmid pO157' plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) tools.plot_parameter(sakai_pO157_annotated, ax, 'd', delta_thresh, annotations=annotations) """ Explanation: which indicates, with these assumptions, that: <div class="alert-success"> <ul> <b> <li> 115 genes have a credible positive effect on passage (treatment) <li> 65 genes have a credible positive effect in the growth (control) step <li> no genes have a credible positive effect for both growth and treatment. </b> </ul> </div> (this confirms our observation in the earlier scatterplot) Plotting distribution of effects on the Sakai genome <a id="plot_effects"></a> We can show the estimated effects, and our confidence in those estimates, on a rough representation of the genome by plotting those values for each locus tag, sorted in order on the genome. In the plots that follow, parameter estimates for each locus tag are rendered as points (the median estimate), with the 50% credibility interval for the estimate indicated as a vertical line. If the 50% CI includes a threshold value - the median value for the bulk parameter estimate of $\beta$ or $\delta$ - then we consider that there is not strong evidence of an effect on survival due to that gene (compared to the bulk), and the interval is coloured blue. If the interval does not include the corresponding threshold value, then it is coloured either green for a positive effect, or magenta for a negative effect. Sakai We split the Sakai estimates into groups: one for the chromosome, and one for each plasmid pOSAK and pO157, on the basis of the locus tag prefixes, annotating them with their start position on the parent molecule. End of explanation """ # Annotate the DH10B results dh10b_annotated = tools.annotate_locus_tags(dh10b_estimates, os.path.join('..', 'data', 'DH10B', 'GCF_000019425.1_ASM1942v1_genomic.gbff')) dh10b_annotated.sort_values('startpos', inplace=True) # Plot genome-wide estimates of beta for DH10B beta_thresh = np.median(dh10b_estimates['b_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of beta for DH10B', plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) tools.plot_parameter(dh10b_estimates, ax, 'b', beta_thresh) # Plot genome-wide estimates of delta for DH10B delta_thresh = np.median(dh10b_estimates['d_median']) # Create figure with title to hold the plotted axis fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(1, 1, 1) title = 'Estimates of delta for DH10B' plt.title("{0} [threshold: {1:.2f}]".format(title, beta_thresh)) tools.plot_parameter(dh10b_estimates, ax, 'd', delta_thresh) """ Explanation: <div class="alert-success"> These plots indicate that most Sakai genes do not produce parameter estimates that are indicative of credible effects in the control or treatment, in either direction. <br /><br /> Where effects are seen they tend to cluster on the genome, which is as would be expected if operons or gene clusters with common function were responsible for producing an effect. This is suggestive that we are measuring a biological effect, rather than noise. <br /><br /> <b>In general, several clusters of both positive and negative effects appear in the chromosome and pO157 plots for effects due to control ($\beta$) and treatment ($\delta$).</b> </div> DH10B We plot similar representations for the DH10B isolate as a control, and see that all parameter estimates for this isolate's locus tags are very similar. <br /><div class="alert-warning"> There is a weak sinusoidal pattern of fitted estimates. As no gene ordering information is available to the model fit, and there is an apparent symmetry to this pattern, it may reflect a real underlying biological process or structure. </div> End of explanation """ # Generate list of candidates with a positive effect under control or treatment. candidates = sakai_estimates[sakai_estimates['ctl_pos'] | sakai_estimates['trt_pos']] candidates = candidates[['locus_tag', 'b_median', 'ctl_pos', 'd_median', 'trt_pos']].sort_values(['ctl_pos', 'trt_pos', 'locus_tag']) candidates.shape # Inspect the data candidates.head() """ Explanation: Identifying Sakai candidates <a id="candidates"></a> From the information above, we can list the 180 Sakai genes/locus tags that appear to impart a positive selective effect on treatment/passage (the green points/bars in the plots immediately above). End of explanation """ # Restrict candidates only to those with an effect on treatment/passage. trt_only_positive = candidates.loc[candidates['trt_pos'] & ~candidates['ctl_pos']] trt_only_positive.shape """ Explanation: We restrict this set to those genes that only have a credible effect on treatment/passage, identifying 115 genes with positive $\delta$ where the 50% CI does not include zero: End of explanation """ # Annotated locus tags with functions from NCBI GenBank files annotated = tools.annotate_locus_tags(trt_only_positive, os.path.join('..', 'data', 'Sakai', 'GCF_000008865.1_ASM886v1_genomic.gbff')) pd.options.display.max_rows = 115 # force to show all rows annotated """ Explanation: We add a column with the functional annotation of each of the candidates that appear to have a positive selective effect under treatment conditions: End of explanation """ # Write data to file in tab-separated format outfile_annotated = os.path.join('datasets', 'trt_positive.tab') annotated.to_csv(outfile_annotated, sep="\t") """ Explanation: Finally, we write this data out in tab-separated format End of explanation """ # Create figure with no title or xticks to hold the plotted axes fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(20, 26)) # Add subplot for each result # 1) Sakai chromosome regions = [('S-loop 71', 'ECs1276', 'ECs1288', 1), ('SpLE1', 'ECs1299', 'ECs1410', 1.8), ('S-loop 225', 'ECs4325', 'ECs4341', 1.8), ('S-loop 231', 'ECs4379', 'ECs4387', 1)] annotations = {k:(tools.get_lt_index(v0, sakai_chromosome_annotated), tools.get_lt_index(v1, sakai_chromosome_annotated), v2) for k, v0, v1, v2 in regions} delta_thresh = np.median(sakai_chromosome_annotated['d_median']) tools.plot_parameter(sakai_chromosome_annotated, ax1, 'd', delta_thresh, annotations=annotations, label="a) Sakai chromosome") # 2) pO157 plasmid regions = [('StcE', 'pO157p01', 'pO157p01', 0.13), ('etp T2SS', 'pO157p02', 'pO157p14', 0.19)] annotations = {k:(tools.get_lt_index(v0, sakai_pO157_annotated), tools.get_lt_index(v1, sakai_pO157_annotated), v2) for k, v0, v1, v2 in regions} delta_thresh = np.median(sakai_pO157_annotated['d_median']) tools.plot_parameter(sakai_pO157_annotated, ax2, 'd', delta_thresh, annotations=annotations, label="b) Sakai pO157") # 3) DH10B chromosome delta_thresh = np.median(dh10b_estimates['d_median']) tools.plot_parameter(dh10b_estimates, ax3, 'd', delta_thresh, label="c) DH10B chromosome") # Save figure as pdf plt.savefig("figure_1.pdf"); """ Explanation: <a id="figure_1"></a> Manuscript Figure 1 The code in the cell below will reproduce figure 1 from the manuscript. End of explanation """
ffmmjj/desafio-dados-2016
experiments/Analise Exploratoria.ipynb
apache-2.0
from preprocessamento_escola_2011 import escolas_info_train, escolas_info_test """ Explanation: Carregamento e junção dos dados End of explanation """ escolas_info_train.info() """ Explanation: O módulo acima carrega os dados e os divide entre conjunto de treinamento(Para análise exploratória) e conjunto de teste(para validação de hipóteses). Os conjuntos já agrupam os questionários com as médias em língua portuguesa e matemática, além de renomear as questões com um nome mais significativo. As questões também foram agrupadas em categorias(INFRA, SEGURANCA, RECURSOS e BIBLIOTECA) para facilitar possíveis agrupamentos posteriores. End of explanation """ def codificar_questoes(questionario_pd): questionario_tratado_pd = questionario_pd.copy() for questoes in questionario_tratado_pd.filter(regex='Q_.*').columns: questionario_tratado_pd[questoes] = questionario_pd[questoes].map({'A': 3, 'B': 2, 'C': 1, 'D': 0}).fillna(-1) return questionario_tratado_pd def limpar_score(questionario_pd, score_names): questionario_tratado_pd = questionario_pd.copy() for score in score_names: questionario_tratado_pd[score] = questionario_pd[score].str.strip().str.replace(',', '.').str.replace('^$', '-1').astype(float) return questionario_tratado_pd escolas_train_clean = limpar_score(codificar_questoes(escolas_info_train), ['MEDIA_MT', 'MEDIA_LP']) """ Explanation: Limpeza inicial dos dados End of explanation """ escolas_info_clean_pd = escolas_train_clean.copy() escolas_info_clean_pd['MEDIA_LP'] = escolas_train_clean['MEDIA_LP'] escolas_questoes_lp = escolas_train_clean.filter(regex='(Q_.*|MEDIA_LP)') media_lp_corrs = escolas_questoes_lp.corr()['MEDIA_LP'] media_lp_corrs.sort_values(ascending=False).index[1:11] """ Explanation: Checagem de correlações End of explanation """ plt.hist(escolas_train_clean['MEDIA_LP'], bins=20) plt.xlabel('Média em Língua Portuguesa') plt.show() """ Explanation: Distribuição das médias em Língua Portuguesa End of explanation """ # Qualidade da biblioteca, de acordo com o dicionario de dados, encontra-se no campo TX_RESP_Q050 plt.scatter(escolas_train_clean['Q_RECURSOS_BIBLIOTECA'], escolas_train_clean['MEDIA_LP']) plt.xlabel('Qualidade da biblioteca') plt.ylabel('Média em Língua Portuguesa') plt.xticks([-1, 0, 1, 2, 3], ['S/R', 'Inexistente', 'Ruim', 'Regular', 'Bom']) plt.show() """ Explanation: Gráfico de correlação entre Qualidade da Biblioteca e Média em Língua Portuguesa End of explanation """
JorgeDeLosSantos/nusa
docs/nusa-info/es/truss-element.ipynb
mit
%matplotlib inline from nusa import * # Importando nusa E,A = 210e9, 3.1416*(10e-3)**2 n1 = Node((0,0)) n2 = Node((2,0)) n3 = Node((0,2)) e1 = Truss((n1,n2),E,A) e2 = Truss((n1,n3),E,A) e3 = Truss((n2,n3),E,A) m = TrussModel() for n in (n1,n2,n3): m.add_node(n) for e in (e1,e2,e3): m.add_element(e) m.add_constraint(n1, ux=0, uy=0) m.add_constraint(n2, uy=0) m.add_force(n3, (500,0)) m.plot_model() m.solve() m.plot_deformed_shape() m.plot_deformed_shape() m.simple_report() """ Explanation: Elemento Truss El elemento Truss plano es un elemento finito con coordenadas locales y globales, tiene un modulo de elasticidad $E$, una sección transversal $A$ y una longitud $L$. Cada elemento tiene dos nodos y un ángulo de inclinación $\theta$ medido en sentido antihorario desde el eje $X$ global, como se muestra en la figura. Sean $C=\cos(\theta)$ y $S=\sin(\theta)$, entonces la matriz de rigidez por elemento está dada por: $$ k = \frac{EA}{L} \begin{bmatrix} C^2 & CS & -C^2 & -CS \ CS & S^2 & -CS & -S^2 \ -C^2 & -CS & C^2 & CS \ -CS & -S^2 & CS & S^2 \ \end{bmatrix} $$ <img src="src/truss-element/truss_element.PNG" width="200px"> El elemento Truss tiene dos grados de libertad en cada nodo: desplazamientos en X e Y. La fuerza en cada elemento se calcula como sigue: $$ f = \frac{EA}{L} \begin{bmatrix} -C & -S & C & S \end{bmatrix} \left{ u \right} $$ Donde $f$ es la fuerza (escalar) en el elemento y $\left{u\right}$ el vector de desplazamientos en el elemento. Una fuerza negativa indica que el elemento está sometido a compresión. El esfuerzo en el elemento se obtiene dividiendo la fuerza $f$ por la sección transversal, es decir: $$ \sigma = \frac{f}{A} $$ Ejemplo 1. Estructura simple de tres elementos Como primer ejemplo vamos a resolver una estructura simple de tres elementos, con un apoyo fijo en A, un soporte simple en C y una fuerza horizontal de 500 N en B, como se muestra en la figura. <figure> <img src="src/truss-element/example_01.png" width="250px"> <center><figcaption>Fuente: [1]</figcaption></center> </figure> End of explanation """ E,A = 200e9, 0.01 n1 = Node((0,0)) n2 = Node((6,0)) n3 = Node((6,4)) n4 = Node((3,4)) e1 = Truss((n1,n2),E,A) e2 = Truss((n2,n3),E,A) e3 = Truss((n4,n3),E,A) e4 = Truss((n1,n4),E,A) e5 = Truss((n2,n4),E,A) m = TrussModel() for n in (n1,n2,n3,n4): m.add_node(n) for e in (e1,e2,e3,e4,e5): m.add_element(e) m.add_constraint(n1, uy=0) m.add_constraint(n3, ux=0, uy=0) m.add_force(n2, (600,0)) m.add_force(n4, (0,-400)) m.plot_model() m.solve() m.plot_deformed_shape() m.simple_report() """ Explanation: Ejemplo 2. <img src="src/truss-element/example_02.png" width="300px"> End of explanation """ E,A = 29e6, 0.1 n1 = Node((0,0)) # A n2 = Node((8*12,6*12)) # B n3 = Node((8*12,0)) # C n4 = Node((16*12,8*12+4)) # D n5 = Node((16*12,0)) # E n6 = Node((24*12,6*12)) # F n7 = Node((24*12,0)) # G n8 = Node((32*12,0)) # H e1 = Truss((n1,n2),E,A) e2 = Truss((n1,n3),E,A) e3 = Truss((n2,n3),E,A) e4 = Truss((n2,n4),E,A) e5 = Truss((n2,n5),E,A) e6 = Truss((n3,n5),E,A) e7 = Truss((n5,n4),E,A) e8 = Truss((n4,n6),E,A) e9 = Truss((n5,n6),E,A) e10 = Truss((n5,n7),E,A) e11 = Truss((n6,n7),E,A) e12 = Truss((n6,n8),E,A) e13 = Truss((n7,n8),E,A) m = TrussModel("Gambrel Roof") for n in (n1,n2,n3,n4,n5,n6,n7,n8): m.add_node(n) for e in (e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,e13): m.add_element(e) m.add_constraint(n1, uy=0) m.add_constraint(n8, ux=0, uy=0) m.add_force(n2, (0,-600)) m.add_force(n4, (0,-600)) m.add_force(n6, (0,-600)) m.add_force(n8, (0,-300)) m.add_force(n1, (0,-300)) m.plot_model() m.solve() m.plot_deformed_shape() m.simple_report() """ Explanation: Ejemplo 3 <figure> <img src="src/truss-element/example_03.png" width="350px"> <center><figcaption>Fuente: [2]</figcaption></center> </figure> End of explanation """
ucsd-ccbb/VAPr
VAPr Quick-Start Guide.ipynb
mit
import os from IPython.display import Image, display, HTML Image(filename=os.path.dirname(os.path.realpath('__file__')) + '/simpler.jpg') """ Explanation: Introduction to the VAPr package for the aggregation and analysis of genomic variant annotations Author: C. Mazzaferro, A. Mark, A. Birmingham, Kathleen Fisch Contact Email: kfisch@ucsd.edu Last Update: November 2017 Background The VAPr package retrieves variant information from ANNOVAR and myvariant.info and consolidates it into a single local database for ease of use in investigating and filtering variant findings. The aggregated information is structured into lists of python dictionaries, with each variant being described by a multi-level dictionary. This approach flexibly accommodates the wide variety of information attributes available for different variants. Further, this specific format permits its parsing to a MongoDb instance (dictionaries are the python representation of JSON objects), which enables the user to efficiently store, query and filter such data. Finally, the package also has the added functionality to create csv and vcf files from MongoDB. The built-in filters allow the user to rapidly query data that meets certain criteria as a list of documents, which can the be transformed into more widely accepted formats such as vcf and csv files. It should be noted that here, the main differential the package offers is the ability to write these files preserving all the annotation data. In the vcf files, for instance, outputs will have a 'Otherinfo' column where all the data coming from ANNOVAR and myvariant.info is condensed (while still preserving its structure). Having the data stored in a database offers a variety of benefits. In particular, it enables the user to set customized queries and rapidly iterate over a specific procedure and get maximum reproducibility. It also enables the storage of data coming from different sources, and its rapid access. Notes on required software the following libraries will be installed upon installing VAPr: - myvariant - pymongo - pyvcf Other libraries that are needed, but should natively e installed on most OS: Pandas Numpy Further, a MongoDB database must be set up. Refer to the documentation page for more information. Similarly, ANNOVAR must be downloaded, alongside with its supporting databases (also listed on the documentation page). Flowchart Diagram End of explanation """ from VAPr import vapr_core import os IN_PATH = "/path/to/vcf" OUT_PATH = "/path/to/out" ANNOVAR_PATH = "/path/to/annovar" MONGODB = 'VariantDatabase' COLLECTION = 'CEU_trio_01012018' annotator = vapr_core.VaprAnnotator(input_dir=IN_PATH, output_dir=OUT_PATH, mongo_db_name=MONGODB, mongo_collection_name=COLLECTION, build_ver='hg19', vcfs_gzipped=False, annovar_install_path=ANNOVAR_PATH) """ Explanation: Import libraries End of explanation """ annotator.download_annovar_databases() """ Explanation: Downloading the Annovar Databases If you plan to use Annovar, please make sure to download the necessary Annovar databases. When Annovar is first installed, it does not install Annovar databases by default. The vapr_core has a method download_annovar_databases() that will download the necessary annovar databases. Note: only run this command the first time that you use VAPr. End of explanation """ dataset = annotator.annotate(num_processes=8) """ Explanation: Run Annovar and MyVariant.info queries, upload variant annotations to MongoDB The following command runs Annovar and processes the annotations, gets MyVariant.info annotations, merges the annotations by HGVS id into a JSON document, and uploads the documents to a MongoDB database. VAPr will also automatically include sample information from the VCF as well. End of explanation """ dataset_light = annotator.annotate_lite(num_processes=8) """ Explanation: 100%|██████████| 8/8 [00:17<00:00, 2.16s/it] Skip Annovar step, export only MyVariant data to MongoDB This will export variant data from a vcf file to MongoDB, annotating variants solely with MyVariant.info. This method does not require annovar, and may result in some empty variant documents. End of explanation """ dataset = vapr_core.VaprDataset(MONGODB, COLLECTION) rare_deleterious_variants = dataset.get_rare_deleterious_variants() rare_deleterious_variants[0] """ Explanation: Query Rare Deleterious Variants You will not have to instantiate a VaprDataset object if you still have your VaprAnnotator object. But for the purpose of demonstrating that the VaprDataset object will make the MongoDB connection to interact with your database, we will do so: End of explanation """ # Apply filter. rare_deleterious_variants = dataset.get_rare_deleterious_variants() """ Explanation: Notes on Variant Filtering & Output Files Here we implement three different filters that allow for the retrieval of specific variants. The filters are implemented as MongoDB queries, and are designed to provide the user with a set of relevant variants. A template is provided for defining custom queries as well. The output of the queries is a list of dictionaries (JSON documents), where each dictionary contains a single variant document and its annotations. Further, the package allows the user to parse these variants into an annotated csv or vcf file. If needed, annotated, unfiltered vcf and csv files can also be created. They will have the same length (number of variants) as the original files, but will contain much more complete annotation data coming from myvariant.info and ANNOVAR databases. Filter #1: Rare deleterious variants criteria 1: 1000 Genomes (ALL) allele frequency (Annovar) < 0.05 or info not available criteria 2: ESP6500 allele frequency (MyVariant.info - CADD) < 0.05 or info not available criteria 3: cosmic70 (MyVariant.info) information is present criteria 4: Func_knownGene (Annovar) is exonic, splicing, or both criteria 5: ExonicFunc_knownGene (Annovar) is not "synonymous SNV" End of explanation """ # Apply filter. known_disease_variants = dataset.get_known_disease_variants() len(known_disease_variants) """ Explanation: Filter #2: Known disease variants criteria: cosmic70 (MyVariant.info) information is present or ClinVar data is present and clinical significance is not Benign or Likely Benign End of explanation """ # Apply filter deleterious_compound_heterozygous = dataset.get_deleterious_compound_heterozygous_variants() """ Explanation: Filter #3: Deleterious compound heterozygous variants criteria 1: genotype_subclass_by_class (VAPr) is compound heterozygous criteria 2: CADD phred score (MyVariant.info - CADD) > 10 End of explanation """ # Apply filter. denovo_variants = dataset.get_de_novo_variants(proband="NA12878", ancestor1="NA12891", ancestor2="NA12892") denovo_variants[0] """ Explanation: Filter #4: De novo variants criteria 1: Variant present in proband criteria 2: Variant not present in either ancestor-1 or ancestor-2 End of explanation """ from pymongo import MongoClient client = MongoClient() db = getattr(client, MONGODB) collection = getattr(db, COLLECTION) filtered = collection.find({"$and": [ {"$or": [{"func_knowngene": "exonic"}, {"func_knowngene": "splicing"}]}, {"cosmic70": {"$exists": True}}, {"1000g2015aug_all": {"$lt": 0.05}} ]}) filtered = list(filtered) """ Explanation: Create your own filter As long as you have a MongoDB instance running, filtering can be perfomed through pymongo as shown by the code below. If a list is intended to be created from it, simply add: filter = list(filter) If you'd like to customize your filters, a good idea would be to look at the available fields to be filtered. Looking at the myvariant.info documentation, you can see what are all the fields avaialble and can be used for filtering. End of explanation """
Scoppio/a-gazeta-de-geringontzan
TobParser.ipynb
mit
from collections import namedtuple import sqlite3 DROP_ALL_TABLES = False """ Explanation: To read and parse the data from Track-o-Bot End of explanation """ conn = sqlite3.connect('agazeta.db') c = conn.cursor() """ Explanation: Dora R. is a great investigator, and she has access to a large database that she is always checking and she can add and take from it at any time. Her database is called "A gazeta de Geringontzan" - os simply "agazeta.db" End of explanation """ try: c.execute('SELECT * FROM apikeys LIMIT 1') except Exception, e: c.execute( 'CREATE TABLE apikeys (id integer primary key, username text, token text, working integer, email text, subscribed integer)') print 'Look! It is working! I have the top two api usernames and tokens from a gazeta!' #for row in c.execute('SELECT username FROM apikeys LIMIT 2'): # print row """ Explanation: Dora R. has a setup, in case she is creating a new database she enters those small keys to have some meat in her sandwich. Also, she is going to run her investigation skills to understand what is happening on the historics of people, but first things have to work. Dora starts by seeing if she can get back the first 2 api's from the data base. End of explanation """ APIkey = namedtuple('APIkey', ['username', 'token']) for row in c.execute('SELECT username, token FROM apikeys WHERE working == 1'): APIkey.username = row[0] APIkey.token = row[1] """ Explanation: She is very excited, it is working! First thing she grabs her pen and paper and starts to look for special things on the api's, maybe she would find something interesting. End of explanation """ get = 'https://trackobot.com/profile/history.json?page={page}&username={username}&token={token}'.format(page=1, username=APIkey.username, token=APIkey.token) """ Explanation: She gets everything read with the last of the username and tokens End of explanation """ import urllib import json """ Explanation: The file has to be loaded from a json online Setting up the system to read JSON files from web End of explanation """ def json_load_byteified(file_handle): return _byteify( json.load(file_handle, object_hook = _byteify), ignore_dicts = True ) def json_loads_byteified(json_text): return _byteify( json.loads(json_text, object_hook = _byteify), ignore_dicts = True ) def _byteify( data, ignore_dicts = False): if isinstance(data, unicode): return data.encode('utf-8') if isinstance(data, list): return [ _byteify( item, ignore_dicts=True) for item in data ] if isinstance(data, dict) and not ignore_dicts: return { _byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True) for key, value in data.iteritems() } return data response = urllib.urlopen(get) resp = response.read() data = json_loads_byteified(resp) """ Explanation: Dora R. hates when her data comes with a "u" in front, it gets messy and hard to read, so it is pretty much manicure. End of explanation """ data.keys() data['meta'].keys() data['meta'] """ Explanation: Dora R. now wants to see what is inside the 'data' json, its keys and values End of explanation """ data['history'][0].keys() """ Explanation: This is the best thing she could find! Here Dora can see how many pages there are, so she can use it to 'spider' around the data. Her eyes shine when she sees all that many possibilities, all those secrets! End of explanation """ def total_turns(data, j): a = 0 for i in range(len(data['history'][j]['card_history'])): a = data['history'][j]['card_history'][i]['turn'] if data['history'][j]['card_history'][i]['turn'] > a else a return a """ Explanation: With 'history' she sees that here lies what is really important, the games! Now she will run her small trick that returns the number of turns a game had End of explanation """ print data['history'][0]['id'],'-', data['history'][0]['added'], data['history'][0]['mode'] print data['history'][0]['hero'], data['history'][0]['hero_deck'], 'vs', data['history'][0]['opponent'], data['history'][0]['opponent_deck'] print 'First player' if not data['history'][0]['coin'] else 'Second player' print 'Turns', total_turns(data, 0) print data['history'][0]['result'] """ Explanation: If she wanted to see who won and with which deck, she would need to do this... End of explanation """ data['history'][0]['card_history'] """ Explanation: Dora R. is also curious about the cards that were used during the game End of explanation """ # Only ranked games for i in range(len(data['history'])): if data['history'][i]['mode'] != 'ranked': continue print data['history'][i]['id'],'-', data['history'][i]['added'] print data['history'][i]['hero'], data['history'][i]['hero_deck'], 'vs', data['history'][i]['opponent'], data['history'][0]['opponent_deck'] print 'First player' if not data['history'][i]['coin'] else 'Second player' print 'Turns', total_turns(data, i) print data['history'][i]['result'] """ Explanation: Now Dora is much more confident, she wants to get all the ranked games from this data and this page! End of explanation """ data['history'][0]['added'] from datetime import datetime datetime.strptime('2016-12-02T02:29:09.000Z', '%Y-%m-%dT%H:%M:%S.000Z') """ Explanation: It all seens perfect, with just one problem, the datetime is weird... she will have to convert it befor being able to add it to the database. End of explanation """ import time d = datetime.strptime(data['history'][0]['added'], '%Y-%m-%dT%H:%M:%S.000Z') print str(int(time.mktime(d.timetuple())))+'!!!', print "POSIX seconds! This will help alot when I try to find my data in time windows!" """ Explanation: Dora R. prefers to work with POSIX dates, she says that they are better to make searchs in the tables... maybe she does not know of the julian date calendar. End of explanation """ try: c.execute('SELECT * FROM archive LIMIT 1') print 'Yeap, working' except Exception, e: c.execute('''CREATE TABLE archive (id integer primary key, matchid integer, date_posix integer, rank integer, hero text, hero_deck text, opponent_hero text, opponent_deck text, coin integer, turns integer, result integer, cards text, opponent_cards text)''') print 'Table archive is done!' """ Explanation: Hell yes! Her tricks do work perfectly, now she can enter the date and time in a more sane order on the database! Creating games database into the A Gazeta Dora R. has enough to be sure that it is possible to get the data that she wants out of the api, now she needs to add into the database. The API and Keys table is simple, just username and token, along with a working statement, so in case a player regenerates the value we may set this flag as 0 to 'unusable', she finds out it would be great to have the email of the person in the database, so she can talk with the person ans kindly asks for her to donate the key again, and to send her findings directly into the email if they are subscribed. CREATE TABLE apikeys (id integer primary key, username text, token text, working integer, email text, subscribed integer) Now she needs a table for her findings... she will add the game results from a date window from an apikey and load it up to the database, first it will need an ID, for each new entry, also, she will parse the data instead of loading JSON's, she won't be running it relational, but she need the speed and reliability of a proper SQL machine. Also, she is not going to store games that are NOT ranked, casual and arena games can skew too much the data. CREATE TABLE archive (id integer primary key, matchid integer, date-posix integer, rank integer, hero text, hero_deck text, opponent_hero text, opponent_deck text, coin integer, turns integer, result integer, cards text, opponent_cards text) End of explanation """ querie = 'SELECT username, token FROM apikeys WHERE working == 1' def api_getter (verbose=False, limit = 0): APIkey = namedtuple('APIkey', ['username', 'token']) querie = 'SELECT username, token FROM apikeys WHERE working == 1' if limit: querie = 'SELECT username, token FROM apikeys WHERE working == 1 LIMIT {limit}'.format(limit=limit) sqlret = [sqlret for sqlret in c.execute(querie)] for row in sqlret: APIkey.username = row[0] APIkey.token = row[1] if verbose: print '{username} {token}'.format(username=APIkey.username, token=APIkey.token) yield (row[0], row[1]) def posix_conversion(date = '2016-12-02T02:29:09.000Z'): d = datetime.strptime( date, '%Y-%m-%dT%H:%M:%S.000Z') return int(time.mktime(d.timetuple())) def Maexxna(from_date, limit=0, verbose=False): # from_date = datetime from_date = time.mktime(from_date.timetuple()) get = 'https://trackobot.com/profile/history.json?page={page}&username={username}&token={token}' for api in api_getter(limit = limit): page = 1 end = False try_and_error = 3 data_history =[] while(True): try: response = urllib.urlopen(get.format(page=page, username=api[0], token=api[1])) try_and_error = 3 except Exception as e: print 'error', e if try_and_error: try_and_error -= 1 continue else: break resp = response.read() data = json_loads_byteified(resp) if verbose: print 'game historic', len(data['history']), for n in range(len(data['history'])): if posix_conversion(data['history'][n]['added']) < from_date: del data['history'][n:len(data['history'])] end = True break if verbose: print 'valid games',len(data['history']) data_history += data['history'] # end of the loop if data['meta']['total_pages'] == data['meta']['current_page'] or end: break page += 1 yield data_history """ Explanation: The setup is good, now Dora R. must take care so she does not add duplicated games to the archive. First she will make a process that will run through the apikeys and then it will capture the games from each layer and pipeline it to another process that will write it into the archive. End of explanation """ from datetime import timedelta d = datetime.today() - timedelta(days=7) for i in Maexxna(from_date=d): print len(i) print 'Done' """ Explanation: Maexxna is ready to run, Dora R. makes a last check to see if it can return stuff properly. End of explanation """ import pandas as pd def Starseeker(verbose = False, iterator = False): def _turns(data): a = 0 for i in range(len(data)): a = data[i]['turn'] if data[i]['turn'] > a else a return a for files in Maexxna(from_date = datetime.today() - timedelta(days=7)): df = pd.DataFrame(columns=['id','matchid', 'date_posix', 'rank', 'hero', 'hero_deck', 'opponent_hero', 'opponent_deck', 'coin', 'turns', 'result', 'cards', 'opponent_cards' ]) index = 0 match = [] for i in range(len(files)): # Only ranked games are going to be stored if files[i]['mode'] != 'ranked': continue game = files[i] my_cards = [] opponent_cards = [] for card in game['card_history']: if card['player'] == 'me': my_cards.append(card['card']['id']) else: opponent_cards.append(card['card']['id']) my_cards = ', '.join(my_cards) opponent_cards = ', '.join(opponent_cards) df.loc[index] = [ int(game['id']),int(game['id']), posix_conversion(game['added']), None if game['rank'] is None else int(game['rank']) , game['hero'], game['hero_deck'], game['opponent'], game['opponent_deck'], 1 if game['coin'] else 0, _turns(game['card_history']), 1 if game['result'] == 'win' else 0, my_cards, opponent_cards ] df = df.fillna(method='ffill') index += 1 match = map(tuple, df.values) sql = 'INSERT OR REPLACE INTO archive VALUES ((SELECT id FROM archive WHERE matchid == ?)'+',?'*12+')' c.executemany( sql , match) Starseeker() c.execute('SELECT * from archive') [description[0] for description in c.description] val = [val[1:] for val in c.execute('SELECT * from archive')] cols = [description[0] for description in c.description] dt = pd.DataFrame(val, columns = cols[1:]) dt heros = [b for b in dt['opponent_hero'].unique()] for h in heros: _h = dt[dt['hero'] == h]['result'] _o = dt[dt['opponent_hero'] == h]['result'] _o = pd.Series([0 if o else 1 for o in _o.values]) print h, _h.sum()+_o.sum(), len(_h)+len(_o), float(_h.sum()+_o.sum())/ float(len(_h)+len(_o)) pd.Series([0 if o else 1 for o in _o.values]) decks = [b for b in dt['opponent_hero'].unique()] for h in heros: _h = list(dt[dt['hero'] == h]['hero_deck'].unique()) _o = list(dt[dt['opponent_hero'] == h]['opponent_deck'].unique()) _h = list(set(_h+_o)) print h, _h list(_o) + list(_h) """ Explanation: 'It is working perfectly!!!' Dora yells, her function works and returns what she needs, altought it may return "empty" history, but thats something she may deal with without much problem. Now she must add those informations to the archive End of explanation """
lukasmerten/CRPropa3
doc/pages/example_notebooks/galactic_lensing/lensing_liouville.v4.ipynb
gpl-3.0
import crpropa import matplotlib.pyplot as plt import numpy as np n = 10000000 # Simulation setup sim = crpropa.ModuleList() # We just need propagation in straight lines here to demonstrate the effect sim.add(crpropa.SimplePropagation()) # collect arriving cosmic rays at Observer 19 kpc outside of the Galactic center # to exaggerate effects obs = crpropa.Observer() pos_earth = crpropa.Vector3d(-19, 0, 0) * crpropa.kpc # observer with radius 500 pc to collect fast reasonable statistics obs.add(crpropa.ObserverSurface(crpropa.Sphere(pos_earth, 0.5 * crpropa.kpc))) # Use CRPropa's particle collector to only collect the cosmic rays at Earth output = crpropa.ParticleCollector() obs.onDetection(output) sim.add(obs) # Discard outwards going cosmic rays, that missed Earth and leave the Galaxy obs_trash = crpropa.Observer() obs_trash.add(crpropa.ObserverSurface(crpropa.Sphere(crpropa.Vector3d(0), 21 * crpropa.kpc))) sim.add(obs_trash) """ Explanation: Galactic Lensing - confirm Liouville Galactic lensing can be applied with the requirement that Liouville's theorem holds, thus in this context: from an isotropic distribution outside the area of influence of the Galactic magnetic field follows an isotropic arrival distribution at any point within our Galaxy. First, we are setting up the oberver which we will place further outside of the Galactic center than Earth to exaggerate the observed effects: End of explanation """ # source setup source = crpropa.Source() # inward=True for inwards directed emission, and False for outwards directed emission center, radius, inward = crpropa.Vector3d(0, 0, 0) * crpropa.kpc, 20 * crpropa.kpc, True source.add(crpropa.SourceLambertDistributionOnSphere(center, radius, inward)) source.add(crpropa.SourceParticleType(-crpropa.nucleusId(1, 1))) source.add(crpropa.SourceEnergy(100 * crpropa.EeV)) sim.run(source, n) print("Number of hits: %i" % len(output)) lons = [] for c in output: v = c.current.getDirection() lons.append(v.getPhi()) plt.hist(np.array(lons), bins=30, color='k', histtype='step') plt.xlabel('lon', fontsize=20) plt.ylabel('counts', fontsize=20) plt.savefig('lon_distribution_lamberts.png', bbox_inches='tight') """ Explanation: Lambert's distribution For the source setup we have to consider that from an isotropic propagation in the extragalactic Universe, the directions on any surface element follows the Lambert's distribution (https://en.wikipedia.org/wiki/Lambert%27s_cosine_law). You could also phrase: vertical incident angles are more frequent due to the larger visible size of the area of the surface element than flat angles. End of explanation """ source = crpropa.Source() source.add(crpropa.SourceUniformShell(center, radius)) source.add(crpropa.SourceIsotropicEmission()) source.add(crpropa.SourceParticleType(-crpropa.nucleusId(1, 1))) source.add(crpropa.SourceEnergy(100 * crpropa.EeV)) sim.run(source, n) print("Number of hits: %i" % len(output)) lons = [] for c in output: v = c.current.getDirection() lons.append(v.getPhi()) plt.hist(np.array(lons), bins=30, color='k', histtype='step') plt.xlabel('lon', fontsize=20) plt.ylabel('counts', fontsize=20) plt.savefig('lon_distribution_double_isotropic.png', bbox_inches='tight') """ Explanation: One can see, this results in an isotropic arrival distribution. Note, that one instead obtains anisotropies if one assumes an isotropic emission from sources that are distributed uniformly on the sphere shell by e.g.. End of explanation """
RaoUmer/distarray
examples/gauss_elimination/ge_notebook.ipynb
bsd-3-clause
# utility imports from __future__ import print_function from pprint import pprint from matplotlib import pyplot as plt # main imports import numpy as np import distarray.globalapi as da from distarray.plotting import plot_array_distribution # output goodness np.set_printoptions(precision=2) # display figures inline %matplotlib inline """ Explanation: Example: Using DistArray for Gaussian Elimination (L-U decomposition) Note: This notebook requires an IPython.parallel cluster to be running. Outside the notebook, run: dacluster start -n4 Gaussian Elimination is an algorithm in Linear Algebra best understood as a series of row operations on the coefficient matrix of a system of linear equations. The method can also be used to calculate the rank, determinant, and inverse of a matrix. The algorithm involves adding multiples of each row to subsequent rows, in order to make the coefficient matrix upper triangular. The resulting system is then solved by back-substitution which is trivial to perform. This algorithm is illustrated in the figure below:<img src="img1.png"> Here i refers to the index of the pivot row (started at 1). Please note that much of this example notebook is adapted from Parallel Gaussian Elimination which is a good starting point for gaining a better understanding of Gaussian Elimination from an computational standpoint. In this notebook we will demonstrate how to perform GE in parallel using the DistArray API. The main challenge in parallelizing Gaussian Elimination on a distributed memory machine is that the calculation of each row requires the calculation of all rows that have come before it and therefore concurrency of operations becomes the overriding issue. This bodes well for the client-engine architecture of IPython.parallel (and consequently DistArray) as the client can keep track of pivot row, while the row transformations can be pushed out to the engines using custom uFuncs. We begin with the imports: End of explanation """ distributions = [('n','b'), ('b','n'), ('b','b')] sizes = [8, 16, 32, 64] print(distributions) """ Explanation: We now define the parameter space for our study. We will perform GE on matrices that are block distributed in any one or both dimensions, while simultaneously varying the size: End of explanation """ context = da.Context() def synthetic_data_generator(contextobj, datashape=(16, 16), distscheme=('b', 'n')): """Return objective matrix with specified size and distribution.""" distribution = da.Distribution(contextobj, shape=datashape, dist=distscheme) _syndata = np.random.random(datashape) syndata = contextobj.fromarray(_syndata, distribution=distribution) return syndata """ Explanation: Next, we create a context and devise a scheme for generating some synthetic data (in this case a matrix) on which to operate: End of explanation """ def parallel_gauss_elim(darray, pivot_row, k, m): """ Perform in-place gaussian elimination locally on all engines. Parameters --------- darray : DistArray Handle for the array to be manipulated (global) pivot_row : numpy.ndarray Array containing pivot row (global) k : integer Pivot row index (global) m : numpy.ndarray Vector containing pivoting factors (global) """ import numpy as np # retrieve local indices for submatrix that needs to be operated on n_rows, n_cols = darray.distribution.global_shape i_slice, j_slice = darray.distribution.local_from_global((slice(k+1, n_rows), slice(k, n_cols))) # limit the slices using actual size of local array n_rows_local, n_cols_local = darray.ndarray.shape i_indices, j_indices = (i_slice.indices(n_rows_local), j_slice.indices(n_cols_local)) # determine which elements of global pivot row correspond to local entries _, piv_slice = darray.distribution.global_from_local((slice(0, n_rows_local), slice(*j_indices))) # limit the slice to the size of the global pivot row piv_indices = piv_slice.indices(n_cols) # determine which elements of global pivot factor vector corresponds to local mul_slice, _ = darray.distribution.global_from_local((slice(*i_indices), slice(0, n_cols_local))) # limit the slice to the size of the global pivot factor vector mul_indices = mul_slice.indices(n_rows) # perform the elimination to create zeros below pivot if (i_indices[0] == i_indices[1] or j_indices[0] == j_indices[1]): # computation for the local block is done return else: for i, mul in zip(xrange(*i_indices), xrange(*mul_indices)): np.subtract(darray.ndarray[i, slice(*j_indices)], np.multiply(m[mul], pivot_row[slice(*piv_indices)]), out=darray.ndarray[i, slice(*j_indices)]) return """ Explanation: In order for the Gaussian Elimination operation to be truly parallel, we need to define a uFunc to perform the desired computation: End of explanation """ context.register(parallel_gauss_elim) """ Explanation: We want to use a nice syntax for calling out uFunc hence we register it with our context (alternatively, we could have just used Context.apply which has a more obscure call format): End of explanation """ def execute_ge(contextobj, darray): N = min(darray.shape) for k in range(N-1): pivot_factors = (d_array[:, k]/d_array[k, k]).toarray() contextobj.parallel_gauss_elim(darray, darray[k, :].toarray(), k, pivot_factors) """ Explanation: All that is left now is to define the high level function that runs on the client and manages the GE operation. Using this function is a way of ensuring synchronicity between the many engines performing this operation. After a pivot row is determined, it is broadcast along with a vector of pivoting factors to the worker engines via the parallel_gauss_elim uFunc. Note how we have actually subverted the need to use canonical MPI constructs (in this case, MPI_Bcast()) by making use of the fact that our uFunc can accept arbitrary arguments. End of explanation """ N = sizes[0] for scheme in distributions: d_array = 1000 * synthetic_data_generator(context, datashape=(N,N), distscheme=scheme) execute_ge(context, d_array) process_coords = [(0, 0), (1, 0), (2, 0), (3, 0)] plot_array_distribution(d_array, process_coords, legend=True, title=str("Distribution Scheme = " + str(scheme))) """ Explanation: In order to enable the reader to better visualize what is happening in this example, we will make the first set of runs with the size fixed at 8, while cycling through the distribution types. We also print out a graphical representation of the distribution of the resulting upper triangular matrices. End of explanation """ #create a dictionary of lists from collections import defaultdict performance_data = defaultdict(list) for scheme in distributions: for N in sizes: d_array = 1000 * synthetic_data_generator(context, datashape=(N,N), distscheme=scheme) _time = %timeit -o -q execute_ge(context, d_array) performance_data[scheme].append(_time.best) plt.plot(sizes, performance_data[scheme], label=str(scheme), linewidth=2) plt.legend(loc=4) plt.xlabel('Problem Size N') plt.ylabel('Execution Time [seconds]') plt.title('Gaussian Elimination N vs t') plt.grid(True) """ Explanation: Now we write a quick routine that runs through all sizes and distributions and records the runtimes. The resulting information is best represented as a plot the data for which is collected in a Dictionary called performance_data. Depending on the contents of your sizes vector, the runtimes may very a great deal on this section. To see the progress of execution, the user may choose to disable the -q (quiet) option on the %timeit magic function. End of explanation """ def execute_lu(contextobj, darray): # create placeholders for lower and upper triangular matrices uarray = contextobj.fromarray(darray.toarray(), distribution=darray.distribution) larray = contextobj.fromarray(np.zeros(darray.shape), distribution=darray.distribution) N = min(darray.shape) for k in range(N-1): pivot_factors = (uarray[:, k]/uarray[k, k]).toarray() pivot_factors[0:k] = 0.0 # populate lower triangular matrix larray[:, k] = pivot_factors contextobj.parallel_gauss_elim(uarray, uarray[k, :].toarray(), k, pivot_factors) larray[-1, -1] = 1.0 return larray, uarray """ Explanation: We see that we observe similar performance from all three distributions with a block-block map marginally most efficient. Application: LU Decomposition In this section we will demonstrate how we can, with minimal modification, use the GE approach to perform LU decomposition of a matrix. Mathematically, LU-factorization follows naturally from GE operations on any given matrix (with the exception of systems that require partial pivoting - these need some special treatement and in this example we don't concern ourselves with these issues of numerical stability of GE). LU-factorization involves expressing a given matrix as a product of two matrices - one of which is lower triangular ($ \mathbf{L} $), and the other upper triangular ($ \mathbf{U} $): $$ \mathbf{A} = \mathbf{L} \mathbf{U} $$ Once we have this factorization, we can make use of it to solve $\mathbf{A}x=b$: $$ \mathbf{A}x = \mathbf{L}\mathbf{U}x = b $$ Which is equivalent to: $$ \mathbf{U}x = \mathbf{L}^{-1}b =:c $$ Since the cost of matrix inversion is prohibitively high, we find $c = \mathbf{L}^{-1} b$ through forward substitution: $$ \mathbf{L}c = b $$ This is easy to do as $\mathbf{L}$ is lower triangular. The final step then becomes to perform backward substitution: $$ \mathbf{U}x=c $$ The procedure demonstrated in the preceeding section gives us a method of finding $\mathbf{U}$, and now we are tasked with computing $\mathbf{L}$. If the series of elementary row operations that the GE process entails are expressed as a series of matrix transformations on $\mathbf{A}$ we end up with a series of trivially invertible matrices, which when multiplied give us $\mathbf{L}$: $$ \mathbf{E}{n} \mathbf{E}{n-1} ... \mathbf{E}{2} \mathbf{E}{1} \mathbf{A} = \mathbf{U} $$ $$ \implies \mathbf{A} = \mathbf{E}{1}^{-1} \mathbf{E}{2}^{-1} ... \mathbf{E}{n-1}^{-1} \mathbf{E}{n}^{-1} \mathbf{U}$$ $$ \implies \mathbf{E}{1}^{-1} \mathbf{E}{2}^{-1} ... \mathbf{E}{n-1}^{-1} \mathbf{E}{n}^{-1} =: \mathbf{L}$$ It turns out that $\mathbf{L}$ is basically composed of the negatives of the off-diagonal elements in the matrix transformations. We now have enough information to write a routine to perform LU-decomposition. Our approach will be to perform the GE in-place on a copy of the objective matrix, and create a new matrix which will be populated with the multiplicative factors. The uFunc for GE will be used by us directly, we need only modify the driver function: End of explanation """ N = sizes[0] for scheme in distributions: d_array = 10 * synthetic_data_generator(context, datashape=(N,N), distscheme=scheme) L, U = execute_lu(context, d_array) if (np.allclose(np.dot(L.toarray(), U.toarray()), d_array.toarray())): print("Success: LU == A for distribution scheme = {}".format(scheme)) else: print("Failure: LU != A for distribution scheme = {}".format(scheme)) """ Explanation: Let us first test our implementation by checking if we can reproduce our objective matrix $\mathbf{A}$ by multiplying $\mathbf{L}$ and $\mathbf{U}$. For multiplication, we will convert the DistArrays back to NumPy arrays and for comparison of floating point entries we use numpy.allclose() which returns True if all entries are equal within a tolerance. End of explanation """ process_coords = [(0, 0), (1, 0), (2, 0), (3, 0)] plot_array_distribution(L, process_coords, legend=True, title=str("Lower Triangular Piece L for Distribution Scheme = " + str(scheme))) plot_array_distribution(U, process_coords, legend=True, title=str("Upper Triangular Piece U for Distribution Scheme = " + str(scheme))) """ Explanation: Hence we have validated our implementation. Just to confirm that our matrices are actually upper and lower triangular, lets generate a schematic for one $\mathbf{LU}$ pair: End of explanation """
ComputationalModeling/spring-2017-danielak
past-semesters/spring_2016/day-by-day/day09-random-walks/Random_Walks.ipynb
agpl-3.0
# put your code for Part 1 here. Add extra cells as necessary! """ Explanation: Random Walks In many situations, it is very useful to think of some sort of process that you wish to model as a succession of random steps. This can describe a wide variety of phenomena - the behavior of the stock market, models of population dynamics in ecosystems, the properties of polymers, the movement of molecules in liquids or gases, modeling neurons in the brain, or in building Google's PageRank search model. This type of modeling is known as a "random walk", and while the process being modeled can vary tremendously, the underlying process is simple. In this exercise, we are going to model such a random walk and learn about some of its behaviors! Learning goals: Model a random walk Learn about the behavior of random walks in one and two dimensions Plot both the distribution of random walks and the outcome of a single random walk Group members Put the name of your group members here! Part 1: One-dimensional random walk. Imagine that you draw a line on the floor, with a mark every foot. You start at the middle of the line (the point you have decided is the "origin"). You then flip a "fair" coin N times ("fair" means that it has equal chances of coming up heads and tails). Every time the coin comes up heads, you take one step to the right. Every time it comes up tails, you take a step to the left. Questions: After $N_{flip}$ coin flips and steps, how far are you from the origin? If you repeat this experiment $N_{trial}$ times, what will the distribution of distances from the origin be, and what is the mean distance that you go from the origin? (Note: "distance" means the absolute value of distance from the origin!) First: as a group, come up with a solution to this problem on your whiteboard. Use a flow chart, pseudo-code, diagrams, or anything else that you need to get started. Check with an instructor before you continue! Then: In pairs, write a code in the space provided below to answer these questions! End of explanation """ # put your code for Part 2 here. Add extra cells as necessary! """ Explanation: Part 2: Two-dimensional walk Now, we're going to do the same thing, but in two dimensions, x and y. This time, you will start at the origin, pick a random direction, and take a step one foot in that direction. You will then randomly pick a new direction, take a step, and so on, for a total of $N_{step}$ steps. Questions: After $N_{step}$ random steps, how far are you from the origin? If you repeat this experiment $N_{trial}$ times, what will the distribution of distances from the origin be, and what is the mean distance that you go from the origin? (Note: "distance" means the absolute value of distance from the origin!) Does the mean value differ from Part 1? For one trial, plot out the steps taken in the x-y plane. Does it look random? First: As before, come up with a solution to this problem on your whiteboard as a group. Check with an instructor before you continue! Then: In pairs, write a code in the space provided below to answer these questions! End of explanation """ # put your code for Part 3 here. Add extra cells as necessary! """ Explanation: Part 3: A different kind of random walk. If you have time, copy and paste your 1D random walk code in the cell below. This time, modify your code so that the coin toss is biased - that you are more likely to take a step in one direction than in the other (i.e., the probability of stepping to the right is $p_{step}$, of stepping to the left is $1-p_{step}$, and $p_{step} \neq 0.5$). How does the distibution of distances gone, as well as the mean distance from the origin, change as $p_{step}$ varies from 0.5? End of explanation """
tensorflow/docs-l10n
site/zh-cn/guide/graph_optimization.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2020 The TensorFlow Authors. End of explanation """ import numpy as np import timeit import traceback import contextlib import tensorflow as tf """ Explanation: 使用 Grappler 优化 TensorFlow 计算图 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://tensorflow.google.cn/guide/graph_optimization"><img src="https://tensorflow.google.cn/images/tf_logo_32px.png">View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/graph_optimization.ipynb"><img src="https://tensorflow.google.cn/images/colab_logo_32px.png">Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/graph_optimization.ipynb"><img src="https://tensorflow.google.cn/images/GitHub-Mark-32px.png">View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/guide/graph_optimization.ipynb"><img src="https://tensorflow.google.cn/images/download_logo_32px.png">Download notebook</a> </td> </table> 概述 TensorFlow 同时使用计算图和 Eager Execution 来执行计算。一个 tf.Graph 包含一组代表计算单元的 tf.Operation 对象(运算)和一组代表在运算之间流动的数据单元的 tf.Tensor 对象。 Grappler 是 TensorFlow 运行时中的默认计算图优化系统。Grappler 通过计算图简化和其他高级优化(例如利用内嵌函数体实现程序间优化),在计算图模式(在 tf.function 内)下应用优化以提高 TensorFlow 计算的性能。优化 tf.Graph 还可以通过优化计算图节点到计算资源的映射来减少设备峰值内存使用量并提高硬件利用率。 使用 tf.config.optimizer.set_experimental_options() 可以更好地控制 tf.Graph 优化。 可用的计算图优化器 Grappler 通过称为 MetaOptimizer 的顶级驱动程序执行计算图优化。TensorFlow 提供以下计算图优化器: 常量折叠优化器 - 通过折叠计算图中的常量节点来静态推断张量的值(如可能),并使用常量使结果具体化。 算术优化器 - 通过消除常见的子表达式并简化算术语句来简化算术运算。 布局优化器 - 优化张量布局以更高效地执行依赖于数据格式的运算,例如卷积。 重新映射优化器 - 通过将常见的子计算图替换为经过优化的融合一体化内核,将子计算图重新映射到更高效的实现上。 内存优化器 - 分析计算图以检查每个运算的峰值内存使用量,并插入 CPU-GPU 内存复制操作以将 GPU 内存交换到 CPU,从而减少峰值内存使用量。 依赖项优化器 - 移除或重新排列控制依赖项,以缩短模型步骤的关键路径或实现其他优化。另外,还移除了实际上是无运算的节点,例如 Identity。 剪枝优化器 - 修剪对计算图的输出没有影响的节点。通常会首先运行剪枝来减小计算图的大小并加快其他 Grappler 传递中的处理速度。 函数优化器 - 优化 TensorFlow 程序的函数库,并内嵌函数体以实现其他程序间优化。 形状优化器 - 优化对形状和形状相关信息进行运算的子计算图。 自动并行优化器 - 通过沿批次维度拆分来自动并行化计算图。默认情况下,此优化器处于关闭状态。 循环优化器 - 通过将循环不变式子计算图提升到循环外并通过移除循环中的冗余堆栈运算来优化计算图控制流。另外,还优化具有静态已知行程计数的循环,并移除条件语句中静态已知的无效分支。 范围分配器优化器 - 引入范围分配器以减少数据移动并合并某些运算。 固定到主机优化器 - 将小型运算交换到 CPU 上。默认情况下,此优化器处于关闭状态。 自动混合精度优化器 - 在适用的情况下将数据类型转换为 float16 以提高性能。目前仅适用于 GPU。 调试剥离器 - 从计算图中剥离与调试运算相关的节点,例如 tf.debugging.Assert、tf.debugging.check_numerics 和 tf.print。默认情况下,此优化器处于关闭状态。 设置 End of explanation """ @contextlib.contextmanager def options(options): old_opts = tf.config.optimizer.get_experimental_options() tf.config.optimizer.set_experimental_options(options) try: yield finally: tf.config.optimizer.set_experimental_options(old_opts) """ Explanation: 创建上下文管理器以轻松切换优化器状态。 End of explanation """ def test_function_1(): @tf.function def simple_function(input_arg): print('Tracing!') a = tf.constant(np.random.randn(2000,2000), dtype = tf.float32) c = a for n in range(50): c = c@a return tf.reduce_mean(c+input_arg) return simple_function """ Explanation: 比较使用和不使用 Grappler 时的执行性能 TensorFlow 2 及更高版本默认情况下会以 Eager 模式执行。使用 tf.function 可将默认执行切换为“计算图”模式。Grappler 在后台自动运行,以应用上述计算图优化并提高执行性能。 常量折叠优化器 作为一个初步的示例,考虑一个对常量执行运算并返回输出的函数。 End of explanation """ with options({'constant_folding': False}): print(tf.config.optimizer.get_experimental_options()) simple_function = test_function_1() # Trace once x = tf.constant(2.2) simple_function(x) print("Vanilla execution:", timeit.timeit(lambda: simple_function(x), number = 1), "s") """ Explanation: 关闭常量折叠优化器并执行以下函数: End of explanation """ with options({'constant_folding': True}): print(tf.config.optimizer.get_experimental_options()) simple_function = test_function_1() # Trace once x = tf.constant(2.2) simple_function(x) print("Constant folded execution:", timeit.timeit(lambda: simple_function(x), number = 1), "s") """ Explanation: 启用常量折叠优化器,然后再次执行函数以观察函数执行的加速情况。 End of explanation """ def test_function_2(): @tf.function def simple_func(input_arg): output = input_arg tf.debugging.check_numerics(output, "Bad!") return output return simple_func """ Explanation: 调试剥离器优化器 考虑一个检查其输入参数的数值并返回自身的简单函数。 End of explanation """ test_func = test_function_2() p1 = tf.constant(float('inf')) try: test_func(p1) except tf.errors.InvalidArgumentError as e: traceback.print_exc(limit=2) """ Explanation: 首先,在调试剥离器优化器关闭的情况下执行该函数。 End of explanation """ with options({'debug_stripper': True}): test_func2 = test_function_2() p1 = tf.constant(float('inf')) try: test_func2(p1) except tf.errors.InvalidArgumentError as e: traceback.print_exc(limit=2) """ Explanation: 由于 test_func 的 Inf 参数,tf.debugging.check_numerics 引发了参数无效错误。 启用调试剥离器优化器,然后再次执行该函数。 End of explanation """
NorfolkDataSci/presentations
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
mit
import pandas as pd import numpy as np import datetime import pandas_datareader.data as web import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import style from sklearn import preprocessing from sklearn import linear_model import quandl, math quandl.ApiConfig.api_key = "_1LjZZVx4HVVTwzCmqxg" """ Explanation: Stock Price Prediction in Linear Regression Predicting the stock price trend by interpreting the seemly chaotic market data has always been an attractive topic to both investors and researchers. Among those popular methods that have been employed, Machine Learning techniques are very popular due to the capacity of identifying stock trend from massive amounts of data that capture the underlying stock price dynamics. In this project, we applied linear regression methods to stock price trend forecasting. End of explanation """ #get stock basic data from quandl df = quandl.get('WIKI/AAPL',start_date="1996-9-26",end_date='2017-12-31') df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']] #calculate highest and lowest price change df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close'] *100.0 #calculate return of stock price df['PCT_change']= (df['Adj. Close']-df['Adj. Open'])/df['Adj. Open'] *100.0 df = df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']] df_orig=df date = df.index df.head() #plot heat map of corrlation corr_stocks=df.corr() corr_stocks=np.absolute(corr_stocks) print(corr_stocks) plt.figure(figsize=(12, 10)) plt.imshow(corr_stocks, cmap='RdYlGn', interpolation='none', aspect='auto') plt.xticks(range(len(corr_stocks)), corr_stocks.columns, rotation='vertical') plt.yticks(range(len(corr_stocks)), corr_stocks.columns); plt.suptitle('Stock Correlations Heat Map', fontsize=15, fontweight='bold') plt.show() print('-------------------------------------------------') print('From the correlation heat map, we can tell that the corrlation bewteen percentage change column and price is') print('very low. So we need to get rid of this column to predict.') #get rid of feature have least correlation df = df[['Adj. Close','HL_PCT','Adj. Volume']] from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error #use high low price change and volume as two features predictor=df[['HL_PCT','Adj. Volume']] #normalize the predictor predictor=preprocessing.scale(predictor) price=df['Adj. Close'] predictor=np.array(predictor) price=np.array(price) #using 90% as training data and 10% as testing data X_train, X_test, y_train, y_test =train_test_split(predictor , price, test_size=0.1,shuffle= False) clf = linear_model.LinearRegression(n_jobs=-1) clf.fit(X_train, y_train) y_pred1 = clf.predict(X_test) print('the coefficient of determination R^2 of the prediction:',clf.score(X_test, y_test)) print("Mean squared error:",mean_squared_error(y_test, y_pred1)) """ Explanation: Use simple stock market daily data as features End of explanation """ forecast_set = clf.predict(X_test) num_samples = df.shape[0] #add Forecase column to dataframe df['Forecast'] = np.nan df['Forecast'][int(0.9*num_samples):num_samples]=forecast_set #plot graph for actual stock price and style.use('ggplot') df['Adj. Close'].plot() df['Forecast'].plot() plt.legend(loc=4) plt.xlabel('Date') plt.ylabel('Price') plt.rcParams['figure.figsize'] = (20,20) plt.show() print('-------------------------') print('from predicion graph we can see that the prediction does not work well') """ Explanation: the first varible is negative because the model can be arbitrarily worse End of explanation """ predictor2=df[['Adj. Close','HL_PCT','Adj. Volume']] predictor2=preprocessing.scale(predictor2) clf2 = linear_model.LinearRegression(n_jobs=-1) X_train2, X_test2, y_train2, y_test2 =train_test_split(predictor2 , price, test_size=0.1,shuffle= False) clf2.fit(X_train2, y_train2) forecast_set2 = clf2.predict(X_test2) print('the coefficient of determination R^2 of the prediction:',clf2.score(X_test2, y_test2)) print("Mean squared error:",mean_squared_error(y_test, forecast_set2)) print('Mean squared error is almost 0, the prediction is very well.') num_samples = df.shape[0] #add Forecase column to dataframe df['Forecast'] = np.nan df['Forecast'][int(0.9*num_samples):num_samples]=forecast_set2 style.use('ggplot') df['Adj. Close'].plot() df['Forecast'].plot() plt.legend(loc=4) plt.xlabel('Date') plt.ylabel('Price') plt.rcParams['figure.figsize'] = (20,20) plt.show() print('-------------------------') print('from predicion graph we can see that prediction works well.') """ Explanation: use price as one of the feature to predict price We can see from previous prediction, even high related correlation featrues did not predict well. However, the highest related featrue is price itself. This time I want to use price as one of the feature to predict price. End of explanation """ from sklearn.linear_model import LinearRegression price_data=pd.DataFrame(df_orig['Adj. Close']) price_data.columns = ['values'] index=price_data.index Date=index[60:5350] x_data = [] y_data = [] for d in range(30,price_data.shape[0]): x = price_data.iloc[d-30:d].values.ravel() y = price_data.iloc[d].values[0] x_data.append(x) y_data.append(y) x_data=np.array(x_data) y_data=np.array(y_data) y_pred = [] y_pred_last = [] y_pred_ma = [] y_true = [] end = y_data.shape[0] for i in range(30,end): x_train = x_data[:i,:] y_train = y_data[:i] x_test = x_data[i,:] y_test = y_data[i] model = LinearRegression() model.fit(x_train,y_train) y_pred.append(model.predict(x_test.reshape(1, -1))) y_true.append(y_test) #Transforms the lists into numpy arrays y_pred = np.array(y_pred) y_true = np.array(y_true) from sklearn.metrics import mean_absolute_error print ('\nMean Absolute Error') print ('MAE Linear Regression', mean_absolute_error(y_pred,y_true)) print("Mean squared error:",mean_squared_error(y_true, y_pred)) plt.title('AAPL stock price ') plt.ylabel('Price') plt.xlabel(u'date') reg_val, = plt.plot(y_pred,color='b',label=u'Linear Regression') true_val, = plt.plot(y_true,color='g', label='True Values', alpha=0.5,linewidth=1) plt.legend(handles=[true_val,reg_val]) plt.show() print('-------------------------') print('from predicion graph we can see that the prediction works well') """ Explanation: Use 30 days stock price to predict 31 days price Because accounting price as a feature is 100% correlation to predict the price. so we can get almost 100% match prediction. I think using previous price to predict future price is best way to predict. End of explanation """ #get apple revenue revenue=quandl.get("SF1/AAPL_REVENUE_MRQ",start_date="1996-9-26",end_date='2017-12-31', authtoken="_1LjZZVx4HVVTwzCmqxg") #get apple total assets total_assets=quandl.get("SF1/AAPL_ASSETS_MRY",start_date="1996-9-26",end_date='2017-12-31', authtoken="_1LjZZVx4HVVTwzCmqxg") #get apple gross profit gross_profit=quandl.get("SF1/AAPL_GP_MRY",start_date="1996-9-26",end_date='2017-12-31', authtoken="_1LjZZVx4HVVTwzCmqxg") #get apple shareholders equity equity=quandl.get("SF1/AAPL_EQUITY_MRQ",start_date="1996-9-26",end_date='2017-12-31', authtoken="_1LjZZVx4HVVTwzCmqxg") #change name of columns revenue.columns = ['revenue'] total_assets.columns = ['total_assets'] gross_profit.columns = ['gross_profit'] equity.columns = ['equity'] fin_data=pd.concat([revenue,total_assets,gross_profit,equity],axis=1) fin_data['date']=fin_data.index #create quarter column and indicate the quater of data fin_data['quarter'] = pd.to_datetime(fin_data['date']).dt.to_period('Q') fin_data.drop('date', axis=1, inplace=True) fin_data.head() ##handle NAN data in chart. while fin_data['total_assets'].isnull().any(): fin_data.loc[fin_data['total_assets'].isnull(),'total_assets'] = fin_data['total_assets'].shift(1) while fin_data['gross_profit'].isnull().any(): fin_data.loc[fin_data['gross_profit'].isnull(),'gross_profit'] = fin_data['gross_profit'].shift(1) while fin_data['equity'].isnull().any(): fin_data.loc[fin_data['equity'].isnull(),'equity'] = fin_data['equity'].shift(1) fin_data=fin_data.fillna(method='bfill') fin_data.head() fin_price=pd.DataFrame(df['Adj. Close']) fin_price.columns=['price'] fin_price['quarter'] = pd.to_datetime(fin_price.index,errors='coerce').to_period('Q') fin_price2=fin_price index=fin_price2.index fin_price.head() #combine two dataframe together, use quarter column as key to combine fin_price1=fin_price.set_index('quarter').join(fin_data.set_index('quarter')) fin_price1=fin_price1.dropna(axis=0) fin_price1.head() print('check NAN in data\n',fin_price1.isnull().any()) #set up index to date. fin_price1.set_index(index).head() ##correlation heat map. corr_other=fin_price1.corr() print(corr_other) plt.figure(figsize=(12, 10)) plt.imshow(corr_other, cmap='RdYlGn', interpolation='none', aspect='auto') plt.xticks(range(len(corr_other)), corr_other.columns, rotation='vertical') plt.yticks(range(len(corr_other)), corr_other.columns); plt.suptitle('financial data Correlations Heat Map', fontsize=15, fontweight='bold') plt.show() print('-------------------------') print('surprisingly the financial fundamental data show high related with price. the correlation are even higher') print('than daily market data.') ##linear regression with all features predictor3=fin_price1[['revenue','total_assets','gross_profit','equity']] #normalize predictor predictor3=preprocessing.scale(predictor3) #print(predictor3) clf3 = linear_model.LinearRegression(n_jobs=-1) X_train3, X_test3, y_train3, y_test3 =train_test_split(predictor3 , fin_price1['price'], test_size=0.1,shuffle= False) clf3.fit(X_train3, y_train3) forecast_set3 = clf3.predict(X_test3) print('confident:',clf3.score(X_test3, y_test3)) print("Mean squared error:",mean_squared_error(y_test3, forecast_set3)) print('Mean squared error is accpetable.') num_samples3 = fin_price1.shape[0] #add Forecase column to dataframe fin_price1['Forecast'] = np.nan fin_price1['Forecast'][int(0.9*num_samples3):num_samples3]=forecast_set3 style.use('ggplot') fin_price1['price'].plot() fin_price1['Forecast'].plot() plt.legend(loc=4) plt.xlabel('Date') plt.ylabel('Price') plt.rcParams['figure.figsize'] = (20,20) plt.show() print('-------------------------') print('our prediction fit the major trend of stock price') """ Explanation: Use financial fundamental data to predict stock price I try to collect more financial fundamental data to predict stock price. To compare with previous 3 predictions, I collect apple quarterly revenue, yearly total assets, yearly gross profit and equity as key feature to forcast stock price. End of explanation """ # Use PCA to reduce the number of features to two, and test. from sklearn.decomposition import PCA #reduce 4 featrues to 2 pca = PCA(n_components=2) predictor3=pca.fit_transform(predictor3) print(predictor3.shape) clf4 = linear_model.LinearRegression(n_jobs=-1) X_train4, X_test4, y_train4, y_test4 =train_test_split(predictor3 , fin_price1['price'], test_size=0.1,shuffle= False) clf4.fit(X_train4, y_train4) forecast_set4 = clf4.predict(X_test4) confidence3=clf4.score(X_test4, y_test4) print('confident:',confidence3) print("Mean squared error:",mean_squared_error(y_test4, forecast_set4)) print('After use PCA, the prediction is worse.') num_samples4 = fin_price1.shape[0] #add Forecase column to dataframe fin_price1['Forecast2'] = np.nan fin_price1['Forecast2'][int(0.9*num_samples3):num_samples3]=forecast_set4 style.use('ggplot') fin_price1['price'].plot() fin_price1['Forecast2'].plot() plt.legend(loc=4) plt.xlabel('Date') plt.ylabel('Price') plt.rcParams['figure.figsize'] = (20,20) plt.show() """ Explanation: Use PCA to reduce the number of features to two Trying to use PCA to processing the features and test accuracy. End of explanation """
jpilgram/phys202-2015-work
assignments/assignment10/ODEsEx02.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed """ Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation """ def lorentz_derivs(yvec, t, sigma, rho, beta): """Compute the the derivatives for the Lorentz system at yvec(t).""" # YOUR CODE HERE #raise NotImplementedError() x=yvec[0] y=yvec[1] z=yvec[2] dx = sigma*(y-x) dy = x*(rho-z)-y dz = x*y - beta*z return np.array([dx,dy,dz]) assert np.allclose(lorentz_derivs((1,1,1),0, 1.0, 1.0, 2.0),[0.0,-1.0,-1.0]) """ Explanation: Lorenz system The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic behavior, such as bifurcations, attractors, and sensitive dependence on initial conditions. The differential equations read: $$ \frac{dx}{dt} = \sigma(y-x) $$ $$ \frac{dy}{dt} = x(\rho-z) - y $$ $$ \frac{dz}{dt} = xy - \beta z $$ The solution vector is $[x(t),y(t),z(t)]$ and $\sigma$, $\rho$, and $\beta$ are parameters that govern the behavior of the solutions. Write a function lorenz_derivs that works with scipy.integrate.odeint and computes the derivatives for this system. End of explanation """ def solve_lorentz(ic, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0): """Solve the Lorenz system for a single initial condition. Parameters ---------- ic : array, list, tuple Initial conditions [x,y,z]. max_time: float The max time to use. Integrate with 250 points per time unit. sigma, rho, beta: float Parameters of the differential equation. Returns ------- soln : np.ndarray The array of the solution. Each row will be the solution vector at that time. t : np.ndarray The array of time points used. """ # YOUR CODE HERE #raise NotImplementedError() t = np.linspace(0,max_time, max_time*250) sol = odeint(lorentz_derivs, ic, t, args=(sigma, rho, beta)) return np.array(sol),np.array(t) assert True # leave this to grade solve_lorenz """ Explanation: Write a function solve_lorenz that solves the Lorenz system above for a particular initial condition $[x(0),y(0),z(0)]$. Your function should return a tuple of the solution array and time array. End of explanation """ N = 5 colors = plt.cm.hot(np.linspace(0,1,N)) for i in range(N): # To use these colors with plt.plot, pass them as the color argument print(colors[i]) def plot_lorentz(N=10, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0): """Plot [x(t),z(t)] for the Lorenz system. Parameters ---------- N : int Number of initial conditions and trajectories to plot. max_time: float Maximum time to use. sigma, rho, beta: float Parameters of the differential equation. """ # YOUR CODE HERE #raise NotImplementedError() np.random.seed(1) sols=[] for i in range(N): data = (np.random.random(3)-0.5)*30 sols.append(solve_lorentz(data, max_time, sigma, rho, beta)) for s in sols: x = [p[0] for p in s[0]] z = [p[2] for p in s[0]] color = plt.cm.hot((x[0]+z[0])/60+0.5) plt.plot(x,z, color=color) plt.xlabel('$x(t)$') plt.ylabel('$z(t)$') plt.title('Lorentz System') plt.box(False) plt.tick_params(axis='x', top='off') plt.tick_params(axis='y', right='off') plt.xlim(-28,28) plt.ylim(-20,65) plot_lorentz() assert True # leave this to grade the plot_lorenz function """ Explanation: Write a function plot_lorentz that: Solves the Lorenz system for N different initial conditions. To generate your initial conditions, draw uniform random samples for x, y and z in the range $[-15,15]$. Call np.random.seed(1) a single time at the top of your function to use the same seed each time. Plot $[x(t),z(t)]$ using a line to show each trajectory. Color each line using the hot colormap from Matplotlib. Label your plot and choose an appropriate x and y limit. The following cell shows how to generate colors that can be used for the lines: End of explanation """ # YOUR CODE HERE #raise NotImplementedError() interact(plot_lorentz, max_time=(1,10,1), N = (1,50,1), sigma = (0.0, 50.0), rho =(0.0, 50.0), beta=fixed(8/3)); """ Explanation: Use interact to explore your plot_lorenz function with: max_time an integer slider over the interval $[1,10]$. N an integer slider over the interval $[1,50]$. sigma a float slider over the interval $[0.0,50.0]$. rho a float slider over the interval $[0.0,50.0]$. beta fixed at a value of $8/3$. End of explanation """
turbomanage/training-data-analyst
courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/4_keras_functional_api.ipynb
apache-2.0
# Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.0 || pip install tensorflow==2.0 """ Explanation: Introducing the Keras Functional API Learning Objectives 1. Understand embeddings and how to create them with the feature column API 1. Understand Deep and Wide models and when to use them 1. Understand the Keras functional API and how to build a deep and wide model with it Introduction In the last notebook, we learned about the Keras Sequential API. The Keras Functional API provides an alternate way of building models which is more flexible. With the Functional API, we can build models with more complex topologies, multiple input or output layers, shared layers or non-sequential data flows (e.g. residual layers). In this notebook we'll use what we learned about feature columns to build a Wide & Deep model. Recall, that the idea behind Wide & Deep models is to join the two methods of learning through memorization and generalization by making a wide linear model and a deep learning model to accommodate both. You can have a look at the original research paper here: Wide & Deep Learning for Recommender Systems. <img src='assets/wide_deep.png' width='80%'> <sup>(image: https://ai.googleblog.com/2016/06/wide-deep-learning-better-together-with.html)</sup> The Wide part of the model is associated with the memory element. In this case, we train a linear model with a wide set of crossed features and learn the correlation of this related data with the assigned label. The Deep part of the model is associated with the generalization element where we use embedding vectors for features. The best embeddings are then learned through the training process. While both of these methods can work well alone, Wide & Deep models excel by combining these techniques together. End of explanation """ import datetime import os import shutil import numpy as np import pandas as pd import tensorflow as tf from matplotlib import pyplot as plt from tensorflow import keras from tensorflow import feature_column as fc from tensorflow.keras import Model from tensorflow.keras.layers import ( Input, Dense, DenseFeatures, concatenate) from tensorflow.keras.callbacks import TensorBoard print(tf.__version__) %matplotlib inline """ Explanation: Start by importing the necessary libraries for this lab. End of explanation """ !ls -l ../data/*.csv """ Explanation: Load raw data We will use the taxifare dataset, using the CSV files that we created in the first notebook of this sequence. Those files have been saved into ../data. End of explanation """ CSV_COLUMNS = [ 'fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key' ] LABEL_COLUMN = 'fare_amount' DEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']] UNWANTED_COLS = ['pickup_datetime', 'key'] def features_and_labels(row_data): label = row_data.pop(LABEL_COLUMN) features = row_data for unwanted_col in UNWANTED_COLS: features.pop(unwanted_col) return features, label def create_dataset(pattern, batch_size=1, mode=tf.estimator.ModeKeys.EVAL): dataset = tf.data.experimental.make_csv_dataset( pattern, batch_size, CSV_COLUMNS, DEFAULTS) dataset = dataset.map(features_and_labels) if mode == tf.estimator.ModeKeys.TRAIN: dataset = dataset.shuffle(buffer_size=1000).repeat() # take advantage of multi-threading; 1=AUTOTUNE dataset = dataset.prefetch(1) return dataset """ Explanation: Use tf.data to read the CSV files We wrote these functions for reading data from the csv files above in the previous notebook. For this lab we will also include some additional engineered features in our model. In particular, we will compute the difference in latitude and longitude, as well as the Euclidean distance between the pick-up and drop-off locations. We can accomplish this by adding these new features to the features dictionary with the function add_engineered_features below. Note that we include a call to this function when collecting our features dict and labels in the features_and_labels function below as well. End of explanation """ # TODO 1 # 1. Bucketize latitudes and longitudes NBUCKETS = 16 latbuckets = np.linspace(start=38.0, stop=42.0, num=NBUCKETS).tolist() lonbuckets = np.linspace(start=-76.0, stop=-72.0, num=NBUCKETS).tolist() fc_bucketized_plat = fc.bucketized_column( source_column=fc.numeric_column("pickup_longitude"), boundaries=lonbuckets) fc_bucketized_plon = fc.bucketized_column( source_column=fc.numeric_column("pickup_latitude"), boundaries=latbuckets) fc_bucketized_dlat = fc.bucketized_column( source_column=fc.numeric_column("dropoff_longitude"), boundaries=lonbuckets) fc_bucketized_dlon = fc.bucketized_column( source_column=fc.numeric_column("dropoff_latitude"), boundaries=latbuckets) # 2. Cross features for locations fc_crossed_dloc = fc.crossed_column( [fc_bucketized_dlat, fc_bucketized_dlon], hash_bucket_size=NBUCKETS * NBUCKETS) fc_crossed_ploc = fc.crossed_column( [fc_bucketized_plat, fc_bucketized_plon], hash_bucket_size=NBUCKETS * NBUCKETS) fc_crossed_pd_pair = fc.crossed_column( [fc_crossed_dloc, fc_crossed_ploc], hash_bucket_size=NBUCKETS**4) # 3. Create embedding columns for the crossed columns fc_pd_pair = fc.embedding_column(categorical_column=fc_crossed_pd_pair, dimension=3) fc_dloc = fc.embedding_column(categorical_column=fc_crossed_dloc, dimension=3) fc_ploc = fc.embedding_column(categorical_column=fc_crossed_ploc, dimension=3) """ Explanation: Feature columns for Wide and Deep model For the Wide columns, we will create feature columns of crossed features. To do this, we'll create a collection of Tensorflow feature columns to pass to the tf.feature_column.crossed_column constructor. The Deep columns will consist of numeric columns and the embedding columns we want to create. End of explanation """ # TODO 2 wide_columns = [ # One-hot encoded feature crosses fc.indicator_column(fc_crossed_dloc), fc.indicator_column(fc_crossed_ploc), fc.indicator_column(fc_crossed_pd_pair) ] deep_columns = [ # Embedding_column to "group" together ... fc.embedding_column(fc_crossed_pd_pair, dimension=10), # Numeric columns fc.numeric_column("pickup_latitude"), fc.numeric_column("pickup_longitude"), fc.numeric_column("dropoff_longitude"), fc.numeric_column("dropoff_latitude") ] """ Explanation: Gather list of feature columns Next we gather the list of wide and deep feature columns we'll pass to our Wide & Deep model in Tensorflow. Recall, wide columns are sparse, have linear relationship with the output while continuous columns are deep, have a complex relationship with the output. We will use our previously bucketized columns to collect crossed feature columns and sparse feature columns for our wide columns, and embedding feature columns and numeric features columns for the deep columns. End of explanation """ INPUT_COLS = [ 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count' ] inputs = {colname : Input(name=colname, shape=(), dtype='float32') for colname in INPUT_COLS } """ Explanation: Build a Wide and Deep model in Keras To build a wide-and-deep network, we connect the sparse (i.e. wide) features directly to the output node, but pass the dense (i.e. deep) features through a set of fully connected layers. Here’s that model architecture looks using the Functional API. First, we'll create our input columns using tf.keras.layers.Input. End of explanation """ def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) # TODO 2 & 3 def build_model(dnn_hidden_units): # Create the deep part of model deep = DenseFeatures(deep_columns, name='deep_inputs')(inputs) for num_nodes in dnn_hidden_units: deep = Dense(num_nodes, activation='relu')(deep) # Create the wide part of model wide = DenseFeatures(wide_columns, name='wide_inputs')(inputs) # Combine deep and wide parts of the model combined = concatenate(inputs=[deep, wide], name='combined') # Map the combined outputs into a single prediction value output = Dense(units=1, activation=None, name='prediction')(combined) # Finalize the model model = Model(inputs=list(inputs.values()), outputs=output) # Compile the keras model model.compile(optimizer="adam", loss="mse", metrics=[rmse, "mse"]) return model """ Explanation: Then, we'll define our custom RMSE evaluation metric and build our wide and deep model. End of explanation """ HIDDEN_UNITS = [10,10] model = build_model(dnn_hidden_units=HIDDEN_UNITS) tf.keras.utils.plot_model(model, show_shapes=False, rankdir='LR') """ Explanation: Next, we can call the build_model to create the model. Here we'll have two hidden layers, each with 10 neurons, for the deep part of our model. We can also use plot_model to see a diagram of the model we've created. End of explanation """ BATCH_SIZE = 1000 NUM_TRAIN_EXAMPLES = 10000 * 5 # training dataset will repeat, wrap around NUM_EVALS = 50 # how many times to evaluate NUM_EVAL_EXAMPLES = 10000 # enough to get a reasonable sample trainds = create_dataset( pattern='../data/taxi-train*', batch_size=BATCH_SIZE, mode=tf.estimator.ModeKeys.TRAIN) evalds = create_dataset( pattern='../data/taxi-valid*', batch_size=BATCH_SIZE, mode=tf.estimator.ModeKeys.EVAL).take(NUM_EVAL_EXAMPLES//1000) %%time steps_per_epoch = NUM_TRAIN_EXAMPLES // (BATCH_SIZE * NUM_EVALS) OUTDIR = "./taxi_trained" shutil.rmtree(path=OUTDIR, ignore_errors=True) # start fresh each time history = model.fit(x=trainds, steps_per_epoch=steps_per_epoch, epochs=NUM_EVALS, validation_data=evalds, callbacks=[TensorBoard(OUTDIR)]) """ Explanation: Next, we'll set up our training variables, create our datasets for training and validation, and train our model. (We refer you the the blog post ML Design Pattern #3: Virtual Epochs for further details on why express the training in terms of NUM_TRAIN_EXAMPLES and NUM_EVALS and why, in this training code, the number of epochs is really equal to the number of evaluations we perform.) End of explanation """ RMSE_COLS = ['rmse', 'val_rmse'] pd.DataFrame(history.history)[RMSE_COLS].plot() """ Explanation: Just as before, we can examine the history to see how the RMSE changes through training on the train set and validation set. End of explanation """
sraejones/phys202-2015-work
assignments/assignment05/InteractEx02.ipynb
mit
%matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display from math import pi """ Explanation: Interact Exercise 2 Imports End of explanation """ def plot_sin1(a, b): x = np.linspace(0, 4 * pi, 100) plt.plot(x, np.sin((c *x) + d)) plt.xlim(0, 4 * pi) plt.ylim(-1.0, 1.0) plt.box(False) plot_sin1(5, 3.4) """ Explanation: Plotting with parameters Write a plot_sin1(a, b) function that plots $sin(ax+b)$ over the interval $[0,4\pi]$. Customize your visualization to make it effective and beautiful. Customize the box, grid, spines and ticks to match the requirements of this data. Use enough points along the x-axis to get a smooth plot. For the x-axis tick locations use integer multiples of $\pi$. For the x-axis tick labels use multiples of pi using LaTeX: $3\pi$. End of explanation """ v = interact(plot_sine1, a=(0.0,5.0,0.1), b=(-5.0,5.0,0.1)); v assert True # leave this for grading the plot_sine1 exercise """ Explanation: Then use interact to create a user interface for exploring your function: a should be a floating point slider over the interval $[0.0,5.0]$ with steps of $0.1$. b should be a floating point slider over the interval $[-5.0,5.0]$ with steps of $0.1$. End of explanation """ # YOUR CODE HERE def plot_sin2 (a, b, style): x = np.linspace(0, 4 * pi, 100) plt.plot(x, np.sin((c *x) + d)) plt.xlim(0, 4 * pi) plt.ylim(-1.0, 1.0) plt.box(False) plot_sin2(4.0, -1.0, 'b--') """ Explanation: In matplotlib, the line style and color can be set with a third argument to plot. Examples of this argument: dashed red: r-- blue circles: bo dotted black: k. Write a plot_sine2(a, b, style) function that has a third style argument that allows you to set the line style of the plot. The style should default to a blue line. End of explanation """ q = interact(plot_sin2, a=(0.0,5.0,0.1), b=(-5.0,5.0,0.1), style={'blue dots': 'b.', 'black circles': 'ko', 'red triangles': 'r^'}); q assert True # leave this for grading the plot_sine2 exercise """ Explanation: Use interact to create a UI for plot_sine2. Use a slider for a and b as above. Use a drop down menu for selecting the line style between a dotted blue line line, black circles and red triangles. End of explanation """
yingchi/fastai-notes
deeplearning1/nbs/lesson3_yingchi.ipynb
apache-2.0
from theano.sandbox import cuda from importlib import reload import utils; reload(utils) from utils import * from __future__ import division, print_function %matplotlib inline path = 'data/dogscats/' model_path = path + 'models/' if not os.path.exists(model_path): os.mkdir(model_path) batch_size=64 """ Explanation: Training a better model This week, we want to improve on the model we have trained from last week from a underfitting or overfitting perspective. End of explanation """ ??vgg_ft """ Explanation: Are we underfitting? So far, our validation accuracy has generally been higher that our training accuracy This leads to 2 questions: 1. How is this possible? 2. Is this desirable? Answer 1): Because of dropout. Dropout refers to a layer taht randomly deletes (i.e. sets to 0) each activation in the previous layer with probability p (usually 0.5). This only happends during training, not when calculating the accuracy on the validation set, which is why the validation set can have higher accuracy than the training set. The purpose of dropout is to avoid overfitting. Why? -- by deleting parts of the neural netowkr at random during training, it ensures that no one part of the network can overfit to one part of the training set. The creation of dropout was one of the key developments in deep learning, which allows us to create rich models w/o overfitting. However, it can also result in underfitting if overused. Answer 2): Not desirable. It is likely that we can get better validation set results with less dropout. Removing dropout We start with our fine-tuned cats vs dogs model (with dropout), then fine-tune again all the dense layers, after removing dropout from them. Action Plan: * Re-create and load our modified VGG model with binary dependent * Split the model between the convolutnional (conv) layers and the dense layers * Pre-calculate the output of the conv layers, so that we don't have to redundently re-calculate them on every epoch * Create a new model with just the dense layers and dropout p set to 0 * Train this new model using the output of the conv layers as training data End of explanation """ ??Vgg16.ft """ Explanation: py def vgg_ft(out_dim): vgg = Vgg16() vgg.ft(out_fim) model = vgg.model return model End of explanation """ model = vgg_ft(2) """ Explanation: py def ft(self, num): """ Replace the last layer of the model with a Dense layer of num neurons. Will also lock the weights of all layers except the new layer so that we only learn weights for the last layer in subsequent training. Args: num (int): Number of neurons in the Dense layer Returns: None """ model = self.model model.pop() for layer in model.layers: layer.trainable=False model.add(Dense(num, activation='softmax')) self.compile() End of explanation """ model.load_weights(model_path + 'finetune3.h5') """ Explanation: ...and load our fine-tuned weights from lesson 2. End of explanation """ model.summary() layers = model.layers # find the lasy convolution layer last_conv_idx = [index for index, layer in enumerate(layers) if type(layer) is Convolution2D][-1] last_conv_idx layers[last_conv_idx] conv_layers = layers[:last_conv_idx+1] conv_model = Sequential(conv_layers) fc_layers = layers[last_conv_idx+1:] """ Explanation: Now, let's train a few iterations w/o dropout. But first, let's pre-calculate the input to the fully connected layers - i.e. the Flatten() layer. Because convolution layers take a lot of time to compute, but Dense layers do not. End of explanation """ batches = get_batches(path+'train', shuffle=False, batch_size=batch_size) val_batches = get_batches(path+'valid', shuffle=False, batch_size=batch_size) val_classes = val_batches.classes trn_classes = batches.classes val_labels = onehot(val_classes) trn_labels = onehot(trn_classes) # Let's get the outputs of the conv model and save them val_features = conv_model.predict_generator(val_batches, val_batches.nb_sample) trn_features = conv_model.predict_generator(batches, batches.nb_sample) save_array(model_path + 'train_convlayer_features.bc', trn_features) save_array(model_path + 'valid_convlayer_features.bc', val_features) trn_features = load_array(model_path+'train_convlayer_features.bc') val_features = load_array(model_path+'valid_convlayer_features.bc') trn_features.shape # Note that the last conv layer is 512, 14, 14 """ Explanation: Now, we can use the exact same approach to create features as we used when we created the linear model from the imagenet predictions in lesson 2. End of explanation """ def proc_wgts(layer): return [o/2 for o in layer.get_weights()] # Such a finely tuned model needs to be updated very slowly!! opt = RMSprop(lr=0.00001, rho=0.7) def get_fc_model(): model = Sequential([ MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]), Flatten(), Dense(4096, activation='relu'), Dropout(0.), Dense(4096, activation='relu'), Dropout(0.), Dense(2, activation='softmax') ]) for l1, l2 in zip(model.layers, fc_layers): l1.set_weights(proc_wgts(l2)) model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) return model fc_model = get_fc_model() """ Explanation: For our new fully connected model, we'll create it using the exact same architecture as the last layers of VGG 16, so that we can conveniently copy pre-trained weights over from that model. End of explanation """ fc_model.fit(trn_features, trn_labels, nb_epoch=8, batch_size=batch_size, validation_data=(val_features, val_labels)) fc_model.save_weights(model_path+'no_dropout.h5') fc_model.load_weights(model_path+'no_dropout.h5') """ Explanation: And fit the model in the usual way: End of explanation """ # dim_ordering='tf' uses tensorflow dimension ordering, # which is the same order as matplotlib uses for display. # Therefore when just using for display purposes, this is more convenient gen = image.ImageDataGenerator( rotation_range=10, width_shift_range=0.1,height_shift_range=0.1, shear_range=0.15, zoom_range=0.1, channel_shift_range=10., horizontal_flip=True, dim_ordering='tf') """ Explanation: Reducing overfitting Now we've gotten a model that overfits. So let's take a few steps to reduce this. Approaches to reduce overfitting Before relying on dropout or other regularization approches to reduce overfitting, try the following techniques first. Because regularization, by definition, biases our model towards simplicity - which we only wnat to do if we know that's necessary. Action Plan: 1. Add more data (Kaggle comp N.A.) 2. Use data augmentation 3. Use architectures that generalize well 4. Add regularization 5. Reduce architecture complexity We assume that you've already collected as much data as you can ,so step (1) isn't relevant. Data augmentation Step 2 - Data augmentation refers to creating additional synthetic data, based on reasonable modifications of your input data. For images, this is likely to involve flipping, rotation, zooming, cropping, panning, minor color changes ... Which types of augmentation are appropriate depends on your data. For instance, for regular photots, you want to use hotizontal flipping, but not vertical flipping. We recommand always using at least some light data aumentation, unless you have so much data that your model will never see the same input twice. Keras comes with very convenient features for automating data augmentation. You simply define what types and maximum amount of augementation you want. End of explanation """ # Create a 'batch' of a single image img = np.expand_dims(ndimage.imread('data/dogscats/test/unknown/7.jpg'),0) # Request the generator to create batches from this image aug_iter = gen.flow(img) # Get 8 examples of these augmentated images aug_imgs = [next(aug_iter)[0].astype(np.uint8) for i in range(8)] # The original plt.imshow(img[0]) # Augmented plots(aug_imgs, (20, 7), 2) # Ensure that we return to theano dimension ordering K.set_image_dim_ordering('th') """ Explanation: So to decide which augmentation methods to use, let's take a look at the generated imaged, and use our intuition. End of explanation """ gen = image.ImageDataGenerator(rotation_range=15, width_shift_range=0.1,height_shift_range=0.1, zoom_range=0.1,horizontal_flip=True) batches = get_batches(path+'train', gen, batch_size=batch_size) val_batches = get_batches(path+'valid', shuffle=False, batch_size=batch_size) ??get_batches """ Explanation: Now, it's time to add a small amount of data augmentation, and see if we can reduce overfitting. The approach will be identical to the method we used to finetune the dense layers in lesson2, except that will use a generator with augmentation configured. Here's how we set up the generator and create batches from it: End of explanation """ fc_model = get_fc_model() for layer in conv_model.layers: layer.trainable = False conv_model.add(fc_model) """ Explanation: py get_batches(dirname, gen=&lt;keras.preprocessing.image.ImageDataGenerator object at 0x7fb1a30544e0&gt;, shuffle=True, batch_size=4, class_mode='categorical', target_size=(224, 224)) When using data augmentation, we can't pre-compute our convolutional layer features, since randomized changes are being made to every input image (--> the result of the conv layers will be different). Therefore, in order to allow data to flow through all the conv layers and our new dense layers, we attach our fully connected model to the conv model -- after ensuring that the conv layers are not trainable. End of explanation """ conv_model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) conv_model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=3, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) conv_model.save_weights(model_path + 'aug1.h5') conv_model.load_weights(model_path + 'aug1.h5') """ Explanation: Now, we can compile, train, and save our model as usual - note we use fit_generator() since we want to pull random images from the directories on every batch End of explanation """ conv_layers[-1].output_shape[1:] def get_bn_layers(p): return [ MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]), Flatten(), Dense(4096, activation='relu'), BatchNormalization(), Dropout(p), Dense(4096, activation='relu'), BatchNormalization(), Dropout(p), Dense(1000, activation='softmax') ] def load_fc_weights_from_vgg16bn(model): "Load weights for model from the dense layers of the VGG16BN model." # See imagenet_batchnorm.ipynb for info on how the weights for # Vgg16BN can be generated from the standard Vgg16 weights. from vgg16bn import Vgg16BN vgg16_bn = Vgg16BN() _, fc_layers = split_at(vgg16_bn.model, Convolution2D) copy_weights(fc_layers, model.layers) p = 0.6 bn_model = Sequential(get_bn_layers(0.6)) load_fc_weights_from_vgg16bn(bn_model) def proc_wgts(layer, prev_p, new_p): scal = (1-prev_p)/(1-new_p) return [o*scal for o in layer.get_weights()] for l in bn_model.layers: if type(l)==Dense: l.set_weights(proc_wgts(l, 0.5, 0.6)) bn_model.pop() for layer in bn_model.layers: layer.trainable=False bn_model.add(Dense(2, activation='softmax')) bn_model.compile(Adam(), 'categorical_crossentropy', metrics=['accuracy']) bn_model.fit(trn_features, trn_labels, nb_epoch=8, validation_data=(val_features, val_labels)) bn_model.save_weights(model_path+'bn.h5') bn_model.load_weights(model_path+'bn.h5') bn_layers = get_bn_layers(0.6) bn_layers.pop() bn_layers.append(Dense(2, activation='softmax')) final_model = Sequential(conv_layers) for layer in final_model.layers: layer.trainable = False for layer in bn_layers: final_model.add(layer) for l1, l2 in zip(bn_model.layers, bn_layers): l2.set_weights(l1.get_weights()) final_model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy']) final_model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=1, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) final_model.save_weights(model_path + 'final1.h5') final_model.fit_generator(batches, samples_per_epoch=batches.nb_sample, nb_epoch=4, validation_data=val_batches, nb_val_samples=val_batches.nb_sample) final_model.save_weights(model_path + 'final2.h5') # you can try to set final_model.optimizer.lr=0.001 and try another model """ Explanation: Batch normalization Batch normalization is a way to ensure that activations don't become too high or too low at any point in the model. Adjusting activiations so that are of similar scales is called normalization. It is very helpful for fast training - if some activations are very high, they will saturate the model and create very large gradients, causing training to fail; if very low, they will cause training to proceed very slowly. Prior to the developement of batchnorm in 2015, only the inputs to a model could be effectively normalized. However, weights in intermediate layers could easily become poorly scaled, due to problems in weight initialization, or a high learning rate combined with random fluctuations in weights. Batchnorm resolves this problem by normalizing each intermediate layer as well. The details of how it works are not terribly important - the important takeaway is: all modern networks should use batchnorm, or something equivalent. 2 reasons for this: 1. Adding batchnorm to a model can result in 10x or more improvements in training speed 2. Normalization greatly reduces the ability of a small number of outlying inputs to over-influence the training. It also tends to reduce overfitting How it works: At a first step, it normalizes intermediate layers (activations) in the same way as input layers can be normalized. But this would not be enough, since the model would then just push the weights up or down indefinitely to try to undo this normalization. So, there are 2 additional steps: 1. Add 2 more trainable parameters to each layer - one to multiply all activations to set an arbitrary standard deviation, and one to add to all activations to set an arbitraty mean 2. Incorporate both the normalization, and the learnt multiply/add parameters, into the gradient calcultions during backprop. This ensures that the weights don't tend to push very high or very low (since the normalization is included in the gradient calculations, so the updates are aware of the normalization). But it also ensures that if a layer does need to change the overall mean or standard deviation in order to match the output scale, it can do so. Adding batchnorm to the model Why VGG does not use this? Because then VGG was created, batchnorm has not been invented. End of explanation """
DSSatPitt/katz-python-workshop
jupyter-notebooks/Running Code.ipynb
cc0-1.0
a = 10 print(a) """ Explanation: Running Code First and foremost, the Jupyter Notebook is an interactive environment for writing and running code. The notebook is capable of running code in a wide range of languages. However, each notebook is associated with a single kernel. This notebook is associated with the IPython kernel, therefor runs Python code. Code cells allow you to enter and run code Run a code cell using Shift-Enter or pressing the <button class='btn btn-default btn-xs'><i class="icon-step-forward fa fa-step-forward"></i></button> button in the toolbar above: End of explanation """ import time time.sleep(10) """ Explanation: There are two other keyboard shortcuts for running code: Alt-Enter runs the current cell and inserts a new one below. Ctrl-Enter run the current cell and enters command mode. Managing the Kernel Code is run in a separate process called the Kernel. The Kernel can be interrupted or restarted. Try running the following cell and then hit the <button class='btn btn-default btn-xs'><i class='icon-stop fa fa-stop'></i></button> button in the toolbar above. End of explanation """ import sys from ctypes import CDLL # This will crash a Linux or Mac system # equivalent calls can be made on Windows # Uncomment these lines if you would like to see the segfault # dll = 'dylib' if sys.platform == 'darwin' else 'so.6' # libc = CDLL("libc.%s" % dll) # libc.time(-1) # BOOM!! """ Explanation: If the Kernel dies you will be prompted to restart it. Here we call the low-level system libc.time routine with the wrong argument via ctypes to segfault the Python interpreter: End of explanation """ print("hi, stdout") from __future__ import print_function print('hi, stderr', file=sys.stderr) """ Explanation: Cell menu The "Cell" menu has a number of menu items for running code in different ways. These includes: Run and Select Below Run and Insert Below Run All Run All Above Run All Below Restarting the kernels The kernel maintains the state of a notebook's computations. You can reset this state by restarting the kernel. This is done by clicking on the <button class='btn btn-default btn-xs'><i class='fa fa-repeat icon-repeat'></i></button> in the toolbar above. sys.stdout and sys.stderr The stdout and stderr streams are displayed as text in the output area. End of explanation """ import time, sys for i in range(8): print(i) time.sleep(0.5) """ Explanation: Output is asynchronous All output is displayed asynchronously as it is generated in the Kernel. If you execute the next cell, you will see the output one piece at a time, not all at the end. End of explanation """ for i in range(50): print(i) """ Explanation: Large outputs To better handle large outputs, the output area can be collapsed. Run the following cell and then single- or double- click on the active area to the left of the output: End of explanation """ for i in range(50): print(2**i - 1) """ Explanation: Beyond a certain point, output will scroll automatically: End of explanation """
landlab/landlab
notebooks/tutorials/terrain_analysis/hack_calculator/hack_calculator.ipynb
mit
import copy import numpy as np import matplotlib as mpl from landlab import RasterModelGrid, imshow_grid from landlab.io import read_esri_ascii from landlab.components import FlowAccumulator, HackCalculator """ Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../../landlab_header.png"></a> Using the HackCalculator Component Background Hack's Law refers to a commonly observed power-law relationship between the length of the longest stream in a drainage basin, $L$, and the area that it drains, $A$: $$L = C A^h$$ where $h$ is commonly in the neighborhood of 0.5 or 0.6. It is named for the American geomorphologist John Hack (see Hack, 1957). A value of 0.5 represents perfect geometry similarity between the areal measure, $A$, and the embedded length $L$. Montgomery and Dietrich (1992) noted a useful "rule of thumb" empirical relationship: $$A \approx \frac{1}{3} L^2$$ which says that, roughly speaking, the surface area of a typical drainage basin is on the order of 1/3 times the square of its longest stream length. But individual drainage basins often deviate somewhat from this idealized behavior, and often it is useful to extract the values of $C$ and $h$ for particular basins. Component overview The HackCalculator provides estimates of the best-fit $C$ and $h$ values for one or more drainage basins within a given area represented by a digital elevation model, which is contained in a grid field called topographic__elevation. The component requires a grid that includes the following fields: topographic__elevation (node) elevation data for the region of interest drainage_area (node) contributing drainage area for each node flow__receiver_node (node) ID of the receiver (node that receives flow) for each node flow__link_to_receiver_node (node) ID of the link connecting node and receiver for each node flow__upstream_node_order (node) array of node IDs in downstream-to-upstream order Apart from topographic__elevation, each of these fields are created and calculated by running the FlowAccumulator component. The component uses the ChannelProfiler component to calculate cumulative downstream length for one or more channels in the terrain. Parameters for the ChannelProfiler may be given as arguments to HackCalculator. When run (using the method calculate_hack_parameters), the component creates a Pandas DataFrame called hack_coefficient_dataframe. It is a pandas dataframe with one row for each basin for which Hack parameters are calculated. Thus, there are as many rows as the number of watersheds identified by the ChannelProfiler. The dataframe has the following index and columns: Index basin_outlet_id: The node ID of the watershed outlet where each set of Hack parameters was estimated. Columns A_max: The drainage area of the watershed outlet. C: The Hack coefficient as defined in the equations above. h: The Hack exponent as defined in the equations above. If you pass the argument save_full_df=True, HackCalculator will generate an additional DataFrame called full_hack_dataframe. It is pandas dataframe with a row for every model grid cell used to estimate the Hack parameters. It has the following index and columns: Index node_id: The node ID of the model grid cell. Columns basin_outlet_id: The node IDs of watershed outlet A: The drainage are of the model grid cell. L_obs: The observed distance to the divide. L_est: The predicted distance to divide based on the Hack coefficient fit. Imports and inline docs First, import what we'll need: End of explanation """ print(HackCalculator.__doc__) """ Explanation: The docstring describes the component and provides some simple examples: End of explanation """ print(HackCalculator.__init__.__doc__) """ Explanation: The __init__ docstring lists the parameters: End of explanation """ # read the DEM (grid_geog, elev) = read_esri_ascii("west_bijou_escarpment_snippet.asc") grid = RasterModelGrid( (grid_geog.number_of_node_rows, grid_geog.number_of_node_columns), xy_spacing=30.0 ) grid.add_field("topographic__elevation", elev, at="node") cmap = copy.copy(mpl.cm.get_cmap("pink")) imshow_grid(grid, elev, cmap=cmap, colorbar_label="Elevation (m)") """ Explanation: Example 1 In this example, we read in a small digital elevation model (DEM) from NASADEM for an area on the Colorado high plains (USA) that includes a portion of an escarpment along the west side of a drainage known as West Bijou Creek (see Rengers & Tucker, 2014). The DEM file is in ESRI Ascii format, but is in a geographic projection, with horizontal units of decimal degrees. To calculate slope gradients properly, we'll first read the DEM into a Landlab grid object that has this geographic projection. Then we'll create a second grid with 30 m cell spacing (approximately equal to the NASADEM's resolution), and copy the elevation field from the geographic DEM. This isn't a proper projection of course, but it will do for purposes of this example. End of explanation """ # instatiated and run flow accumulator fa = FlowAccumulator( grid, flow_director="FlowDirectorD8", # use D8 routing depression_finder="LakeMapperBarnes", # pit filler method="D8", # pit filler use D8 too redirect_flow_steepest_descent=True, # re-calculate flow dirs reaccumulate_flow=True, # re-calculate drainagea area ) fa.run_one_step() # run the flow accumulator # instantiate and run HackCalculator component hc = HackCalculator(grid) hc.calculate_hack_parameters() """ Explanation: Next, we run the HackCalculator on this DEM. First we need to instantiate and run FlowAccumulator to calculate flow directions and drainage area. End of explanation """ hc.hack_coefficient_dataframe """ Explanation: Here is the resulting DataFrame, containing the area of the largest drainage basin and its corresponding $C$ and $h$ values: End of explanation """ hc.profiler.plot_profiles_in_map_view(colorbar_label="Elevation (m)") """ Explanation: You can access the embedded ChannelProfiler via HackCalculator.profiler: The ChannelProfiler data is an ordered dict, in this case containing data for one watershed: the one that drains to node 6576 (for details see the reference documentation and tutorial resources for ChannelProfiler). For this example, we might wish to visualize the main channel for which the Hack coefficient and exponent were calculated. We can do that with the profiler's plot_profiles_in_map_view method: End of explanation """ imshow_grid( grid, "distance_to_divide", colorbar_label="Distance from drainage divide (m)" ) """ Explanation: The component also provides a node field called distance_to_divide that, as the name implies, contains the streamwise distance between a node and its source at a drainage divide: End of explanation """ # create grid and copy DEM into it grid = RasterModelGrid( (grid_geog.number_of_node_rows, grid_geog.number_of_node_columns), xy_spacing=30.0 ) grid.add_field("topographic__elevation", elev, at="node") # instatiated and run flow accumulator fa = FlowAccumulator( grid, flow_director="FlowDirectorD8", # use D8 routing depression_finder="LakeMapperBarnes", # pit filler method="D8", # pit filler use D8 too redirect_flow_steepest_descent=True, # re-calculate flow dirs reaccumulate_flow=True, # re-calculate drainagea area ) fa.run_one_step() # run the flow accumulator # instantiate and run HackCalculator component hc = HackCalculator(grid, save_full_df=True) hc.calculate_hack_parameters() hc.hack_coefficient_dataframe hc.full_hack_dataframe """ Explanation: Example 2: full data frame The next example is the same as the first, but here we request and examine the "full dataframe": End of explanation """ # create grid and copy DEM into it grid = RasterModelGrid( (grid_geog.number_of_node_rows, grid_geog.number_of_node_columns), xy_spacing=30.0 ) grid.add_field("topographic__elevation", elev, at="node") # instatiated and run flow accumulator fa = FlowAccumulator( grid, flow_director="FlowDirectorD8", # use D8 routing depression_finder="LakeMapperBarnes", # pit filler method="D8", # pit filler use D8 too redirect_flow_steepest_descent=True, # re-calculate flow dirs reaccumulate_flow=True, # re-calculate drainagea area ) fa.run_one_step() # run the flow accumulator # instantiate and run HackCalculator component hc = HackCalculator(grid, number_of_watersheds=5) hc.calculate_hack_parameters() hc.hack_coefficient_dataframe hc.profiler.plot_profiles_in_map_view(colorbar_label="Elevation (m)") """ Explanation: Example 3: multiple watersheds By default, the ChannelProfiler extracts data from just one watershed, which is why the above example reports Hack parameters for just one basin. Here we re-run the analysis with five basins. End of explanation """ # create grid and copy DEM into it grid = RasterModelGrid( (grid_geog.number_of_node_rows, grid_geog.number_of_node_columns), xy_spacing=30.0 ) grid.add_field("topographic__elevation", elev, at="node") # instatiated and run flow accumulator fa = FlowAccumulator( grid, flow_director="FlowDirectorD8", # use D8 routing depression_finder="LakeMapperBarnes", # pit filler method="D8", # pit filler use D8 too redirect_flow_steepest_descent=True, # re-calculate flow dirs reaccumulate_flow=True, # re-calculate drainagea area ) fa.run_one_step() # run the flow accumulator # instantiate and run HackCalculator component hc = HackCalculator( grid, number_of_watersheds=5, main_channel_only=False, minimum_channel_threshold=2.0e4, ) hc.calculate_hack_parameters() hc.hack_coefficient_dataframe hc.profiler.plot_profiles_in_map_view(colorbar_label="Elevation (m)") """ Explanation: Example 4: multiple channels per basin So far, we have only performed the calculation on the main channel in each drainage basin. We can operate on all the channels in each basin by setting the ChannelProfiler parameter main_channel_only to False. While we're at it, we will also specify a drainage area threshold for channels of 20,000 m$^2$. End of explanation """
rajeshb/SelfDrivingCar
T1P1-Finding-Lane-Lines/P1.ipynb
mit
# importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline # calculate running average for line coordinates def running_average(avg, sample, n=12): if (avg == 0): return sample avg -= avg / n; avg += sample / n; return int(avg); # global variables - need to reset for before each of the video processing prev_left_line = [] prev_right_line = [] # setting globals def set_global_prev_left_line(left_line): global prev_left_line if prev_left_line and left_line: x1, y1, x2, y2 = prev_left_line prev_left_line = (running_average(x1, left_line[0])),(running_average(y1, left_line[1])),(running_average(x2, left_line[2])),(running_average(y2, left_line[3])) else: prev_left_line = left_line def set_global_prev_right_line(right_line): global prev_right_line if prev_right_line and right_line: x1, y1, x2, y2 = prev_right_line prev_right_line = (running_average(x1, right_line[0])),(running_average(y1, right_line[1])),(running_average(x2, right_line[2])),(running_average(y2, right_line[3])) else: prev_right_line = right_line # reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') # printing out some stats and plotting print('This image is:', type(image), 'with dimesions:', image.shape) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray') """ Explanation: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip "raw-lines-example.mp4" (also contained in this repository) to see what the output should look like after using the helper functions below. Once you have a result that looks roughly like "raw-lines-example.mp4", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right. Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the "play" button above) to display the image. Note If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the "Kernel" menu above and selecting "Restart & Clear Output". The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below. <figure> <img src="line-segments-example.jpg" width="380" alt="Combined Image" /> <figcaption> <p></p> <p style="text-align: center;"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> </figcaption> </figure> <p></p> <figure> <img src="laneLines_thirdPass.jpg" width="380" alt="Combined Image" /> <figcaption> <p></p> <p style="text-align: center;"> Your goal is to connect/average/extrapolate line segments to get output like this</p> </figcaption> </figure> End of explanation """ import math def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Or use BGR2GRAY if you read an image with cv2.imread() # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold, high_threshold): """Applies the Canny transform""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Applies a Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 #filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) #returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def draw_lines(img, lines, color=[255, 0, 0], thickness=2): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below """ for line in lines: for x1,y1,x2,y2 in line: cv2.line(img, (x1, y1), (x2, y2), color, thickness) def average_lines(lines): line_top = [] line_bottom = [] for line in lines: for x1,y1,x2,y2 in line: if y1 < y2: line_top.append([x1, y1]) line_bottom.append([x2, y2]) else: line_top.append([x2, y2]) line_bottom.append([x1, y1]) if len(line_top) > 0: average_top = [ int(np.average([point[0] for point in line_top])), int(np.average([point[1] for point in line_top]))] else: average_top = [] if len(line_bottom) > 0: average_bottom = [ int(np.average([point[0] for point in line_bottom])), int(np.average([point[1] for point in line_bottom]))] else: average_bottom = [] return average_top + average_bottom def segment_hough_lines(lines): left_lines = [] right_lines = [] # Segment left and right lines based on their slope for line in lines: for x1,y1,x2,y2 in line: slope = (y2 - y1) / (x2 - x1) if abs(slope) < 0.5: # skip and continue, if the slope is less than 0.5 continue if slope >= 0: right_lines.append(line) else: left_lines.append(line) return right_lines, left_lines def find_largest_lines(lines): largest_right_line = [] largest_left_line = [] largest_right_line_length = 0.0 largest_left_line_length = 0.0 # Segment left and right lines based on their slope for line in lines: for x1,y1,x2,y2 in line: slope = (y2 - y1) / (x2 - x1) if abs(slope) < 0.5: # skip and continue, if the slope is less than 0.5 continue line_length = math.hypot(x2 - x1, y2 - y1) if slope >= 0: if line_length > largest_right_line_length: largest_right_line = [x1, y1, x2, y2] largest_right_line_length = line_length else: if line_length > largest_left_line_length: largest_left_line = [x1, y1, x2, y2] largest_left_line_length = line_length return largest_right_line, largest_left_line def extrapolate_line(line, top_max, bottom_max): x1, y1, x2, y2 = line a = np.array([[x1, 1], [x2, 1]]) b = np.array([y1, y2]) m, c = np.linalg.solve(a, b) # find the extrapolated bottom y2 = top_max x2 = int((y2 - c)/m) # find the extrapolated top y1 = bottom_max x1 = int((y1 - c)/m) return [x1, y1, x2, y2] def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns an image with hough lines drawn. """ # Image dimensions img_height = img.shape[0] img_width = img.shape[1] lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img_height, img_width, 3), dtype=np.uint8) """ Approach 1 - Based on largest hough line """ """ # Get largest left/right lines from hough lines largest_right_line, largest_left_line = find_largest_lines(lines) # Extrapolate the line to the top and bottom of the region of interest if largest_right_line: final_right_line = extrapolate_line(largest_right_line, top_max = int(img_height * 0.6), bottom_max = img_width) set_global_prev_right_line(final_right_line) else: final_right_line = prev_right_line if largest_left_line: final_left_line = extrapolate_line(largest_left_line, top_max = int(img_height * 0.6), bottom_max = img_width) set_global_prev_left_line(final_left_line) else: final_left_line = prev_left_line """ """ # Approach 2 - Average the left and right lines """ # Segment hough lines right_lines, left_lines = segment_hough_lines(lines) # Find average for a line average_right_line = average_lines(right_lines) average_left_line = average_lines(left_lines) # Extrapolate the line to the top and bottom of the region of interest if average_right_line: final_right_line = extrapolate_line(average_right_line, top_max = int(img_height * 0.6), bottom_max = img_width) set_global_prev_right_line(final_right_line) else: final_right_line = prev_right_line if average_left_line: final_left_line = extrapolate_line(average_left_line, top_max = int(img_height * 0.6), bottom_max = img_width) set_global_prev_left_line(final_left_line) else: final_left_line = prev_left_line #new_lines = [[final_right_line], [final_left_line]] new_lines = [[prev_right_line], [prev_left_line]] draw_lines(line_img, new_lines, thickness=10) return line_img # Python 3 has support for cool math symbols. def weighted_img(img, initial_img, α=0.8, β=1., λ=0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * α + img * β + λ NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, α, img, β, λ) def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # you should return the final output (image with lines are drawn on lanes) # Image dimensions img_height = image.shape[0] img_width = image.shape[1] # Step 1: Convert to Grayscale processed_image = grayscale(image) # Step 2: Gaussian Blur Transform kernel_size = 7 processed_image = gaussian_blur(processed_image, kernel_size) # Step 3: Canny Transform low_threshold = 100 high_threshold = 200 processed_image = canny(processed_image, low_threshold, high_threshold) # Step 4: Region of Interest bottom_left = [100, img_height] bottom_right = [img_width - 80, img_height] top_left = [int(0.4 * img_width), int(0.6 * img_height)] top_right = [int(0.6 * img_width), int(0.6 * img_height)] processed_image = region_of_interest(processed_image, [np.array([bottom_left, top_left, top_right, bottom_right], dtype=np.int32)]) # Step 5: Hough lines rho = 1.0 theta = np.pi/180 threshold = 25 min_line_len = 50 max_line_gap = 200 processed_image = hough_lines(img=processed_image, theta=theta, rho=rho, min_line_len=min_line_len, max_line_gap=max_line_gap, threshold=threshold) # Step 6: Weighted Image processed_image = weighted_img(img=processed_image, initial_img=image) return processed_image img = process_image(mpimg.imread("test_images/solidYellowCurve2.jpg")) #plt.plot(x, y, 'b--', lw=4) plt.imshow(img, cmap='gray') """ Explanation: Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are: cv2.inRange() for color selection cv2.fillPoly() for regions selection cv2.line() to draw lines on an image given endpoints cv2.addWeighted() to coadd / overlay two images cv2.cvtColor() to grayscale or change color cv2.imwrite() to output images to file cv2.bitwise_and() to apply a mask to an image Check out the OpenCV documentation to learn about these and discover even more awesome functionality! Below are some helper functions to help get you started. They should look familiar from the lesson! End of explanation """ import os test_images_dir = "test_images/" test_out_dir = "test_output/" if not os.path.exists(test_out_dir): os.makedirs(test_out_dir) for file in os.listdir(test_images_dir): # Ignore hidden files if file.startswith('.'): continue image = mpimg.imread(test_images_dir + file) processed_image = process_image(image) out_file = test_out_dir + file #cv2.imwrite(out_file, processed_image) mpimg.imsave(out_file, processed_image) print('Processed [{0}] -> [{1}]'.format(file, out_file)) print("Done with processing images in {0} folder.".format(test_images_dir)) """ Explanation: Test on Images Now you should build your pipeline to work on the images in the directory "test_images" You should make sure your pipeline works well on these images before you try the videos. run your solution on all test_images and make copies into the test_images directory). End of explanation """ # Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML """ Explanation: Test on Videos You know what's cooler than drawing lanes over images? Drawing lanes over video! We can test our solution on two provided videos: solidWhiteRight.mp4 solidYellowLeft.mp4 End of explanation """ # Reset global variables set_global_prev_left_line([]) set_global_prev_right_line([]) white_output = 'white.mp4' clip1 = VideoFileClip("solidWhiteRight.mp4") white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!! %time white_clip.write_videofile(white_output, audio=False) """ Explanation: Let's try the one with the solid white lane on the right first ... End of explanation """ HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(white_output)) """ Explanation: Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. End of explanation """ # Reset global variables set_global_prev_left_line([]) set_global_prev_right_line([]) yellow_output = 'yellow.mp4' clip2 = VideoFileClip('solidYellowLeft.mp4') yellow_clip = clip2.fl_image(process_image) %time yellow_clip.write_videofile(yellow_output, audio=False) HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(yellow_output)) """ Explanation: At this point, if you were successful you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. Modify your draw_lines function accordingly and try re-running your pipeline. Now for the one with the solid yellow lane on the left. This one's more tricky! End of explanation """ # Reset global variables set_global_prev_left_line([]) set_global_prev_right_line([]) challenge_output = 'extra.mp4' clip2 = VideoFileClip('challenge.mp4') challenge_clip = clip2.fl_image(process_image) %time challenge_clip.write_videofile(challenge_output, audio=False) HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(challenge_output)) """ Explanation: Reflections Congratulations on finding the lane lines! As the final step in this project, we would like you to share your thoughts on your lane finding pipeline... specifically, how could you imagine making your algorithm better / more robust? Where will your current algorithm be likely to fail? Please add your thoughts below, and if you're up for making your pipeline more robust, be sure to scroll down and check out the optional challenge video below! Finding lane lines project is a starter project with relatively a simple use case. For a real self-driving car scenarios, finding lane lines need to take care of complex scenarios, real world road conditions, lights and other factors. Finding lane lines project doesn't take into consideration of normal driving scenarios, like junctions, signals, lane changes etc. Algorithms for finding lane lines project is based on successful canny and hough lines algorithms, any road conditions that may not work well for canny and hough lines requirements/assumptions will have challenges. Making the algorithm work for a video (moving car) is much different from making it work for a single image. For video, the algorithm needs to consider prior frames and average the lane lines for smoother lane prediction/projections. Tried 2 different approaches, first one based on largest line segment, extrapolating and averaging with prior frames. Second approach was to average both left and right segments, extrapolate and average with prior frames. Haven't found significant difference on the results for the given videos. Averaging with prior frames needed to be balanced based on our tests. Noticed that, larger the number of prior frames for average, it affects the average lane line to be off the actual lane line on the frame. To have a smooth lane line projection, average lane line to be drawn instead of that frame's lane line. Many of the values and parameters could be further adjusted for better results, on the other hand, tuning to specific scenarios may not work well for more challenging scenarios. It would be interesting to find out how to come up with algorithms & parameter values that works well regardless of the road conditions!! For example, Optional Challenge video has a few different scenarios on road conditions, with a few frames not having clear lane lines, shadows and turns. Algorithms had to be revised to take into consideration of those conditions. Good to start with a simple finding lane line project and move towards more challenging scenarios. Looking forward to upcoming projects! Submission If you're satisfied with your video outputs it's time to submit! Submit this ipython notebook for review. Optional Challenge Try your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project! End of explanation """
lukas/scikit-class
examples/notebooks/Lesson-2-Feature-Extraction.ipynb
gpl-2.0
import pandas as pd import numpy as np df = pd.read_csv('../scikit/tweets.csv') target = df['is_there_an_emotion_directed_at_a_brand_or_product'] text = df['tweet_text'] # We need to remove the empty rows from the text before we pass into CountVectorizer fixed_text = text[pd.notnull(text)] fixed_target = target[pd.notnull(text)] # Do the feature extraction from sklearn.feature_extraction.text import CountVectorizer count_vect = CountVectorizer() # initialize the count vectorizer count_vect.fit(fixed_text) # set up the columns """ Explanation: Feature Extraction Goals Introduction to Feature Extraction Do Feature Extraction on Text - Introduction to Bag of Words Introduction Machine Learning algorithms all take the same basic form of input: a fixed length list of numbers. Very few real world problems are a fixed length list of numbers, so a crucial step in machine learning is converting the data into this format. Sometimes the individual numbers are called "features" so this process is sometimes called "feature extraction". A fixed length list of numbers is also known as a vector. A list of vectors with all the same length is known as a matrix. Right now our input is a list of tweets that looks like this: <img src="images/tweets.png" width="400"/> We need to convert it into a list of feature vectors that look like this: <img src="images/features.png" width="400"/> You might want to stop and think about how you might do this. Bag of Words One way to convert our input into a vector is to make each row correspond to a different word and each cell correspond to the number of times that word occured in a particular tweet. <img src="images/tweet-transform.png" width="600"/> This creates a lot of columns! This is the most basic feature extraction method used on text in natural language processing. Scikit has methods to make this transofrmation really easy. In sklearn.feature_extraction.text there is a class called CountVectorizer we will use. CountVecotizer has two important methods 1. fit sets things up, associating each word with a column 2. transform converts a list of strings into feature vectors End of explanation """ count_vect.transform(["My iphone is awesome"]) """ Explanation: Now our count_vect object is able to transform text into feautre vectors. We can try it out: End of explanation """ print(count_vect.transform(["My iphone is awesome"])) """ Explanation: A sparse matrix is a matrix with mostly zeros, and we are definitely dealing with a sparse matric since most of the counts here are zero. End of explanation """ counts = count_vect.transform(fixed_text) print(counts.shape) """ Explanation: This notation says that cells in columns 876, 4573, 4596, 5699 are one and all other cells are zero. We have one row here because we passed in a list of length one - just the tweet "My iphone is awesome". Some questions to ask yourself now: - which words correspond to which columns? - is our transformation case senstitive? - how many columns do we have? Let's do the transformation on all of our tweets to build our big feature matrix (you can think of a matrix as a list of fixed size vectors). End of explanation """
zzsza/TIL
python/pyecharts.ipynb
mit
import pyecharts import pandas as pd import numpy as np attr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] bar = pyecharts.Bar("Bar chart", "precipitation and evaporation one year") bar.add("precipitation", attr, v1, mark_line=["average"], mark_point=["max", "min"]) bar.add("evaporation", attr, v2, mark_line=["average"], mark_point=["max", "min"]) bar.render() bar.height = 500 bar.width = 800 bar attr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] bar = pyecharts.Bar("Bar chart", "precipitation and evaporation one year") bar.use_theme("dark") bar.add("precipitation", attr, v1, mark_line=["average"], mark_point=["max", "min"]) bar.add("evaporation", attr, v2, mark_line=["average"], mark_point=["max", "min"]) bar.height = 500 bar.width = 800 bar """ Explanation: pyecharts HTML 에서 확인하면 이쁜 그래프도 보입니다!!! Baidu에서 데이터 시각화를 위해 만든 오픈소스인 Echarts의 파이썬 버전 다양한 그래프 제공 공식 문서 Dynamic 단, 옵션의 단추가 중국어 그래프를 그릴 때, echarts와 echartql을 로컬에서 찾으려고 함 따라서 nbconvert를 사용해 HTML으로 저장한 후, 쉘에서 수정 sed -i "" "s|/nbextensions/echarts/echarts-gl.min|https://cdn.jsdelivr.net/npm/echarts-gl@1.1.1/dist/echarts-gl.min|g; s|/nbextensions/echarts/echarts.min|https://cdnjs.cloudflare.com/ajax/libs/echarts/4.1.0/echarts.min|g" 파일이름.ipynb End of explanation """ title = "bar chart2" index = pd.date_range("8/24/2018", periods=6, freq="M") df1 = pd.DataFrame(np.random.randn(6), index=index) df2 = pd.DataFrame(np.random.rand(6), index=index) dfvalue1 = [i[0] for i in df1.values] dfvalue2 = [i[0] for i in df2.values] _index = [i for i in df1.index.format()] bar = pyecharts.Bar(title, "Profit and loss situation") bar.add("profit", _index, dfvalue1) bar.add("loss", _index, dfvalue2) bar.height = 500 bar.width = 800 bar from pyecharts import Bar, Line, Overlap attr = ['A','B','C','D','E','F'] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line Bar") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap from pyecharts import Pie attr = ['A','B','C','D','E','F'] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] pie = Pie("pie chart", title_pos="center", width=600) pie.add("A", attr, v1, center=[25, 50], is_random=True, radius=[30, 75], rosetype='radius') pie.add("B", attr, v2, center=[75, 50], is_randome=True, radius=[30, 75], rosetype='area', is_legend_show=False, is_label_show=True) pie """ Explanation: In pandas End of explanation """ bar = Bar("가로 그래프") bar.add("A", attr, v1) bar.add("B", attr, v2, is_convert=True) bar.width=800 bar """ Explanation: 가로 그래프 End of explanation """ import random attr = ["{}th".format(i) for i in range(30)] v1 = [random.randint(1, 30) for _ in range(30)] bar = Bar("Bar - datazoom - slider ") bar.add("", attr, v1, is_label_show=True, is_datazoom_show=True) # bar.render() bar days = ["{}th".format(i) for i in range(30)] days_v1 = [random.randint(1, 30) for _ in range(30)] bar = Bar("Bar - datazoom - xaxis/yaxis") bar.add( "", days, days_v1, is_datazoom_show=True, datazoom_type="slider", datazoom_range=[10, 25], is_datazoom_extra_show=True, datazoom_extra_type="slider", datazoom_extra_range=[10, 25], is_toolbox_show=False, ) # bar.render() bar """ Explanation: 슬라이더 End of explanation """ from pyecharts import Bar3D bar3d = Bar3D("3D Graph", width=1200, height=600) x_axis = [ "12a", "1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a", "12p", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p" ] y_axis = [ "Saturday", "Friday", "Thursday", "Wednesday", "Tuesday", "Monday", "Sunday" ] data = [ [0, 0, 5], [0, 1, 1], [0, 2, 0], [0, 3, 0], [0, 4, 0], [0, 5, 0], [0, 6, 0], [0, 7, 0], [0, 8, 0], [0, 9, 0], [0, 10, 0], [0, 11, 2], [0, 12, 4], [0, 13, 1], [0, 14, 1], [0, 15, 3], [0, 16, 4], [0, 17, 6], [0, 18, 4], [0, 19, 4], [0, 20, 3], [0, 21, 3], [0, 22, 2], [0, 23, 5], [1, 0, 7], [1, 1, 0], [1, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [1, 6, 0], [1, 7, 0], [1, 8, 0], [1, 9, 0], [1, 10, 5], [1, 11, 2], [1, 12, 2], [1, 13, 6], [1, 14, 9], [1, 15, 11], [1, 16, 6], [1, 17, 7], [1, 18, 8], [1, 19, 12], [1, 20, 5], [1, 21, 5], [1, 22, 7], [1, 23, 2], [2, 0, 1], [2, 1, 1], [2, 2, 0], [2, 3, 0], [2, 4, 0], [2, 5, 0], [2, 6, 0], [2, 7, 0], [2, 8, 0], [2, 9, 0], [2, 10, 3], [2, 11, 2], [2, 12, 1], [2, 13, 9], [2, 14, 8], [2, 15, 10], [2, 16, 6], [2, 17, 5], [2, 18, 5], [2, 19, 5], [2, 20, 7], [2, 21, 4], [2, 22, 2], [2, 23, 4], [3, 0, 7], [3, 1, 3], [3, 2, 0], [3, 3, 0], [3, 4, 0], [3, 5, 0], [3, 6, 0], [3, 7, 0], [3, 8, 1], [3, 9, 0], [3, 10, 5], [3, 11, 4], [3, 12, 7], [3, 13, 14], [3, 14, 13], [3, 15, 12], [3, 16, 9], [3, 17, 5], [3, 18, 5], [3, 19, 10], [3, 20, 6], [3, 21, 4], [3, 22, 4], [3, 23, 1], [4, 0, 1], [4, 1, 3], [4, 2, 0], [4, 3, 0], [4, 4, 0], [4, 5, 1], [4, 6, 0], [4, 7, 0], [4, 8, 0], [4, 9, 2], [4, 10, 4], [4, 11, 4], [4, 12, 2], [4, 13, 4], [4, 14, 4], [4, 15, 14], [4, 16, 12], [4, 17, 1], [4, 18, 8], [4, 19, 5], [4, 20, 3], [4, 21, 7], [4, 22, 3], [4, 23, 0], [5, 0, 2], [5, 1, 1], [5, 2, 0], [5, 3, 3], [5, 4, 0], [5, 5, 0], [5, 6, 0], [5, 7, 0], [5, 8, 2], [5, 9, 0], [5, 10, 4], [5, 11, 1], [5, 12, 5], [5, 13, 10], [5, 14, 5], [5, 15, 7], [5, 16, 11], [5, 17, 6], [5, 18, 0], [5, 19, 5], [5, 20, 3], [5, 21, 4], [5, 22, 2], [5, 23, 0], [6, 0, 1], [6, 1, 0], [6, 2, 0], [6, 3, 0], [6, 4, 0], [6, 5, 0], [6, 6, 0], [6, 7, 0], [6, 8, 0], [6, 9, 0], [6, 10, 1], [6, 11, 0], [6, 12, 2], [6, 13, 1], [6, 14, 3], [6, 15, 4], [6, 16, 0], [6, 17, 0], [6, 18, 0], [6, 19, 0], [6, 20, 1], [6, 21, 2], [6, 22, 2], [6, 23, 6] ] range_color = ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026'] bar3d.add( "", x_axis, y_axis, [[d[1], d[0], d[2]] for d in data], is_visualmap=True, visual_range=[0, 20], visual_range_color=range_color, grid3d_width=200, grid3d_depth=80, ) bar3d.width=700 bar3d.height=500 bar3d """ Explanation: 3D End of explanation """ from pyecharts import Boxplot boxplot = Boxplot("Box plot") x_axis = ['expr1', 'expr2', 'expr3', 'expr4', 'expr5'] y_axis = [ [850, 740, 900, 1070, 930, 850, 950, 980, 980, 880, 1000, 980, 930, 650, 760, 810, 1000, 1000, 960, 960], [960, 940, 960, 940, 880, 800, 850, 880, 900, 840, 830, 790, 810, 880, 880, 830, 800, 790, 760, 800], [880, 880, 880, 860, 720, 720, 620, 860, 970, 950, 880, 910, 850, 870, 840, 840, 850, 840, 840, 840], [890, 810, 810, 820, 800, 770, 760, 740, 750, 760, 910, 920, 890, 860, 880, 720, 840, 850, 850, 780], [890, 840, 780, 810, 760, 810, 790, 810, 820, 850, 870, 870, 810, 740, 810, 940, 950, 800, 810, 870] ] _yaxis = boxplot.prepare_data(y_axis) boxplot.add("boxplot", x_axis, _yaxis) boxplot """ Explanation: Boxplot End of explanation """ from pyecharts import Funnel attr = ["A", "B", "C", "D", "E", "F"] value = [20, 40, 60, 80, 100, 120] funnel = Funnel("퍼널 그래프") funnel.add( "퍼널", attr, value, is_label_show=True, label_pos="inside", label_text_color="#fff", ) funnel.width=700 funnel.height=500 funnel """ Explanation: 퍼널 End of explanation """ from pyecharts import Gauge gauge = Gauge("Gauge Graph") gauge.add("이용률", "가운데", 66.66) gauge """ Explanation: Gauge End of explanation """
ianozsvald/example_conversion_of_excel_to_pandas
joining_two_sheets/Joining On a CSV and XLS File.ipynb
mit
import pandas as pd # load both sheets as new dataframes shows_df = pd.read_csv("show_category.csv") views_df = pd.read_excel("views.xls") """ Explanation: Join two sheets, groupby and sum on the joined data End of explanation """ shows_df.head() shows_df = shows_df.set_index('showname') shows_df.head() """ Explanation: Change the index to be the showname End of explanation """ views_df.head() views_df = views_df.set_index('viewer_id') views_df.head() # note that we can have repeating viewer_id values (they're non-unique) # we can select out the column to work on, then use the built-in str (string) functions # to replace hyphens (we do this and just print the result to screen) views_df['show_watched'].str.replace("-", "") # now we do the fix in-place views_df['show_watched'] = views_df['show_watched'].str.replace("-", "") # NOTE if you comment out the line above, you'll get a NaN in the final table # as `battle-star` won't be joined views_df print("Index info:", views_df.index) views_df.ix[22] # select the items with index 22 (note this is an integer, not string value) """ Explanation: Do the same for views DANGER note that battle-star has a hyphen! End of explanation """ shows_views_df = views_df.join(shows_df, on='show_watched') shows_views_df # take out two relevant columns, group by category, sum the views shows_views_df[['views', 'category']].groupby('category').sum() """ Explanation: Join on shows watched against category PROBLEM - we have NaN values for the last two Firefly entries. Can you do something, earlier on, to fix this, from here inside the Notebook? End of explanation """
NII-cloud-operation/Jupyter-LC_docker
sample-notebooks/01_About NII Extensions - NII謹製の機能拡張について.ipynb
bsd-3-clause
! echo "This is 1st step" > foo; cat foo ! echo ".. 2nd step..." >> foo && cat foo !echooooo ".. 3rd step... will fail" >> foo && cat foo """ Explanation: Literate Computing for Reproducible Infrastructure <img src="./images/literate_computing-logo.png" alt='LC_LOGO' align='left'/> NII Cloud Operation is a team supporting researchers and teachers in our institute. To make users more productive our team serves many roles, which are maintaining private OpenStack infrastructure, setting up various software stacks, consulting their configuration and optimization, and managing almost everything.<br> Literate Computing for Reproducible Infrastrucre is our project, which seeks to utilize Jupyter Notebook in operational engineering area for seeking ..<br> 計算機インフラの御守では種々雑多なドキュメンテーションが不可欠です。日々の作業で証跡を残す、手順を整理して共有・再利用する、ユーザマニュアルや教材を整備する.. 国立情報学研究所(NII)のクラウド運用担当では、これらをシームレスに記述・蓄積する方法を研究しています。 表題の Literate Computing for Reproducible Infrastructure は、そのような取り組みのプロジェクト名です。プロジェクトでは Jupyter Notebook を用いてドキュメンテーションを行うことで、運用作業の信頼性向上、手順やノウハウの蓄積・流通が容易になることを目指しています。 インフラ運用の場面において 機械的に再現できる、人が読み解ける手順 を手段として、過度に自動化に依存することのない、レジリエントな 人間中心の機械化 をめざしています。そこでは、作業を効率化しつつもブラックボックス化せず、作業に対する理解をチーム内でコミュニケーションできる、また、目的と手段の整合性や限界を理解し議論・評価できると言った場を維持することで、ノウハウの移転・共有を促し運用者のスキル向上とエンジニアリングチームの再生産をはかる ことを重視しています。 多くの現場では、管理サーバにログインしコンソール上で作業を行う、作業内容や証跡はWiki等に随時転記して共有する.. といった形態が一般的と思います。これに対しLC4RIでは運用管理サーバ上にNotebookサーバを配備し、作業単位毎にNotebookを作成、作業内容やメモを記述しながら随時実行するといった作業形態を推奨しています。作業の証跡を齟齬なく記録する仕組み、過去の作業記録を参照して機械的に再現あるいは流用できる仕組み、機械的に実行できるとともに人が読み解き補完することもできるNotebook手順を整備しています。 プロジェクトの成果物は GitHub NII Cloud Operation Teamで公開しています。 Hadoop や Elastic Search など学術機関でポピュラーなインフラにに関する構築や 運用の手順を整理したもの、また、構築や運用の手順を記述するために便利な Jupyterの機能拡張 を掲載しています。 This notebook demonstrates our project's extensions for Literate Computing for Reproducible Infrastructure. <br> この Notebook では拡張した機能の概要を紹介します。 (2019.06.20) Jupyter-run_through <span lang="ja">- まとめ実行機能</span> Usage: * Freeze: Preventing miss-operation; once a code cell has been executed, it freezes against unintended execution and modification. Note that the freeze is implemented as different state from standard cell lock's. The freeze only make an executed cell un-editable temporally.<br> //誤操作を防ぐ; いったんセルを実行すると"凍結"され解凍しないと再実行できない。また、セルの編集をロックすることもできる。 Bricks: Giving a summarized perspective for execution control; embedded "cells" underneath are represented as bricks and be able to run through altogether with a click, while markdowns and codes are collapsed using <span class='fa fa-fw fa-external-link'></span>Collapsible Headings<br> //まとめ実行; マークダウンを畳み込んだ際に、畳み込まれた範囲にあるすべての"Cell"を一連の"brick"として表示する。一連の"brick"を1-clickでまとめて実行できる。 Run_through: Execute collapsed code cells as a whole; Simply reuse workflows without paying much attention to details, whithout needs for arrenge nor customization. Run throughout the notebook as an executable checklist, then verify error if it occurs.<br> //定型的な作業をまとめて実行する; 詳細は気にせずNotebook形式の手順を気軽に利用, アレンジやカスタマイズはあまり必要がない。まとめて実行してエラーが発生した時だけ詳細を確認したい; 実行可能なチェックリストとして用いる。 <span class='fa fa-fw fa-external-link'></span> GitHub: Jupyter-LC_run_through <div style="width:30%;right"> [![DEMO LC_run_through](http://img.youtube.com/vi/pkzE_nwtEKQ/0.jpg)<span class='fa fa-fw fa-youtube'></span>LC_run_through](https://www.youtube.com/watch?v=pkzE_nwtEKQ)</div> How-to: run_through <br> The <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span> on the collapsed headding indicates there are collapsed markdowns and cells. With clicking <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span> and <span class='fa fa-fw fa-caret-down' style='color:#a0a0a0;'></span> switch the expand/collapse.<br clear="right"> <img src="./images/run_through.png" align="right" width=30% />When headings are collapsed, executable cells underneath are represented as blicks. Each blick <span class='fa fa-fw fa-square' style='color:#cccccc;'></span> represents its collesponding cell's status, the gray means 'not executed yet'. Click <span class='fa fa-fw fa-play-circle'></span> runs through cells altogeather.<br clear="right"> <img src="./images/run_through_OK.png" width=30% align=right /> Normally executed and completed cells truned to light green <span class='fa fa-fw fa-square' style='color:#88ff88;'></span>. In addition completed cells are "frozen" <span class='fa fa-fw fa-snowflake-o' style='background-color:cornflowerblue;color:white;'></span>, that would not be executed again until "unfrozen" via toolbar <span class='fa fa-fw fa-snowflake-o'style='color:gray;'></span>.<br clear="right"> <img src="./images/run_through_NG.png" width=30% align=right /> In the case of error cells' execution is aborted and the blick turned to light coral<span class='fa fa-fw fa-square' style='color:#ff8888;'></span>. You can examine the error by expanding folded cells with <span class='fa fa-fw fa-caret-right'></span>. まとめ実行機能 <br> 表題の左側にある <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span> は、詳細な手順が畳み込まれていることを示しています。 <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span> をクリックすると、 <span class='fa fa-fw fa-caret-down' style='color:#a0a0a0;'></span> に変化し、畳み込まれている内容を表示することができます。この畳み込み表示機能は "Collapsible Headings"を利用しています。オリジナルの Collapsible Headings ではマークダウンの階層を畳み込むだけだったのですが、、 <br><br> <img src="./images/run_through.png" align="right" width=30% /> まとめ実行機能では、畳みこまれている内容に「手順」(実行可能なセル)が含まれていると右のように正方形の箱 <span class='fa fa-fw fa-square' style='color:#cccccc;'></span>として可視化されます。箱の数は畳み込まれている手順のステップ数を示しています。 また、表示領域右上の<span class='fa fa-fw fa-play-circle'></span> を押すと、配下の手順をまとめて実行することができます。<br clear="right"> <img src="./images/run_through_OK.png" width=30% align=right /> すべてのステップが終了すると右のように箱の表示が変化します。実行が正常に完了したステップは薄緑 <span class='fa fa-fw fa-square' style='color:#88ff88;'></span>に表示されます。また、完了したステップは、再度 まとめ実行ボタン<span class='fa fa-fw fa-play-circle'></span>をクリックしても実行されないよう凍結されます。 箱内側のスノーフレーク &ldquo;<span class='fa fa-fw fa-snowflake-o' style='background-color:#cccccc;color:white;'></span>&rdquo; は、セルが凍結状態 <span class='fa fa-fw fa-snowflake-o' style='background-color:#88ff88;color:white;'></span><span class='fa fa-fw fa-snowflake-o' style='background-color:cornflowerblue;color:white;'></span>であることを示しています。<br clear="right"> <img src="./images/run_through_NG.png" width=30% align=right /> 途中でエラーが発生した場合は当該のステップが薄紅<span class='fa fa-fw fa-square' style='color:#ff8888;'></span>に表示されます。畳み込み表示を <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span> をクリックし解除すると、それぞれのステップの実行内容を確認することができます。<br clear="right"> <img src="./images/run_through_Frozen2.png" width=20% align=right /> セルの凍結 <br> 実行が正常に終わったセルは凍結 <span class='fa fa-fw fa-snowflake-o' style='background-color:cornflowerblue;color:white;'></span> されます。凍結状態のセルはそのままでは実行することも、修正することもできません。凍結状態を解除するにはツールから<span class='fa fa-fw fa-snowflake-o' style='color:gray;'></span>をクリックします。 凍結機能は、実行済みの範囲を識別するとともに、偶発的な重複実行を防止するためのものです。また、まとめ実行ボタン<span class='fa fa-fw fa-play-circle'></span>は一定期間、チャタリングを防止するように制御しています。<br> エラーのセル<span class='fa fa-fw fa-square' style='color:#ff8888;'></span>は内容を修正して再実行することができます。実行が終わって凍結状態 <span class='fa fa-fw fa-snowflake-o' style='background-color:cornflowerblue;color:white;'></span> のセルはスキップされるので、エラーを修正した後、まとめ実行ボタン<span class='fa fa-fw fa-play-circle'></span>を再度押すことで作業を継続できます。修正したセル<span class='fa fa-fw fa-square' style='color:#ff8888;'></span>(未実行)と継続する未実行のセル<span class='fa fa-fw fa-square' style='color:#cccccc;'></span>が実行されます。<br> <br> エラーの原因が当該のセル単体ではなく、遡ったセルの実行結果に依存している場合は、必要な範囲まで凍結を解除することになります。まとめて凍結を解除するには、ツールから<span class='fa fa-fw fa-snowflake-o' style='color:gray;'></span><span class='fa fa-fw fa-fast-forward'></span>、<span class='fa fa-fw fa-snowflake-o' style='color:gray;'></span><span class='fa fa-fw fa-forward'></span>を利用することができます。 <br clear="right"> Example Run_through: Try &ldquo;<span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span>&rdquo;, which will collapse cells, then, &ldquo;<span class='fa fa-fw fa-play-circle'></span>&rdquo; will run through four bricks.<br> <br> <span class='fa fa-fw fa-square' style='color:#88ff88;'></span>: The light green bricks indicate successfull completion.<br> <span class='fa fa-fw fa-square' style='color:#ff8888;'></span>: The third light coral brick indicates some error.<br> <br> <span class='fa fa-fw fa-snowflake-o' style='background-color:#cccccc;color:white;'></span><span class='fa fa-fw fa-snowflake-o' style='background-color:#88ff88;color:white;'></span><span class='fa fa-fw fa-snowflake-o' style='background-color:cornflowerblue;color:white;'></span>: The snow flake indicates those bricks are frozen. Executions and edits are prohibitted. The &ldquo;<span class='fa fa-fw fa-snowflake-o' style='color:gray;'></span>&rdquo; will unfrozen bricks.<br> The succeeded cells <span class='fa fa-fw fa-square' style='color:#88ff88;'></span> will be automatically frozen in order to prevent accidental duplicate operations. Error cells <span class='fa fa-fw fa-square' style='color:#ff8888;'></span> remain unfrozen, then you can fix errors and re-execute the cell. You can continue execution on following not-yet-executed cells <span class='fa fa-fw fa-square' style='color:#cccccc;'></span>. 畳み込んだステップのまとめ実行: 表題の横に <span class='fa fa-fw fa-caret-down' style='color:#a0a0a0;'></span> が表示されている場合はクリックしてセルを畳み込んでください。畳み込まれた状態では <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span>に変化します。<br> この例では <span class='fa fa-fw fa-play-circle'></span> をクリックすると4ステップをまとめ実行します。実行が終わったステップは薄緑の表示<span class='fa fa-fw fa-square' style='color:#88ff88;'></span>となります。以下では3番目がエラーとなり薄紅表示<span class='fa fa-fw fa-square' style='color:#ff8888;'></span>され、実行が中断します。<br> <span class='fa fa-fw fa-caret-right' style='color:#a0a0a0;'></span> をクリックしてエラーの内容を確認します。 エラーのセルを修正すると、続きから実行することができます。<br> <br> 凍結状態のセルは実行することも、修正することもできません。再度実行する場合にはウインドウ上部の<span class='fa fa-fw fa-snowflake-o' style='color:gray;'></span>をクリックすることで凍結を解除します。<br> End of explanation """ ! cat foo """ Explanation: "echo" に修正して実行してみましょう。 End of explanation """ %env lc_wrapper 8:8:10:10 # lc_wrapper s:h:e:f # # s : Summary starts when # of output lines exceed 's' (default s=1) # h : Summary displays the first h lines and max 2 x h error lines. # e : Max # of output lines in progress. # f : Summary displays the last f lines (default f=1) !!from time import sleep with open("./resources/bootstrap.log", "r") as f: # "/var/log/bootstrap.log" count = 0 limit = 100 for line in f: count = count+1 if count > limit: break print(line, end=''), sleep(0.05) print ("after", limit, "lines are ignored") # # Emulate large log output.. """ Explanation: Jupyter-LC_wrapper Usage: * Summarize massive output lines.<br> //大量のログ出力を要約表示する。 * At each cell’s execution all original output lines are saved into an individual file with a time stamp.<br> //複数の実行ログを各々ファイルに保存し、後で全体を参照したり、結果を比較できるようにする。 <span class='fa fa-fw fa-external-link'></span> GitHub: Jupyter-LC_wrapper <p lang="all"><div style="width:30%"> [![DEMO LC_wrapper](http://img.youtube.com/vi/-28XG7aHYY8/0.jpg) <span class='fa fa-fw fa-youtube'></span>LC_wrapper Kernel](https://www.youtube.com/watch?v=-28XG7aHYY8)</div> </p> You can review whole output and compare with previous results from different executions.<br> When you install some pakages, there would be massive log lines. Jupyter Web UI is inefficient for handling a large number of output lines. 例えば、某かのパッケージ群をインストールしたりすると大量のログが出力されますが、JupyetrのWeb UI上で大量の出力を扱うのはなにかと不便です。 Jupyterの Cell の中でログの内容を検索したり、比較したりするのはまどろっこしく手間がかかります。<br> Jupyter-LC_wrapper を用いると:<br> ・ Output Cell には要約されてた結果が出力されるようになります(例:最初10行と最後の10行)。<br> ・ オリジナルの出力結果全体はファイルに保存されます。<br> ・ 実行毎に各々のファイルに結果が保存されるので出力結果を比較することができます。<br> ・ 要約中でも、エラーなど特定のパターン含む行を表示します(lc_wrapper_regex.txt などいくつかの方法でカスタマイズ可)。<br> Cellでコマンドを実行する際に先頭に "!!" を付加すると、LC_wrapper の機能が有効になります。 Cellで shell を呼び出す場合は "!!!" を付加してください。 End of explanation """ import pandas import matplotlib import matplotlib.pyplot as plt import random %matplotlib inline plot_df = pandas.DataFrame({ 'col1': [12, 3, random.randint(1,10), 4], 'col2': [3, 12, 5, 2], 'col3': [random.randint(4,7), 10, 3, random.randint(0,2)], 'col4': [random.randint(0,11), 5, random.randint(6,12), random.randint(0,5)], }) plot_df plot_df.plot() """ Explanation: Jupyter-multi_outputs 用途: * 出力結果を保存する。 * 現在の出力結果と、以前の出力結果を比較する(いまのところ文字列のみ)。 <span class='fa fa-fw fa-external-link'></span> Jupyter-multi-outputs <img src="./images/multi_outputs.png" align="right" width=40% />実行後セルの左側に表示される <span class='fa fa-fw fa-thumb-tack'></span> をクリックすると、出力セルの内容がタブ形式で保存されます。 保存された出力のタブを選択した際に表示される <span class='fa fa-fw fa-exchange'></span> をクリックすると、現在の出力と比較することができます。<br><br> 何度もセルを試行する場合、毎回の結果を保存しておくことができます。<br> お手本となる手順や教材を Notebook で作成する際に、期待される結果や正解を保存しておくなどの用途が考えられます。 End of explanation """ plot_df """ Explanation: 上の例では、タブをクリックすると以前の出力結果を参照することができます。 End of explanation """ plot_df.transpose """ Explanation: 以前の出力結果を選択表示すると <span class='fa fa-fw fa-thumb-tack'></span> が <span class='fa fa-fw fa-exchange'></span> に変わります。この <span class='fa fa-fw fa-exchange'></span>をクリックすると、選択している出力と現在の出力を比較することができます。 End of explanation """
jgarciab/wwd2017
class1/class_1b_data_structures.ipynb
gpl-3.0
##Some code to run at the beginning of the file, to be able to show images in the notebook ##Don't worry about this cell #Print the plots in this screen %matplotlib inline #Be able to plot images saved in the hard drive from IPython.display import Image #Make the notebook wider from IPython.core.display import display, HTML display(HTML("<style>.container { width:90% !important; }</style>")) """ Explanation: Working with data 2017. Class 1 Contact Javier Garcia-Bernardo garcia@uva.nl 0. Structure About Python Data types, structures and code Read csv files to dataframes Basic operations with dataframes My first plots Debugging python Summary End of explanation """ ##this is a list print([1,2,3]) print(type([1,2,3])) # A list can combine several data types this_is_list1 = [3.5,"I'm another string",4] print(this_is_list1) # It can even combine several data structures, for instance a list inside a list this_is_list2 = [3.5,"I'm another string",4,this_is_list1] print(this_is_list2) """ Explanation: 2. PYTHON: Data types, structures and code Python uses variables and code. 2.1 Variables Variables tell the computer to save something (a number, a string, a spreadsheet) with a name. For instance, if you write variable_name = 3, the computer knows that variable_name is 3. Variables can represents: - 2.1.1 Data types: Numbers, strings and others - 2.1.2 Data structures: - Lists, tables... (which organize data types) 2.2 Code Instructions to modify variables Can be organized in functions 2.1.2 Most common data structures 2.1.2.1 list = notebook (you can add things, take out things, everything is in order). e.g. a list of the numbers 1,2 and 3: [1,2,3] 2.1.2.2 tuple = book (you cannot change it after it's printed). (1,2,3) 2.1.2.3 set = keywords in a paper (you can check if something exists easily). {1,2,3} 2.1.2.4 dictionary = index (you can find content easily). {"a":1, "b":2, "c":3} 2.1.2.5 numpy array = fast list for math. np.array([1,2,3]) 2.1.2.6 pandas dataframe = spreedsheet. np.DataFrame([1,2,3],columns=["a","b","c"]) They have methods = ways to edit the data structure. For example add, delete, find, sort... (= functions in excel) 2.1.2.1 Lists Combines a series of variables in order Fast to add and delete variables, slow to find variables (needs to go over all the elements) End of explanation """ ## A list this_is_a_list = [1,3,2,"b"] print("Original: ", this_is_a_list) """ Explanation: OPERATIONS IN LISTS End of explanation """ ## Add elements this_is_a_list.append("c") print("Added c: ", this_is_a_list) """ Explanation: Add element End of explanation """ ## Get element. The first element has index 0, which means that this_is_a_list[0] gets the first element print("Fourth element: ", this_is_a_list[3]) """ Explanation: Retrieve element CAREFUL: The first element has index 0, which means that this_is_a_list[0] gets the first element and this_is_a_list[1] gets the second element End of explanation """ this_is_a_list this_is_a_list[1:3] #All list this_is_a_list = [0,1,2,3,4] print(this_is_a_list) #"Second to end element (included)" print("Second to end element: ", this_is_a_list[1:]) #Second to the fourth (included) print("Second to the fourth (included): ",this_is_a_list[1:4]) #First to the last element (not included) print("First to the last element (not included): ",this_is_a_list[:-1]) """ Explanation: Get slices - Get a part of list. This is important End of explanation """ print("Original: ", this_is_a_list) ## Remove 4th element and save it as removed_element removed_element = this_is_a_list.pop(3) print(removed_element) print("The list is now: ", this_is_a_list) this_is_a_list = [1,2,3,4,5] """ Explanation: Remove element End of explanation """ #Search print(3 in this_is_a_list) #Find index print(this_is_a_list.index(4)) """ Explanation: Search - element in list - Note that this also works for strings (in fact, a string is very similar to a list of characters): "eggs" in "eegs and bacon" End of explanation """ ## Count the number of elements in a list this_is_a_list = [1, 3, 2] len_this_is_a_list = len(this_is_a_list) #you tell the computer to sum it and save it as `sum_this_is_a_list` print("Length: ", len_this_is_a_list) """ Explanation: Length End of explanation """ ## Sort a list this_is_a_list = [1, 3, 2] this_is_a_list = sorted(this_is_a_list) #you tell the computer to sort it, and to save it with the same name print("Sorted: ", this_is_a_list) """ Explanation: Sort End of explanation """ ## Sum a list this_is_a_list = [1, 3, 2] sum_this_is_a_list = sum(this_is_a_list) #you tell the computer to sum it and save it as `sum_this_is_a_list` print("Sum: ", sum_this_is_a_list) sum(["1","2"]) """ Explanation: Sum End of explanation """ print(float("1")) """ Explanation: Notice that we wrote this_is_a_list.pop(), but sum(this_is_a_list) and sorted(this_is_a_list) This is because .pop() only works in lists (.pop() is a method of the data structure List), while sum() and sorted() work with many different data structures. Some standard functions: - sum() - len() - sorted() - min() - max() - list() #convert to list - set() #convert to set - dict() #convert to dictionary - tuple() #convert to tuple - float() #convert to float End of explanation """ ## Create a list [0,1,2,3,4] print(list(range(0,5,1))) print(range(5)) #for all practical issues you don't need to convert them ## Create the list [1,2,3,4] print(list(range(1,5,1))) ## Create the list [1,3,4,5,7,9] print(list(range(1,10,2))) import numpy as np np.arange(0,5,0.5) """ Explanation: CREATING RANGES range(start,stop,step) generates a list of numbers between start and stop (not including the number stop), jumping in steps of size step. See examples below. Useful for example if we want to do one thing many times. We will see their importance on Thursday. They are not really lists but very similar, in the examples I'll convert them to lists to see what's inside. End of explanation """ #we create a string and call it "eggs and bacon" our_string = "eggs and bacon" #now we divide it into words, creating a list and saving it with the name our_list_of_wrods our_list_of_words = our_string.split() print(our_list_of_words) #we can do the opossite and join the words using the function "join". " ".join(our_list_of_words) #we can join the words using any character we want in the quoted par of (" ".join) ":::".join(our_list_of_words) #we can also divide a string using other characters instead of space. #for example let's split in the "a"s our_string = "eggs and bacon" print(our_string.split("a")) #we can change parts of the word our_string = "eggs and bacon" print(our_string.replace("bacon","tofu")) #we can find where a word start. For example let's find how many characters there are before "and" our_string = "eggs and bacon and" print(our_string.find("and")) #and we can use this to slice the string like we did with the list our_string1 = "10 events" our_string2 = "120 events" our_string3 = "2 events" #we find the index of and index_and1 = our_string1.find("event") index_and2 = our_string2.find("event") index_and3 = our_string3.find("event") print(index_and1) print(index_and2) print(index_and3) print(our_string1) #and keep all the string until that index print(our_string1[:our_string1.find("event")]) print(our_string2[:index_and2]) print(our_string3[:index_and3]) """ Explanation: WORKING WITH STRINGS AND LISTS - Divide a string into words - Join many words in a list into a string - Replace an element - Find an element End of explanation """ this_is_a_list? our_string1.find? """ Explanation: ipython help End of explanation """ this_is_a_tuple = (1,3,2,"b") print(this_is_a_tuple) this_is_a_list = list(this_is_a_tuple) print(this_is_a_list) #If we try to pop and elment, like with lists, we get an error. this_is_a_tuple.pop(0) """ Explanation: 2.B.Tuples The same than a list but inmutable (fixed size). You can't add or remove elements. I (almost) never use them, but you may encounter them. End of explanation """ Image(filename='./images/set-operations-illustrated-with-venn-diagrams.png') {1,2,3} - {2,5,6} #Let's create a list with repeated elements this_is_a_list = [3,1,1,1,2,3] print(this_is_a_list) #Now we convert it to a set and see how the repeated elements are gone this_is_a_set1 = set(this_is_a_list) print(this_is_a_set1) #You can also create sets like this this_is_a_set2 = {1,2,4} print(this_is_a_set2) ## Union print(this_is_a_set1 | this_is_a_set2) ## Intersection print(this_is_a_set1 & this_is_a_set2) ## Diference set_1 - set2 print(this_is_a_set1 - this_is_a_set2) ## Diference set_2 - set1 print(this_is_a_set2 - this_is_a_set1) ## Very useful for words. Imagine we have two articles, one saying "eggs bacon python" and another saying "bacon spam" #We can find which words they have in common print({"eggs","bacon","python"} & {"bacon","spam"}) """ Explanation: 2.B.Sets One element of each kind (no repeated elements!) -> If you convert a list to a set you find the unique elements. Allows for intersecting Example: Which words are different between two sets End of explanation """ #First we need to import it import numpy as np #Sum of a list a_list = [0,1,2,3,4,5,6] #Using the standard function print(sum(a_list)) #Using numpy print(np.sum(a_list)) ##How to find the mean() of a list of numbers? mean() does not exist print(mean(a_list)) a_list = [0,1,2,3,4,5,6] a_np_array = np.array(a_list) a_np_array**10 ##but numpy rescues you import numpy as np a_list = [0,1,2,3,4,5,6] #first convert the list to an array. #This is not required when you use np.mean(a_list), but it is required in some other ocassions. a_np_array = np.array(a_list) print(type(a_list)) print(type(a_np_array)) print(np.mean(a_np_array)) ##you can take powers print(a_np_array**2) #this would not work with a list ##or square roots print(np.sqrt(a_np_array)) #this would work with a list #or some basic statistics import numpy as np import scipy.stats #another library for more complicated statistics #we create a list with numbers 0,1,2...998,999 numElements = 1000 this_is_an_list = list(range(numElements)) this_is_an_array = np.array(this_is_an_list) print(this_is_an_array[:10]) #print only the 10 first elements to make sure it's okay #and print some stats print(np.mean(this_is_an_array)) print(np.std(this_is_an_array)) print(np.median(this_is_an_array)) print(scipy.stats.mode(this_is_an_array)) print(scipy.stats.skew(this_is_an_array)) """ Explanation: 2.B.Dictionary Like in a index, finds a page in the book very very fast. It combiens keys (word in the index) with values (page number associated to the word): {key1: value2, key2: value2} The keys can be numbers, strings or tuples, but NOT lists (if you try Python will give the error unhashable key) We won't use dicts today so we'll cover them on Thursday 2.B.Numpy array Part of the numpy package Extremely fast (and easy) to do math You can slice them like lists It gives many cool functions, like mean(), or ** over a list End of explanation """ #Let's start with this array this_is_an_array = np.array([1,2,3,4,5,6,7,8,9,10]) print(this_is_an_array) #If we want the elements greater or equal (>=) to 5, we could do: print(this_is_an_array[4:]) #However this case was very easy, but what getting the elements >= 5 in here: #[ 5, 9, 4, 3, 2, 8, 6, 7, 10, 1] unsorted_array = np.array([ 5, 9, 4, 3, 2, 8, 6, 7, 10, 1]) print(unsorted_array) unsorted_array >= 5 unsorted_array[np.array([ True, True, False, False, False, True, True, True, True, False])] #We can do the following: unsorted_array[unsorted_array >= 5] #which means keep the elements of unsorted_array that are larger or equal to 5 #unsorted_array[condition] print(unsorted_array[unsorted_array >= 5]) #This is a special kind of slicing where you filter elements with a condition. #Lists do not allow you to do this #How does it work? By creating another array, of the same lenght, with False and Trues print(unsorted_array) print(this_is_an_array >= 5) #the same than comparing 3 >= 5, but numpy compares every number inside the array. """ Explanation: IMPORTANT: NUMPY ARRAYS ALLOW YOU TO FILTER BY A CONDITION array_name[array_condition] For example, maybe you have a list [1,2,3,4,5,6,7,8,9,10] and you want the elements greater or equal to 5. Numpy can help End of explanation """ #We can use variables condition = this_is_an_array >= 5 #the computer does the = at the end always print(unsorted_array[condition]) #What if we want to get the numbers between 5 and 9 (6, 7,9)? unsorted_array = np.array([ 5, 9, 4, 3, 2, 8, 6, 7, 10, 1]) #We do it with two steps #Step 1: Greater than 5 condition_gt5 = unsorted_array > 5 unsorted_array_gt5 = unsorted_array[condition_gt5] print("Greater than 5", unsorted_array_gt5) #Step 2: Lower than 9 condition_lw9 = unsorted_array_gt5 < 9 #we are using the new array unsorted_array_gt5_lw9 = unsorted_array_gt5[condition_lw9] print("Greater than 5 and lower than 9", unsorted_array_gt5_lw9) unsorted_array = np.array([ 5, 9, 4, 3, 2, 8, 6, 7, 10, 1]) condition_gt5 = unsorted_array > 5 condition_lw9 = unsorted_array < 9 print(unsorted_array[condition_gt5 & condition_lw9]) """ Explanation: When you do unsorted_array[condition], the computer check if the first element of the array condition is True If it is True, then it keeps the first element of unsorted_array. The computer then checks the second element of the condition array. If it is True, then it keeps the second element of unsorted_array And keeps doing this until the end End of explanation """ ##first we import it import pandas as pd """ Explanation: 2.B.Pandas dataframe I They correspond to excel spreadsheets Part of the pandas package It is a big, complicated library that we will use a lot. They are based on numpy arrays, so anything you can do with numpy arrays you can do with the rows or columns of a dataframe Read/write csv files. It can also read stata or excel files (and sometimes spss), but who likes those programs. Tip: Always save spreadsheets as .csv data We'll explore it through examples End of explanation """ Image(url="http://www.relatably.com/m/img/boring-memes/when-my-friend-tell-me-a-boring-story_o_1588863.jpg") """ Explanation: End of explanation """
4dsolutions/Python5
Martian Math.ipynb
mit
from tetravolume import S3, Tetrahedron from qrays import Qvector print("S3:", S3) """ Explanation: Oregon Curriculum Network <br /> Discovering Math with Python Martian Multiplication <a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/42107444461/in/dateposted-public/" title="5 x 2 &#x3D; 10"><img src="https://farm1.staticflickr.com/830/42107444461_d299ff6aed.jpg" width="500" height="312" alt="5 x 2 &#x3D; 10"></a><script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script> <div align="center">5 x 2 = 10</div> Earthians (Earthlings) start with a square, subdivided into a grid, and show multiplication as a matter of slicing out rectangles, n x m. Martians, in contrast, start with an equilateral triangle, subdivided into a grid, and show multiplication as a matter of slicing out triangles, also n x m. The above triangle, in two shades of green, represents 2 x 6 = 12 i.e. the area of the triangle under the red line is equal to that of 12 grid triangles, shown in tan with green borders. If you mentally swivel the lighter green obtuse triangle about a vertex shared in common with a second such area, you may see how the result fills exactly 4 unit triangles. Light green (4) + dark green (8) = 12. No lets add another edge from the common origin and multiply three numbers instead of two. Below we see what a volume of 2 x 2 x 5 = 20 might look like. Of course any number of tetrahedrons may have the same volume. This strange way of multiplying is consistent with the Earthling way. The Pythagorean Theorem is still true. <a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/40322965820/in/dateposted-public/" title="pythag2"><img src="https://farm1.staticflickr.com/982/40322965820_fabe4d6c43_o.jpg" width="166" height="197" alt="pythag2"></a><script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script> Multiplying inside the IVM, the way Martians do it, provides a canonical OABC for any OA x OB x OC. ABC is "the lid" and simply "closing the lid" is all it takes to define the corresponding volume. <a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/41211295565/in/dateposted-public/" title="Martian Multiplication"><img src="https://farm1.staticflickr.com/907/41211295565_59145e2f63.jpg" width="500" height="312" alt="Martian Multiplication"></a><script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script> <div align="center">5 x 2 x 2 = 20</div> The reason we see these matrix edges as length 2 sometimes is they connect adjacent CCP sphere centers, thinking of spheres as unit radius (R = 1, D = 2). Other times we say D = 1, R = 1/2. Without the Martian model of multipliction, it makes no sense to see a cube of face diagonals 2, having a volume of 3. Only if the inscribed tetrahedron were unit volume would that make sense, but that's the Martian construct. "Only on Mars does Synergetics ring true" might be some song in the hymnal. <a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/21077777642/in/photolist-FRd2LJ-y7z7Xm-frqefo-8thDyL-6zKk1y-5KBFWR-5KFVMm-5uinM4" title="Conversion Constant"><img src="https://farm1.staticflickr.com/702/21077777642_9803ddb65e.jpg" width="500" height="375" alt="Conversion Constant"></a><script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script> <div align="center">Cube edges = 2 x Tetrahedron edges;<br /> Cube:Tetrahedron volume ratio = S3</div> A cube of edges R has S3 times the volume of a tetrahedron of edges D (D = 2R). Each shape (cube and tetrahedron) counts as a unit of volume in its respective systems (XYZ versus IVM). S3 is sometimes called the Synergetics Constant, although more technically it's the Synergetics Constant to the 3rd power. End of explanation """ p = Qvector((2,1,0,1)) q = Qvector((2,1,1,0)) r = Qvector((2,0,1,1)) print(q.angle(p), p.angle(r), r.angle(q)) def make_tet(v0,v1,v2): """ three edges from any corner, remaining three edges computed """ tet = Tetrahedron(v0.length(), v1.length(), v2.length(), (v0-v1).length(), (v1-v2).length(), (v2-v0).length()) return tet.ivm_volume(), tet.xyz_volume() def ivm(a,b,c): """ Return the IVM volume of a given tetrahedron. Edges all start from same corner of a regular tet. """ # vectors all mutually 60 degrees e.g. at reg tet corner p = Qvector((2,1,0,1)) q = Qvector((2,1,1,0)) r = Qvector((2,0,1,1)) result = make_tet(a*q, b*p, c*r) # scale as required return result[0] # make_tet returns (ivm_volume, xyz_volume) def xyz(a,b,c): """ Return the XYZ volume of a given tetrahedron. Edges all start from same corner of a regular tet. """ # vectors all mutually 60 degrees e.g. at reg tet corner p = Qvector((2,1,0,1)) q = Qvector((2,1,1,0)) r = Qvector((2,0,1,1)) result = make_tet(a*q, b*p, c*r) # scale as required return result[1] # make_tet returns (ivm_volume, xyz_volume) ivmvol = ivm(2,2,5) xyzvol = xyz(2,2,5) print("IVM volume: ", round(ivmvol, 5)) print("XYZ volume: ", round(xyzvol, 5)) xyzvol * S3 == ivmvol """ Explanation: Tetravolumes times 1/S3 gives the corresponding volume in terms of XYZ cubes. The XYZ cube volume times S3 gives the corresponding value in tetravolumes, presuming the calibration defined above. We test that in the code cells below. The Qvector type, imported above and used below, implements the "Quadray coordinate system" i.e. vectors built from linear combinations of four basis rays from the center of a regular tetrahedron to its four corners. Think of the methane molecule (carbon in the middle, a hydrogen at each vertex). The vectors p, q, r defined below, represent three vectors from a common origin (0,0,0,0) that happen to define three corners of the cuboctahedron defining the same regular tetrahedron, of which there are eight all told. The cuboctahedron consists of 8 regular tetrahedrons and four half-octahedrons, in terms of volume (and shape). Since our canonical octahedron (same length edges as tetrahedron) has volume 4, the cuboctahedron has a volume of 8 + 6 * 2 or 8 + 12 = 20. Here's the cuboctahedron. The Qvectors p, q, r point to inter-adjacent balls in the same triangle, from the common origin at the very center of this packing (from the center of the ball at the origin). <div align="center">One-frequency Cuboctahedral Packing (CCP)</div> End of explanation """ ivmvol = ivm(1,1,1) print(ivmvol) """ Explanation: One reason we want to multiply this way is to establish a unit volume tetrahedron. The edges interconnect adjacent unit radius spheres, and so are 2R. The volume is 1. Sometimes we picture a "tetrahedral book" with two triangular covers lying flat, and a single page turning back and forth, hinged at the spine (like in any book). When the page is straight up vertical, that right tetrahedron of edges D (except for the page tip to cover tip) has a volume equivalent to that of a cube with edges R. So this is another way to show the relationship between two units of volume. The right tetrahedron is bigger than the regular tetrahedron by a scale factor of S3. <a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/40322964880/in/dateposted-public/" title="s3"><img src="https://farm1.staticflickr.com/976/40322964880_a43dd99667_z.jpg" width="640" height="396" alt="s3"></a><script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script> End of explanation """ ivmvol = ivm(2,2,2) print(ivmvol) """ Explanation: Double the length of the edges, and volume increases 8-fold, like in ordinary multiplication. End of explanation """
bearing/dosenet-analysis
Programming Lesson Modules/Module 6- Data Binning.ipynb
mit
%matplotlib inline import csv import io import urllib.request import matplotlib.pyplot as plt import numpy as np from datetime import datetime url = 'http://radwatch.berkeley.edu/sites/default/files/dosenet/etch_roof.csv' response = urllib.request.urlopen(url) reader = csv.reader(io.TextIOWrapper(response)) timedata = [] counts = [] CPMerror = [] line = 0 for row in reader: if line != 0: timedata.append(datetime.fromtimestamp(float(row[2],))) # 3rd column if CSV is a UNIX timestamp that can be converted # to datetime via fromtimestamp counts.append(float(row[6])) CPMerror.append(float(row[7])) line += 1 """ Explanation: Module 6- Data Binning author: Radley Rigonan Data Binning is a broad data-processing technique in which data sets are placed into groups known as "bins". It is known by other names bucketing, discretization, data chopping, and many others. Data Binning is applicable in a variety of situations such as histograms, processes in which you breakdown data by demographics, and processes that summarize large sets of data. However, while it is a very popular are useful technique, it also has its fair share of problems. The following example demonstrates pros and cons of binning: End of explanation """ def month_bin(timedata, cpm, error): # First, we initialize important values. Year = [timedata[-1].year] Month = [timedata[-1].month] sumCPM = [0] # because mean = sum/total, we can just add CPM values as we iterate along the month sumError = [0] DataCount = [0] # variable to count total number of points per month bin_num = 0 # variable to track current month; also tracks number of bins for i in range(len(counts)-1,0,-1): # iterate from last point to first point on CSV in steps of -1 if Year[bin_num] == timedata[i].year: # if current bin year is same as iterated year if Month[bin_num] == timedata[i].month: # if current bin month is same as iterated month, they belong in same bin! sumCPM[bin_num] += counts[i] sumError[bin_num] += CPMerror[i] # so we collect the data we need... DataCount[bin_num] += 1 else: Year.append(timedata[i].year) # if the months don't match: Month.append(timedata[i].month) sumCPM.append(0) # add another bin by appending 0 and increasing bin_num sumError.append(0) DataCount.append(0) bin_num += 1 else: # if current bin year doesn't match iterated year: Year.append(timedata[i].year) Month.append(timedata[i].month) # add another bin by appending 0 and increasing bin_num sumCPM.append(0) sumError.append(0) DataCount.append(0) bin_num += 1 binnedCPM = np.array(sumCPM) / np.array(DataCount) # np.array allows us to perform element-by-elemtent division avgError = np.array(sumError) / np.array(DataCount) stdError = avgError / np.sqrt(DataCount) # standard error is average error divided by sqrt(# of elements) strDates = [str(m)+'-'+str(n) for m,n in zip(Month,Year)] # convert Month Year values into string values for datetime binnedDates = [] for i in range(0,len(Month)): binnedDates.append(datetime.strptime(strDates[i],'%m-%Y')) # now everything is in the proper format! fig, ax = plt.subplots() ax.plot(binnedDates,binnedCPM, 'ro-') ax.errorbar(binnedDates,binnedCPM, yerr=stdError, fmt='ro', ecolor='r') plt.xticks(rotation=30) plt.title('DoseNet: Time-Averaged CPM (Etcheverry Roof)') plt.xlabel('Date') plt.ylabel('Average CPM') month_bin(timedata, counts, CPMerror) """ Explanation: For this example, I will bin DoseNet data from our device on the Etcheverry Roof and average the data. Afterwards, I will plot the data to show the consequences of data binning. While I perform this technique with my own code, it is important to note that there are many built-in functions within Python and plenty of examples of data binning you can find online. End of explanation """