markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Note that the sliders can be linkedd in order to preserve the aspect ratio of the figure. The state can be updated as: | zoom_options = {'min': 0.5, 'max': 10., 'step': 0.3, 'zoom': [2., 3.]}
wid.set_widget_state(zoom_options, allow_callback=True) | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:image"></a>7. Image Options
This is a widget for selecting options related to rendering an image. It defines the colourmap, the alpha value for transparency as well as the interpolation. Specifically: | # Initial options
image_options = {'alpha': 1.,
'interpolation': 'bilinear',
'cmap_name': None}
# Create widget
wid = ImageOptionsWidget(image_options, render_function=render_function)
# Set styling
wid.style(box_style='success', padding=10, border_visible=True, border_radius=45)
... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
The widget can be updated with a new dict of options as: | wid.set_widget_state({'alpha': 0.8, 'interpolation': 'none', 'cmap_name': 'gray'}, allow_callback=True) | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:line"></a>8. Line Options
The following widget allows the selection of options for rendering line objects. The initial options are passed in as a dict and control the width, style and colour of the lines. Note that a different colour can be defined for different objects using the labels argument. | # Initial options
line_options = {'render_lines': True,
'line_width': 1,
'line_colour': ['blue', 'red'],
'line_style': '-'}
# Create widget
wid = LineOptionsWidget(line_options, render_function=render_function,
labels=['menpo', 'widgets'])
# ... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
The Render lines tick box also controls the visibility of the rest of the options. So by updating the state with render_lines=False, the options disappear. | wid.set_widget_state({'render_lines': False, 'line_width': 5, 'line_colour': ['purple'], 'line_style': '--'},
allow_callback=True, labels=None) | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:marker"></a>9. Marker Options
Similar to the LineOptionsWidget, this widget allows to selecting options for rendering markers. The options define the edge width, face colour, edge colour, style and size of the markers. | # Initial options
marker_options = {'render_markers': True,
'marker_size': 20,
'marker_face_colour': ['red', 'green'],
'marker_edge_colour': ['black', 'blue'],
'marker_style': 'o',
'marker_edge_width': 1}
# Create widget
wid... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:numbering"></a>10. Numbering Options
The NumberingOptionsWidget is used in case you want to render some numbers next to the plotted points. | # Initial options
numbers_options = {'render_numbering': True,
'numbers_font_name': 'serif',
'numbers_font_size': 10,
'numbers_font_style': 'normal',
'numbers_font_weight': 'normal',
'numbers_font_colour': ['black'],
... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
Of course the state of the widget can be updated as: | wid.set_widget_state({'render_numbering': True, 'numbers_font_name': 'serif', 'numbers_font_size': 10,
'numbers_font_style': 'normal', 'numbers_font_weight': 'normal',
'numbers_font_colour': ['green'], 'numbers_horizontal_align': 'center',
'numbers_ve... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:axes"></a>11. Axes Options
Before presenting the AxesOptionsWidget, let's first see two widgets that are ued as its basic components for selecting the axes limits as well as the axes ticks.
AxesLimitsWidget has 3 basic functions per axis:
* auto: Allows matplotlib to automatically set the limits.
* percent... | # Create widget
wid = AxesLimitsWidget(axes_x_limits=[0, 10], axes_y_limits=0.1, render_function=render_function)
# Set styling
wid.style(box_style='danger')
# Display widget
wid | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
Note that the percentage mode is accompanied by a ListWidget that expects a single float, whereas the range mode invokes a ListWidget that expects two float numbers. The state of the widget can be changed as: | wid.set_widget_state([-200, 200], None, allow_callback=True) | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
On the other hand, AxesTicksWidget has two functionalities per axis:
* auto: Allows matplotlib to automatically set the ticks.
* list: Enables a ListWidget to select the ticks. | # Initial options
axes_ticks = {'x': [],
'y': [10., 20., 30.]}
# Create widget
wid = AxesTicksWidget(axes_ticks, render_function=render_function)
# St styling
wid.style(box_style='danger')
# Display widget
wid | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
The state can be updated as: | wid.set_widget_state({'x': list(range(5)), 'y': None}, allow_callback=True) | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
The AxesOptionsWidget involves the AxesLimitsWidget and AxesTicksWidget widgets and also allows the selection of font-related options. As always, the initial options are provided in a dict: | # Initial options
axes_options = {'render_axes': True,
'axes_font_name': 'serif',
'axes_font_size': 10,
'axes_font_style': 'normal',
'axes_font_weight': 'normal',
'axes_x_limits': None,
'axes_y_limits': None,
... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
The state of the widget can be updated as: | axes_options = {'render_axes': True, 'axes_font_name': 'serif',
'axes_font_size': 10, 'axes_font_style': 'normal', 'axes_font_weight': 'normal',
'axes_x_limits': [0., 0.05], 'axes_y_limits': 0.1, 'axes_x_ticks': [0, 100], 'axes_y_ticks': None}
wid.set_widget_state(axes_options, allow_c... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:legend"></a>12. Legend Options
LegendOptionsWidget allows to control the (many) options of renderinf the legend of a figure. | # Initial options
legend_options = {'render_legend': True,
'legend_title': '',
'legend_font_name': 'serif',
'legend_font_style': 'normal',
'legend_font_size': 10,
'legend_font_weight': 'normal',
'legend_marker_sc... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:grid"></a>13. Grid Options
The following simple widget controls the rendering of the grid lines of a plot, their style and width. | # Initial options
grid_options = {'render_grid': True,
'grid_line_width': 1,
'grid_line_style': '-'}
# Create widget
wid = GridOptionsWidget(grid_options, render_function=render_function)
# Set styling
wid.style(box_style='warning')
# Display widget
wid
wid.set_widget_state({'rende... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
<a name="sec:features"></a>14. HOG, DSIFT, Daisy, LBP, IGO Options
The following widgets allow to select options regarding HOG, DSIFT, Daisy, LBP and IGO features. | # Initial options
hog_options = {'mode': 'dense',
'algorithm': 'dalaltriggs',
'num_bins': 9,
'cell_size': 8,
'block_size': 2,
'signed_gradient': True,
'l2_norm_clip': 0.2,
'window_height': 1,
'window_... | menpowidgets/Custom Widgets/Widgets Tools.ipynb | grigorisg9gr/menpo-notebooks | bsd-3-clause |
If we visualize how the algorithm progresses, we can pre-emptiveley stop execution of the tour evaluation. Since the order of the permutations is deterministic, we can observe that the cost monotonically decreases.
This monotonic decrease is a result of the min function we call on costs. In actuality, since we're evalu... | from algs import brute_force_N, brute_force
from parsers import TSP
from graphgen import EUC_2D
from parstats import get_stats, dist_across_cost, scatter_vis
from itertools import permutations
tsp_prob = TSP('../data/a280.tsp')
tsp_prob.graph = EUC_2D(6)
tsp_prob.spec = dict(comment="Random euclidean graph",
... | reports/01_exact_algorithms.ipynb | DhashS/Olin-Complexity-Final-Project | gpl-3.0 |
If we tweak the code slightly, we can see what it's doing without a reduce step: | # %load -s brute_force_N_no_reduce algs.py
def brute_force_N_no_reduce(p, n, perf=False):
import itertools as it
#Generate all possible tours (complete graph)
tours = list(it.permutations(p.nodes())) #O(V!)
costs = []
if not perf:
cost_data = pd.DataFrame(columns=["$N$", "cost", "opt_co... | reports/01_exact_algorithms.ipynb | DhashS/Olin-Complexity-Final-Project | gpl-3.0 |
Given this is a randomly distributed dataset, it makes sense that the distribution across costs looks like a gaussian. Let's confirm by checking how correlated they are | from scipy.stats import pearsonr
pearsonr(cost_stats.cost, cost_stats.opt_cost)
pearsonr(cost_stats["$N$"], cost_stats.cost) | reports/01_exact_algorithms.ipynb | DhashS/Olin-Complexity-Final-Project | gpl-3.0 |
2. Visualize the First 24 Training Images | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(20,5))
for i in range(36):
ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
ax.imshow(np.squeeze(x_train[i])) | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
3. Rescale the Images by Dividing Every Pixel in Every Image by 255 | # rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255 | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
4. Break Dataset into Training, Testing, and Validation Sets | from keras.utils import np_utils
# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:50... | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
5. Define the Model Architecture | from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
# define the model
model = Sequential()
model.add(Flatten(input_shape = x_train.shape[1:]))
model.add(Dense(1000, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(D... | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
6. Compile the Model | # compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy']) | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
7. Train the Model | from keras.callbacks import ModelCheckpoint
# train the model
checkpointer = ModelCheckpoint(filepath='MLP.weights.best.hdf5', verbose=1,
save_best_only=True)
hist = model.fit(x_train, y_train, batch_size=32, epochs=20,
validation_data=(x_valid, y_valid), callbacks=[checkpo... | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
8. Load the Model with the Best Classification Accuracy on the Validation Set | # load the weights that yielded the best validation accuracy
model.load_weights('MLP.weights.best.hdf5') | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
9. Calculate Classification Accuracy on Test Set | # evaluate and print test accuracy
score = model.evaluate(x_test, y_test, verbose=0)
print('\n', 'Test accuracy:', score[1]) | aind2-cnn/cifar10-classification/cifar10_mlp.ipynb | elmaso/tno-ai | gpl-3.0 |
Time to build the network
Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.
<img src="assets/neural_network.p... | class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
# Initialize we... | first-neural-network/Your_first_neural_network.ipynb | ClementPhil/deep-learning | mit |
Training the network
Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se... | import sys
### Set the hyperparameters here ###
iterations = 100
learning_rate = 0.1
hidden_nodes = 2
output_nodes = 1
N_i = train_features.shape[1]
network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)
losses = {'train':[], 'validation':[]}
for ii in range(iterations):
# Go through a random ba... | first-neural-network/Your_first_neural_network.ipynb | ClementPhil/deep-learning | mit |
We create a system object and provide:
Hamiltonian,
dynamics, and
magnetisation configuration. | system = oc.System(name="first_notebook") | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
Our Hamiltonian should only contain exchange, demagnetisation, and Zeeman energy terms. We will apply the external magnetic field in the $x$ direction for the purpose of this demonstration: | A = 1e-12 # exchange energy constant (J/m)
H = (5e6, 0, 0) # external magnetic field in x-direction (A/m)
system.hamiltonian = oc.Exchange(A=A) + oc.Demag() + oc.Zeeman(H=H) | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
The dynamics of the system is governed by the LLG equation containing precession and damping terms: | gamma = 2.211e5 # gamma parameter (m/As)
alpha = 0.2 # Gilbert damping
system.dynamics = oc.Precession(gamma=gamma) + oc.Damping(alpha=alpha) | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
We initialise the system in positive $y$ direction, i.e. (0, 1, 0), which is different from the equlibrium state we expect for the external Zeeman field applied in $x$ direction: | L = 100e-9 # cubic sample edge length (m)
d = 5e-9 # discretisation cell size (m)
mesh = oc.Mesh(p1=(0, 0, 0), p2=(L, L, L), cell=(d, d, d))
Ms = 8e6 # saturation magnetisation (A/m)
system.m = df.Field(mesh, value=(0, 1, 0), norm=Ms) | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
We can check the characteristics of the system we defined by asking objects to represent themselves: | mesh
system.hamiltonian
system.dynamics | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
We can also visualise the current magnetisation field: | system.m.plot_plane("z"); | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
After the system object is created, we can minimise its energy (relax it) using the Minimisation Driver (MinDriver). | md = oc.MinDriver()
md.drive(system) | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
The system is now relaxed, and we can plot its slice and compute its average magnetisation. | # centre of the system is assumed for plane to be plotted
system.m.plot_plane("z");
# plane can be chosen manually as well
system.m.plot_plane(z=10e-9);
system.m.average | workshops/Durham/.ipynb_checkpoints/tutorial0_first_notebook-checkpoint.ipynb | joommf/tutorial | bsd-3-clause |
As you can see above, we have a session on the server. It has been assigned a unique session ID and more user-friendly name. In this case, we are using the binary CAS protocol as opposed to the REST interface. We can now run CAS actions in the session. Let's begin with a simple one: listnodes. | # Run the builtins.listnodes action
nodes = conn.listnodes()
nodes | communities/Your First CAS Connection from Python.ipynb | sassoftware/sas-viya-programming | apache-2.0 |
The listnodes action returns a CASResults object (which is just a subclass of Python's ordered dictionary). It contains one key ('nodelist') which holds a Pandas DataFrame. We can now grab that DataFrame to do further operations on it. | # Grab the nodelist DataFrame
df = nodes['nodelist']
df | communities/Your First CAS Connection from Python.ipynb | sassoftware/sas-viya-programming | apache-2.0 |
Use DataFrame selection to subset the columns. | roles = df[['name', 'role']]
roles
# Extract the worker nodes using a DataFrame mask
roles[roles.role == 'worker']
# Extract the controllers using a DataFrame mask
roles[roles.role == 'controller'] | communities/Your First CAS Connection from Python.ipynb | sassoftware/sas-viya-programming | apache-2.0 |
In the code above, we are doing some standard DataFrame operations using expressions to filter the DataFrame to include only worker nodes or controller nodes. Pandas DataFrames support lots of ways of slicing and dicing your data. If you aren't familiar with them, you'll want to get acquainted on the Pandas web site.... | conn.close() | communities/Your First CAS Connection from Python.ipynb | sassoftware/sas-viya-programming | apache-2.0 |
4. Solving the model
4.1 Solow model as an initial value problem
The Solow model with can be formulated as an initial value problem (IVP) as follows.
$$ \dot{k}(t) = sf(k(t)) - (g + n + \delta)k(t),\ t\ge t_0,\ k(t_0) = k_0 \tag{4.1.0} $$
The solution to this IVP is a function $k(t)$ describing the time-path of capital... | solowpy.CobbDouglasModel.analytic_solution? | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
Example: Computing the analytic trajectory
We can compute an analytic solution for our Solow model like so... | # define model parameters
cobb_douglas_params = {'A0': 1.0, 'L0': 1.0, 'g': 0.02, 'n': 0.03, 's': 0.15,
'delta': 0.05, 'alpha': 0.33}
# create an instance of the solow.Model class
cobb_douglas_model = solowpy.CobbDouglasModel(params=cobb_douglas_params)
# specify some initial condition
k0 = 0.5 ... | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
...and we can make a plot of this solution like so... | fig, ax = plt.subplots(1, 1, figsize=(8,6))
# compute the solution
ti = np.linspace(0, 100, 1000)
analytic_traj = cobb_douglas_model.analytic_solution(ti, k0)
# plot this trajectory
ax.plot(ti, analytic_traj[:,1], 'r-')
# equilibrium value of capital stock (per unit effective labor)
ax.axhline(cobb_douglas_model.ste... | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
4.2.2 Linearized solution to general model
In general there will not be closed-form solutions for the Solow model. The standard approach to obtaining general analytical results for the Solow model is to linearize the equation of motion for capital stock (per unit effective labor). Linearizing the equation of motion of ... | # specify some initial condition
k0 = 0.5 * cobb_douglas_model.steady_state
# grid of t values for which we want the value of k(t)
ti = np.linspace(0, 100, 10)
# generate a trajectory!
cobb_douglas_model.linearized_solution(ti, k0) | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
4.2.3 Accuracy of the linear approximation | # initial condition
t0, k0 = 0.0, 0.5 * cobb_douglas_model.steady_state
# grid of t values for which we want the value of k(t)
ti = np.linspace(t0, 100, 1000)
# generate the trajectories
analytic = cobb_douglas_model.analytic_solution(ti, k0)
linearized = cobb_douglas_model.linearized_solution(ti, k0)
fig, ax = plt.... | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
4.3 Finite-difference methods
Four of the best, most widely used ODE integrators have been implemented in the scipy.integrate module (they are called dopri5, dop85, lsoda, and vode). Each of these integrators uses some type of adaptive step-size control: the integrator adaptively adjusts the step size $h$ in order to k... | fig, ax = plt.subplots(1, 1, figsize=(8,6))
# lower and upper bounds for initial conditions
k_star = solow.cobb_douglas.analytic_steady_state(cobb_douglas_model)
k_l = 0.5 * k_star
k_u = 2.0 * k_star
for k0 in np.linspace(k_l, k_u, 5):
# compute the solution
ti = np.linspace(0, 100, 1000)
analytic_traj =... | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
4.3.2 Accuracy of finite-difference methods | t0, k0 = 0.0, 0.5
numeric_soln = cobb_douglas_model.ivp.solve(t0, k0, T=100, integrator='lsoda')
fig, ax = plt.subplots(1, 1, figsize=(8,6))
# compute and plot the numeric approximation
t0, k0 = 0.0, 0.5
numeric_soln = cobb_douglas_model.ivp.solve(t0, k0, T=100, integrator='lsoda')
ax.plot(numeric_soln[:,0], numeric_... | notebooks/4 Solving the model.ipynb | solowPy/binder | mit |
Create Model Test/Validation Data | x_test = np.random.rand(len(x_train)).astype(np.float32)
print(x_test)
noise = np.random.normal(scale=0.01, size=len(x_train))
y_test = x_test * 0.1 + 0.3 + noise
print(y_test)
pylab.plot(x_train, y_train, '.')
with tf.device("/cpu:0"):
W = tf.get_variable(shape=[], name='weights')
print(W)
b = tf.get_variab... | oreilly.ml/high-performance-tensorflow/notebooks/03_Train_Model_CPU.ipynb | shareactorIO/pipeline | apache-2.0 |
Look at the Model Graph In Tensorboard
Navigate to the Graph tab at this URL:
http://[ip-address]:6006
Accuracy of Random Weights | def test(x, y):
return sess.run(loss_op, feed_dict={x_observed: x, y_observed: y})
test(x=x_test, y=y_test)
loss_summary_scalar_op = tf.summary.scalar('loss', loss_op)
loss_summary_merge_all_op = tf.summary.merge_all() | oreilly.ml/high-performance-tensorflow/notebooks/03_Train_Model_CPU.ipynb | shareactorIO/pipeline | apache-2.0 |
Train Model | %%time
max_steps = 400
run_metadata = tf.RunMetadata()
for step in range(max_steps):
if (step < max_steps):
test_summary_log, _ = sess.run([loss_summary_merge_all_op, loss_op], feed_dict={x_observed: x_test, y_observed: y_test})
train_summary_log, _ = sess.run([loss_summary_merge_all_op, train_op], feed_di... | oreilly.ml/high-performance-tensorflow/notebooks/03_Train_Model_CPU.ipynb | shareactorIO/pipeline | apache-2.0 |
Look at the Train and Test Loss Summary In Tensorboard
Navigate to the Scalars tab at this URL:
http://[ip-address]:6006 | from tensorflow.python.saved_model import utils
tensor_info_x_observed = utils.build_tensor_info(x_observed)
print(tensor_info_x_observed)
tensor_info_y_pred = utils.build_tensor_info(y_pred)
print(tensor_info_y_pred)
export_path = "/root/models/linear/cpu/%s" % version
print(export_path)
from tensorflow.python.sav... | oreilly.ml/high-performance-tensorflow/notebooks/03_Train_Model_CPU.ipynb | shareactorIO/pipeline | apache-2.0 |
Look at the Model On Disk
You must replace [version] with the version number | %%bash
ls -l /root/models/linear/cpu/[version] | oreilly.ml/high-performance-tensorflow/notebooks/03_Train_Model_CPU.ipynb | shareactorIO/pipeline | apache-2.0 |
HACK: Save Model in Previous Model Format
We will use this later. | from tensorflow.python.framework import graph_io
graph_io.write_graph(sess.graph, "/root/models/optimize_me/", "unoptimized_cpu.pb")
sess.close() | oreilly.ml/high-performance-tensorflow/notebooks/03_Train_Model_CPU.ipynb | shareactorIO/pipeline | apache-2.0 |
S be carefull!
while Loop | i=0
while i<10:
print(i)
i+=1 | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
Queez
Once upon a time, there was king, who wanted lots of soldiers. So he commanded every couple in the country to have children, until their first dauter born. Then the family is banned from having any more child.
What will be the ratio of boy/girls in this country? | from random import randint
children = 0
boy = 0
for i in range(10000):
gender = randint(0,1) # boy=1, girl=0
children += 1
while gender != 0:
boy += gender
gender = randint(0,1)
children += 1
print(boy/children) | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
Control Statments
break, continue and pass | for i in range(10):
print(i)
if i == 5:
break
for i in range(10):
print(i)
if i > 5:
continue
print("Hey")
def func():
pass
func() | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
tuple | t = (0,1,'test')
print(t)
t[0]=1
(1,) | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
Dictionaries
items get keys pop update values | d = {}
d['name'] = 'Hamed'
d['family name'] = 'Seyed-allaei'
d[0]=12
d['a']=''
print(d)
print(d['name'])
print(d[0])
for i,j in d.items():
print(i,j)
| Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
set
in, not in, len(), ==, !=, <=, <, |, &, -, ^ | a = set(['c', 'a','b','b'])
b = set(['c', 'd','e'])
print(a,b)
a | b
a & b
a - b
b - a
a ^ b | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
List comprehention | l = []
for i in range(10):
l.append(i*i)
print(l)
[i*i for i in range(10)]
{i:i**2 for i in range(10)} | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
Generators
next() | def myrange(n):
i = 0
while i < n:
yield i
yield i**2
i+=1
x = myrange(10)
type(x)
next(x)
[i for i in myrange(10)]
for i in myrange(10):
print(i) | Python-02.ipynb | ComputationalPhysics2015-IPM/Python-01 | gpl-2.0 |
Pandas has great support for datetime objects and general time series analysis operations. We'll be working with an example of predicting the number of airline passengers (in thousands) by month adapted from this tutorial.
First, download this dataset and load it into a Pandas Dataframe by specifying the 'Month' column... | dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m')
data = pd.read_csv('AirPassengers.csv', parse_dates=['Month'], index_col='Month',date_parser=dateparse)
print data.head() | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Note that Pandas is using the 'Month' column as the Dataframe index. | ts = data["#Passengers"]
ts.index | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
We can index into the Dataframe in two ways - either by using a string representation for the index or by constructing a datetime object. | ts['1949-01-01']
from datetime import datetime
ts[datetime(1949,1,1)] | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
We can also use the Pandas datetime index support to retrieve entire years | ts['1949']
ts['1949-01-01':'1949-05-01'] | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Finally, let's plot the time series to get an intial visualization of how the series grows. | plt.plot(ts) | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Stationarity
Most of the important results for time series forecasting (including the ARIMA model, which we focus on today) assume that the series is stationary - that is, its statistical properties like mean and variance are constant. However, the graph above certainly isn't stationary, given the obvious growth. Thus,... | ts_log = np.log(ts)
plt.plot(ts_log) | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
A simple moving average is the most basic way to predict the trend of a series, taking advantage of the generally continuous nature of trends. For example, if I told you to predict the number of wins of a basketball team this season, without giving you any information about the team apart from its past record, you woul... | moving_avg = pd.Series(ts_log).rolling(window=12).mean()
plt.plot(ts_log)
plt.plot(moving_avg, color='red') | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
You might be unhappy with having to choose a window size. How do we know what window size we want if we don't know much about the data? One solution is to average over all past data, discounting earlier values because they have less predictive power than more recent values. This method is known as smoothing. | expwighted_avg = pd.Series(ts_log).ewm(halflife=12).mean()
plt.plot(ts_log)
plt.plot(expwighted_avg, color='red') | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Now we can subtract the trend from the original data (eliminating the null values in the case of the simple moving average) to create a new series that is hopefully more stationary. The blue graph represents the smoothing difference, while the red graph represents the simple moving average difference | ts_exp_moving_avg_diff = ts_log - expwighted_avg
ts_log_moving_avg_diff = ts_log - moving_avg
ts_log_moving_avg_diff.dropna(inplace=True)
plt.plot(ts_exp_moving_avg_diff)
plt.plot(ts_log_moving_avg_diff, color='red') | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Now there is no longer an upward trend, suggesting a stationarity. There does seem to be a strong seasonality effect, as the number of passengers is low at the beginning and middle of the year but spikes at the first and third quarters.
Dealing with Seasonality
One baseline way of dealing with both trend and seasonalit... | ts_log_diff = ts_log - ts_log.shift()
plt.plot(ts_log_diff) | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Another method of dealing with trend and seasonality is separating the two effects, then removing both from the time series to obtain the stationary series. We'll be using the statsmodels module, which you can get via pip by running the following command in the terminal.
python -mpip install statsmodels
We will use the... | from statsmodels.tsa.seasonal import seasonal_decompose
decomposition = seasonal_decompose(ts_log)
trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid
plt.subplot(411)
plt.plot(ts_log, label='Original')
plt.legend(loc='best')
plt.subplot(412)
plt.plot(trend, label='Trend')
plt... | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Forecasting
Using the seasonal decomposition, we were able to separate the trend and seasonality effects, which is great for time series analysis. However, another goal of working with time series is forecasting the future - how do we do that given the tools that we've been using and the stationary series we've obtaine... | from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(ts_log, order=(2, 1, 2))
results_ARIMA = model.fit(disp=-1)
plt.plot(ts_log_diff)
plt.plot(results_ARIMA.fittedvalues, color='red')
plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2)) | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Now that we have a model for the stationary series that we can use to predict future values in the stationary series, and we want to get back to the original series. Note that we won't have a value for the first element because we are working with a one step lag. The following procedure takes care of that. | predictions_ARIMA_diff = pd.Series(results_ARIMA.fittedvalues, copy=True)
predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum()
predictions_ARIMA_log = pd.Series(ts_log.ix[0], index=ts_log.index)
predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum,fill_value=0) | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Now, we can plot the prediction (green) against the actual data. Note that the prediction model captures the seasonality and trend of the original series. It's not perfect, and additional steps can be made to tune the model. The important takeaway from this workshop is the general time series procedure of separating th... | predictions_ARIMA = np.exp(predictions_ARIMA_log)
plt.plot(ts)
plt.plot(predictions_ARIMA)
plt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-ts)**2)/len(ts))) | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
Challenge: ARIMA Tuning
This is an open ended challenge. There aren't any right or wrong answers, we'd just like to see how you would approach tuning the ARIMA model.
As you can see above, the ARIMA predictions could certainly use some tuning. Try manually tuning $p$, $d$, and $q$ and see how that changes the ARIMA pre... | # TODO: adjust the p, d, and q parameters to model the AR, MA, and ARMA models. Then, adjust these parameters to optimally tune the ARIMA model.
test_model = ARIMA(ts_log, order=(2, 1, 2))
test_results_ARIMA = test_model.fit(disp=-1)
test_predictions_ARIMA_diff = pd.Series(test_results_ARIMA.fittedvalues, copy=Tru... | 4/0-Time-Series-Analysis.ipynb | dataventures/workshops | mit |
1. What are truncated distributions?
<a class="anchor" id="1"></a>
The support of a probability distribution is the set of values
in the domain with non-zero probability. For example, the
support of the normal distribution is the whole real line (even if
the density gets very small as we move away from the mean, techni... | def truncated_normal_model(num_observations, high, x=None):
loc = numpyro.sample("loc", dist.Normal())
scale = numpyro.sample("scale", dist.LogNormal())
with numpyro.plate("observations", num_observations):
numpyro.sample("x", TruncatedNormal(loc, scale, high=high), obs=x) | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Let's now check that we can use this model in a typical MCMC workflow.
Prior simulation | high = 1.2
num_observations = 250
num_prior_samples = 100
prior = Predictive(truncated_normal_model, num_samples=num_prior_samples)
prior_samples = prior(PRIOR_RNG, num_observations, high) | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Inference
To test our model, we run mcmc against some synthetic data.
The synthetic data can be any arbitrary sample from the prior simulation. | # -- select an arbitrary prior sample as true data
true_idx = 0
true_loc = prior_samples["loc"][true_idx]
true_scale = prior_samples["scale"][true_idx]
true_x = prior_samples["x"][true_idx]
plt.hist(true_x.copy(), bins=20)
plt.axvline(high, linestyle=":", color="k")
plt.xlabel("x")
plt.show()
# --- Run MCMC and check... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Removing the truncation
Once we have inferred the parameters of our model, a common task is to understand what the data would look like without the truncation. In this example, this is easily done by simply "pushing" the value of high to infinity. | pred = Predictive(truncated_normal_model, posterior_samples=mcmc.get_samples())
pred_samples = pred(PRED_RNG, num_observations, high=float("inf")) | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Let's finally plot these samples and compare them to the original, observed data. | # thin the samples to not saturate matplotlib
samples_thinned = pred_samples["x"].ravel()[::1000]
f, axes = plt.subplots(1, 2, figsize=(15, 5), sharex=True)
axes[0].hist(
samples_thinned.copy(), label="Untruncated posterior", bins=20, density=True
)
axes[0].set_title("Untruncated posterior")
vals, bins, _ = axes... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
The plot on the left shows data simulated from the posterior distribution with the truncation removed, so we are able to see how the data would look like if it were not truncated. To sense check this, we discard the simulated samples that are above the truncation point and make histogram of those and compare it to a hi... | def TruncatedSoftLaplace(
loc=0.0, scale=1.0, *, low=None, high=None, validate_args=None
):
return TruncatedDistribution(
base_dist=SoftLaplace(loc, scale),
low=low,
high=high,
validate_args=validate_args,
)
def truncated_soft_laplace_model(num_observations, high, x=None):
... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
And, as before, we check that we can use this model in the steps of a typical workflow: | high = 2.3
num_observations = 200
num_prior_samples = 100
prior = Predictive(truncated_soft_laplace_model, num_samples=num_prior_samples)
prior_samples = prior(PRIOR_RNG, num_observations, high)
true_idx = 0
true_x = prior_samples["x"][true_idx]
true_loc = prior_samples["loc"][true_idx]
true_scale = prior_samples["sc... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Important
The sample method of the TruncatedDistribution class relies on inverse-transform sampling.
This has the implicit requirement that the base distribution should have an icdf method already available.
If this is not the case, we will not be able to call the sample method on any instances of our distribution, nor... | def FoldedStudentT(df, loc=0.0, scale=1.0):
return FoldedDistribution(StudentT(df, loc=loc, scale=scale))
def folded_student_model(num_observations, x=None):
df = numpyro.sample("df", dist.Gamma(6, 2))
loc = numpyro.sample("loc", dist.Normal())
scale = numpyro.sample("scale", dist.LogNormal())
with... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
And we check that we can use our distribution in a typical workflow: | # --- prior sampling
num_observations = 500
num_prior_samples = 100
prior = Predictive(folded_student_model, num_samples=num_prior_samples)
prior_samples = prior(PRIOR_RNG, num_observations)
# --- choose any prior sample as the ground truth
true_idx = 0
true_df = prior_samples["df"][true_idx]
true_loc = prior_samples... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
5. Building your own truncated distribution <a class="anchor" id="5"></a>
If the
TruncatedDistribution and
FoldedDistribution
classes are not sufficient to solve your problem,
you might want to look into writing your own truncated distribution from the ground up.
This can be a tedious process, so this section will give... | class _RightExtendedReal(constraints.Constraint):
"""
Any number in the interval (-inf, inf].
"""
def __call__(self, x):
return (x == x) & (x != float("-inf"))
def feasible_like(self, prototype):
return jnp.zeros_like(prototype)
right_extended_real = _RightExtendedReal()
class ... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Let's try it out! | def truncated_normal_model(num_observations, x=None):
loc = numpyro.sample("loc", dist.Normal())
scale = numpyro.sample("scale", dist.LogNormal())
high = numpyro.sample("high", dist.Normal())
with numpyro.plate("observations", num_observations):
numpyro.sample("x", RightTruncatedNormal(loc, scal... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
As before, we run mcmc against some synthetic data.
We select any random sample from the prior as the ground truth: | true_idx = 0
true_loc = prior_samples["loc"][true_idx]
true_scale = prior_samples["scale"][true_idx]
true_high = prior_samples["high"][true_idx]
true_x = prior_samples["x"][true_idx]
plt.hist(true_x.copy())
plt.axvline(true_high, linestyle=":", color="k")
plt.xlabel("x")
plt.show() | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Run MCMC and check the estimates: | mcmc = MCMC(NUTS(truncated_normal_model), **MCMC_KWARGS)
mcmc.run(MCMC_RNG, num_observations, true_x)
mcmc.print_summary() | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Compare estimates against the ground truth: | print(f"True high : {true_high:3.2f}")
print(f"True loc : {true_loc:3.2f}")
print(f"True scale: {true_scale:3.2f}") | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Note that, even though we can recover good estimates for the true values,
we had a very high number of divergences. These divergences happen because
the data can be outside of the support that we are allowing with our priors.
To fix this, we can change the prior on high so that it depends on the observations: | def truncated_normal_model_2(num_observations, x=None):
loc = numpyro.sample("loc", dist.Normal())
scale = numpyro.sample("scale", dist.LogNormal())
if x is None:
high = numpyro.sample("high", dist.Normal())
else:
# high is greater or equal to the max value in x:
delta = numpyro.... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
And the divergences are gone.
In practice, we usually want to understand how the data
would look like without the truncation. To do that in NumPyro,
there is no need of writing a separate model, we can simply
rely on the condition handler to push the truncation point to infinity: | model_without_truncation = numpyro.handlers.condition(
truncated_normal_model,
{"high": float("inf")},
)
estimates = mcmc.get_samples().copy()
estimates.pop("high") # Drop to make sure these are not used
pred = Predictive(
model_without_truncation,
posterior_samples=estimates,
)
pred_samples = pred(PRE... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
5.3 Example: Left-truncated Poisson <a class="anchor" id="5.3"></a>
As a final example, we now implement a left-truncated Poisson distribution.
Note that a right-truncated Poisson could be reformulated as a particular
case of a categorical distribution, so we focus on the less trivial case.
Class attributes
For a trunc... | def scipy_truncated_poisson_icdf(args): # Note: all arguments are passed inside a tuple
rate, low, u = args
rate = np.asarray(rate)
low = np.asarray(low)
u = np.asarray(u)
density = sp_poisson(rate)
low_cdf = density.cdf(low - 1)
normalizer = 1.0 - low_cdf
x = normalizer * u + low_cdf
... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Let's try it out! | def discrete_distplot(samples, ax=None, **kwargs):
"""
Utility function for plotting the samples as a barplot.
"""
x, y = np.unique(samples, return_counts=True)
y = y / sum(y)
if ax is None:
ax = plt.gca()
ax.bar(x, y, **kwargs)
return ax
def truncated_poisson_model(num_observa... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Prior samples | # -- prior samples
num_observations = 1000
num_prior_samples = 100
prior = Predictive(truncated_poisson_model, num_samples=num_prior_samples)
prior_samples = prior(PRIOR_RNG, num_observations) | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Inference
As in the case for the truncated normal, here it is better to replace
the prior on the low parameter so that it is consistent with the observed data.
We'd like to have a categorical prior on low (so that we can use DiscreteHMCGibbs)
whose highest category is equal to the minimum value of x (so that prior and ... | def truncated_poisson_model(num_observations, x=None, k=5):
zeros = jnp.zeros((k,))
low = numpyro.sample("low", dist.Categorical(logits=zeros))
rate = numpyro.sample("rate", dist.LogNormal(1, 1))
with numpyro.plate("observations", num_observations):
numpyro.sample("x", LeftTruncatedPoisson(rate,... | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
To do inference, we set k = x.min() + 1. Note also the use of DiscreteHMCGibbs: | mcmc = MCMC(DiscreteHMCGibbs(NUTS(truncated_poisson_model)), **MCMC_KWARGS)
mcmc.run(MCMC_RNG, num_observations, true_x, k=true_x.min() + 1)
mcmc.print_summary()
true_rate | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
As before, one needs to be extra careful when estimating the truncation point.
If the truncation point is known is best to provide it. | model_with_known_low = numpyro.handlers.condition(
truncated_poisson_model, {"low": true_low}
) | notebooks/source/truncated_distributions.ipynb | pyro-ppl/numpyro | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.