markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Verify Results Copy the output file to local run the following command, and compare with the downloaded output sort -nrk 2,2 part-00000 | head -n 20 The wc1-part-00000 is the output of the previous wordcount (wordcount1)
# 1. list the output, download the output to local, and cat the output file # 2. use bash cmd to find out the most frequently used 20 words from the previous example, # and compare the results with this output # stop dfs and yarn !{hadoop_root + 'sbin/stop-yarn.sh'} # don't stop hdfs for now, later use # !{hadoop...
notes/.ipynb_checkpoints/1-hadoop-streaming-py-wordcount-checkpoint.ipynb
dsiufl/2015-Fall-Hadoop
mit
This will read the saved model into the variable ecoli.
print(ecoli) print("Reactions:", len(ecoli.reactions)) print("Metabolites:", len(ecoli.metabolites))
getting_started.ipynb
resendislab/cobrame-docker
apache-2.0
We can now run the optimization for the model. This will take around 10 minutes.
from cobrame.solve.algorithms import binary_search %time binary_search(ecoli, min_mu=0.1, max_mu=1.0, debug=True, mu_accuracy=1e-2)
getting_started.ipynb
resendislab/cobrame-docker
apache-2.0
If we want to we could also visualize the model fluxes on a map of the E. coli central carbon metabolism obtained from iJO1366.
import escher view = escher.Builder("iJO1366.Central metabolism") view.reaction_data = ecoli.get_metabolic_flux() view.display_in_notebook()
getting_started.ipynb
resendislab/cobrame-docker
apache-2.0
Python truth value testing Any object can be tested for truth value Truth value testing is used in flow control or in Boolean operations All objects are evaluated as True except: None (aka. null) False Zero of any numeric type: 0, 0L, 0.0, 0j, 0x0, 00 Any empty sequence or mapping: '', [], (), {} Instances of user-def...
# Let's try boolean operations print True or True print True or False print False or True # Boolean or. Short-circuited, so it only evaluates the second argument if the first one is False print True and True print True and False print False and True # Boolean or. Short-circuited, so it only evaluates the second ar...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Python boolean operands: ALWAYS return one of the incoming arguments! x or y => if x is false, then y, else x x and y => if x is false, then x, else y not x => if x is false, then True, else False They are short-circuited, so second argument is not always evaluated Can take any object type as arguments Even funct...
spam = 2 eggs = 2.5 print spam == 2 # equal print spam != eggs # not equal print spam >= eggs # greater than or equal print spam > eggs # strictly greater than print spam <= eggs # less than or equal print spam < eggs # strictly less than print spam is 2 # object identi...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Flow Control Let's start with the conditional execution
spam = [1, 2, 3] # True eggs = "" # False if spam: print "spam is True" else: print "spam is False" print "outside the conditional" # Notice that theres is no closing fi statement if spam: print "spam is True" else: print "spam is False" print "still inside the conditional"
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
REMEMBER: Indentation is Python's way of grouping statements!! Typically four spaces per indentation level No curly brackets { } or semicolons ; used anywhere This enforces a more readable code
if eggs: print "eggs is True" elif spam: print "eggs is False and spam is True" else: print "eggs and spam are False" if eggs: print "eggs is True" elif max(spam) > 5: print "eggs is False and second condition is True" elif len(spam) == 3 and not eggs is None: print "third condition is true" el...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Let's see the ternary operator
spam = [1, 2, 3] # True eggs = "" # False print "first option" if spam else "second option" print "first option" if eggs else "second option" print "first option" if eggs else "second option" if spam else "last option" # We can even concatenate them print "first option" if eggs else ("second option" if sp...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Time for the while loop
spam = [1, 2, 3] while len(spam) > 0: print spam.pop(0) spam = [1, 2, 3] idx = 0 while idx < len(spam): print spam[idx] idx += 1
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
What about the for loop?
spam = [1, 2, 3] for item in spam: # The for loop only iterates over the items of a sequence print item spam = [1, 2, 3] for item in spam[::-1]: # As we saw, slicing may be slow. Keep it in mind print item eggs = "eggs" for letter in eggs: # It can loop over characters of a string print lette...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Let's see how to interact with loops iterations
spam = [1, 2, 3] for item in spam: if item == 2: break print item
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
break statement halts a loop execution (inside while or for) Only affects the closer inner (or smallest enclosing) loop
# A bit more complicated example spam = ["one", "two", "three"] for item in spam: # This loop is never broken for letter in item: if letter in "wh": # Check if letter is either 'w' or 'h' break # Break only the immediate inner loop print letter ...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
continue statement halts current iteration (inside while or for) loops continue its normal execution
spam = [1, 2, 3, 4, 5, 6, 7, 8] eggs = 5 while len(spam) > 0: value = spam.pop() if value == eggs: print "Value found:", value break else: # Note that else has the same indentation than while print "The right value was not found" spam = [1, 2, 3, 4, 6, 7...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
else clause after a loop is executed if all iterations were run without break statement called
spam = [1, 2, 3] for item in spam: pass
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
pass statement is Python's noop (does nothing) Let's check exception handling
spam = [1, 2, 3] try: print spam[5] except: # Use try and except to capture exceptions print "Failed" spam = {"one": 1, "two": 2, "three": 3} try: print spam[5] except IndexError as e: # Inside the except clause 'e' will contain the exception instance print "IndexError", e except KeyEr...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Let's see another construction
try: f = open("tmp_file.txt", "a") except: print "Exception opening file" else: try: f.write("I'm writing to a file...\n") except: print "Can not write to a file" finally: f.close()
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Not pythonic, too much code for only three real lines
try: with open("tmp_file.txt", "a") as f: f.write("I'm writing to a file...\n") except: print "Can not open file for writing"
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Where is the file closed? What happens if an exception is raised? Python context managers Encapsulate common patterns used wrapping code blocks where real runs the program logic Usually try/except/finally patterns Several uses: Automatic cleanup, closing files or network or DB connections when exiting the context bl...
spam = [0, 1, 2, 3, 4] eggs = [0, 10, 20, 30] fooo = [] for s in spam: for e in eggs: if s > 1 and e > 1: fooo.append(s * e) print fooo
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Short code, right?
spam = [0, 1, 2, 3, 4] eggs = [0, 10, 20, 30] fooo = [s * e for s in spam for e in eggs if s > 1 and e > 1] print fooo
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
What about now?
fooo = [s * s for s in spam] # This is the most basic list comprehension construction print fooo fooo = [s * s for s in spam if s > 1] # We can add 'if' clauses print fooo spam = [1, 2, 3, 4] eggs = [0, -1, -2, -3] fooo = [l.upper() * (s + e) for s in spam for e in eggs for l in "SpaM aNd eGgs aNd s...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
List comprehension is faster than standard loops (low level C optimizations) However, built-in functions are still faster (see Functional and iterables tools module) There is also dict comprehension (2.7 or higher)
spam = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] fooo = {s: len(s) for s in spam} # The syntax is a merge of list comprehension and dicts print fooo spam = [(0, 'monday'), (1, 'tuesday'), (2, 'wednesday'), (3, 'thursday'), (4, 'friday')] fooo = {s: idx for idx, s in spam...
basic/3_Booleans_Flow_Control_and_Comprehension.ipynb
ealogar/curso-python
apache-2.0
Create a sample DataFrame with some missing values.
df = pd.DataFrame({ 'colA': ['aaa', NaN, NaN, NaN, 'bbb', 'ccc'], 'colB': ['xxx', 'yyy', NaN, 'zzz', NaN, 'www'], #'colC': [NaN, 3, NaN, 1, 0, 9] }) df
pandas-snippets.ipynb
maxalbert/pandas-snippets
unlicense
Task: replace missing values in column colA with those in colB (if they exist). First we define a filtering expression ("condition") cond which encodes the condition which we'd like to use for filling in the values. In this case we could actually use the simpler condition cond = df.colA.isnull() because it doesn't matt...
cond = df.colA.isnull() & ~df.colB.isnull() cond
pandas-snippets.ipynb
maxalbert/pandas-snippets
unlicense
We can use this to extract the desired columns if we wish.
df[cond]
pandas-snippets.ipynb
maxalbert/pandas-snippets
unlicense
Now we can do the assignment. Note that we use the .loc operator to avoid a warning about "trying to set values on a copy of a slice from a DataFrame" which would happen if we used for example the following expression df[cond]['colA'] = df[cond]['colB'] (See http://pandas.pydata.org/pandas-docs/stable/indexing.html#ind...
df.loc[cond, 'colA'] = df.loc[cond, 'colB']
pandas-snippets.ipynb
maxalbert/pandas-snippets
unlicense
The resulting DataFrame does indeed have the values yyy and zzz filled in column colA.
df
pandas-snippets.ipynb
maxalbert/pandas-snippets
unlicense
Geometry and mesh generation
g = GeometryMeshPyTriangle(np.array([(0, 0), (1, 0), (1, 0.2), (2, 0.4), (2, 0.6), (1, 0.8), (1, 1), (0, 1)])) m = g.mesh(0.03) m.draw() m.show()
learning/Example 1 - Stokes equations.ipynb
kinnala/sp.fem
agpl-3.0
Assembly
from spfem.element import ElementTriP1, ElementTriP2, ElementH1Vec from spfem.assembly import AssemblerElement
learning/Example 1 - Stokes equations.ipynb
kinnala/sp.fem
agpl-3.0
Next we create assemblers for the elements. We can give different elements for the solution vector and the test function. In this case we form the blocks $A$ and $B$ separately.
a = AssemblerElement(m, ElementH1Vec(ElementTriP2())) b = AssemblerElement(m, ElementH1Vec(ElementTriP2()), ElementTriP1()) c = AssemblerElement(m, ElementTriP1()) def stokes_bilinear_a(du, dv): def inner_product(a, b): return a[0][0]*b[0][0] +\ a[0][1]*b[0][1] +\ a[1][0]*b[1]...
learning/Example 1 - Stokes equations.ipynb
kinnala/sp.fem
agpl-3.0
In our case, we only want to check the modularization of our software for Java production code. So we just leave the files that are belonging to the main source code. What to keep here exactly is very specific to your own project. With Jupyter and pandas, we can make our decisions for this transparent and thus retracea...
prod_code = git_log.copy() prod_code = prod_code[prod_code.file.str.endswith(".java")] prod_code = prod_code[prod_code.file.str.startswith("backend/src/main")] prod_code = prod_code[~prod_code.file.str.endswith("package-info.java")] prod_code.head()
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Analysis We want to see which files are changing (almost) together. A good start for this is to create this view onto our dataset with the pivot_table method of the underlying pandas' DataFrame. But before this, we need a marker column that signals that a commit occurred. We can create an additional column named hit f...
prod_code['hit'] = 1 prod_code.head()
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Now, we can transform the data as we need it: For the index, we choose the filename, as columns, we choose the unique sha key of a commit. Together with the commit hits as values, we are now able to see which file changes occurred in which commit. Note that the pivoting also change the order of both indexes. They are n...
commit_matrix = prod_code.reset_index().pivot_table( index='file', columns='sha', values='hit', fill_value=0) commit_matrix.iloc[0:5,50:55]
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
As already mentioned in a previous blog post, we are now able to look at our problem from a mathematician' s perspective. What we have here now with the commit_matrix is a collection of n-dimensional vectors. Each vector represents a filename and the components/dimensions of such a vector are the commits with either t...
from sklearn.metrics.pairwise import cosine_distances dissimilarity_matrix = cosine_distances(commit_matrix) dissimilarity_matrix[:5,:5]
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
To be able to better understand the result, we add the file names from the commit_matrix as index and column index to the dissimilarity_matrix.
import pandas as pd dissimilarity_df = pd.DataFrame( dissimilarity_matrix, index=commit_matrix.index, columns=commit_matrix.index) dissimilarity_df.iloc[:5,:2]
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Now, we see the result in a better representation: For each file pair, we get the distance of the commit vectors. This means that we have now a distance measure that says how dissimilar two files were changed in respect to each other. Visualization Heatmap To get an overview of the result's data, we can plot the matrix...
%matplotlib inline import seaborn as sns sns.heatmap( dissimilarity_df, xticklabels=False, yticklabels=False );
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Because of the alphabetically ordered filenames and the "feature-first" architecture of the software under investigation, we get the first glimpse of how changes within modules are occurring together and which are not. To get an even better view, we can first extract the module's names with an easy string operation an...
modules = dissimilarity_df.copy() modules.index = modules.index.str.split("/").str[6] modules.index.name = 'module' modules.columns = modules.index modules.iloc[25:30,25:30]
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Then, we can create another heatmap that shows the name of the modules on both axes for further evaluation. We also just take a look at a subset of the data for representational reasons.
import matplotlib.pyplot as plt plt.figure(figsize=[10,9]) sns.heatmap(modules.iloc[:180,:180]);
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Discussion Starting at the upper left, we see the "comment" module with a pretty dark area very clearly. This means, that files around this module changed together very often. If we go to the middle left, we see dark areas between the "comment" module and the "framework" module as well as the "site" module further dow...
from sklearn.manifold import MDS # uses a fixed seed for random_state for reproducibility model = MDS(dissimilarity='precomputed', random_state=0) dissimilarity_2d = model.fit_transform(dissimilarity_df) dissimilarity_2d[:5]
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
The result is a 2D matrix that we can plot with matplotlib to get a first glimpse of the distribution of the calculated distances.
plt.figure(figsize=(8,8)) x = dissimilarity_2d[:,0] y = dissimilarity_2d[:,1] plt.scatter(x, y);
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
With the plot above, we see that the 2D transformation somehow worked. But we can't see * which filenames are which data points * how the modules are grouped all together So we need to enrich the data a little bit more and search for a better, interactive visualization technique. Let's add the filenames to the matrix a...
dissimilarity_2d_df = pd.DataFrame( dissimilarity_2d, index=commit_matrix.index, columns=["x", "y"]) dissimilarity_2d_df.head()
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
Author
prod_code.groupby(['file', 'author'])['hit'].count().groupby(['file', 'author']).max() dissimilarity_2d_df['module'] = dissimilarity_2d_df.index.str.split("/").str[6]
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
OK, here comes the ugly part: We have to transform all the data to the format our interactive visualization library pygal needs for its XY chart. We need to * group the data my modules * add every distance information * for each file as well as * the filename itself in a specific dictionary-like data structure. B...
plot_data = pd.DataFrame(index=dissimilarity_2d_df['module']) plot_data['value'] = tuple(zip(dissimilarity_2d_df['x'], dissimilarity_2d_df['y'])) plot_data['label'] = dissimilarity_2d_df.index plot_data['data'] = plot_data[['label', 'value']].to_dict('records') plot_dict = plot_data.groupby(plot_data.index).data.apply(...
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
With this nice little data structure, we can fill pygal's XY chart and create an interactive chart.
import pygal xy_chart = pygal.XY(stroke=False) [xy_chart.add(entry[0], entry[1]) for entry in plot_dict.iteritems()] # uncomment to create the interactive chart # xy_chart.render_in_browser() xy_chart
prototypes/Checking the modularization of software systems by analyzing co-changing source code files (Conway's law edition).ipynb
feststelltaste/software-analytics
gpl-3.0
For our hidden weights (the arrow in the diagram which loops back to its matrix), we initialize it using an identity matrix.
def wgts_and_bias(n_in, n_out): return init_wgts(n_in, n_out), init_bias(n_out) def id_and_bias(n): return shared(np.eye(n, dtype=np.float32)), init_bias(n)
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
We have to build up a computation-graph, a series of steps saying 'in the future I'm going to give you some data, and when I do I want you to do these steps...' So we start off by describing the types of data we'll give it
# we'll give it some input data t_inp = T.matrix('inp') # some output data t_outp = T.matrix('outp') # give it some way of initializing the first hidden state t_h0 = T.vector('h0') # also give it a learning rate which we can change later lr = T.scalar('lr') # we create a list of all args we provide to Theano later all...
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
To create the weights & biases, up above we have a function called wgts_and_bias(..) in which we tell Theano the size of the matrix we want to create. The matrix that goes from input to hidden has n_input rows and n_hidden collumns. wgts_and_bias returns a tuple of weights and biases. To create the weights, we first ca...
# weights & bias to hidden layer W_h = id_and_bias(b_hidden) # weights & bias to input W_x = wgts_and_bias(n_input, n_hidden) # weights & bias to output W_y = wgts_and_bias(n_hidden, n_output) # stick all manually constructed weight matrices and bias vectors # in a list: w_all = list(chain.from_iterable([W_h, W_x, W_y...
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
Python has a function, chain.from_iterable(..), that takes a list of tuples and turns them into one big list. The next thing we have to do is tell Theano what happens each time we take a single step of this RNN. There's no such thing as a for-loop on a GPU bc the GPU is built to & wants to parallelize things & do multi...
# example of scan: def scan(fn, start, seq): res = [] # array of results prev = start for s in seq: app = fn(prev, s) # apply function to previous result & next elem in sequence res.append(app) prev = app return res scan(lambda prev,curr: prev+curr, 0, range(5)) # output: # [0,...
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
The fucntion we'll call on ea. step thru is a fn called step. step takes the input, x, does a dot-product by the weight-matrix we created earlier, W_x, adds on the bias term we created earlier, b_x. then we do the same thing, taking our previous hidden state h, multiplying it by the hidden weight-matrix W_h and adding ...
def step(x, h, W_h, b_h, W_x, b_x, W_y, b_y): h = nnet.relu(T.dot(x, W_x) + b_x + T.dot(h, W_h) + b_h) y = nnet.softmax(T.dot(h, W_y) + b_y) return h, T.flatten(y, 1)
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
For the sequence we're passing into it -- we're just describing a computation here, so we tell Theano it will will be a matrix. For the starting point, outputs_info=[t_h0, None], we tell Theano via t_h0 = T.vector('h0') we'll provide it an initial hidden state. Finally, in Theano you have to tell it what all the other ...
[v_h, v_y], = theano.scan(step, sequences=t_inp, outputs_info=[t_h0, None], non_sequences=w_all)
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
By this point we've described how to execute a whole sequence of stesp for an RNN. We haven't given it any data to do it; we've just set up the computation. When that computation is run, it's going to return 2 things bc step returns 2 things: the hidden state v_h, and our output activations v_y. Now we need to calculat...
error = nnet.categorical_crossentropy(v_y, t_outp).sum() g_all = T.grad(error, w_all) # "please tell me the gradient, `g_all`, of the function `error`, # wrt. these gradients: `w_all`" # Theano will symbolically calculate all the derivatives for you.
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
We're ready now to build our final function. It takes as input, all our arguments, all_args. It'll create the error as its output. At each step it's going to do some updates via upd_dict. What upd_dict does is create a dictionary that's going to map every noe of our weights to the weight w minus each one of our gradien...
def upd_dict(w_all, g_all, lr): return OrderedDict({w: w-g*lr for (w,g) in zip(wgts,grads)}) upd = upd_dict(w_all, g_all, lr) fn = theano.function(all_args, error, updates=upd, allow_input_downcast=True)
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
We create our one-hot encoded X's and Y's, and we have to manually create our own loop; Theano has nothing built-in for this. We go through every element of our input X, and call that function that we just created above, and pass in all its inputs, all_args, for initial hidden state t_h0, input t_inp, target t_outp, an...
X = oh_x_rnn Y = oh_y_rnn # X.shape, Y.shape err=0.0; l_rate=0.01 for i in range(len(X)): err+=fn(np.zeros(n_hidden), X[i], Y[i], l_rate) if i % 1000 == 999: print("Error:{:.3f}".format(err/1000)) err=0.0
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
At the end of learning (via the loop above), we create a new Theano fn which takes some piece of input along with some initial hidden state, and produce not the loss, but the output. This is to do testing: the fn goes from out inputs to our vector of outputs v_y. Our predictions preds, will be to take that fn f_y, pass...
f_y = theano.function([t_h0, t_inp], v_y, allow_input_downcast=True) pred = np.argmax(f_y(np.zeros(n_hidden), X[6]), axis=1) # grabbing sample input text act = np.argmax(X[6], axis=1) # displaying input text [indices_char[o] for o in act] # displaying expected outputs [indices_char[o] for o in pred]
FAI_old/Lesson6/L6_Theano_RNN_Notes.ipynb
WNoxchi/Kaukasos
mit
MoveStrategy and MoveScheme After you've set up your ensembles, you need to create a scheme to sample those ensembles. This is done by the MoveStrategy and MoveScheme objects. OpenPathSampling uses a simple default scheme for any network, in which first you choose a type of move to do (shooting, replica exchange, etc),...
scheme = paths.DefaultScheme(network)
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
OpenPathSampling comes with a nice tool to visualize the move scheme. There are two main columns in the output of this visualization: at the left, you see a visualization of the move decision tree. On the right, you see the input and output ensembles for each PathMover. The move decision tree part of the visualization ...
move_vis = paths.visualize.MoveTreeBuilder.from_scheme(scheme) SVG(move_vis.svg())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
MoveSchemes are built from MoveStrategy objects In the end, you must give your PathSimulator object a single MoveScheme. However, this scheme might involve several different strategies (for example, whether you want to do one-way shooting or two-way shooting is one strategy decision, and it each can be combined with ei...
# example: switching between AllSetRepEx and NearestNeighborRepEx scheme = paths.DefaultScheme(network) scheme.append(strategies.AllSetRepExStrategy())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Now when we visualize this, note the difference in the replica exchange block: we have 6 movers instead of 4, and now we allow the exchanges between the innermost and outermost ensembles.
move_vis = paths.visualize.MoveTreeBuilder.from_scheme(scheme) SVG(move_vis.svg())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
What if you changed your mind, or wanted to go the other way? Of course, you could just create a new scheme from scratch. However, you can also append a NearestNeighborRepExStrategy after the AllSetRepExStrategy and, from that, return to nearest-neighbor replica exchange. For NearestNeighborRepExStrategy, the default i...
scheme.append(strategies.NearestNeighborRepExStrategy(), force=True) move_vis = paths.visualize.MoveTreeBuilder.from_scheme(scheme) SVG(move_vis.svg())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Combination strategies OpenPathSampling provides a few shortcuts to strategies which combine several substrategies into a whole. DefaultMoveStrategy The DefaultMoveStrategy converts the move scheme to one which follows the default OpenPathSampling behavior. TODO: note that this isn't always the same as the default sche...
# example: single replica
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Examples of practical uses In the examples above, we saw how to change from nearest neighbor replica exchange to all (in-set) replica exchange, and we saw how to switch to a single replica move strategy. In the next examples, we'll look at several other uses for move strategies. Adding a specific extra replica exchange...
ens00 = network.sampling_transitions[0].ensembles[0] ens02 = network.sampling_transitions[0].ensembles[2] extra_repex = strategies.SelectedPairsRepExStrategy(ensembles=[ens00, ens02], replace=False) scheme = paths.DefaultScheme(network) scheme.append(extra_repex)
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Now we have 7 replica exchange movers (5 not including MS-outer), as can be seen in the move tree visualization.
move_vis = paths.visualize.MoveTreeBuilder.from_scheme(scheme) SVG(move_vis.svg())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
First crossing shooting point selection for some ensembles For ensembles which are far from the state, sometimes uniform shooting point selection doesn't work. If the number of frames inside the interface is much larger than the number outside the interface, then you are very likely to select a shooting point inside th...
# select the outermost ensemble in each sampling transition special_ensembles = [transition.ensembles[-1] for transition in network.sampling_transitions] alternate_shooting = strategies.OneWayShootingStrategy( selector=paths.UniformSelector(), # TODO: change this ensembles=special_ensembles ) # note that repla...
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Two different kinds of shooting for one ensemble In importance sampling approaches like TIS, you're seeking a balance between two sampling goals. On the one hand, most of space has a negligible (or zero) contribution to the property being measured, so you don't want your steps to be so large that your trials are never ...
# example: add extra shooting (in a different group, preferably) extra_shooting = strategies.OneWayShootingStrategy( selector=paths.UniformSelector(), # TODO: change this group='small_step_shooting' ) scheme = paths.DefaultScheme(network) scheme.append(extra_shooting)
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
In the visualization of this, you'll see that we have 2 blocks of shooting moves: one is the pre-existing group called 'shooting', and the other is this new group 'small_step_shooting'.
move_vis = paths.visualize.MoveTreeBuilder.from_scheme(scheme) SVG(move_vis.svg())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
RepEx-Shoot-RepEx One of the mains goals of OpenPathSampling is to allow users to develop new approaches. New move strategies certainly represents one direction of possible research. This particular example also shows you how to implement such features. It includes both implementation of a custom PathMover and a custom...
# example: custom subclass of `MoveStrategy` class RepExShootRepExStrategy(strategies.MoveStrategy): _level = strategies.levels.GROUP # we define an init function mainly to set defaults for `replace` and `group` def __init__(self, ensembles=None, group="repex_shoot_repex", replace=True, network=None): ...
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
You'll notice that the combo_mover we defined above is within a RandomChoiceMover: that random choice is for the group 'repex_shoot_repex', which has only this one member. In this, we have used the default replace=True, which removes the old groups for the shooting movers and replica exchange movers. If you would like ...
# TODO: there appears to be a bug in MoveTreeBuilder with this scheme move_vis = paths.visualize.MoveTreeBuilder.from_scheme(scheme) SVG(move_vis.svg())
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Modifying the probabilities of moves The DefaultStrategy includes default choices for the probability of making each move type, and then treats all moves within a given type with equal probability. Above, we described how to change the probability of a specific move type; now we're going to discuss changing the probabi...
# TODO: This is done differently (and more easily) now # example: getting into the details #scheme = paths.DefaultScheme(network) #move_decision_tree = scheme.move_decision_tree() #ens = network.sampling_transitions[0].ensembles[-1] #shooting_chooser = [m for m in move_decision_tree.movers if m.movers==scheme.movers['s...
examples/misc/move_strategies_and_schemes.ipynb
jhprinz/openpathsampling
lgpl-2.1
Create matrix of features and matrix of target variable. In this case we are excluding column 1, 2 & 3 as those are ‘row_number’, ‘customerid’ & 'Surname' which are not useful in our analysis. Column 14, ‘Exited’ is our Target Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder ## Read this for categorical Encoding : http://pbpython.com/categorical-encoding.html ##pd.get_dummies(dataset, columns=["Geography", "Gender"], prefix=["Geography", "Gender"]).head() def getXy_1(dataset,target): df = pd.get_dummies(dataset, columns=["G...
DeepNetwork/Keras/BankChurn.ipynb
prashantas/MyDataScience
bsd-2-clause
I know you are tired of data preprocessing but I promise this is the last step. If you carefully observe data, you will find that data is not scaled properly. Some variable has value in thousands while some have value is tens or ones. We don’t want any of our variable to dominate on other so let’s go and scale data. ‘S...
from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.fit_transform(X_test) X_train X_train.shape import keras from keras.models import Sequential from keras.layers.core import Dense,Dropout, Dropout,Activation model = Sequential() model.add(Dense(1...
DeepNetwork/Keras/BankChurn.ipynb
prashantas/MyDataScience
bsd-2-clause
Carregamento e junção dos dados
from preprocessamento_escola_2011 import escolas_info_train, escolas_info_test
experiments/Analise Exploratoria.ipynb
ffmmjj/desafio-dados-2016
apache-2.0
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...
escolas_info_train.info()
experiments/Analise Exploratoria.ipynb
ffmmjj/desafio-dados-2016
apache-2.0
Limpeza inicial dos dados
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_trat...
experiments/Analise Exploratoria.ipynb
ffmmjj/desafio-dados-2016
apache-2.0
Checagem de correlações
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]
experiments/Analise Exploratoria.ipynb
ffmmjj/desafio-dados-2016
apache-2.0
Distribuição das médias em Língua Portuguesa
plt.hist(escolas_train_clean['MEDIA_LP'], bins=20) plt.xlabel('Média em Língua Portuguesa') plt.show()
experiments/Analise Exploratoria.ipynb
ffmmjj/desafio-dados-2016
apache-2.0
Gráfico de correlação entre Qualidade da Biblioteca e Média em Língua Portuguesa
# 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', ...
experiments/Analise Exploratoria.ipynb
ffmmjj/desafio-dados-2016
apache-2.0
Logical 'OR' operator This is all well and good for the 'and' logical operator. What about the 'or' logical operator. If we would like the following: python if x1 == 1 or x2 == 1: y1 == 1 else: y1 == 0 We can use the following linear constraints: python y1 &lt;= x1 + x2 y1 * 2 &gt;= x1 + x2 So that: * if x<sub>...
import pandas as pd import pulp factories = pd.DataFrame.from_csv('csv/factory_variables.csv', index_col=['Month', 'Factory']) factories demand = pd.DataFrame.from_csv('csv/monthly_demand.csv', index_col=['Month']) demand
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 6.ipynb
sysid/nbs
mit
We'll begin by defining our decision variables, we have an additional binary variable for switching on the factory.
# Production production = pulp.LpVariable.dicts("production", ((month, factory) for month, factory in factories.index), lowBound=0, cat='Integer') # Factory Status, On or Off factory_status = pulp.LpVariable....
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 6.ipynb
sysid/nbs
mit
We instantiate our model and define our objective function, including start up costs
# Instantiate the model model = pulp.LpProblem("Cost minimising scheduling problem", pulp.LpMinimize) # Select index on factory A or B factory_A_index = [tpl for tpl in factories.index if tpl[1] == 'A'] factory_B_index = [tpl for tpl in factories.index if tpl[1] == 'B'] # Define objective function model += pulp.lpSum...
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 6.ipynb
sysid/nbs
mit
Now we begin to build up our constraints as in Part 5
# Production in any month must be equal to demand months = demand.index for month in months: model += production[(month, 'A')] + production[(month, 'B')] == demand.loc[month, 'Demand'] # Production in any month must be between minimum and maximum capacity, or zero. for month, factory in factories.index: min_pr...
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 6.ipynb
sysid/nbs
mit
But now we want to add in our constraints for switching on. A factory switches on if: * It is off in the previous month (m-1) * AND it on in the current month (m). As we don't know if the factory is on before month 0, we'll assume that the factory has switched on if it is on in month 1.
for month, factory in factories.index: # In month 1, if the factory ison, we assume it turned on if month == 1: model += switch_on[month, factory] == factory_status[month, factory] # In other months, if the factory is on in the current month AND off in the previous month, switch on = 1 else...
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 6.ipynb
sysid/nbs
mit
We'll then solve our model
model.solve() pulp.LpStatus[model.status] output = [] for month, factory in production: var_output = { 'Month': month, 'Factory': factory, 'Production': production[(month, factory)].varValue, 'Factory Status': factory_status[(month, factory)].varValue, 'Switch On': switch_on...
LP/Introduction-to-linear-programming/LaTeX_formatted_ipynb_files/Introduction to Linear Programming with Python - Part 6.ipynb
sysid/nbs
mit
This example covers debugging strategies for PyRTL. For general python debugging we recommend healthy use of the "assert" statement, and use of "pdb" for tracking down bugs. However, PyRTL introduces some new complexities because the place where functionality is defined (when you construct and operate on PyRTL class...
# building three inputs in1, in2, in3 = (pyrtl.Input(8, "in" + str(x)) for x in range(1, 4)) out = pyrtl.Output(10, "out") add1_out = adders.kogge_stone(in1, in2) add2_out = adders.kogge_stone(add1_out, in2) out <<= add2_out
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
The most basic way of debugging PyRTL is to connect a value to an output wire and use the simulation to trace the output. A simple "print" statement doesn't work because the values in the wires are not populated during creation time If we want to check the result of the first addition, we can connect an output wire to ...
debug_out = pyrtl.Output(9, "debug_out") debug_out <<= add1_out
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Now simulate the circuit. Let's create some random inputs to feed our adder.
vals1 = [int(2**random.uniform(1, 8) - 2) for _ in range(20)] vals2 = [int(2**random.uniform(1, 8) - 2) for _ in range(20)] vals3 = [int(2**random.uniform(1, 8) - 2) for _ in range(20)] sim_trace = pyrtl.SimulationTrace() sim = pyrtl.Simulation(tracer=sim_trace) for cycle in range(len(vals1)): sim.step({ '...
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
In order to get the result data, you do not need to print a waveform of the trace You always have the option to just pull the data out of the tracer directly
print("---- Inputs and debug_out ----") print("in1: ", str(sim_trace.trace['in1'])) print("in2: ", str(sim_trace.trace['in2'])) print("debug_out: ", str(sim_trace.trace['debug_out'])) print('\n')
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Below, I am using the ability to directly retrieve the trace data to verify the correctness of the first adder
for i in range(len(vals1)): assert(sim_trace.trace['debug_out'][i] == sim_trace.trace['in1'][i] + sim_trace.trace['in2'][i])
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Probe Now that we have built some stuff, let's clear it so we can try again in a different way. We can start by clearing all of the hardware from the current working block. The working block is a global structure that keeps track of all the hardware you have built thus far. A "reset" will clear it so we can start fr...
pyrtl.reset_working_block()
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
In this example, we will be multiplying two numbers using tree_multiplier() Again, create the two inputs and an output
print("---- Using Probes ----") in1, in2 = (pyrtl.Input(8, "in" + str(x)) for x in range(1, 3)) out1, out2 = (pyrtl.Output(8, "out" + str(x)) for x in range(1, 3)) multout = multipliers.tree_multiplier(in1, in2) #The following line will create a probe named "std_probe for later use, like an output. pyrtl.probe(multou...
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
We could also do the same thing during assignment. The next command will create a probe (named 'stdout_probe') that refers to multout (returns the wire multout). This achieves virtually the same thing as 4 lines above, but it is done during assignment, so we skip a step by probing the wire before the multiplication. Th...
out1 <<= pyrtl.probe(multout, 'stdout_probe') * 2
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Probe can also be used with other operations like this:
pyrtl.probe(multout + 32, 'adder_probe') pyrtl.probe(multout[2:7], 'select_probe') out2 <<= pyrtl.probe(multout)[2:16] # notice probe names are not absolutely necessary
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
As one can see, probe can be used on any wire any time, such as before or during its operation, assignment, etc. Now on to the simulation... For variation, we'll recreate the random inputs:
vals1 = [int(2**random.uniform(1, 8) - 2) for _ in range(10)] vals2 = [int(2**random.uniform(1, 8) - 2) for _ in range(10)] sim_trace = pyrtl.SimulationTrace() sim = pyrtl.Simulation(tracer=sim_trace) for cycle in range(len(vals1)): sim.step({ 'in1': vals1[cycle], 'in2': vals2[cycle]})
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Now we will show the values of the inputs and probes and look at that, we didn't need to make any outputs! (although we did, to demonstrate the power and convenience of probes)
sim_trace.render_trace() sim_trace.print_trace()
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Say we wanted to have gotten more information about one of those probes above at declaration. We could have used pyrtl.set_debug_mode() before their creation, like so:
print("--- Probe w/ debugging: ---") pyrtl.set_debug_mode() pyrtl.probe(multout - 16, 'debugsubtr_probe)') pyrtl.set_debug_mode(debug=False)
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
WireVector Stack Trace Another case that might arise is that a certain wire is causing an error to occur in your program. WireVector Stack Traces allow you to find out more about where a particular WireVector was made in your code. With this enabled the WireVector will store exactly were it was created, which should he...
pyrtl.set_debug_mode() test_out = pyrtl.Output(9, "test_out") test_out <<= adders.kogge_stone(in1, in2)
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Now to retrieve information:
wire_trace = test_out.init_call_stack
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
This data is generated using the traceback.format_stack() call from the Python standard library's Traceback module (look at the Python standard library docs for details on the function). Therefore, the stack traces are stored as a list with the outermost call first.
print("---- Stack Trace ----") for frame in wire_trace: print(frame)
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Storage of Additional Debug Data WARNING: the debug information generated by the following two processes are not guaranteed to be preserved when functions (eg. pyrtl.synthesize() ) are done over the block. However, if the stack trace does not give you enough information about the WireVector, you can also embed addition...
dummy_wv = pyrtl.WireVector(1, name="blah")
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Also, because of the flexible nature of Python, you can also add custom properties to the WireVector.
dummy_wv.my_custom_property_name = "John Clow is great" dummy_wv.custom_value_028493 = 13 # removing the WireVector from the block to prevent problems with the rest of # this example pyrtl.working_block().remove_wirevector(dummy_wv)
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause
Trivial Graph Format Finally, there is a handy way to view your hardware creations as a graph. The function output_to_trivialgraph will render your hardware a formal that you can then open with the free software "yEd" (http://en.wikipedia.org/wiki/YEd). There are options under the "hierarchical" rendering to draw somet...
pyrtl.working_block().sanity_check() pyrtl.passes._remove_unused_wires(pyrtl.working_block()) # so that trivial_graph() will work print("--- Trivial Graph Format ---") with io.StringIO() as tgf: pyrtl.output_to_trivialgraph(tgf) print(tgf.getvalue())
ipynb-examples/example4-debuggingtools.ipynb
UCSBarchlab/PyRTL
bsd-3-clause