markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
IL/XL and XY, multi-line header, multiple attributes Load everything (default) X and Y are loaded as cdp_x and cdp_y, to be consistent with the seisnc standard in segysak.
ds = gio.read_odt('../data/OdT/3d_horizon/Segment_XY-and-ILXL_Multi-line-header.dat') ds import matplotlib.pyplot as plt plt.scatter(ds.coords['cdp_x'], ds.coords['cdp_y'], s=5)
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
Load only inline, crossline, TWT There is only one attribute here: Z, which is the two-way time of the horizon. Note that when loading data from OpendTect, you always get an xarray.Dataset, even if there's only a single attribute. This is because the format supports multiple grids and we didn't want you to have to guess what a given file would produce.
fname = '../data/OdT/3d_horizon/Segment_XY-and-ILXL_Multi-line-header.dat' names = ['Inline', 'Crossline', 'Z'] # Must match OdT DAT file. ds = gio.read_odt(fname, names=names) ds
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
XY only If you have a file with no IL/XL, gio can try to load data using only X and Y: If there's a header you can load any number of attributes. If there's no header, you can only one attribute (e.g. TWT) automagically... OR, if there's no header, you can provide names to tell gio what everything is. gio must create fake inline and crossline numbers; you can provide an origin and a step size. For example, notice above that the true inline and crossline numbers are: inline: 376, 378, 380, etc. crossline: 812, 814, 816, etc. So we can pass an origin of (376, 812) and a step of (2, 2) to mimic these. Header present
fname = '../data/OdT/3d_horizon/Segment_XY_Single-line-header.dat' ds = gio.read_odt(fname, origin=(376, 812), step=(2, 2)) ds ds['twt'].plot()
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
No header, more than one attribute: raises an error
fname = '../data/OdT/3d_horizon/Segment_XY_No-header.dat' ds = gio.read_odt(fname) ds # Raises an error: fname = '../data/OdT/3d_horizon/Segment_XY_No-header.dat' ds = gio.read_odt(fname, names=['X', 'Y', 'TWT']) ds ds['twt'].plot()
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
Sparse data Sometimes a surface only exists at a few points, e.g. a 3D seismic interpretation grid. In general, loading data like this is completely safe if you have inline and xline locations. If you only have (x, y) locations, gio will attempt to load it, but you should inspect the result carefullly.
fname = '../data/OdT/3d_horizon/Nimitz_Salmon_XY-and-ILXL_Single-line-header.dat' ds = gio.read_odt(fname) ds ds['twt'].plot.imshow()
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
Multiple horizons in one file You can export multiple horizons from OpendTect. These will be loaded as one xarray.Dataset as different Data variables. (The actual attribute you exported from OdT is always called Z; this information is not retained in the xarray.)
fname = '../../gio-dev/data/OdT/3d_horizon/multi_horizon/Multi_header_H2_and_H4_X_Y_iL_xL_Z_in_sec.dat' ds = gio.read_odt(fname) ds ds['F3_Demo_2_FS6'].plot() ds['F3_Demo_4_Truncation'].plot()
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
Multi-horizon, no header Unfortunately, OdT exports (x, y) in the first two columns, meaning you can't assume that columns 3 and 4 are inline, crossline. So if there's no header, and XY as well as inline/xline, you have to give the column names:
import gio fname = '../data/OdT/3d_horizon/Test_Multi_XY-and-ILXL_Z-only.dat' ds = gio.read_odt(fname, names=['Horizon', 'X', 'Y', 'Inline', 'Crossline', 'Z']) ds
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
Undefined values These are exported as '1e30' by default. You can override this (not add to it, which is the default pandas behaviour) by passing one or more na_values.
fname = '../data/OdT/3d_horizon/Segment_XY_No-header_NULLs.dat' ds = gio.read_odt(fname, names=['X', 'Y', 'TWT']) ds ds['twt'].plot()
docs/userguide/Read_OpendTect_horizons.ipynb
agile-geoscience/gio
apache-2.0
In many cases, it is easier to use the subplots function, which creates a new Figure along with an array of Axes objects that can be indexed in a rational manner:
f, ax = plt.subplots(2, 2,figsize=(15,5)) for i in range(2): for j in range(2): plt.sca(ax[i,j]) plt.plot(np.random.rand(20)) plt.xlabel('x') plt.ylabel('y') plt.tight_layout()
Matplotlib/Matplotlib.ipynb
JAmarel/Phys202
mit
Go to lxmls/deep learning/mlp.py:class NumpyMLP:def grads() and complete the code of the NumpyMLP class with the Backpropagation recursion that we just saw.
def grads(self, x, y): """ Computes the gradients of the network with respect to cross entropy error cost """ # Run forward and store activations for each layer activations = self.forward(x, all_outputs=True) # For each layer in reverse store the gradients for each parameter nabla_params = [None] * (2*self.n_layers) for n in np.arange(self.n_layers-1, -1, -1): # Get weigths and bias (always in even and odd positions) # Note that sometimes we need the weight from the next layer W = self.params[2*n] b = self.params[2*n+1] if n != self.n_layers-1: W_next = self.params[2*(n+1)] # Solving Exercise 5.1 if n < self.n_layers - 1 : ent = np.dot(W_next.T, ent ) ent *= activations[ n ] * (1 - activations[ n ] ) # This is correct but confusing n+1 is n in the guide else: # NOTE: This assumes cross entropy cost if self.actvfunc[ n ] == 'sigmoid': ent = ( activations[ n ] - y ) / y.shape[ 0 ] elif self.actvfunc[ n ] == 'softmax': I = index2onehot( y , W.shape[ 0 ] ) ent = (activations[ n ] - I ) / y.shape[ 0 ] nabla_W = np.zeros( W.shape ) for l in np.arange( ent.shape[ 1 ] ): if n == 0: nabla_W += np.outer( ent[ :, l ], x[ :, l] ) else: nabla_W += np.outer( ent[ :, l ], activations[ n - 1] [ :, l ] ) nabla_b = np.sum( ent , 1, keepdims=True ) #End of the solution 5.1 # Store the gradients nabla_params[2*n] = nabla_W nabla_params[2*n+1] = nabla_b return nabla_params
.ipynb_checkpoints/Lxmls_Day5-checkpoint.ipynb
jnobre/lxmls-toolkit-2017
mit
5.5.2 Symbolic Forward Pass Exercise 5.3 Complete the method forward() inside of the lxmls/deep learning/mlp.py:class TheanoMLP. Note that this is called only once at the initialization of the class. To debug your implementation put a breakpoint at the init function call. Hint: Note that this is very similar to NumpyMLP.forward(). You just need to keep track of the symbolic variable representing the output of the network after each layer is applied and compile the function at the end. After you are finished instantiate a Theano class and check that Numpy and Theano forward pass are the same.
def _forward(self, x, all_outputs=False): """ Symbolic forward pass all_outputs = True return symbolic input and intermediate activations """ # This will store activations at each layer and the input. This is # needed to compute backpropagation if all_outputs: activations = [x] # Input tilde_z = x # ---------- # Solution to Exercise 5.3 for n in range(self.n_layers): # Get weigths and bias (always in even and odd positions) W = self.params[2*n] b = self.params[2*n+1] z = T.dot(W, tilde_z) + b # Linear transformation # see e.g. theano.printing.debugprint(tilde_z) z.name = 'z%d' % (n+1) # Non-linear transformation if self.actvfunc[n] == "sigmoid": tilde_z = T.nnet.sigmoid( z ) elif self.actvfunc[n] == "softmax": tilde_z = T.nnet.softmax( z.T ).T tilde_z.name = 'tilde_z%d' % (n+1) # Name variable if all_outputs: activations.append(tilde_z) # End of solution to Exercise 5.3 # ---------- if all_outputs: tilde_z = activations return tilde_z mlp_a = dl.NumpyMLP(geometry, actvfunc) mlp_b = dl.TheanoMLP(geometry, actvfunc)
.ipynb_checkpoints/Lxmls_Day5-checkpoint.ipynb
jnobre/lxmls-toolkit-2017
mit
5.5.4 Symbolic mini-batch update Exercise 5.5 Define the updates list. This is a list where each element is a tuple of a parameter and the update rule to be applied that parameter. In this case we are defining the SGD update rule, but take into account that using more complex update rules like e.g. momentum or adam implies just replacing the last line of the following snippet.
W2, b2 = mlp_a.params[2:4] # Second layer symbolic variables _W2 = theano.shared(value=W2, name='W2', borrow=True) _b2 = theano.shared(value=b2, name='b2', borrow=True, broadcastable=(False, True)) _z2 = T.dot(_W2, _tilde_z1) + _b2 _tilde_z2 = T.nnet.softmax(_z2.T).T # Ground truth _y = T.ivector('y') # Cost _F = -T.mean(T.log(_tilde_z2[_y, T.arange(_y.shape[0])])) # Gradient _nabla_F = T.grad(_F, _W1) nabla_F = theano.function([_x, _y], _nabla_F) # Print computation graph print "\nThis is my softmax classification cost\n" theano.printing.debugprint(_F)
.ipynb_checkpoints/Lxmls_Day5-checkpoint.ipynb
jnobre/lxmls-toolkit-2017
mit
Exercise 5.6
import time # Understanding the mini-batch function and givens/updates parameters # Numpy geometry = [train_x.shape[0], 20, 2] actvfunc = ['sigmoid', 'softmax'] mlp_a = dl.NumpyMLP(geometry, actvfunc) # init_t = time.clock() sgd.SGD_train(mlp_a, n_iter, bsize=bsize, lrate=lrate, train_set=(train_x, train_y)) print "\nNumpy version took %2.2f sec" % (time.clock() - init_t) acc_train = sgd.class_acc(mlp_a.forward(train_x), train_y)[0] acc_test = sgd.class_acc(mlp_a.forward(test_x), test_y)[0] print "Amazon Sentiment Accuracy train: %f test: %f\n" % (acc_train, acc_test) # Theano grads mlp_b = dl.TheanoMLP(geometry, actvfunc) init_t = time.clock() sgd.SGD_train(mlp_b, n_iter, bsize=bsize, lrate=lrate, train_set=(train_x, train_y)) print "\nCompiled gradient version took %2.2f sec" % (time.clock() - init_t) acc_train = sgd.class_acc(mlp_b.forward(train_x), train_y)[0] acc_test = sgd.class_acc(mlp_b.forward(test_x), test_y)[0] print "Amazon Sentiment Accuracy train: %f test: %f\n" % (acc_train, acc_test) # Theano compiled batch # Cast data into the types and shapes used in the theano graph # IMPORTANT: This is the main source of errors when beginning with theano train_x = train_x.astype(theano.config.floatX) train_y = train_y.astype('int32') # Model mlp_c = dl.TheanoMLP(geometry, actvfunc) # Define givens variables to be used in the batch update # Get symbolic variables returning a mini-batch of data # Define updates variable. This is a list of gradient descent updates # The output is a list following theano.function updates parameter. This # consists on a list of tuples with each parameter and update rule _x = T.matrix('x') _y = T.ivector('y') _F = mlp_c._cost(_x, _y) updates = [(par, par - lrate*T.grad(_F, par)) for par in mlp_c.params] # # Define the batch update function. This will return the cost of each batch # and update the MLP parameters at the same time using updates batch_up = theano.function([_x, _y], _F, updates=updates) n_batch = int(np.ceil(float(train_x.shape[1])/bsize)) # init_t = time.clock() sgd.SGD_train(mlp_c, n_iter, batch_up=batch_up, n_batch=n_batch, bsize=bsize, train_set=(train_x, train_y)) print "\nTheano compiled batch update version took %2.2f sec" % (time.clock() - init_t) init_t = time.clock() acc_train = sgd.class_acc(mlp_c.forward(train_x), train_y)[0] acc_test = sgd.class_acc(mlp_c.forward(test_x), test_y)[0] print "Amazon Sentiment Accuracy train: %f test: %f\n" % (acc_train, acc_test)
.ipynb_checkpoints/Lxmls_Day5-checkpoint.ipynb
jnobre/lxmls-toolkit-2017
mit
Sequential container Define a forward and backward pass procedures.
class Sequential(Module): """ This class implements a container, which processes `input` data sequentially. `input` is processed by each module (layer) in self.modules consecutively. The resulting array is called `output`. """ def __init__ (self): super(Sequential, self).__init__() self.modules = [] def add(self, module): """ Adds a module to the container. """ self.modules.append(module) def updateOutput(self, input): """ Basic workflow of FORWARD PASS: y_0 = module[0].forward(input) y_1 = module[1].forward(y_0) ... output = module[n-1].forward(y_{n-2}) Just write a little loop. """ # Your code goes here. ################################################ self.y = [np.array(input)] for module in self.modules: self.y.append(module.forward(self.y[-1])) self.y.pop(0) self.output = self.y[-1] return self.output def backward(self, input, gradOutput): """ Workflow of BACKWARD PASS: g_{n-1} = module[n-1].backward(y_{n-2}, gradOutput) g_{n-2} = module[n-2].backward(y_{n-3}, g_{n-1}) ... g_1 = module[1].backward(y_0, g_2) gradInput = module[0].backward(input, g_1) !!! To ech module you need to provide the input, module saw while forward pass, it is used while computing gradients. Make sure that the input for `i-th` layer the output of `module[i]` (just the same input as in forward pass) and NOT `input` to this Sequential module. !!! """ # Your code goes here. ################################################ g = np.array(gradOutput) self.y = [np.array(input)] + self.y for i, module in enumerate(reversed(self.modules)): g = module.backward(self.y[-i - 2], g) self.gradInput = g self.y.pop(0) return self.gradInput def zeroGradParameters(self): for module in self.modules: module.zeroGradParameters() def getParameters(self): """ Should gather all parameters in a list. """ return [x.getParameters() for x in self.modules] def getGradParameters(self): """ Should gather all gradients w.r.t parameters in a list. """ return [x.getGradParameters() for x in self.modules] def __repr__(self): string = "".join([str(x) + '\n' for x in self.modules]) return string def __getitem__(self,x): return self.modules.__getitem__(x)
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
Layers input: batch_size x n_feats1 output: batch_size x n_feats2
class Linear(Module): """ A module which applies a linear transformation A common name is fully-connected layer, InnerProductLayer in caffe. The module should work with 2D input of shape (n_samples, n_feature). """ def __init__(self, n_in, n_out): super(Linear, self).__init__() # This is a nice initialization stdv = 1./np.sqrt(n_in) self.W = np.random.uniform(-stdv, stdv, size = (n_out, n_in)) self.b = np.random.uniform(-stdv, stdv, size = n_out) self.gradW = np.zeros_like(self.W) self.gradb = np.zeros_like(self.b) def updateOutput(self, input): # Your code goes here. ################################################ self.output = np.add(input.dot(self.W.T), self.b) return self.output def updateGradInput(self, input, gradOutput): # Your code goes here. ################################################ self.gradInput = gradOutput.dot(self.W) return self.gradInput def accGradParameters(self, input, gradOutput): # Your code goes here. ################################################ self.gradW = gradOutput.T.dot(input) self.gradb = gradOutput.sum(axis=0) def zeroGradParameters(self): self.gradW.fill(0) self.gradb.fill(0) def getParameters(self): return [self.W, self.b] def getGradParameters(self): return [self.gradW, self.gradb] def __repr__(self): s = self.W.shape q = 'Linear %d -> %d' %(s[1],s[0]) return q input_dim = 3 output_dim = 2 x = np.random.randn(5, input_dim) w = np.random.randn(output_dim, input_dim) b = np.random.randn(output_dim) dout = np.random.randn(5, output_dim) linear = Linear(input_dim, output_dim) def update_W_matrix(new_W): linear.W = new_W return linear.forward(x) def update_bias(new_b): linear.b = new_b return linear.forward(x) dx = linear.backward(x, dout) dx_num = eval_numerical_gradient_array(lambda x: linear.forward(x), x, dout) dw_num = eval_numerical_gradient_array(update_W_matrix, w, dout) db_num = eval_numerical_gradient_array(update_bias, b, dout) print 'Testing Linear_backward function:' print 'dx error: ', rel_error(dx_num, dx) print 'dw error: ', rel_error(dw_num, linear.gradW) print 'db error: ', rel_error(db_num, linear.gradb)
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
This one is probably the hardest but as others only takes 5 lines of code in total. - input: batch_size x n_feats - output: batch_size x n_feats
class SoftMax(Module): def __init__(self): super(SoftMax, self).__init__() def updateOutput(self, input): # start with normalization for numerical stability self.output = np.subtract(input, input.max(axis=1, keepdims=True)) # Your code goes here. ################################################ self.output = np.exp(self.output) out_sum = self.output.sum(axis=1, keepdims=True) self.output = np.divide(self.output, out_sum) return self.output def updateGradInput(self, input, gradOutput): # Your code goes here. ################################################ batch_size, n_feats = self.output.shape a = self.output.reshape(batch_size, n_feats, -1) b = self.output.reshape(batch_size, -1, n_feats) self.gradInput = np.multiply(gradOutput.reshape(batch_size, -1, n_feats), np.subtract(np.multiply(np.eye(n_feats), a), np.multiply(a, b))).sum(axis=2) return self.gradInput def __repr__(self): return "SoftMax" soft_max = SoftMax() x = np.random.randn(5, 3) dout = np.random.randn(5, 3) dx_numeric = eval_numerical_gradient_array(lambda x: soft_max.forward(x), x, dout) dx = soft_max.backward(x, dout) # The error should be around 1e-10 print 'Testing SoftMax grad:' print 'dx error: ', rel_error(dx_numeric, dx)
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
Implement dropout. The idea and implementation is really simple: just multimply the input by $Bernoulli(p)$ mask. This is a very cool regularizer. In fact, when you see your net is overfitting try to add more dropout. While training (self.training == True) it should sample a mask on each iteration (for every batch). When testing this module should implement identity transform i.e. self.output = input. input: batch_size x n_feats output: batch_size x n_feats
class Dropout(Module): def __init__(self, p=0.5): super(Dropout, self).__init__() self.p = p self.mask = None def updateOutput(self, input): # Your code goes here. ################################################ if self.training: self.mask = np.random.binomial(1, self.p, size=len(input)) else: self.mask = np.ones(len(input)) self.mask = self.mask.reshape(len(self.mask), -1) self.output = np.multiply(input, self.mask) return self.output def updateGradInput(self, input, gradOutput): # Your code goes here. ################################################ self.gradInput = np.multiply(gradOutput, self.mask) return self.gradInput def __repr__(self): return "Dropout"
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
Implement Leaky Rectified Linear Unit. Expriment with slope.
class LeakyReLU(Module): def __init__(self, slope = 0.03): super(LeakyReLU, self).__init__() self.slope = slope def updateOutput(self, input): # Your code goes here. ################################################ self.output = input.copy() self.output[self.output < 0] *= self.slope return self.output def updateGradInput(self, input, gradOutput): # Your code goes here. ################################################ self.gradInput = gradOutput.copy() self.gradInput[input < 0] *= self.slope return self.gradInput def __repr__(self): return "LeakyReLU"
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
The MSECriterion, which is basic L2 norm usually used for regression, is implemented here for you.
class MSECriterion(Criterion): def __init__(self): super(MSECriterion, self).__init__() def updateOutput(self, input, target): self.output = np.sum(np.power(np.subtractact(input, target), 2)) / input.shape[0] return self.output def updateGradInput(self, input, target): self.gradInput = np.subtract(input, target) * 2 / input.shape[0] return self.gradInput def __repr__(self): return "MSECriterion"
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
You task is to implement the ClassNLLCriterion. It should implement multiclass log loss. Nevertheless there is a sum over y (target) in that formula, remember that targets are one-hot encoded. This fact simplifies the computations a lot. Note, that criterions are the only places, where you divide by batch size.
class ClassNLLCriterion(Criterion): def __init__(self): a = super(ClassNLLCriterion, self) super(ClassNLLCriterion, self).__init__() def updateOutput(self, input, target): # Use this trick to avoid numerical errors eps = 1e-15 input_clamp = np.clip(input, eps, 1 - eps) # Your code goes here. ################################################ self.output = -np.sum(np.multiply(target, np.log(input_clamp))) / len(input) return self.output def updateGradInput(self, input, target): # Use this trick to avoid numerical errors input_clamp = np.maximum(1e-15, np.minimum(input, 1 - 1e-15) ) # Your code goes here. ################################################ self.gradInput = np.subtract(input_clamp, target) / len(input) return self.gradInput def __repr__(self): return "ClassNLLCriterion"
hw5/hw1_Modules.ipynb
Boialex/MIPT-ML
gpl-3.0
So building and training Neural Networks in Python in simple! But it is also powerful! Neural Style Transfer: github.com/titu1994/Neural-Style-Transfer <font size=20> <table border="0"><tr> <td><img src="img/golden_gate.jpg" width=250></td> <td>+</td> <td><img src="img/starry_night.jpg" width=250></td> <td>=</td> <td><img src="img/golden_gate_iteration_20.png" width=250></td> </tr></table> </font> Neural Networks <!-- [Yann LeCun Slides](https://drive.google.com/folderview?id=0BxKBnD5y2M8NclFWSXNxa0JlZTg&usp=drive_web) ([local](pdf/000c-yann-lecun-lecon-inaugurale-college-de-france-20160204.pdf)) ![Intelligent Systems](img/LeCun_flight.png) --> <img src='img/LeCun_flight.png' align='middle' width=800> A neuron looks something like this Symbolically we can represent the key parts we want to model as In order to build an artifical "brain" we need to connect together many neurons in a "neural network" We can model the response of each neuron with various activation functions Training a Neural Network <!-- ![Perceptron Model](img/perceptron_node.png) --> <img src='img/perceptron_node.png' align='middle' width=400> Mathematically the activation of each neuron can be represented by where $W$ and $b$ are the weights and bias respectively. Loss Function <!-- ![Loss Function](img/loss_function.png) --> <img src='img/loss_function.png' width=800> Neural Networks in Python Keras High level library for specifying and training neural networks Can use Theano or TensorFlow as backend Keras makes Neural Networks awesome! Theano Python library that provides efficient (low-level) tools for working with Neural Networks In particular: Automatic Differentiation (AD) Compiled computation graphs GPU accelerated computation Tensorflow Deep Learning framework by Google The MNIST Dataset 70,000 handwritten digits 60,000 for training 10,000 for testing As 28x28 pixel images
from __future__ import absolute_import, print_function, division from ipywidgets import interact, interactive, widgets import numpy as np np.random.seed(1337) # for reproducibility
PyconZA-2016.ipynb
snth/ctdeep
mit
Let's load some data
from keras.datasets import mnist #(images_train, labels_train), (images_test, labels_test) = mnist.load_data() print("Data shapes:") print('images',images_train.shape) print('labels', labels_train.shape)
PyconZA-2016.ipynb
snth/ctdeep
mit
and then visualise it
%matplotlib inline import matplotlib import matplotlib.pyplot as plt def plot_mnist_digit(image, figsize=None): """ Plot a single MNIST image.""" fig = plt.figure() ax = fig.add_subplot(1, 1, 1) if figsize: ax.set_figsize(*figsize) ax.matshow(image, cmap = matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show() def plot_1_by_2_images(image, reconstruction, figsize=None): fig = plt.figure(figsize=figsize) ax = fig.add_subplot(1, 2, 1) ax.matshow(image, cmap = matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) ax = fig.add_subplot(1, 2, 2) ax.matshow(reconstruction, cmap = matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show() def plot_10_by_10_images(images, figsize=None): """ Plot 100 MNIST images in a 10 by 10 table. Note that we crop the images so that they appear reasonably close together. The image is post-processed to give the appearance of being continued.""" fig = plt.figure(figsize=figsize) #images = [image[3:25, 3:25] for image in images] #image = np.concatenate(images, axis=1) for x in range(10): for y in range(10): ax = fig.add_subplot(10, 10, 10*y+x+1) ax.matshow(images[10*y+x], cmap = matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show() def plot_10_by_20_images(left, right, figsize=None): """ Plot 100 MNIST images next to their reconstructions""" fig = plt.figure(figsize=figsize) for x in range(10): for y in range(10): ax = fig.add_subplot(10, 21, 21*y+x+1) ax.matshow(left[10*y+x], cmap = matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) ax = fig.add_subplot(10, 21, 21*y+11+x+1) ax.matshow(right[10*y+x], cmap = matplotlib.cm.binary) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.show() plot_10_by_10_images(images_train, figsize=(8,8)) def draw_image(i): plot_mnist_digit(images_train[i]) print('label:', labels_train[i]) interact(draw_image, i=(0, len(images_train)-1)) None
PyconZA-2016.ipynb
snth/ctdeep
mit
Data Preprocessing Transform "images" to "features" ... Most machine learning algorithms expect a flat array of numbers
def to_features(X): return X.reshape(-1, 784).astype("float32") / 255.0 def to_images(X): return (X*255.0).astype('uint8').reshape(-1, 28, 28) print('data shape:', images_train.shape, images_train.dtype) print('features shape', to_features(images_train).shape, to_features(images_train).dtype)
PyconZA-2016.ipynb
snth/ctdeep
mit
Split the data into a "training" and "test" set ...
#(images_train, labels_train), (images_test, labels_test) = mnist.load_data() X_train = to_features(images_train) X_test = to_features(images_test) print(X_train.shape, 'training samples') print(X_test.shape, 'test samples')
PyconZA-2016.ipynb
snth/ctdeep
mit
Transform the labels to a "one-hot" encoding ...
# The labels need to be transformed into class indicators from keras.utils import np_utils y_train = np_utils.to_categorical(labels_train, nb_classes=10) y_test = np_utils.to_categorical(labels_test, nb_classes=10) print('labels_train:', labels_train.shape, labels_train.dtype) print('y_train:', y_test.shape, y_train.dtype)
PyconZA-2016.ipynb
snth/ctdeep
mit
For example, let's inspect the first 2 labels:
print('labels_train[:2]:\n', labels_train[:2][:, np.newaxis]) print('y_train[:2]\n', y_train[:2])
PyconZA-2016.ipynb
snth/ctdeep
mit
Once the model is trained, we can evaluate its performance on the test data.
mlp.evaluate(X_test, y_test) #plot_10_by_10_images(images_test, figsize=(8,8)) def draw_mlp_prediction(j): plot_mnist_digit(to_images(X_test)[j]) prediction = mlp.predict_classes(X_test[j:j+1], verbose=False)[0] print('predict:', prediction, '\tactual:', labels_test[j]) interact(draw_mlp_prediction, j=(0, len(X_test)-1)) None
PyconZA-2016.ipynb
snth/ctdeep
mit
Deep Learning Why do we want Deep Neural Networks? Universal Approximation Theorem The theorem thus states that simple neural networks can represent a wide variety of interesting functions when given appropriate parameters; however, it does not touch upon the algorithmic learnability of those parameters. Power of combinations On the (Small) Number of Atoms in the Universe On the number of Go positions While <a href="https://www.theguardian.com/technology/2016/mar/09/google-deepmind-alphago-ai-defeats-human-lee-sedol-first-game-go-contest">discussing</a> the complexity of the game of Go, <a href="https://en.wikipedia.org/wiki/Demis_Hassabis">Demis Hassabis</a> said: <blockquote> <i>There are more possible Go positions than there are atoms in the universe.</i> </blockquote> A Go board has 19 &times; 19 points, each of which can be empty or occupied by black or white, so there are 3<sup>(19 &times; 19)</sup> <tt>&cong;</tt> 10<sup>172</sup> possible board positions, but "only" about 10<sup>170</sup> of those positions are legal. <p>The crucial idea is, that as a number of <i>physical things</i>, 10<sup>80</sup> is a really big number. But as a number of <i>combinations</i> of things, 10<sup>80</sup> is a rather small number. It doesn't take a universe of stuff to get up to 10<sup>80</sup> combinations; we can get there with, for example, a passphrase field that is 40 characters long: <blockquote id="passphrase"> <tt>a correct horse battery staple troubador</tt> </blockquote> ### On the number of digital pictures ### There is an art project to display every possible picture. Surely that would take a long time, because there must be many possible pictures. But how many? We will assume the color model known as True Color, in which each pixel can be one of 2^24 ≅ 17 million distinct colors. The digital camera shown below left has 12 million pixels, and we'll also consider much smaller pictures: the array below middle, with 300 pixels, and the array below right with just 12 pixels; shown are some of the possible pictures: <img src="img/norvig_atoms.png" align="center"> **Quiz: Which of these produces a number of pictures similar to the number of atoms in the universe?** **Answer: An array of n pixels produces (17 million)^n different pictures. (17 million)^12 ≅ 10^86, so the tiny 12-pixel array produces a million times more pictures than the number of atoms in the universe!** How about the 300 pixel array? It can produce 10^2167 pictures. You may think the number of atoms in the universe is big, but that's just peanuts to the number of pictures in a 300-pixel array. And 12M pixels? 10^86696638 pictures. Fuggedaboutit! So the number of possible pictures is really, really, really big. And the number of atoms in the universe is looking relatively small, at least as a number of combinations. ### ==> The Curse of Dimensionality! ### Feature Hierarchies <!-- ![Feature Hierarchy](img/feature_hierarchy.png) --> <img src="img/feature_hierarchy.png" width=800> # A Deeper MLP Next we build a two-layer MLP with the same number of hidden nodes, half in each layer.
from keras.models import Sequential nb_layers = 2 mlp2 = Sequential() # add hidden layers for i in range(nb_layers): mlp2.add(Dense(output_dim=nb_hidden//nb_layers, input_dim=nb_input if i==0 else nb_hidden//nb_layers, init='uniform')) mlp2.add(Activation('sigmoid')) # add output layer mlp2.add(Dense(output_dim=nb_output, input_dim=nb_hidden//nb_layers, init='uniform')) mlp2.add(Activation('softmax')) mlp2.compile(loss='categorical_crossentropy', optimizer='SGD', metrics=["accuracy"]) mlp2.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1)
PyconZA-2016.ipynb
snth/ctdeep
mit
Did you notice anything about the accuracy? Let's train it some more.
mlp2.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1) mlp2.evaluate(X_test, y_test)
PyconZA-2016.ipynb
snth/ctdeep
mit
Autoencoders Hinton 2006 (local)
from IPython.display import HTML HTML('<iframe src="pdf/Hinton2006-science.pdf" width=800 height=400></iframe>') from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout print('nb_input =', nb_input) print('nb_hidden =', nb_hidden) ae = Sequential() # encoder ae.add(Dense(nb_hidden, input_dim=nb_input, init='uniform')) ae.add(Activation('sigmoid')) # decoder ae.add(Dense(nb_input, input_dim=nb_hidden, init='uniform')) ae.add(Activation('sigmoid')) ae.compile(loss='mse', optimizer='SGD') nb_epoch = 1 ae.fit(X_train, X_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1) plot_10_by_20_images(images_test, to_images(ae.predict(X_test)), figsize=(10,5)) from keras.optimizers import SGD sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) ae.compile(loss='mse', optimizer=sgd) nb_epoch = 1 ae.fit(X_train, X_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1) plot_10_by_20_images(images_test, to_images(ae.predict(X_test)), figsize=(10,5)) def draw_ae_prediction(j): X_plot = X_test[j:j+1] prediction = ae.predict(X_plot, verbose=False) plot_1_by_2_images(to_images(X_plot)[0], to_images(prediction)[0]) interact(draw_ae_prediction, j=(0, len(X_test)-1)) None
PyconZA-2016.ipynb
snth/ctdeep
mit
A better Autoencoder
from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout def make_autoencoder(nb_input=nb_input, nb_hidden=nb_hidden, activation='sigmoid', init='uniform'): ae = Sequential() # encoder ae.add(Dense(nb_hidden, input_dim=nb_input, init=init)) ae.add(Activation(activation)) # decoder ae.add(Dense(nb_input, input_dim=nb_hidden, init=init)) ae.add(Activation(activation)) return ae nb_epoch = 1 ae2 = make_autoencoder(activation='sigmoid', init='glorot_uniform') ae2.compile(loss='mse', optimizer='adam') ae2.fit(X_train, X_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1) plot_10_by_20_images(images_test, to_images(ae2.predict(X_test)), figsize=(10,5)) def draw_ae2_prediction(j): X_plot = X_test[j:j+1] prediction = ae2.predict(X_plot, verbose=False) plot_1_by_2_images(to_images(X_plot)[0], to_images(prediction)[0]) interact(draw_ae2_prediction, j=(0, len(X_test)-1)) None
PyconZA-2016.ipynb
snth/ctdeep
mit
Stacked Autoencoder
from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout class StackedAutoencoder(object): def __init__(self, layers, mode='autoencoder', activation='sigmoid', init='uniform', final_activation='softmax', dropout=0.2, optimizer='SGD', metrics=None): self.layers = layers self.mode = mode self.activation = activation self.final_activation = final_activation self.init = init self.dropout = dropout self.optimizer = optimizer self.metrics = metrics self._model = None self.build() self.compile() def _add_layer(self, model, i, is_encoder): if is_encoder: input_dim, output_dim = self.layers[i], self.layers[i+1] activation = self.final_activation if i==len(self.layers)-2 else self.activation else: input_dim, output_dim = self.layers[i+1], self.layers[i] activation = self.activation model.add(Dense(output_dim=output_dim, input_dim=input_dim, init=self.init)) model.add(Activation(activation)) def build(self): self.encoder = Sequential() self.decoder = Sequential() self.autoencoder = Sequential() for i in range(len(self.layers)-1): self._add_layer(self.encoder, i, True) self._add_layer(self.autoencoder, i, True) #if i<len(self.layers)-2: # self.autoencoder.add(Dropout(self.dropout)) # Note that the decoder layers are in reverse order for i in reversed(range(len(self.layers)-1)): self._add_layer(self.decoder, i, False) self._add_layer(self.autoencoder, i, False) def compile(self): print("Compiling the encoder ...") self.encoder.compile(loss='categorical_crossentropy', optimizer=self.optimizer, metrics=self.metrics) print("Compiling the decoder ...") self.decoder.compile(loss='mse', optimizer=self.optimizer, metrics=self.metrics) print("Compiling the autoencoder ...") return self.autoencoder.compile(loss='mse', optimizer=self.optimizer, metrics=self.metrics) def fit(self, X_train, Y_train, batch_size, nb_epoch, verbose=1): result = self.autoencoder.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=verbose) # copy the weights to the encoder for i, l in enumerate(self.encoder.layers): l.set_weights(self.autoencoder.layers[i].get_weights()) for i in range(len(self.decoder.layers)): self.decoder.layers[-1-i].set_weights(self.autoencoder.layers[-1-i].get_weights()) return result def pretrain(self, X_train, batch_size, nb_epoch, verbose=1): for i in range(len(self.layers)-1): # Greedily train each layer print("Now pretraining layer {} [{}-->{}]".format(i+1, self.layers[i], self.layers[i+1])) ae = Sequential() self._add_layer(ae, i, True) #ae.add(Dropout(self.dropout)) self._add_layer(ae, i, False) ae.compile(loss='mse', optimizer=self.optimizer, metrics=self.metrics) ae.fit(X_train, X_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=verbose) # Then lift the training data up one layer print("\nTransforming data from", X_train.shape, "to", (X_train.shape[0], self.layers[i+1])) enc = Sequential() self._add_layer(enc, i, True) enc.compile(loss='mse', optimizer=self.optimizer, metrics=self.metrics) enc.layers[0].set_weights(ae.layers[0].get_weights()) enc.layers[1].set_weights(ae.layers[1].get_weights()) X_train = enc.predict(X_train, verbose=verbose) print("\nShape check:", X_train.shape, "\n") # Then copy the learned weights self.encoder.layers[2*i].set_weights(ae.layers[0].get_weights()) self.encoder.layers[2*i+1].set_weights(ae.layers[1].get_weights()) self.autoencoder.layers[2*i].set_weights(ae.layers[0].get_weights()) self.autoencoder.layers[2*i+1].set_weights(ae.layers[1].get_weights()) self.decoder.layers[-1-(2*i)].set_weights(ae.layers[-1].get_weights()) self.decoder.layers[-1-(2*i+1)].set_weights(ae.layers[-2].get_weights()) self.autoencoder.layers[-1-(2*i)].set_weights(ae.layers[-1].get_weights()) self.autoencoder.layers[-1-(2*i+1)].set_weights(ae.layers[-2].get_weights()) def evaluate(self, X_test, Y_test): return self.autoencoder.evaluate(X_test, Y_test) def predict(self, X, verbose=False): return self.autoencoder.predict(X, verbose=verbose) def _get_paths(self, name): model_path = "models/{}_model.yaml".format(name) weights_path = "models/{}_weights.hdf5".format(name) return model_path, weights_path def save(self, name='autoencoder'): model_path, weights_path = self._get_paths(name) open(model_path, 'w').write(self.autoencoder.to_yaml()) self.autoencoder.save_weights(weights_path, overwrite=True) def load(self, name='autoencoder'): model_path, weights_path = self._get_paths(name) self.autoencoder = keras.models.model_from_yaml(open(model_path)) self.autoencoder.load_weights(weights_path) nb_epoch = 3 sae = StackedAutoencoder(layers=[nb_input, 500, 150, 50, 10], activation='sigmoid', final_activation='softmax', init='uniform', dropout=0.25, optimizer='SGD') # replace with 'adam', 'relu', 'glorot_uniform' sae.fit(X_train, X_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1) plot_10_by_20_images(images_test, to_images(sae.predict(X_test)), figsize=(10,5)) def draw_sae_prediction(j): X_plot = X_test[j:j+1] prediction = sae.predict(X_plot, verbose=False) plot_1_by_2_images(to_images(X_plot)[0], to_images(prediction)[0]) print(sae.encoder.predict(X_plot, verbose=False)[0]) interact(draw_sae_prediction, j=(0, len(X_test)-1)) None sae.pretrain(X_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1)
PyconZA-2016.ipynb
snth/ctdeep
mit
Visualising the Filters
def visualise_filter(model, layer_index, filter_index): from keras import backend as K # build a loss function that maximizes the activation # of the nth filter on the layer considered layer_output = model.layers[layer_index].get_output() loss = K.mean(layer_output[:, filter_index]) # compute the gradient of the input picture wrt this loss input_img = model.layers[0].input grads = K.gradients(loss, input_img)[0] # normalization trick: we normalize the gradient grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) # this function returns the loss and grads given the input picture iterate = K.function([input_img], [loss, grads]) # we start from a gray image with some noise input_img_data = np.random.random((1,nb_input,)) # run gradient ascent for 20 steps step = 1 for i in range(100): loss_value, grads_value = iterate([input_img_data]) input_img_data += grads_value * step #print("Current loss value:", loss_value) if loss_value <= 0.: # some filters get stuck to 0, we can skip them break print("Current loss value:", loss_value) # decode the resulting input image if loss_value>0: #return input_img_data[0] return input_img_data else: raise ValueError(loss_value) def draw_filter(i): flt = visualise_filter(mlp, 3, 4) #print(flt) plot_mnist_digit(to_images(flt)[0]) interact(draw_filter, i=[0, 9])
PyconZA-2016.ipynb
snth/ctdeep
mit
But, did you know that they are both referring to the same 7 object? In other words, variables in Python are always references or pointers to data so the variables are not technically holding the value. Pointers are like phone numbers that "point at" phones but pointers themselves are not the phone itself. We can uncover this secret level of indirection using the built-in id(x) function that returns the physical memory address pointed out by x. To demonstrate that, let's ask what x and y point at:
x = y = 7 print(id(x)) print(id(y))
notes/aliasing.ipynb
parrt/msan501
mit
Wow! They are the same. That number represents the memory location where Python has stored the shared 7 object. Of course, as programmers we don't think of these atomic elements as referring to the same object; just keep in mind that they do. We are more likely to view them as copies of the same number, as lolviz shows visually:
from lolviz import * callviz(varnames=['x','y'])
notes/aliasing.ipynb
parrt/msan501
mit
Let's verify that the same thing happens for strings:
name = 'parrt' userid = name # userid now points at the same memory as name print(id(name)) print(id(userid))
notes/aliasing.ipynb
parrt/msan501
mit
Ok, great, so we are in fact sharing the same memory address to hold the string 'parrt' and both of the variable names point at that same shared space. We call this aliasing, in the language implementation business. Things only get freaky when we start changing shared data. This can't happen with integers and strings because they are immutable (can't be changed). Let's look at two identical copies of a single list:
you = [1,3,5] me = [1,3,5] print(id(you)) print(id(me)) callviz(varnames=['you','me'])
notes/aliasing.ipynb
parrt/msan501
mit
Those lists have the same value but live a different memory addresses. They are not aliased; they are not shared. Consequently, changing one does not change the other:
you = [1,3,5] me = [1,3,5] print(you, me) you[0] = 99 print(you, me)
notes/aliasing.ipynb
parrt/msan501
mit
On the other hand, let's see what happens if we make you and me share the same copy of the list (point at the same memory location):
you = [1,3,5] me = you print(id(you)) print(id(me)) print(you, me) callviz(varnames=['you','me'])
notes/aliasing.ipynb
parrt/msan501
mit
Now, changing one appears to change the other, but in fact both simply refer to the same location in memory:
you[0] = 99 print(you, me) callviz(varnames=['you','me'])
notes/aliasing.ipynb
parrt/msan501
mit
Don't confuse changing the pointer to the list with changing the list elements:
you = [1,3,5] me = you callviz(varnames=['you','me']) me = [9,7,5] # doesn't affect `you` at all print(you) print(me) callviz(varnames=['you','me'])
notes/aliasing.ipynb
parrt/msan501
mit
This aliasing of data happens a great deal when we pass lists or other data structures to functions. Passing list Quantity to a function whose argument is called data means that the two are aliased. We'll look at this in more detail in the "Visibility of symbols" section of Organizing your code with functions. Shallow copies
X = [[1,2],[3,4]] Y = X.copy() # shallow copy callviz(varnames=['X','Y']) X[0][1] = 99 callviz(varnames=['X','Y']) print(Y)
notes/aliasing.ipynb
parrt/msan501
mit
Feedforward Network 一樣有輸入 x, 輸出 y。 但是中間預測、計算的樣子有點不同。 <img src="https://upload.wikimedia.org/wikipedia/en/5/54/Feed_forward_neural_net.gif" /> 模型是這樣的 一樣考慮輸入是四維向量,輸出有 3 個類別。 我們的輸入 $x=\begin{pmatrix} x_0 \ x_1 \ x_2 \ x_3 \end{pmatrix} $ 是一個向量,我們看成 column vector 好了 第 0 層 而 Weight: $ W^{(0)} = \begin{pmatrix} W^{(0)}0 \ W^{(0)}_1 \ W^{(0)}_2 \ W^{(0)}_3 \ W^{(0)}_4 \ W^{(0)}_5 \end{pmatrix} = \begin{pmatrix} W^{(0)}{0,0} & W^{(0)}{0,1} & W^{(0)}{0,2} & W^{(0)}{0,3}\ W^{(0)}{0,0} & W^{(0)}{0,1} & W^{(0)}{0,2} & W^{(0)}{0,3}\ W^{(0)}{0,0} & W^{(0)}{0,1} & W^{(0)}{0,2} & W^{(0)}{0,3}\ W^{(0)}{0,0} & W^{(0)}{0,1} & W^{(0)}{0,2} & W^{(0)}{0,3}\ W^{(0)}{0,0} & W^{(0)}{0,1} & W^{(0)}{0,2} & W^{(0)}{0,3}\ W^{(0)}{0,0} & W^{(0)}{0,1} & W^{(0)}{0,2} & W^{(0)}_{0,3} \end{pmatrix} $ Bias: $b^{(0)}=\begin{pmatrix} b^{(0)}_0 \ b^{(0)}_1 \ b^{(0)}_2 \ b^{(0)}_3 \ b^{(0)}_4 \ b^{(0)}_5 \end{pmatrix} $ 我們先計算"線性輸出" $ c^{(0)} = \begin{pmatrix} c^{(0)}_0 \ c^{(0)}_1 \ c^{(0)}_2 \ c^{(0)}_3 \ c^{(0)}_4 \ c^{(0)}_5 \end{pmatrix} = W^{(0)}x+b^{(0)} = \begin{pmatrix} W^{(0)}_0 x + b^{(0)}_0 \ W^{(0)}_1 x + b^{(0)}_1 \ W^{(0)}_2 x + b^{(0)}_2 \ W^{(0)}_3 x + b^{(0)}_3 \ W^{(0)}_4 x + b^{(0)}_4 \ W^{(0)}_5 x + b^{(0)}_5 \end{pmatrix} $, 然後再將結果逐項對一個非線性的函數 $f$ 最後得到一個向量。 $d^{(0)} = \begin{pmatrix} d^{(0)}_0 \ d^{(0)}_1 \ d^{(0)}_2 \ d^{(0)}_3 \ d^{(0)}_4 \ d^{(0)}_5 \end{pmatrix} = f({W x + b}) = \begin{pmatrix} f(c^{(0)}_0) \ f(c^{(0)}_1) \ f(c^{(0)}_2) \ f(c^{(0)}_3) \ f(c^{(0)}_4) \ f(c^{(0)}_5) \end{pmatrix} $ 這裡的 $f$ 常常會用 sigmoid , tanh,或者 ReLU ( https://en.wikipedia.org/wiki/Activation_function )。 第 1 層 這裡接到輸出,其實和 softmax regression 一樣。 只是輸入變成 $d^{(0)}, Weight 和 Bias 現在叫做 W^{(1)} 和 b^{(1)} 因為維度改變,現在 W^{(1)} 是 3x6 的矩陣。 後面接到的輸出都一樣。 所以線性輸出 $ c^{(1)} = W^{(1)} d^{(0)} + b^{(1)} $ $ d^{(1)} = e^{c^{(1)}} $ 當輸入為 x, 最後的 softmax 預測類別是 i 的機率為 $q_i = Predict_{W^{(0)}, W^{(1)}, b^{(0)}, b^{(1)}}(Y=i|x) = \frac {d^{(1)}_i} {\sum_j d^{(1)}_j}$ 合起來看,就是 $q = \frac {d^{(1)}} {\sum_j d^{(1)}_j}$ 問題 我們簡化一下算式,如果 $W^{(0)}, W^{(1)}, b^{(0)}, b^{(1)}$ 設定為 $A, b, C, d$ (C, d 與前面無關),請簡化成為一個算式。 可以利用 softmax function 的符號 $\sigma (\mathbf {z} ){j}={\frac {e^{z{j}}}{\sum k e^{z{k}}}}$
# 參考答案 %run solutions/ff_oneline.py
Week11/DIY_AI/FeedForward-Forward Propagation.ipynb
tjwei/HackNTU_Data_2017
mit
任務:計算最後的猜測機率 $q$ 設定:輸入 4 維, 輸出 3 維, 隱藏層 6 維 * 設定一些權重 $A,b,C,d$ (隨意自行填入,或者用 np.random.randint(-2,3, size=...)) * 設定輸入 $x$ (隨意自行填入,或者用 np.random.randint(-2,3, size=...)) * 自行定義 relu, sigmoid 函數 (Hint: np.maximum) * 算出隱藏層 $z$ * 自行定義 softmax * 算出最後的 q
# 請在這裡計算 np.random.seed(1234) # 參考答案,設定權重 %run -i solutions/ff_init_variables.py display(A) display(b) display(C) display(d) display(x) # 參考答案 定義 relu, sigmoid 及計算 z %run -i solutions/ff_compute_z.py display(z_relu) display(z_sigmoid) # 參考答案 定義 softmax 及計算 q %run -i solutions/ff_compute_q.py display(q_relu) display(q_sigmoid)
Week11/DIY_AI/FeedForward-Forward Propagation.ipynb
tjwei/HackNTU_Data_2017
mit
練習 設計一個網路: * 輸入是二進位 0 ~ 15 * 輸出依照對於 3 的餘數分成三類
# Hint 下面產生數字 i 的 2 進位向量 i = 13 x = Vector(i%2, (i>>1)%2, (i>>2)%2, (i>>3)%2) x # 請在這裡計算 # 參考解答 %run -i solutions/ff_mod3.py
Week11/DIY_AI/FeedForward-Forward Propagation.ipynb
tjwei/HackNTU_Data_2017
mit
練習 設計一個網路來判斷井字棋是否有連成直線(只需要判斷其中一方即可): * 輸入是 9 維向量,0 代表空格,1 代表有下子 * 輸出是二維(softmax)或一維(sigmoid)皆可,用來代表 True, False 有連線的例子 ``` X X__ XXX XXX XX_ _XX X _XX X ``` 沒連線的例子 ``` XX_ X__ _XX X XX_ X_X __X XX _X ```
# 請在這裡計算 #參考答案 %run -i solutions/ff_tic_tac_toe.py # 測試你的答案 def my_result(x): # return 0 means no, 1 means yes return (C@relu(A@x+b)+d).argmax() # or sigmoid based # return (C@relu(A@x+b)+d) > 0 def truth(x): x = x.reshape(3,3) return (x.all(axis=0).any() or x.all(axis=1).any() or x.diagonal().all() or x[::-1].diagonal().all()) for i in range(512): x = np.array([[(i>>j)&1] for j in range(9)]) assert my_result(x) == truth(x) print("test passed")
Week11/DIY_AI/FeedForward-Forward Propagation.ipynb
tjwei/HackNTU_Data_2017
mit
Applications in Quantum Information Phase and Frequency Learning
>>> from qinfer import * >>> model = SimplePrecessionModel() >>> prior = UniformDistribution([0, 1]) >>> n_particles = 2000 >>> n_experiments = 100 >>> updater = SMCUpdater(model, n_particles, prior) >>> heuristic = ExpSparseHeuristic(updater) >>> true_params = prior.sample() >>> for idx_experiment in range(n_experiments): ... experiment = heuristic() ... datum = model.simulate_experiment(true_params, experiment) ... updater.update(datum, experiment) >>> print(updater.est_mean()) model = SimplePrecessionModel() prior = UniformDistribution([0, 1]) updater = SMCUpdater(model, 2000, prior) heuristic = ExpSparseHeuristic(updater) true_params = prior.sample() est_hist = [] for idx_experiment in range(100): experiment = heuristic() datum = model.simulate_experiment(true_params, experiment) updater.update(datum, experiment) est_hist.append(updater.est_mean()) plt.plot(est_hist, label='Est.') plt.hlines(true_params, 0, 100, label='True') plt.legend(ncol=2) plt.xlabel('# of Experiments Performed') plt.ylabel(r'$\omega$') paperfig('freq-est-updater-loop')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
State and Process Tomography
import matplotlib os.path.join(matplotlib.get_configdir(), 'stylelib') >>> from qinfer import * >>> from qinfer.tomography import * >>> basis = pauli_basis(1) # Single-qubit Pauli basis. >>> model = TomographyModel(basis) >>> prior = GinibreReditDistribution(basis) >>> updater = SMCUpdater(model, 8000, prior) >>> heuristic = RandomPauliHeuristic(updater) >>> true_state = prior.sample() >>> >>> for idx_experiment in range(500): >>> experiment = heuristic() >>> datum = model.simulate_experiment(true_state, experiment) >>> updater.update(datum, experiment) >>> >>> plt.figure(figsize=(4, 4)) >>> plot_rebit_posterior(updater, true_state=true_state, rebit_axes=[1, 3], legend=False, region_est_method='hull') >>> plt.legend(ncol=1, numpoints=1, scatterpoints=1, bbox_to_anchor=(1.9, 0.5), loc='right') >>> plt.xticks([-1, 0, 1]) >>> plt.yticks([-1, 0, 1]) >>> plt.xlabel(r'$\operatorname{Tr}(\sigma_x \rho)$') >>> plt.ylabel(r'$\operatorname{Tr}(\sigma_z \rho)$') >>> paperfig('rebit-tomo')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Randomized Benchmarking
>>> from qinfer import * >>> import numpy as np >>> p, A, B = 0.95, 0.5, 0.5 >>> ms = np.linspace(1, 800, 201).astype(int) >>> signal = A * p ** ms + B >>> n_shots = 25 >>> counts = np.random.binomial(p=signal, n=n_shots) >>> data = np.column_stack([counts, ms, n_shots * np.ones_like(counts)]) >>> mean, cov = simple_est_rb(data, n_particles=12000, p_min=0.8) >>> print(mean, np.sqrt(np.diag(cov))) from qinfer import * import numpy as np p, A, B = 0.95, 0.5, 0.5 ms = np.linspace(1, 800, 201).astype(int) signal = A * p ** ms + B n_shots = 25 counts = np.random.binomial(p=signal, n=n_shots) data = np.column_stack([counts, ms, n_shots * np.ones_like(counts)]) mean, cov, extra = simple_est_rb(data, n_particles=12000, p_min=0.8, return_all=True) fig, axes = plt.subplots(ncols=2, figsize=(8, 3)) plt.sca(axes[0]) extra['updater'].plot_posterior_marginal(range_max=1) plt.xlim(xmax=1) ylim = plt.ylim(ymin=0) plt.vlines(p, *ylim) plt.ylim(*ylim); plt.legend(['Posterior', 'True'], loc='upper left', ncol=1) plt.sca(axes[1]) extra['updater'].plot_covariance() paperfig('rb-simple-est')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Additional Functionality Derived Models
>>> from qinfer import * >>> import numpy as np >>> model = BinomialModel(SimplePrecessionModel()) >>> n_meas = 25 >>> prior = UniformDistribution([0, 1]) >>> updater = SMCUpdater(model, 2000, prior) >>> true_params = prior.sample() >>> for t in np.linspace(0.1,20,20): ... experiment = np.array([(t, n_meas)], dtype=model.expparams_dtype) ... datum = model.simulate_experiment(true_params, experiment) ... updater.update(datum, experiment) >>> print(updater.est_mean()) model = BinomialModel(SimplePrecessionModel()) n_meas = 25 prior = UniformDistribution([0, 1]) updater = SMCUpdater(model, 2000, prior) heuristic = ExpSparseHeuristic(updater) true_params = prior.sample() est_hist = [] for t in np.linspace(0.1, 20, 20): experiment = np.array([(t, n_meas)], dtype=model.expparams_dtype) datum = model.simulate_experiment(true_params, experiment) updater.update(datum, experiment) est_hist.append(updater.est_mean()) plt.plot(est_hist, label='Est.') plt.hlines(true_params, 0, 20, label='True') plt.legend(ncol=2) plt.xlabel('# of Times Sampled (25 measurements/ea)') plt.ylabel(r'$\omega$') paperfig('derived-model-updater-loop')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Time-Dependent Models
>>> from qinfer import * >>> import numpy as np >>> prior = UniformDistribution([0, 1]) >>> true_params = np.array([[0.5]]) >>> n_particles = 2000 >>> model = RandomWalkModel( ... BinomialModel(SimplePrecessionModel()), NormalDistribution(0, 0.01**2)) >>> updater = SMCUpdater(model, n_particles, prior) >>> t = np.pi / 2 >>> n_meas = 40 >>> expparams = np.array([(t, n_meas)], dtype=model.expparams_dtype) >>> for idx in range(1000): ... datum = model.simulate_experiment(true_params, expparams) ... true_params = np.clip(model.update_timestep(true_params, expparams)[:, :, 0], 0, 1) ... updater.update(datum, expparams) prior = UniformDistribution([0, 1]) true_params = np.array([[0.5]]) model = RandomWalkModel(BinomialModel(SimplePrecessionModel()), NormalDistribution(0, 0.01**2)) updater = SMCUpdater(model, 2000, prior) expparams = np.array([(np.pi / 2, 40)], dtype=model.expparams_dtype) data_record = [] trajectory = [] estimates = [] for idx in range(1000): datum = model.simulate_experiment(true_params, expparams) true_params = np.clip(model.update_timestep(true_params, expparams)[:, :, 0], 0, 1) updater.update(datum, expparams) data_record.append(datum) trajectory.append(true_params[0, 0]) estimates.append(updater.est_mean()[0]) ts = 40 * np.pi / 2 * np.arange(len(data_record)) / 1e3 plt.plot(ts, trajectory, label='True') plt.plot(ts, estimates, label='Estimated') plt.xlabel(u'$t$ (µs)') plt.ylabel(r'$\omega$ (GHz)') plt.legend(ncol=2) paperfig('time-dep-rabi')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Performance and Robustness Testing
performance = perf_test_multiple( # Use 100 trials to estimate expectation over data. 100, # Use a simple precession model both to generate, # data, and to perform estimation. SimplePrecessionModel(), # Use 2,000 particles and a uniform prior. 2000, UniformDistribution([0, 1]), # Take 50 measurements with $t_k = ab^k$. 50, ExpSparseHeuristic ) # Calculate the Bayes risk by taking a mean over the trial index. risk = np.mean(performance['loss'], axis=0) plt.semilogy(risk) plt.xlabel('# of Experiments Performed') plt.ylabel('Bayes Risk') paperfig('bayes-risk')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Parallelization Here, we demonstrate parallelization with ipyparallel and the DirectViewParallelizedModel model. First, create a model which is not designed to be useful, but rather to be expensive to evaluate a single likelihood.
class ExpensiveModel(FiniteOutcomeModel): """ The likelihood of this model randomly generates a dim-by-dim conjugate-symmetric matrix for every expparam and modelparam, exponentiates it, and returns the overlap with the |0> state. """ def __init__(self, dim=36): super(ExpensiveModel, self).__init__() self.dim=dim @property def n_modelparams(self): return 2 @property def expparams_dtype(self): return 'float' def n_outcomes(self, expparams): return 2 def are_models_valid(self, mps): return np.ones(mps.shape).astype(bool) def prob(self): # random symmetric matrix mat = np.random.rand(self.dim, self.dim) mat += mat.T # and exponentiate resulting square matrix mat = expm(1j * mat) # compute overlap with |0> state return np.abs(mat[0,0])**2 def likelihood(self, outcomes, mps, eps): # naive for loop. pr0 = np.empty((mps.shape[0], eps.shape[0])) for idx_eps in range(eps.shape[0]): for idx_mps in range(mps.shape[0]): pr0[idx_mps, idx_eps] = self.prob() # compute the prob of each outcome by taking pr0 or 1-pr0 return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Now, we can use Jupyter's %timeit magic to see how long it takes, for example, to compute the likelihood 5x1000x10=50000 times.
emodel = ExpensiveModel(dim=16) %timeit -q -o -n1 -r1 emodel.likelihood(np.array([0,1,0,0,1]), np.zeros((1000,1)), np.zeros((10,1)))
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Next, we initialize the Client which communicates with the parallel processing engines. In the accompaning paper, this code was run on a single machine with dual "Intel(R) Xeon(R) CPU X5675 @ 3.07GHz" processors, for a total of 12 physical cores, and therefore, 24 engines were online.
# Do not demand that ipyparallel be installed, or ipengines be running; # instead, fail silently. run_parallel = True try: from ipyparallel import Client import dill rc = Client() # set profile here if desired dview = rc[:] dview.execute('from qinfer import *') dview.execute('from scipy.linalg import expm') print("Number of engines available: {}".format(len(dview))) except: run_parallel = False print('Parallel Engines or libraries could not be initialized; Parallel section will not be evaluated.')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Finally, we run the parallel tests, looping over different numbers of engines used.
if run_parallel: par_n_particles = 5000 par_test_outcomes = np.array([0,1,0,0,1]) par_test_modelparams = np.zeros((par_n_particles, 1)) # only the shape matters par_test_expparams = np.zeros((10, 1)) # only the shape matters def compute_L(model): model.likelihood(par_test_outcomes, par_test_modelparams, par_test_expparams) serial_time = %timeit -q -o -n1 -r1 compute_L(emodel) serial_time = serial_time.all_runs[0] n_engines = np.arange(2,len(dview)+1,2) par_time = np.zeros(n_engines.shape[0]) for idx_ne, ne in enumerate(n_engines): dview_test = rc[:ne] dview_test.use_dill() par_model = DirectViewParallelizedModel(emodel, dview_test, serial_threshold=1) result = %timeit -q -o -n1 -r1 compute_L(par_model) par_time[idx_ne] = result.all_runs[0]
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
And plot the results.
if run_parallel: fig = plt.figure() plt.plot(np.concatenate([[1], n_engines]), np.concatenate([[serial_time], par_time])/serial_time,'-o') ax = plt.gca() ax.set_xscale('log', basex=2) ax.set_yscale('log', basey=2) plt.xlim([0.8, np.max(n_engines)+2]) plt.ylim([2**-4,1.2]) plt.xlabel('# Engines') plt.ylabel('Normalized Computation Time') par_xticks = [1,2,4,8,12,16,24] ax.set_xticks(par_xticks) ax.set_xticklabels(par_xticks) paperfig('parallel-likelihood')
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
Appendices Custom Models
from qinfer import FiniteOutcomeModel import numpy as np class MultiCosModel(FiniteOutcomeModel): @property def n_modelparams(self): return 2 @property def is_n_outcomes_constant(self): return True def n_outcomes(self, expparams): return 2 def are_models_valid(self, modelparams): return np.all(np.logical_and(modelparams > 0, modelparams <= 1), axis=1) @property def expparams_dtype(self): return [('ts', 'float', 2)] def likelihood(self, outcomes, modelparams, expparams): super(MultiCosModel, self).likelihood(outcomes, modelparams, expparams) pr0 = np.empty((modelparams.shape[0], expparams.shape[0])) w1, w2 = modelparams.T t1, t2 = expparams['ts'].T for idx_model in range(modelparams.shape[0]): for idx_experiment in range(expparams.shape[0]): pr0[idx_model, idx_experiment] = ( np.cos(w1[idx_model] * t1[idx_experiment] / 2) * np.cos(w2[idx_model] * t2[idx_experiment] / 2) ) ** 2 return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0) >>> mcm = MultiCosModel() >>> modelparams = np.dstack(np.mgrid[0:1:100j,0:1:100j]).reshape(-1, 2) >>> expparams = np.empty((81,), dtype=mcm.expparams_dtype) >>> expparams['ts'] = np.dstack(np.mgrid[1:10,1:10] * np.pi / 2).reshape(-1, 2) >>> D = mcm.simulate_experiment(modelparams, expparams, repeat=2) >>> print(isinstance(D, np.ndarray)) True >>> D.shape == (2, 10000, 81) True
qinfer-1.0-paper.ipynb
QInfer/qinfer-examples
agpl-3.0
12. Cleanup BigQuery artifacts This notebook helps to clean up interim tables generated while executing notebooks from 01 to 09. Import required modules
# Add custom utils module to Python environment. import os import sys sys.path.append(os.path.abspath(os.pardir)) from google.cloud import bigquery from utils import helpers
packages/propensity/12.cleanup.ipynb
google/compass
apache-2.0
Set parameters
# Get GCP configurations. configs = helpers.get_configs('config.yaml') dest_configs = configs.destination # GCP project ID where queries and other computation will be run. PROJECT_ID = dest_configs.project_id # BigQuery dataset name to store query results (if needed). DATASET_NAME = dest_configs.dataset_name
packages/propensity/12.cleanup.ipynb
google/compass
apache-2.0
List all tables in the BigQuery Dataset
# Initialize BigQuery Client. bq_client = bigquery.Client() all_tables = [] for table in bq_client.list_tables(DATASET_NAME): all_tables.append(table.table_id) print(all_tables)
packages/propensity/12.cleanup.ipynb
google/compass
apache-2.0
Remove list of tables Select table names from the printed out list in above cell.
# Define specific tables to remove from the dataset. tables_to_delete = ['table1', 'table2'] # Or uncomment below to remove all tables in the dataset. # tables_to_delete = all_tables # Remove tables from BigQuery dataset. for table_id in tables_to_delete: bq_client.delete_table(f'{PROJECT_ID}.{DATASET_NAME}.{table_id}')
packages/propensity/12.cleanup.ipynb
google/compass
apache-2.0
Normally, I would just write %run Stack.ipynb here. As this does not work in Deepnote, I have included the implementation of the class Stack here.
class Stack: def __init__(self): self.mStackElements = [] def push(self, e): self.mStackElements.append(e) def pop(self): assert len(self.mStackElements) > 0, "popping empty stack" self.mStackElements = self.mStackElements[:-1] def top(self): assert len(self.mStackElements) > 0, "top of empty stack" return self.mStackElements[-1] def isEmpty(self): return self.mStackElements == [] def copy(self): C = Stack() C.mStackElements = self.mStackElements[:] return C def __str__(self): C = self.copy() result = C._convert() return result def _convert(self): if self.isEmpty(): return '|' t = self.top() self.pop() return self._convert() + ' ' + str(t) + ' |' def createStack(L): S = Stack() n = len(L) for i in range(n): S.push(L[i]) return S
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{toFloat}(s)$ tries to convert the string $s$ to a floating point number. If this works out, this number is returned. Otherwise, the string $s$ is returned unchanged.
def toFloat(s): try: return float(s) except ValueError: return s toFloat('0.123') toFloat('+')
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The module re provides support for <a href='https://en.wikipedia.org/wiki/Regular_expression'>regular expressions</a>. These are needed for <em style="color:blue;">tokenizing</em> a string. The function $\texttt{tokenize}(s)$ takes a string and splits this string into a list of tokens. Whitespace is discarded.
def tokenize(s): regExp = r''' 0|[1-9][0-9]* | # integer (?:0|[1-9][0-9])+[.][0-9]+ | # floating point number \*\* | # power operator [-+*/()] | # arithmetic operators and parentheses [ \t] | # white space sqrt | # square root sin | # sine function cos | # cosine function tan | # tangent function asin | # arcus sine acos | # arcus cosine atan | # arcus tangent exp | # exponential function log | # natural logarithm x | # variable e | # Euler's number pi # π ''' L = [toFloat(t) for t in re.findall(regExp, s, flags=re.VERBOSE) if not isWhiteSpace(t)] return list(reversed(L)) tokenize('x**2 - 2')
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{findZero}(f, a, b, n)$ takes a function $f$ and two numbers $a$ and $b$ such that $a < b$, $f(a) \leq 0$, and $0 \leq f(b)$. It uses the bisection method to find a number $x \in [a, b]$ such that $f(x) \approx 0$.
def findZero(f, a, b, n): assert a < b , f'{a} has to be less than b' assert f(a) * f(b) <= 0, f'f({a}) * f({b}) > 0' if f(a) <= 0 <= f(b): for k in range(n): c = 0.5 * (a + b) # print(f'f({c}) = {f(c)}, {b-a}') if f(c) < 0: a = c elif f(c) > 0: b = c else: return c else: for k in range(n): c = 0.5 * (a + b) # print(f'f({c}) = {f(c)}, {b-a}') if f(c) > 0: a = c elif f(c) < 0: b = c else: return c return (a + b) / 2 def f(x): return 2 - x ** 2 r = findZero(f, 0, 2, 54) r r * r
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{precedence}(o)$ calculates the precedence of the operator $o$.
def precedence(op): "your code here" assert False, f'unkown operator in precedence: {op}'
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{isConstOperator}(o)$ returns True of $o$ is a constant like eor pi. The variable x is also considered as a constant operator.
def isConstOperator(op): "your code here"
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{isLeftAssociative}(o)$ returns True of $o$ is left associative.
def isLeftAssociative(op): "your code here" assert False, f'unkown operator in isLeftAssociative: {op}'
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{evalBefore}(o_1, o_2)$ receives to strings representing arithmetical operators. It returns True if the operator $o_1$ should be evaluated before the operator $o_2$ in an arithmetical expression of the form $a \;\texttt{o}_1\; b \;\texttt{o}_2\; c$. In order to determine whether $o_1$ should be evaluated before $o_2$ it uses the <em style="color:blue">precedence</em> and the <em style="color:blue">associativity</em> of the operators. Its behavior is specified by the following rules: - $\texttt{precedence}(o_1) > \texttt{precedence}(o_2) \rightarrow \texttt{evalBefore}(\texttt{o}_1, \texttt{o}_2) = \texttt{True}$, - $o_1 = o_2 \wedge \neg\texttt{isUnaryOperator}(o_1)\rightarrow \texttt{evalBefore}(\texttt{o}_1, \texttt{o}_2) = \texttt{isLeftAssociative}(o_1)$, - $\texttt{isUnaryOperator}(o_1) \wedge \texttt{isUnaryOperator}(o_2) \rightarrow \texttt{evalBefore}(\texttt{o}_1, \texttt{o}_2) = \texttt{False}$, - $\texttt{precedence}(o_1) = \texttt{precedence}(o_2) \wedge o_1 \not= o_2 \wedge \neg\texttt{isUnaryOperator}(o_1) \rightarrow \texttt{evalBefore}(\texttt{o}_1, \texttt{o}_2) = \texttt{True}$, - $\texttt{precedence}(o_1) < \texttt{precedence}(o_2) \rightarrow \texttt{evalBefore}(\texttt{o}_1, \texttt{o}_2) = \texttt{False}$.
def evalBefore(stackOp, nextOp): "your code here" assert False, f'incomplete case distinction in evalBefore({stackOp}, {nextOp})'
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The class Calculator supports three member variables: - the token stack mTokens, - the operator stack mOperators, - the argument stack mArguments, - the floating point number mValue, which is the current value of x. The constructor takes a list of tokens TL and initializes the token stack with these tokens.
class Calculator: def __init__(self, TL, x): self.mTokens = createStack(TL) self.mOperators = Stack() self.mArguments = Stack() self.mValue = x
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The method __str__ is used to convert an object of class Calculator to a string.
def toString(self): return '\n'.join(['_'*50, 'TokenStack: ' + str(self.mTokens), 'Arguments: ' + str(self.mArguments), 'Operators: ' + str(self.mOperators), '_'*50]) Calculator.__str__ = toString del toString
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function $\texttt{evaluate}(\texttt{self})$ evaluates the expression that is given by the tokens on the mTokenStack. There are two phases: 1. The first phase is the <em style="color:blue">reading phase</em>. In this phase the tokens are removed from the token stack mTokens. 2. The second phase is the <em style="color:blue">evaluation phase</em>. In this phase, the remaining operators on the operator stack mOperators are evaluated. Note that some operators are already evaluated in the reading phase. We can describe what happens in the reading phase using <em style="color:blue">rewrite rules</em> that describe how the three stacks mTokens, mArguments and mOperators are changed in each step. Here, a step is one iteration of the first while-loop of the function evaluate. The following rewrite rules are executed until the token stack mTokens is empty. 1. If the token on top of the token stack is an integer, it is removed from the token stack and pushed onto the argument stack. The operator stack remains unchanged in this case. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [\texttt{token} ] & \wedge \ \texttt{isInteger}(\texttt{token}) & \Rightarrow \[0.2cm] \texttt{mArguments}' = \texttt{mArguments} + [\texttt{token}] & \wedge \ \texttt{mTokens}' = \texttt{mTokensRest} & \wedge \ \texttt{mOperators}' = \texttt{mOperators} \end{array} $$ Here, the primed variable $\texttt{mArguments}'$ refers to the argument stack after $\texttt{token}$ has been pushed onto it. In the following rules we implicitly assume that the token on top of the token stack is not an integer but rather a parenthesis or a proper operator. In order to be more concise, we suppress this precondition from the following rewrite rules. 2. If the operator stack is empty, the next token is pushed onto the operator stack. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [\texttt{op} ] & \wedge \ \texttt{mOperators} = [] & \Rightarrow \[0.2cm] \texttt{mOperators}' = \texttt{mOperators} + [\texttt{op}] & \wedge \ \texttt{mTokens}' = \texttt{mTokensRest} & \wedge \ \texttt{mArguments}' = \texttt{mArguments} \end{array} $$ 3. If the next token is an opening parenthesis, this parenthesis token is pushed onto the operator stack. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [\texttt{'('} ] & \Rightarrow \[0.2cm] \texttt{mOperators}' = \texttt{mOperators} + [\texttt{'('}] & \wedge \ \texttt{mTokens}' = \texttt{mTokensRest} & \wedge \ \texttt{mArguments}' = \texttt{mArguments} \end{array} $$ 4. If the next token is a closing parenthesis and the operator on top of the operator stack is an opening parenthesis, then both parentheses are removed. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [\texttt{')'} ] & \wedge \ \texttt{mOperators} =\texttt{mOperatorsRest} + [\texttt{'('}] & \Rightarrow \[0.2cm] \texttt{mOperators}' = \texttt{mOperatorsRest} & \wedge \ \texttt{mTokens}' = \texttt{mTokensRest} & \wedge \ \texttt{mArguments}' = \texttt{mArguments} \end{array} $$ 5. If the next token is a closing parenthesis but the operator on top of the operator stack is not an opening parenthesis, the operator on top of the operator stack is evaluated. Note that the token stack is not changed in this case. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [\texttt{')'} ] & \wedge \ \texttt{mOperatorsRest} + [\texttt{op}] & \wedge \ \texttt{op} \not= \texttt{'('} & \wedge \ \texttt{mArguments} = \texttt{mArgumentsRest} + [\texttt{lhs}, \texttt{rhs}] & \Rightarrow \[0.2cm] \texttt{mOperators}' = \texttt{mOperatorsRest} & \wedge \ \texttt{mTokens}' = \texttt{mTokens} & \wedge \ \texttt{mArguments}' = \texttt{mArgumentsRest} + [\texttt{lhs} \;\texttt{op}\; \texttt{rhs}] \end{array} $$ Here, the expression $\texttt{lhs} \;\texttt{op}\; \texttt{rhs}$ denotes evaluating the operator $\texttt{op}$ with the arguments $\texttt{lhs}$ and $\texttt{rhs}$. 6. If the token on top of the operator stack is an opening parenthesis, then the operator on top of the token stack is pushed onto the operator stack. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [\texttt{op}] & \wedge \ \texttt{op} \not= \texttt{')'} & \wedge \ \texttt{mOperators} = \texttt{mOperatorsRest} + [\texttt{'('}] & \Rightarrow \[0.2cm] \texttt{mOperator}' = \texttt{mOperator} + [\texttt{op}] & \wedge \ \texttt{mTokens}' = \texttt{mTokensRest} & \wedge \ \texttt{mArguments}' = \texttt{mArguments} \end{array} $$ In the remaining cases neither the token on top of the token stack nor the operator on top of the operator stack can be a parenthesis. The following rules will implicitly assume that this is the case. 7. If the operator on top of the operator stack needs to be evaluated before the operator on top of the token stack, the operator on top of the operator stack is evaluated. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [o_2] & \wedge \ \texttt{mOperatorsRest} + [o_1] & \wedge \ \texttt{evalBefore}(o_1, o_2) & \wedge \ \texttt{mArguments} = \texttt{mArgumentsRest} + [\texttt{lhs}, \texttt{rhs}] & \Rightarrow \[0.2cm] \texttt{mOperators}' = \texttt{mOperatorRest} & \wedge \ \texttt{mTokens}' = \texttt{mTokens} & \wedge \ \texttt{mArguments}' = \texttt{mArgumentsRest} + [\texttt{lhs} \;o_1\; \texttt{rhs}] \end{array} $$ 8. Otherwise, the operator on top of the token stack is pushed onto the operator stack. $$\begin{array}{lc} \texttt{mTokens} = \texttt{mTokensRest} + [o_2] & \wedge \ \texttt{mOperators} = \texttt{mOperatorsRest} + [o_1] & \wedge \ \neg \texttt{evalBefore}(o_1, o_2) & \Rightarrow \[0.2cm] \texttt{mOperators}' = \texttt{mOperators} + [o_2] & \wedge \ \texttt{mTokens}' = \texttt{mTokensRest} & \wedge \ \texttt{mArguments}' = \texttt{mArguments} \end{array} $$ In every step of the evaluation phase we - remove one operator from the operator stack, - remove its arguments from the argument stack, - evaluate the operator, and - push the result back on the argument stack.
def evaluate(self): "your code here" return self.mArguments.top() Calculator.evaluate = evaluate del evaluate
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The method $\texttt{popAndEvaluate}(\texttt{self})$ removes an operator from the operator stack and removes the corresponding arguments from the arguments stack. It evaluates the operator and pushes the result on the argument stack.
def popAndEvaluate(self): "your code here" Calculator.popAndEvaluate = popAndEvaluate del popAndEvaluate
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function testEvaluateExpr takes three arguments: - s is a string that can be interpreted as an arithmetic expression. This string might contain the variable $x$. In this arithmetic expression, unary function symbols need not be be followed by parenthesis. - t is a string that contains an arithmetic expression. The syntax of this expression has to follow the rules of the programming language python. - x is a floating point value. This value is supposed to be the value of the variable $x$ that might occur in s and t. The function evaluates susing the class Calculator, while t is evaluated using the predefined function eval. If the results differ, an exception is raised.
def testEvaluateExpr(s, t, x): TL = tokenize(s) C = Calculator(TL, x) r1 = C.evaluate() r2 = eval(t, { 'math': math }, { 'x': x }) assert r1 == r2, f'{r1} != {r2}' testEvaluateExpr('sin cos x', 'math.sin(math.cos(x))', 0) testEvaluateExpr('sin x**2', 'math.sin(math.pi)**2', math.pi) testEvaluateExpr('log e ** x + 1 * 2 - 3', 'math.log(math.e**x) + 1 * 2 - 3 ', 1)
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The function computeZero takes three arguments: * s is a string that can be interpreted as a function $f$ of the variable x. For example, s could be equal to 'x * x - 2.0'. * left and right are floating point numbers. It is required that the function $f$ changes signs in the interval $[\texttt{left}, \texttt{right}]$. Then computeZero returns a floating point value $x_0$ such that $f(x_0) \approx 0$.
def computeZero(s, left, right): TL = tokenize(s) def f(x): c = Calculator(TL, x) return c.evaluate() return findZero(f, left, right, 54);
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
The cell below should output the number 0.7390851332151607.
computeZero('log exp x - cos(sqrt(x**2))', 0, 1)
Python/Chapter-06/Calculator-Frame.ipynb
karlstroetmann/Algorithms
gpl-2.0
Find maximum derivative of dispersion_difference_function over a range. This could be used as a bound for $\epsilon$ to guarantee results.
def find_max_der(expression,symbol,input_range): expr_der = sp.diff(expression,symbol) expr_def_func = ufuncify([symbol],expr_der) return max(abs(expr_def_func(input_range))) ## Apply the triangle inequality over a range of nus nus = np.asarray([6.+ i*5e-2 for i in range(1+int(1e3))]) max_derivative = sum([find_max_der(exp,om,nus) for om,exp in zip([nu1,nu2,nu3],expressions)]) max_derivative
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Methods for systematic search over ranges Definitions: base -- The number base to use, i.e. the factor to increase the grid resolution at each step. starting_i -- index of starting step. 0 means we use a grid of size base by base. max_i -- final index. eps -- desired resolution at step max_i Description To look for solutions more efficiently, we can recursively enhance the resolution of the grid in which we are looking. At each step, decrease the cutoff eps_current by some factor (for now let's make it base). For the set of voxels in each step that are close enough to a solution of the equation, increase the resolution by a factor of base and examine the resulting smaller voxels. Continue until the last step.
eps = 0.00002 starting_i = 0 max_i = 4 base = 10 min_value = 6. max_value = 20. @timeit def setup_ranges(max_i,base): ranges= {} for i in range(max_i+1): ranges[i] = np.linspace(min_value,max_value,1+pow(base,i+1)) return ranges
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Note: How to obtain the index of $\nu_3$.
i = 2 1+pow(base,i+1) np.linspace(min_value,max_value,1+pow(base,i+1)) spacing = (max_value-min_value)/ pow(base,i+1) spacing num_indices_from_zero = min_value / spacing num_indices_from_zero ranges[i] sample_index = solution_containing_voxels[2].keys()[1000] sample_index ranges[2][(sum(sample_index)+int(num_indices_from_zero))]
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Main methods used
@timeit def initial_voxels(max_i,base,starting_i,eps): solution_containing_voxels = {} eps_current = eps * pow(base,max_i-starting_i) solution_containing_voxels[starting_i] = {} for i1,om1 in enumerate(ranges[starting_i]): for i2,om2 in enumerate(ranges[starting_i]): err = k_of_nu1_nu2(om1,om2) if abs(err) < eps_current: solution_containing_voxels[starting_i][i1,i2] = err return solution_containing_voxels @timeit def add_high_res_voxels(max_i,base,starting_i,eps,solution_containing_voxels): for i in range(starting_i+1,max_i+1): eps_current = eps * pow(base,max_i-i) solution_containing_voxels[i] = {} for (i1,i2) in solution_containing_voxels[i-1]: step_size = int(base/2) max_length = pow(base,i+1) for i1_new in range(max(0,i1*base-step_size),min(max_length,i1*base+step_size+1)): for i2_new in range(max(0,i2*base-step_size),min(max_length,i2*base+step_size+1)): err = k_of_nu1_nu2(ranges[i][i1_new],ranges[i][i2_new]) if abs(err) < eps_current: solution_containing_voxels[i][i1_new,i2_new] = err @timeit def plot_voxels(solution_containing_voxels,i): voxels = np.zeros((1+pow(base,i+1),1+pow(base,i+1))) for (i1,i2) in solution_containing_voxels[i]: voxels[i1,i2] = 1 plot_arr(voxels) def voxel_solutions(ranges,k_of_nu1_nu2,max_i,base,starting_i,eps): solution_containing_voxels = initial_voxels(ranges,k_of_nu1_nu2,max_i, base,starting_i,eps) add_high_res_voxels(ranges,k_of_nu1_nu2,max_i,base,starting_i,eps, solution_containing_voxels) return solution_containing_voxels ranges = setup_ranges(max_i,base) solution_containing_voxels = initial_voxels(max_i,base,starting_i,eps) add_high_res_voxels(max_i,base,starting_i,eps,solution_containing_voxels) plot_voxels(solution_containing_voxels,0) plot_voxels(solution_containing_voxels,1) plot_voxels(solution_containing_voxels,2) ## Number of solutions found for each resolution: for i in range(0,5): print len(solution_containing_voxels[i]) ## Number of solutions found for each resolution: plt.title('Number of voxels per step') plt.semilogy([(len(solution_containing_voxels[i])) for i in range(0,max_i)])
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Different bases comparison Base 10
eps = 0.006 starting_i = 0 max_i = 2 base = 10 ## maximum grid length: 1+pow(base,max_i+1) ranges = setup_ranges(max_i,base) solution_containing_voxels = initial_voxels(max_i,base,starting_i,eps) add_high_res_voxels(max_i,base,starting_i,eps,solution_containing_voxels) ## Number of solutions found for each resolution: for i in range(0,max_i+1): print len(solution_containing_voxels[i]) ## Number of solutions found for each resolution: plt.title('Number of voxels per step') plt.semilogy([(len(solution_containing_voxels[i])) for i in range(0,max_i+1)]) plot_voxels(solution_containing_voxels,max_i)
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Base 2
eps = 0.006 starting_i = 0 max_i = 9 base = 2 ## maximum grid length: 1+pow(base,max_i+1) ranges = setup_ranges(max_i,base) solution_containing_voxels = initial_voxels(max_i,base,starting_i,eps) add_high_res_voxels(max_i,base,starting_i,eps,solution_containing_voxels) ## Number of solutions found for each resolution: for i in range(0,max_i+1): print len(solution_containing_voxels[i]) ## Number of solutions found for each resolution: plt.title('Number of voxels per step') plt.semilogy([(len(solution_containing_voxels[i])) for i in range(0,max_i+1)]) plot_voxels(solution_containing_voxels,max_i)
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Discussion The number of solution voxels increases by a factor of base at each step. This happens because the function being optimize is close to linear near the solutions and because we decrease eps_current by a factor of base at each step. As a result, the total number of voxels increases by a factor of base**2 at each step, but the thickness of the solution voxel surface decreases by a factor of base. The cost of the algorithm is dominated by the last step. This is because the number of voxels increases approximately by a factor of base at each step, and the computational cost at each step is the number of voxels from the previous step multiplied by base**2. As such, the algorithm runtime is essentially the number of solution points. Notice in the above experiments the runtime was similar for different bases used. A more careful analysis assuming a large number of points and the scaling described above gives a geometric series for the runtime, where the sum starts at the last step ($b$ stands for base and $p$ stands for number of points): \begin{align} b^2(\frac{p}{b} + \frac{p}{b^2} + ...) = p\left( b + 1 + \frac{1}{b} + ...\right) \approx \frac{pb^2}{b-1}. \end{align} The other factor contributing to the runtime is breaking away from the scaling law in the above discussion. Using the same technique for $\chi^{(3)}$. Let's extend the above search technique to using four-wave mixing. The problems here will be larger, so runtime may be more important. For this reason, I tested different values of epsilon at each stage. Using a smaller epsilon will improve the runtime, but may miss correct solutions. Compare the number of solutions and runtime to the methods used in the notebook Dispersion_relation_two_approaches. The complexity is essentially linear in the number of solutions, but here the constant factor may be large if epsilon is not chosen carefully at each step. For this reason one may prefer to use the other techniques for $\chi^{(3)}$ problems. The number of solutions in the method below converges to the number of solutions using the other two methods.
eps = 2e-4 starting_i = 0 max_i = 1 base = 10 relative_scalings = [4,4,10] phi1_min = 30. phi1_max = 34. ranges1 = {} for i in range(0,2): ranges1[i] = np.linspace(phi1_min,phi1_max,relative_scalings[0]*pow(base,i+1)+1) phi2_min = -13 phi2_max = -9 ranges2 = {} for i in range(0,2): ranges2[i] = np.linspace(phi2_min,phi2_max,relative_scalings[1]*pow(base,i+1)+1) nu3_min = -26. nu3_max = -16. ranges3 = {} for i in range(0,2): ranges3[i] = np.linspace(nu3_min,nu3_max,relative_scalings[2]*pow(base,i+1)+1) print len(ranges1[1]),len(ranges2[1]),len(ranges3[1]) phi1, phi2 = sp.symbols('phi_1 phi_2') ex1 = (k_symb(nu1,pol='e')+k_symb(nu2,pol='e')).expand().subs({nu1:(phi1 + phi2)/2, nu2: (phi1-phi2)/2}) ex2 = -(k_symb(nu3,pol='e')+k_symb(nu4,pol='e')).expand().subs(nu4,-phi1-nu3) f_phi12_nu3 =ufuncify([phi1,phi2,nu3], ex1-ex2) @timeit def initial_voxels_4wv(max_i,base,starting_i,eps,eps_factor = None): if eps_factor is None: eps_factor = pow(base,max_i-starting_i) eps_current = eps * eps_factor solution_containing_voxels = {} solution_containing_voxels[starting_i] = {} for i1,om1 in enumerate(ranges1[starting_i]): for i2,om2 in enumerate(ranges2[starting_i]): for i3,om3 in enumerate(ranges3[starting_i]): err = f_phi12_nu3(om1,om2,om3) if abs(err) < eps_current: solution_containing_voxels[starting_i][i1,i2,i3] = err return solution_containing_voxels @timeit def add_high_res_voxels_4wv(max_i,base,starting_i,eps,solution_containing_voxels): for i in range(starting_i+1,max_i+1): eps_current = eps * pow(base,max_i-i) solution_containing_voxels[i] = {} for (i1,i2,i3) in solution_containing_voxels[i-1]: step_size = int(base/2) max_length = pow(base,i+1) for i1_new in range(max(0,i1*base-step_size),min(relative_scalings[0]*max_length,i1*base+step_size+1)): for i2_new in range(max(0,i2*base-step_size),min(relative_scalings[1]*max_length,i2*base+step_size+1)): for i3_new in range(max(0,i3*base-step_size),min(relative_scalings[2]*max_length,i3*base+step_size+1)): err = f_phi12_nu3(ranges1[i][i1_new],ranges2[i][i2_new],ranges3[i][i3_new]) if abs(err) < eps_current: solution_containing_voxels[i][i1_new,i2_new,i3_new] = err eps_factors = [1.5,2.,2.5,3.,3.5,4.] num_found = {} for eps_factor in eps_factors: solution_containing_voxels_4wv = initial_voxels_4wv(max_i,base,starting_i,eps,eps_factor = eps_factor) print 'big voxels: ', len(solution_containing_voxels_4wv[0].keys()) add_high_res_voxels_4wv(max_i,base,starting_i,eps,solution_containing_voxels_4wv) num_found[eps_factor] = len(solution_containing_voxels_4wv[1].keys()) print 'little voxels: ', num_found[eps_factor] plt.title('number of solutions found as a function of the epsilon multiplier for the voxel method') plt.plot(eps_factors, [num_found[eps] for eps in eps_factors] )
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Finding solutions in the voxels: In general the nus to be considered do not lie on a grid. For this reason it is necessary to find which nus lie in each voxel. Setup for the experiment
eps = 0.006 starting_i = 0 max_i = 2 base = 10 ranges = setup_ranges(max_i,base) solution_containing_voxels = initial_voxels(max_i,base,starting_i,eps) add_high_res_voxels(max_i,base,starting_i,eps,solution_containing_voxels) i = 2 ## where to draw points from. scale = 0.1 ## scale on random noise to add to points Delta = ranges[i][1] - ranges[i][0] ## Delta here was made with ranges[0] spacing range_min = ranges[i][0] ranges_perturbed = [num+random.random()*scale for num in ranges[2]] ## make values = [ int(round( (el - range_min) / Delta)) for el in ranges_perturbed] def make_dict_values_to_lists_of_inputs(values,inputs): D = {} for k, v in zip(values,inputs): D.setdefault(k, []).append(v) return D D = make_dict_values_to_lists_of_inputs(values,ranges_perturbed) solution_nus = [] for indices in solution_containing_voxels[i].keys(): if all([ind in D for ind in indices]): ## check all indices are in D, for it in itertools.product(*[D[ind] for ind in indices]): ## get all nus in the voxel. solution_nus.append(it) plt.figure(figsize=(13,13)) plt.title('perturbed grid points still in the solution voxels') plt.scatter([el[0] for el in solution_nus],[el[1] for el in solution_nus])
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Development for method to be used in the package
def setup_ranges(max_i,base,min_value = 6.,max_value = 11.): ranges= {} for i in range(max_i+1): ranges[i] = np.linspace(min_value,max_value,1+pow(base,i+1)) return ranges @timeit def initial_voxels(ranges,k_of_nu1_nu2,max_i,base,starting_i,eps): solution_containing_voxels = {} eps_current = eps * pow(base,max_i-starting_i) solution_containing_voxels[starting_i] = {} for i1,om1 in enumerate(ranges[starting_i]): for i2,om2 in enumerate(ranges[starting_i]): err = k_of_nu1_nu2(om1,om2) if abs(err) < eps_current: solution_containing_voxels[starting_i][i1,i2] = err return solution_containing_voxels @timeit def add_high_res_voxels(ranges,k_of_nu1_nu2,max_i,base,starting_i,eps,solution_containing_voxels): for i in range(starting_i+1,max_i+1): eps_current = eps * pow(base,max_i-i) solution_containing_voxels[i] = {} for (i1,i2) in solution_containing_voxels[i-1]: step_size = int(base/2) max_length = pow(base,i+1) for i1_new in range(max(0,i1*base-step_size),min(max_length,i1*base+step_size+1)): for i2_new in range(max(0,i2*base-step_size),min(max_length,i2*base+step_size+1)): err = k_of_nu1_nu2(ranges[i][i1_new],ranges[i][i2_new]) if abs(err) < eps_current: solution_containing_voxels[i][i1_new,i2_new] = err @timeit def plot_voxels(solution_containing_voxels,i): voxels = np.zeros((1+pow(base,i+1),1+pow(base,i+1))) for (i1,i2) in solution_containing_voxels[i]: voxels[i1,i2] = 1 plot_arr(voxels) def voxel_solutions(ranges,k_of_nu1_nu2,max_i,base,starting_i,eps): solution_containing_voxels = initial_voxels(ranges,k_of_nu1_nu2,max_i, base,starting_i,eps) add_high_res_voxels(ranges,k_of_nu1_nu2,max_i,base,starting_i,eps, solution_containing_voxels) return solution_containing_voxels def generate_k_func(pols=(1,1,-1),n_symb = None): lambd,nu,nu1,nu2,nu3,nu4 = sp.symbols( 'lambda nu nu_1 nu_2 nu_3 nu_4') l2 = lambd **2 if n_symb is None: def n_symb(pol=1): '''Valid for lambda between 0.5 and 5. (units are microns)''' s = 1. if pol == 1: s += 2.6734 * l2 / (l2 - 0.01764) s += 1.2290 * l2 / (l2 - 0.05914) s += 12.614 * l2 / (l2 - 474.6) else: s += 2.9804 * l2 / (l2 - 0.02047) s += 0.5981 * l2 / (l2 - 0.0666) s += 8.9543 * l2 / (l2 - 416.08) return sp.sqrt(s) def k_symb(symbol=nu,pol=1): '''k is accurate for nu inputs between 6-60 (units are 1e13 Hz).''' return ((n_symb(pol=pol) * symbol ) .subs(lambd,scipy.constants.c / (symbol*1e7))) expressions = [k_symb(nu1,pols[0]), k_symb(nu2,pols[1]), k_symb(nu3,pols[2])] dispersion_difference_function = sum(expressions) dispersion_difference_function = dispersion_difference_function.subs( nu3,-nu1-nu2) k_of_nu1_nu2 = ufuncify([nu1,nu2], dispersion_difference_function) return k_of_nu1_nu2 pols = (1,1,-1) k_of_nu1_nu2 = generate_k_func(pols) eps = 0.006 starting_i = 0 max_i = 2 base = 10 min_value = 6. max_value = 20. ranges = setup_ranges(max_i,base,min_value,max_value) pos_nus_lst = np.random.uniform(min_value,max_value,1000) ## 100 random values Delta = ranges[max_i][1] - ranges[max_i][0] ## spacing in grid used ## get index values values = [ int(round( (freq - min_value) / Delta)) for freq in pos_nus_lst] ## make a dict to remember which frequencies belong in which grid voxel. grid_indices_to_unrounded = make_dict_values_to_lists_of_inputs(values,pos_nus_lst) grid_indices_to_ham_index = make_dict_values_to_lists_of_inputs(values,range(len(pos_nus_lst))) solution_containing_voxels = voxel_solutions(ranges,k_of_nu1_nu2, max_i,base,starting_i,eps) ## Let's figure out which indices we can expect for nu3 spacing = (max_value-min_value)/ pow(base,max_i+1) num_indices_from_zero = min_value / spacing ## float, round up or down solutions_nu1_and_nu2 = solution_containing_voxels[max_i].keys() solution_indices = [] for indices in solutions_nu1_and_nu2: for how_to_round_last_index in range(2): last_index = (sum(indices) + int(num_indices_from_zero) + how_to_round_last_index) if last_index < 0 or last_index >= len(ranges[max_i]): print "breaking!" break current_grid_indices = (indices[0],indices[1],last_index) if all([ind in grid_indices_to_ham_index for ind in current_grid_indices]): for it in itertools.product(*[grid_indices_to_ham_index[ind] for ind in current_grid_indices]): solution_indices.append(it) len(solutions_nu1_and_nu2) len(solution_indices) sample_indices = solution_indices[random.randint(0,len(solution_indices)-1)] sample_indices pos_nus_lst[sample_indices[0]], pos_nus_lst[sample_indices[1]], pos_nus_lst[sample_indices[2]] pos_nus_lst[sample_indices[0]]+pos_nus_lst[sample_indices[1]] - pos_nus_lst[sample_indices[2]] np.zeros((0,0)) tuple(map(lambda z: int(np.sign(z)),(4.5,5.5,-3.4))) 1e-2 import math def make_dict_values_to_lists_of_inputs(values,inputs): ''' Make a dictionary mapping value to lists of corresponding inputs. Args: values (list of floats): Values in a list, corresponding to the inputs. inputs (list of floats): Inputs in a list. Returns: D (dict): dictionary mapping value to lists of corresponding inputs. ''' D = {} for k, v in zip(values,inputs): if not math.isnan(k): D.setdefault(k, []).append(v) return D make_dict_values_to_lists_of_inputs([float('NaN'),3,4,5],[1,1,2,3]) math.isnan(float('NaN'))
Dispersion_relation_chi_2_voxels_approach.ipynb
tabakg/potapov_interpolation
gpl-3.0
Let's imagine we measure 2 quantities, $x_1$ and $x_2$ for some objects, and we know the classes that these objects belong to, e.g., "star", 0, or "galaxy", 1 (maybe we classified these objects by hand, or knew through some other means). We now observe ($x_1$, $x_2$) for some new object and want to know whether it belongs in class 0 or 1. We'll first generate some fake data with known classes:
a = np.random.multivariate_normal([1., 0.5], [[4., 0.], [0., 0.25]], size=512) b = np.random.multivariate_normal([10., 8.], [[1., 0.], [0., 25]], size=1024) X = np.vstack((a,b)) y = np.concatenate((np.zeros(len(a)), np.ones(len(b)))) X.shape, y.shape plt.figure(figsize=(6,6)) plt.scatter(X[:,0], X[:,1], c=y, cmap='RdBu', marker='.', alpha=0.4) plt.xlim(-10, 20) plt.ylim(-10, 20) plt.title('Training data') plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.tight_layout()
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
We now observe a new point, and would like to know which class it belongs to:
np.random.seed(42) new_pt = np.random.uniform(-10, 20, size=2) plt.figure(figsize=(6,6)) plt.scatter(X[:,0], X[:,1], c=y, cmap='RdBu', marker='.', alpha=0.5, linewidth=0) plt.scatter(new_pt[0], new_pt[1], marker='+', color='g', s=100, linewidth=3) plt.xlim(-10, 20) plt.ylim(-10, 20) plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.tight_layout()
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
KNN works by predicting the class of a new point based on the classes of the K training data points closest to the new point. The two things that can be customized about this method are K, the number of points to use, and the distance metric used to compute the distances between the new point and the training data. If the dimensions in your data are measured with different units or with very different measurement uncertainties, you might need to be careful with the way you choose this metric. For simplicity, we'll start by fixing K=16 and use a Euclidean distance to see how this works in practice:
K = 16 def distance(pts1, pts2): pts1 = np.atleast_2d(pts1) pts2 = np.atleast_2d(pts2) return np.sqrt( (pts1[:,0]-pts2[:,0])**2 + (pts1[:,1]-pts2[:,1])**2) # compute the distance between all training data points and the new point dists = distance(X, new_pt) # get the classes (from the training data) of the K nearest points nearest_classes = y[np.argsort(dists)[:K]] nearest_classes
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
All of the closest points are from class 1, so we would classify the new point as class=1. If there is a mixture of possible classes, take the class with more neighbors. If it's a tie, choose a class at random. That's it! Let's see how to use the KNN classifier in scikit-learn:
from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=16) clf.fit(X, y) clf.predict(new_pt.reshape(1, -1)) # input has to be 2D
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
Let's visualize the decision boundary of this classifier by evaluating the predicted class for a grid of trial data:
grid_1d = np.linspace(-10, 20, 256) grid_x1, grid_x2 = np.meshgrid(grid_1d, grid_1d) grid = np.stack((grid_x1.ravel(), grid_x2.ravel()), axis=1) y_grid = clf.predict(grid) plt.figure(figsize=(6,6)) plt.pcolormesh(grid_x1, grid_x2, y_grid.reshape(grid_x1.shape), cmap='Set3', alpha=1.) plt.scatter(X[:,0], X[:,1], marker='.', alpha=0.65, linewidth=0) plt.xlim(-10, 20) plt.ylim(-10, 20) plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.tight_layout()
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
KNN is very simple, but is very fast and is therefore useful in problems with large or wide datasets. Let's now look at a more complicated example where the training data classes overlap significantly:
a = np.random.multivariate_normal([6., 0.5], [[8., 0.], [0., 0.25]], size=512) b = np.random.multivariate_normal([10., 4.], [[2., 0.], [0., 8]], size=1024) X2 = np.vstack((a,b)) y2 = np.concatenate((np.zeros(len(a)), np.ones(len(b)))) plt.figure(figsize=(6,6)) plt.scatter(X2[:,0], X2[:,1], c=y2, cmap='RdBu', marker='.', alpha=0.4) plt.xlim(-10, 20) plt.ylim(-10, 20) plt.title('Training data') plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.tight_layout()
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
What does the decision boundary look like in this case, as a function of the number of neighbors, K:
for K in [4, 16, 64, 256]: clf2 = KNeighborsClassifier(n_neighbors=K) clf2.fit(X2, y2) y_grid2 = clf2.predict(grid) plt.figure(figsize=(6,6)) plt.pcolormesh(grid_x1, grid_x2, y_grid2.reshape(grid_x1.shape), cmap='Set3', alpha=1.) plt.scatter(X2[:,0], X2[:,1], marker='.', alpha=0.65, linewidth=0) plt.xlim(-10, 20) plt.ylim(-10, 20) plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.title("$K={0}$".format(K)) plt.tight_layout()
day1/notebooks/demo-KNN.ipynb
AstroHackWeek/AstroHackWeek2017
mit
3. Enter DV360 Monthly Budget Mover Recipe Parameters No changes made can be made in DV360 from the start to the end of this process Make sure there is budget information for the current and previous month's IOs in DV360 Make sure the provided spend report has spend data for every IO in the previous month Spend report must contain 'Revenue (Adv Currency)' and 'Insertion Order ID' There are no duplicate IO Ids in the categories outlined below This process must be ran during the month of the budget it is updating If you receive a 502 error then you must separate your jobs into two, because there is too much information being pulled in the sdf Manually run this job Once the job has completed go to the table for the new sdf and export to a csv Take the new sdf and upload it into DV360 Modify the values below for your use case, can be done multiple times, then click play.
FIELDS = { 'recipe_timezone':'America/Los_Angeles', # Timezone for report dates. 'recipe_name':'', # Table to write to. 'auth_write':'service', # Credentials used for writing data. 'auth_read':'user', # Credentials used for reading data. 'partner_id':'', # The sdf file types. 'budget_categories':'{}', # A dictionary to show which IO Ids go under which Category. {"CATEGORY1":[12345,12345,12345], "CATEGORY2":[12345,12345]} 'filter_ids':[], # Comma separated list of filter ids for the request. 'excluded_ios':'', # A comma separated list of Inserion Order Ids that should be exluded from the budget calculations 'version':'5', # The sdf version to be returned. 'is_colab':True, # Are you running this in Colab? (This will store the files in Colab instead of Bigquery) 'dataset':'', # Dataset that you would like your output tables to be produced in. } print("Parameters Set To: %s" % FIELDS)
colabs/monthly_budget_mover.ipynb
google/starthinker
apache-2.0
4. Execute DV360 Monthly Budget Mover This does NOT need to be modified unless you are changing the recipe, click play.
from starthinker.util.configuration import execute from starthinker.util.recipe import json_set_fields TASKS = [ { 'dataset':{ 'description':'Create a dataset where data will be combined and transfored for upload.', 'auth':{'field':{'name':'auth_write','kind':'authentication','order':1,'default':'service','description':'Credentials used for writing data.'}}, 'dataset':{'field':{'name':'dataset','kind':'string','order':1,'description':'Place where tables will be created in BigQuery.'}} } }, { 'dbm':{ 'auth':{'field':{'name':'auth_read','kind':'authentication','order':1,'default':'user','description':'Credentials used for reading data.'}}, 'report':{ 'timeout':90, 'filters':{ 'FILTER_ADVERTISER':{ 'values':{'field':{'name':'filter_ids','kind':'integer_list','order':7,'default':'','description':'The comma separated list of Advertiser Ids.'}} } }, 'body':{ 'timezoneCode':{'field':{'name':'recipe_timezone','kind':'timezone','description':'Timezone for report dates.','default':'America/Los_Angeles'}}, 'metadata':{ 'title':{'field':{'name':'recipe_name','kind':'string','prefix':'Monthly_Budget_Mover_','order':1,'description':'Name of report in DV360, should be unique.'}}, 'dataRange':'PREVIOUS_MONTH', 'format':'CSV' }, 'params':{ 'type':'TYPE_GENERAL', 'groupBys':[ 'FILTER_ADVERTISER_CURRENCY', 'FILTER_INSERTION_ORDER' ], 'metrics':[ 'METRIC_REVENUE_ADVERTISER' ] } } }, 'delete':False } }, { 'monthly_budget_mover':{ 'auth':'user', 'is_colab':{'field':{'name':'is_colab','kind':'boolean','default':True,'order':7,'description':'Are you running this in Colab? (This will store the files in Colab instead of Bigquery)'}}, 'report_name':{'field':{'name':'recipe_name','kind':'string','prefix':'Monthly_Budget_Mover_','order':1,'description':'Name of report in DV360, should be unique.'}}, 'budget_categories':{'field':{'name':'budget_categories','kind':'json','order':3,'default':'{}','description':'A dictionary to show which IO Ids go under which Category. {"CATEGORY1":[12345,12345,12345], "CATEGORY2":[12345,12345]}'}}, 'excluded_ios':{'field':{'name':'excluded_ios','kind':'integer_list','order':4,'description':'A comma separated list of Inserion Order Ids that should be exluded from the budget calculations'}}, 'sdf':{ 'auth':'user', 'version':{'field':{'name':'version','kind':'choice','order':6,'default':'5','description':'The sdf version to be returned.','choices':['SDF_VERSION_5','SDF_VERSION_5_1']}}, 'partner_id':{'field':{'name':'partner_id','kind':'integer','order':1,'description':'The sdf file types.'}}, 'file_types':'INSERTION_ORDER', 'filter_type':'FILTER_TYPE_ADVERTISER_ID', 'read':{ 'filter_ids':{ 'single_cell':True, 'values':{'field':{'name':'filter_ids','kind':'integer_list','order':4,'default':[],'description':'Comma separated list of filter ids for the request.'}} } }, 'time_partitioned_table':False, 'create_single_day_table':False, 'dataset':{'field':{'name':'dataset','kind':'string','order':6,'default':'','description':'Dataset to be written to in BigQuery.'}}, 'table_suffix':'' }, 'out_old_sdf':{ 'bigquery':{ 'dataset':{'field':{'name':'dataset','kind':'string','order':8,'default':'','description':'Dataset that you would like your output tables to be produced in.'}}, 'table':{'field':{'name':'recipe_name','kind':'string','prefix':'SDF_OLD_','description':'Table to write to.'}}, 'schema':[ ], 'skip_rows':0, 'disposition':'WRITE_TRUNCATE' }, 'file':'/content/old_sdf.csv' }, 'out_new_sdf':{ 'bigquery':{ 'dataset':{'field':{'name':'dataset','kind':'string','order':8,'default':'','description':'Dataset that you would like your output tables to be produced in.'}}, 'table':{'field':{'name':'recipe_name','kind':'string','prefix':'SDF_NEW_','description':'Table to write to.'}}, 'schema':[ ], 'skip_rows':0, 'disposition':'WRITE_TRUNCATE' }, 'file':'/content/new_sdf.csv' }, 'out_changes':{ 'bigquery':{ 'dataset':{'field':{'name':'dataset','kind':'string','order':8,'default':'','description':'Dataset that you would like your output tables to be produced in.'}}, 'table':{'field':{'name':'recipe_name','kind':'string','prefix':'SDF_BUDGET_MOVER_LOG_','description':'Table to write to.'}}, 'schema':[ ], 'skip_rows':0, 'disposition':'WRITE_TRUNCATE' }, 'file':'/content/log.csv' } } } ] json_set_fields(TASKS, FIELDS) execute(CONFIG, TASKS, force=True)
colabs/monthly_budget_mover.ipynb
google/starthinker
apache-2.0
Specify the cell size along the rows (delr) and along the columns (delc) and the top and bottom of the aquifer for the DIS package.
#--dis data delr, delc = 50.0, 50.0 botm = np.array([-10., -30., -50.])
original_libraries/flopy-master/examples/Notebooks/swiex4.ipynb
mjasher/gac
gpl-2.0
Define the IBOUND array and starting heads for the BAS package. The corners of the model are defined to be inactive.
#--bas data #--ibound - active except for the corners ibound = np.ones((nlay, nrow, ncol), dtype= np.int) ibound[:, 0, 0] = 0 ibound[:, 0, -1] = 0 ibound[:, -1, 0] = 0 ibound[:, -1, -1] = 0 #--initial head data ihead = np.zeros((nlay, nrow, ncol), dtype=np.float)
original_libraries/flopy-master/examples/Notebooks/swiex4.ipynb
mjasher/gac
gpl-2.0
Define the layers to be confined and define the horizontal and vertical hydraulic conductivity of the aquifer for the LPF package.
#--lpf data laytyp=0 hk=10. vka=0.2
original_libraries/flopy-master/examples/Notebooks/swiex4.ipynb
mjasher/gac
gpl-2.0
Define the boundary condition data for the model
#--boundary condition data #--ghb data colcell, rowcell = np.meshgrid(np.arange(0, ncol), np.arange(0, nrow)) index = np.zeros((nrow, ncol), dtype=np.int) index[:, :10] = 1 index[:, -10:] = 1 index[:10, :] = 1 index[-10:, :] = 1 nghb = np.sum(index) lrchc = np.zeros((nghb, 5)) lrchc[:, 0] = 0 lrchc[:, 1] = rowcell[index == 1] lrchc[:, 2] = colcell[index == 1] lrchc[:, 3] = 0. lrchc[:, 4] = 50.0 * 50.0 / 40.0 #--create ghb dictionary ghb_data = {0:lrchc} #--recharge data rch = np.zeros((nrow, ncol), dtype=np.float) rch[index == 0] = 0.0004 #--create recharge dictionary rch_data = {0: rch} #--well data nwells = 2 lrcq = np.zeros((nwells, 4)) lrcq[0, :] = np.array((0, 30, 35, 0)) lrcq[1, :] = np.array([1, 30, 35, 0]) lrcqw = lrcq.copy() lrcqw[0, 3] = -250 lrcqsw = lrcq.copy() lrcqsw[0, 3] = -250. lrcqsw[1, 3] = -25. #--create well dictionary base_well_data = {0:lrcq, 1:lrcqw} swwells_well_data = {0:lrcq, 1:lrcqw, 2:lrcqsw} #--swi2 data adaptive = False nadptmx = 10 nadptmn = 1 nu = [0, 0.025] numult = 5.0 toeslope = nu[1] / numult #0.005 tipslope = nu[1] / numult #0.005 z1 = -10.0 * np.ones((nrow, ncol)) z1[index == 0] = -11.0 z = np.array([[z1, z1]]) iso = np.zeros((nlay, nrow, ncol), dtype=np.int) iso[0, :, :][index == 0] = 1 iso[0, :, :][index == 1] = -2 iso[1, 30, 35] = 2 ssz=0.2 #--swi2 observations obsnam = ['layer1_', 'layer2_'] obslrc=[[1, 31, 36], [2, 31, 36]] nobs = len(obsnam) iswiobs = 1051
original_libraries/flopy-master/examples/Notebooks/swiex4.ipynb
mjasher/gac
gpl-2.0