markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
-----Insert non-native gates, which are immediately decomposed into native ones | circuit.append(IsingGate(0.2)(a, c))
circuit.append(XYGate(0.5)(a, c))
circuit.append(cirq.HPowGate(exponent=-0.4)(a))
print(circuit) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Optimizing a quantum circuitUse the `IQMDevice.simplify_circuit` method to run a sequence of optimization passes on a circuit | circuit = cirq.Circuit(device=adonis)
circuit.append(cirq.H(a))
circuit.append(cirq.CNOT(a, c))
circuit.append(cirq.measure(a, c, key='result'))
print(circuit)
adonis.simplify_circuit(circuit)
print(circuit) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Simulating a quantum circuitCircuits that contain IQM-native gates can be simulated using the standard Cirq simulators | sim = cirq.Simulator()
samples = sim.run(circuit, repetitions=100)
print('Samples:')
print(samples.histogram(key='result'))
print('\nState before the measurement:')
result = sim.simulate(circuit[:-1])
print(result) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Note that the above output vector represents the state before the measurement in the optimized circuit, not the original one, which would have the same phase for both terms. `IQMDevice.simplify_circuit` has eliminated a `ZPowGate` which has no effect on the measurement.--- Creating a quantum circuit from an OpenQASM 2.... | qasm_program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg meas[3];
rx(1.7) q[1];
h q[0];
cx q[1], q[2];
ising(-0.6) q[0], q[2]; // OpenQASM extension
"""
circuit = circuit_from_qasm(qasm_program)
print(circuit) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Decompose the circuit for the Adonis architecture | decomposed = adonis.map_circuit(circuit)
print(decomposed) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Capsule Networks (CapsNets) Based on the paper: [Dynamic Routing Between Capsules](https://arxiv.org/abs/1710.09829), by Sara Sabour, Nicholas Frosst and Geoffrey E. Hinton (NIPS 2017). Inspired in part from Huadong Liao's implementation: [CapsNet-TensorFlow](https://github.com/naturomics/CapsNet-Tensorflow). Introdu... | from IPython.display import HTML
# Display the video in an iframe:
HTML("""<iframe width="560" height="315"
src="https://www.youtube.com/embed/pPN8d0E3900"
frameborder="0"
allowfullscreen></iframe>""") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Imports To support both Python 2 and Python 3: | from __future__ import division, print_function, unicode_literals | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
To plot pretty figures: | %matplotlib inline
import matplotlib
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
We will need NumPy and TensorFlow: | import numpy as np
import tensorflow as tf | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Reproducibility Let's reset the default graph, in case you re-run this notebook without restarting the kernel: | tf.reset_default_graph() | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's set the random seeds so that this notebook always produces the same output: | np.random.seed(42)
tf.set_random_seed(42) | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Load MNIST Yes, I know, it's MNIST again. But hopefully this powerful idea will work as well on larger datasets, time will tell. | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/") | Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's look at what these hand-written digit images look like: | n_samples = 5
plt.figure(figsize=(n_samples * 2, 3))
for index in range(n_samples):
plt.subplot(1, n_samples, index + 1)
sample_image = mnist.train.images[index].reshape(28, 28)
plt.imshow(sample_image, cmap="binary")
plt.axis("off")
plt.show() | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
And these are the corresponding labels: | mnist.train.labels[:n_samples] | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's build a Capsule Network to classify these images. Here's the overall architecture, enjoy the ASCII art! ;-)Note: for readability, I left out two arrows: Labels β Mask, and Input Images β Reconstruction Loss. ``` Loss β βββββββββββ΄βββββ... | X = tf.placeholder(shape=[None, 28, 28, 1], dtype=tf.float32, name="X") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Primary Capsules The first layer will be composed of 32 maps of 6Γ6 capsules each, where each capsule will output an 8D activation vector: | caps1_n_maps = 32
caps1_n_caps = caps1_n_maps * 6 * 6 # 1152 primary capsules
caps1_n_dims = 8 | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
To compute their outputs, we first apply two regular convolutional layers: | conv1_params = {
"filters": 256,
"kernel_size": 9,
"strides": 1,
"padding": "valid",
"activation": tf.nn.relu,
}
conv2_params = {
"filters": caps1_n_maps * caps1_n_dims, # 256 convolutional filters
"kernel_size": 9,
"strides": 2,
"padding": "valid",
"activation": tf.nn.relu
}
co... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Note: since we used a kernel size of 9 and no padding (for some reason, that's what `"valid"` means), the image shrunk by 9-1=8 pixels after each convolutional layer (28Γ28 to 20Γ20, then 20Γ20 to 12Γ12), and since we used a stride of 2 in the second convolutional layer, the image size was divided by 2. This is how we ... | caps1_raw = tf.reshape(conv2, [-1, caps1_n_caps, caps1_n_dims],
name="caps1_raw") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now we need to squash these vectors. Let's define the `squash()` function, based on equation (1) from the paper:$\operatorname{squash}(\mathbf{s}) = \dfrac{\|\mathbf{s}\|^2}{1 + \|\mathbf{s}\|^2} \dfrac{\mathbf{s}}{\|\mathbf{s}\|}$The `squash()` function will squash all vectors in the given array, along the given axis ... | def squash(s, axis=-1, epsilon=1e-7, name=None):
with tf.name_scope(name, default_name="squash"):
squared_norm = tf.reduce_sum(tf.square(s), axis=axis,
keep_dims=True)
safe_norm = tf.sqrt(squared_norm + epsilon)
squash_factor = squared_norm / (1. + square... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's apply this function to get the output $\mathbf{u}_i$ of each primary capsules $i$ : | caps1_output = squash(caps1_raw, name="caps1_output") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Great! We have the output of the first capsule layer. It wasn't too hard, was it? However, computing the next layer is where the fun really begins. Digit Capsules To compute the output of the digit capsules, we must first compute the predicted output vectors (one for each primary / digit capsule pair). Then we can run... | caps2_n_caps = 10
caps2_n_dims = 16 | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
For each capsule $i$ in the first layer, we want to predict the output of every capsule $j$ in the second layer. For this, we will need a transformation matrix $\mathbf{W}_{i,j}$ (one for each pair of capsules ($i$, $j$)), then we can compute the predicted output $\hat{\mathbf{u}}_{j|i} = \mathbf{W}_{i,j} \, \mathbf{u}... | init_sigma = 0.01
W_init = tf.random_normal(
shape=(1, caps1_n_caps, caps2_n_caps, caps2_n_dims, caps1_n_dims),
stddev=init_sigma, dtype=tf.float32, name="W_init")
W = tf.Variable(W_init, name="W") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now we can create the first array by repeating `W` once per instance: | batch_size = tf.shape(X)[0]
W_tiled = tf.tile(W, [batch_size, 1, 1, 1, 1], name="W_tiled") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
That's it! On to the second array, now. As discussed earlier, we need to create an array of shape (_batch size_, 1152, 10, 8, 1), containing the output of the first layer capsules, repeated 10 times (once per digit, along the third dimension, which is axis=2). The `caps1_output` array has a shape of (_batch size_, 1152... | caps1_output_expanded = tf.expand_dims(caps1_output, -1,
name="caps1_output_expanded")
caps1_output_tile = tf.expand_dims(caps1_output_expanded, 2,
name="caps1_output_tile")
caps1_output_tiled = tf.tile(caps1_output_tile, [1, 1, caps2_n_caps, 1, ... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's check the shape of the first array: | W_tiled | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Good, and now the second: | caps1_output_tiled | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Yes! Now, to get all the predicted output vectors $\hat{\mathbf{u}}_{j|i}$, we just need to multiply these two arrays using `tf.matmul()`, as explained earlier: | caps2_predicted = tf.matmul(W_tiled, caps1_output_tiled,
name="caps2_predicted") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's check the shape: | caps2_predicted | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Perfect, for each instance in the batch (we don't know the batch size yet, hence the "?") and for each pair of first and second layer capsules (1152Γ10) we have a 16D predicted output column vector (16Γ1). We're ready to apply the routing by agreement algorithm! Routing by agreement First let's initialize the raw rout... | raw_weights = tf.zeros([batch_size, caps1_n_caps, caps2_n_caps, 1, 1],
dtype=np.float32, name="raw_weights") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
We will see why we need the last two dimensions of size 1 in a minute. Round 1 First, let's apply the softmax function to compute the routing weights, $\mathbf{c}_{i} = \operatorname{softmax}(\mathbf{b}_i)$ (equation (3) in the paper): | routing_weights = tf.nn.softmax(raw_weights, dim=2, name="routing_weights") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's compute the weighted sum of all the predicted output vectors for each second-layer capsule, $\mathbf{s}_j = \sum\limits_{i}{c_{i,j}\hat{\mathbf{u}}_{j|i}}$ (equation (2)-left in the paper): | weighted_predictions = tf.multiply(routing_weights, caps2_predicted,
name="weighted_predictions")
weighted_sum = tf.reduce_sum(weighted_predictions, axis=1, keep_dims=True,
name="weighted_sum") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
There are a couple important details to note here:* To perform elementwise matrix multiplication (also called the Hadamard product, noted $\circ$), we use the `tf.multiply()` function. It requires `routing_weights` and `caps2_predicted` to have the same rank, which is why we added two extra dimensions of size 1 to `rou... | caps2_output_round_1 = squash(weighted_sum, axis=-2,
name="caps2_output_round_1")
caps2_output_round_1 | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Good! We have ten 16D output vectors for each instance, as expected. Round 2 First, let's measure how close each predicted vector $\hat{\mathbf{u}}_{j|i}$ is to the actual output vector $\mathbf{v}_j$ by computing their scalar product $\hat{\mathbf{u}}_{j|i} \cdot \mathbf{v}_j$. * Quick math reminder: if $\vec{a}$ and... | caps2_predicted | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
And now let's look at the shape of `caps2_output_round_1`, which holds 10 outputs vectors of 16D each, for each instance: | caps2_output_round_1 | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
To get these shapes to match, we just need to tile the `caps2_output_round_1` array 1152 times (once per primary capsule) along the second dimension: | caps2_output_round_1_tiled = tf.tile(
caps2_output_round_1, [1, caps1_n_caps, 1, 1, 1],
name="caps2_output_round_1_tiled") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
And now we are ready to call `tf.matmul()` (note that we must tell it to transpose the matrices in the first array, to get ${\hat{\mathbf{u}}_{j|i}}^T$ instead of $\hat{\mathbf{u}}_{j|i}$): | agreement = tf.matmul(caps2_predicted, caps2_output_round_1_tiled,
transpose_a=True, name="agreement") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
We can now update the raw routing weights $b_{i,j}$ by simply adding the scalar product $\hat{\mathbf{u}}_{j|i} \cdot \mathbf{v}_j$ we just computed: $b_{i,j} \gets b_{i,j} + \hat{\mathbf{u}}_{j|i} \cdot \mathbf{v}_j$ (see Procedure 1, step 7, in the paper). | raw_weights_round_2 = tf.add(raw_weights, agreement,
name="raw_weights_round_2") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
The rest of round 2 is the same as in round 1: | routing_weights_round_2 = tf.nn.softmax(raw_weights_round_2,
dim=2,
name="routing_weights_round_2")
weighted_predictions_round_2 = tf.multiply(routing_weights_round_2,
caps2_predicted,
... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
We could go on for a few more rounds, by repeating exactly the same steps as in round 2, but to keep things short, we will stop here: | caps2_output = caps2_output_round_2 | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Static or Dynamic Loop? In the code above, we created different operations in the TensorFlow graph for each round of the routing by agreement algorithm. In other words, it's a static loop.Sure, instead of copy/pasting the code several times, we could have written a `for` loop in Python, but this would not change the f... | def condition(input, counter):
return tf.less(counter, 100)
def loop_body(input, counter):
output = tf.add(input, tf.square(counter))
return output, tf.add(counter, 1)
with tf.name_scope("compute_sum_of_squares"):
counter = tf.constant(1)
sum_of_squares = tf.constant(0)
result = tf.while_loop... | (328350, 100)
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
As you can see, the `tf.while_loop()` function expects the loop condition and body to be provided _via_ two functions. These functions will be called only once by TensorFlow, during the graph construction phase, _not_ while executing the graph. The `tf.while_loop()` function stitches together the graph fragments create... | sum([i**2 for i in range(1, 100 + 1)]) | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Joke aside, apart from reducing the graph size, using a dynamic loop instead of a static loop can help reduce how much GPU RAM you use (if you are using a GPU). Indeed, if you set `swap_memory=True` when calling the `tf.while_loop()` function, TensorFlow will automatically check GPU RAM usage at each loop iteration, an... | def safe_norm(s, axis=-1, epsilon=1e-7, keep_dims=False, name=None):
with tf.name_scope(name, default_name="safe_norm"):
squared_norm = tf.reduce_sum(tf.square(s), axis=axis,
keep_dims=keep_dims)
return tf.sqrt(squared_norm + epsilon)
y_proba = safe_norm(caps2_ou... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
To predict the class of each instance, we can just select the one with the highest estimated probability. To do this, let's start by finding its index using `tf.argmax()`: | y_proba_argmax = tf.argmax(y_proba, axis=2, name="y_proba") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's look at the shape of `y_proba_argmax`: | y_proba_argmax | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
That's what we wanted: for each instance, we now have the index of the longest output vector. Let's get rid of the last two dimensions by using `tf.squeeze()` which removes dimensions of size 1. This gives us the capsule network's predicted class for each instance: | y_pred = tf.squeeze(y_proba_argmax, axis=[1,2], name="y_pred")
y_pred | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Okay, we are now ready to define the training operations, starting with the losses. Labels First, we will need a placeholder for the labels: | y = tf.placeholder(shape=[None], dtype=tf.int64, name="y") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Margin loss The paper uses a special margin loss to make it possible to detect two or more different digits in each image:$ L_k = T_k \max(0, m^{+} - \|\mathbf{v}_k\|)^2 - \lambda (1 - T_k) \max(0, \|\mathbf{v}_k\| - m^{-})^2$* $T_k$ is equal to 1 if the digit of class $k$ is present, or 0 otherwise.* In the paper, $m... | m_plus = 0.9
m_minus = 0.1
lambda_ = 0.5 | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Since `y` will contain the digit classes, from 0 to 9, to get $T_k$ for every instance and every class, we can just use the `tf.one_hot()` function: | T = tf.one_hot(y, depth=caps2_n_caps, name="T") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
A small example should make it clear what this does: | with tf.Session():
print(T.eval(feed_dict={y: np.array([0, 1, 2, 3, 9])})) | [[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's compute the norm of the output vector for each output capsule and each instance. First, let's verify the shape of `caps2_output`: | caps2_output | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
The 16D output vectors are in the second to last dimension, so let's use the `safe_norm()` function with `axis=-2`: | caps2_output_norm = safe_norm(caps2_output, axis=-2, keep_dims=True,
name="caps2_output_norm") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's compute $\max(0, m^{+} - \|\mathbf{v}_k\|)^2$, and reshape the result to get a simple matrix of shape (_batch size_, 10): | present_error_raw = tf.square(tf.maximum(0., m_plus - caps2_output_norm),
name="present_error_raw")
present_error = tf.reshape(present_error_raw, shape=(-1, 10),
name="present_error") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Next let's compute $\max(0, \|\mathbf{v}_k\| - m^{-})^2$ and reshape it: | absent_error_raw = tf.square(tf.maximum(0., caps2_output_norm - m_minus),
name="absent_error_raw")
absent_error = tf.reshape(absent_error_raw, shape=(-1, 10),
name="absent_error") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
We are ready to compute the loss for each instance and each digit: | L = tf.add(T * present_error, lambda_ * (1.0 - T) * absent_error,
name="L") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now we can sum the digit losses for each instance ($L_0 + L_1 + \cdots + L_9$), and compute the mean over all instances. This gives us the final margin loss: | margin_loss = tf.reduce_mean(tf.reduce_sum(L, axis=1), name="margin_loss") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Reconstruction Now let's add a decoder network on top of the capsule network. It is a regular 3-layer fully connected neural network which will learn to reconstruct the input images based on the output of the capsule network. This will force the capsule network to preserve all the information required to reconstruct t... | mask_with_labels = tf.placeholder_with_default(False, shape=(),
name="mask_with_labels") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's use `tf.cond()` to define the reconstruction targets as the labels `y` if `mask_with_labels` is `True`, or `y_pred` otherwise. | reconstruction_targets = tf.cond(mask_with_labels, # condition
lambda: y, # if True
lambda: y_pred, # if False
name="reconstruction_targets") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Note that the `tf.cond()` function expects the if-True and if-False tensors to be passed _via_ functions: these functions will be called just once during the graph construction phase (not during the execution phase), similar to `tf.while_loop()`. This allows TensorFlow to add the necessary operations to handle the cond... | reconstruction_mask = tf.one_hot(reconstruction_targets,
depth=caps2_n_caps,
name="reconstruction_mask") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's check the shape of `reconstruction_mask`: | reconstruction_mask | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's compare this to the shape of `caps2_output`: | caps2_output | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Mmh, its shape is (_batch size_, 1, 10, 16, 1). We want to multiply it by the `reconstruction_mask`, but the shape of the `reconstruction_mask` is (_batch size_, 10). We must reshape it to (_batch size_, 1, 10, 1, 1) to make multiplication possible: | reconstruction_mask_reshaped = tf.reshape(
reconstruction_mask, [-1, 1, caps2_n_caps, 1, 1],
name="reconstruction_mask_reshaped") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
At last! We can apply the mask: | caps2_output_masked = tf.multiply(
caps2_output, reconstruction_mask_reshaped,
name="caps2_output_masked")
caps2_output_masked | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
One last reshape operation to flatten the decoder's inputs: | decoder_input = tf.reshape(caps2_output_masked,
[-1, caps2_n_caps * caps2_n_dims],
name="decoder_input") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
This gives us an array of shape (_batch size_, 160): | decoder_input | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Decoder Now let's build the decoder. It's quite simple: two dense (fully connected) ReLU layers followed by a dense output sigmoid layer: | n_hidden1 = 512
n_hidden2 = 1024
n_output = 28 * 28
with tf.name_scope("decoder"):
hidden1 = tf.layers.dense(decoder_input, n_hidden1,
activation=tf.nn.relu,
name="hidden1")
hidden2 = tf.layers.dense(hidden1, n_hidden2,
ac... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Reconstruction Loss Now let's compute the reconstruction loss. It is just the squared difference between the input image and the reconstructed image: | X_flat = tf.reshape(X, [-1, n_output], name="X_flat")
squared_difference = tf.square(X_flat - decoder_output,
name="squared_difference")
reconstruction_loss = tf.reduce_sum(squared_difference,
name="reconstruction_loss") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Final Loss The final loss is the sum of the margin loss and the reconstruction loss (scaled down by a factor of 0.0005 to ensure the margin loss dominates training): | alpha = 0.0005
loss = tf.add(margin_loss, alpha * reconstruction_loss, name="loss") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Final Touches Accuracy To measure our model's accuracy, we need to count the number of instances that are properly classified. For this, we can simply compare `y` and `y_pred`, convert the boolean value to a float32 (0.0 for False, 1.0 for True), and compute the mean over all the instances: | correct = tf.equal(y, y_pred, name="correct")
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32), name="accuracy") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Training Operations The paper mentions that the authors used the Adam optimizer with TensorFlow's default parameters: | optimizer = tf.train.AdamOptimizer()
training_op = optimizer.minimize(loss, name="training_op") | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Init and Saver And let's add the usual variable initializer, as well as a `Saver`: | init = tf.global_variables_initializer()
saver = tf.train.Saver() | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
And... we're done with the construction phase! Please take a moment to celebrate. :) Training Training our capsule network is pretty standard. For simplicity, we won't do any fancy hyperparameter tuning, dropout or anything, we will just run the training operation over and over again, displaying the loss, and at the e... | n_epochs = 10
batch_size = 50
restore_checkpoint = True
n_iterations_per_epoch = mnist.train.num_examples // batch_size
n_iterations_validation = mnist.validation.num_examples // batch_size
best_loss_val = np.infty
checkpoint_path = "./my_capsule_network"
with tf.Session() as sess:
if restore_checkpoint and tf.tr... | Epoch: 1 Val accuracy: 98.7000% Loss: 0.416563 (improved)
Epoch: 2 Val accuracy: 99.0400% Loss: 0.291740 (improved)
Epoch: 3 Val accuracy: 99.1200% Loss: 0.241666 (improved)
Epoch: 4 Val accuracy: 99.2800% Loss: 0.211442 (improved)
Epoch: 5 Val accuracy: 99.3200% Loss: 0.196026 (improved)
Epoch: 6 Val accura... | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Training is finished, we reached over 99.3% accuracy on the validation set after just 5 epochs, things are looking good. Now let's evaluate the model on the test set. Evaluation | n_iterations_test = mnist.test.num_examples // batch_size
with tf.Session() as sess:
saver.restore(sess, checkpoint_path)
loss_tests = []
acc_tests = []
for iteration in range(1, n_iterations_test + 1):
X_batch, y_batch = mnist.test.next_batch(batch_size)
loss_test, acc_test = sess.run... | INFO:tensorflow:Restoring parameters from ./my_capsule_network
Final test accuracy: 99.4300% Loss: 0.165047
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
We reach 99.43% accuracy on the test set. Pretty nice. :) Predictions Now let's make some predictions! We first fix a few images from the test set, then we start a session, restore the trained model, evaluate `caps2_output` to get the capsule network's output vectors, `decoder_output` to get the reconstructions, and `... | n_samples = 5
sample_images = mnist.test.images[:n_samples].reshape([-1, 28, 28, 1])
with tf.Session() as sess:
saver.restore(sess, checkpoint_path)
caps2_output_value, decoder_output_value, y_pred_value = sess.run(
[caps2_output, decoder_output, y_pred],
feed_dict={X: sample_images,
... | INFO:tensorflow:Restoring parameters from ./my_capsule_network
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Note: we feed `y` with an empty array, but TensorFlow will not use it, as explained earlier. And now let's plot the images and their labels, followed by the corresponding reconstructions and predictions: | sample_images = sample_images.reshape(-1, 28, 28)
reconstructions = decoder_output_value.reshape([-1, 28, 28])
plt.figure(figsize=(n_samples * 2, 3))
for index in range(n_samples):
plt.subplot(1, n_samples, index + 1)
plt.imshow(sample_images[index], cmap="binary")
plt.title("Label:" + str(mnist.test.label... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
The predictions are all correct, and the reconstructions look great. Hurray! Interpreting the Output Vectors Let's tweak the output vectors to see what their pose parameters represent. First, let's check the shape of the `cap2_output_value` NumPy array: | caps2_output_value.shape | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's create a function that will tweak each of the 16 pose parameters (dimensions) in all output vectors. Each tweaked output vector will be identical to the original output vector, except that one of its pose parameters will be incremented by a value varying from -0.5 to 0.5. By default there will be 11 steps (-0.5, ... | def tweak_pose_parameters(output_vectors, min=-0.5, max=0.5, n_steps=11):
steps = np.linspace(min, max, n_steps) # -0.25, -0.15, ..., +0.25
pose_parameters = np.arange(caps2_n_dims) # 0, 1, ..., 15
tweaks = np.zeros([caps2_n_dims, n_steps, 1, 1, 1, caps2_n_dims, 1])
tweaks[pose_parameters, :, 0, 0, 0, p... | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's compute all the tweaked output vectors and reshape the result to (_parameters_Γ_steps_Γ_instances_, 1, 10, 16, 1) so we can feed the array to the decoder: | n_steps = 11
tweaked_vectors = tweak_pose_parameters(caps2_output_value, n_steps=n_steps)
tweaked_vectors_reshaped = tweaked_vectors.reshape(
[-1, 1, caps2_n_caps, caps2_n_dims, 1]) | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Now let's feed these tweaked output vectors to the decoder and get the reconstructions it produces: | tweak_labels = np.tile(mnist.test.labels[:n_samples], caps2_n_dims * n_steps)
with tf.Session() as sess:
saver.restore(sess, checkpoint_path)
decoder_output_value = sess.run(
decoder_output,
feed_dict={caps2_output: tweaked_vectors_reshaped,
mask_with_labels: True... | INFO:tensorflow:Restoring parameters from ./my_capsule_network
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Let's reshape the decoder's output so we can easily iterate on the output dimension, the tweak steps, and the instances: | tweak_reconstructions = decoder_output_value.reshape(
[caps2_n_dims, n_steps, n_samples, 28, 28]) | _____no_output_____ | Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Lastly, let's plot all the reconstructions, for the first 3 output dimensions, for each tweaking step (column) and each digit (row): | for dim in range(3):
print("Tweaking output dimension #{}".format(dim))
plt.figure(figsize=(n_steps / 1.2, n_samples / 1.5))
for row in range(n_samples):
for col in range(n_steps):
plt.subplot(n_samples, n_steps, row * n_steps + col + 1)
plt.imshow(tweak_reconstructions[dim, ... | Tweaking output dimension #0
| Apache-2.0 | extra_capsnets.ipynb | jbagnato/handson-ml |
Detecting depression in Tweets using Baye's Theorem Installing and importing libraries | !pip install wordcloud
!pip install nltk
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from math import log, sqrt
import pandas as pd
import numpy as np
impo... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Loading the Data | tweets = pd.read_csv('sentiment_tweets3.csv')
tweets.head(20)
tweets.drop(['Unnamed: 0'], axis = 1, inplace = True)
tweets['label'].value_counts()
tweets.info() | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Splitting the Data in Training and Testing Sets As you can see, I used almost all the data for training: 98% and the rest for testing. | totalTweets = 8000 + 2314
trainIndex, testIndex = list(), list()
for i in range(tweets.shape[0]):
if np.random.uniform(0, 1) < 0.98:
trainIndex += [i]
else:
testIndex += [i]
trainData = tweets.iloc[trainIndex]
testData = tweets.iloc[testIndex]
tweets.info()
trainData['label'].value_counts()
trai... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Wordcloud Analysis | depressive_words = ' '.join(list(tweets[tweets['label'] == 1]['message']))
depressive_wc = WordCloud(width = 512,height = 512, collocations=False, colormap="Blues").generate(depressive_words)
plt.figure(figsize = (10, 8), facecolor = 'k')
plt.imshow(depressive_wc)
plt.axis('off')
plt.tight_layout(pad = 0)
plt.show()
po... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Pre-processing the data for the training: Tokenization, stemming, and removal of stop words | def process_message(message, lower_case = True, stem = True, stop_words = True, gram = 2):
if lower_case:
message = message.lower()
words = word_tokenize(message)
words = [w for w in words if len(w) > 2]
if gram > 1:
w = []
for i in range(len(words) - gram + 1):
w += ... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Predictions with TF-IDF Depressive Tweets | pm = process_message('Lately I have been feeling unsure of myself as a person & an artist')
sc_tf_idf.classify(pm)
pm = process_message('Extreme sadness, lack of energy, hopelessness')
sc_tf_idf.classify(pm)
pm = process_message('Hi hello depression and anxiety are the worst')
sc_tf_idf.classify(pm)
pm = process_messa... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Positive Tweets | pm = process_message('Loving how me and my lovely partner is talking about what we want.')
sc_tf_idf.classify(pm)
pm = process_message('Very rewarding when a patient hugs you and tells you they feel great after changing the diet and daily habits')
sc_tf_idf.classify(pm)
pm = process_message('Happy Thursday everyone. ... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Predictions with Bag-of-Words (BOW) Depressive tweets | pm = process_message('Hi hello depression and anxiety are the worst')
sc_bow.classify(pm)
pm = process_message('My depression will not let me work out')
sc_bow.classify(pm)
pm = process_message('Feeling down...')
sc_bow.classify(pm) | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
Positive Tweets | pm = process_message('Loving how me and my lovely partner is talking about what we want.')
sc_bow.classify(pm)
pm = process_message('Very rewarding when a patient hugs you and tells you they feel great after changing the diet and daily habits')
sc_bow.classify(pm)
pm = process_message('Happy Thursday everyone. Thought ... | _____no_output_____ | MIT | Sentimental Analysis/Detecting-Depression-in-Tweets/Depression_detection_tweets.ipynb | Manas-Garg/sentimental-analysis |
import torch
import torchvision
import torch.nn as nn
import matplotlib.pyplot as plt
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from torch.utils.data.dataloader import DataLoader
from google.colab import drive
drive.mount('/content/drive')
!unzip -q /content/drive/My... | _____no_output_____ | MIT | notebooks/Sig-mu_vae.ipynb | Anmol42/IDP-sem4 | |
MicroGrid Energy Management SummaryThe goal of the Microgrid problem is to compute an optimal power flow within the distributed sources, loads, storages and a main grid. On a given time horizon $H$, the optimal power flow poblem aims to find the optimal command of the components, e.g.charging/discharging for storage, ... | from pyomo.environ import *
from pyomo.dae import ContinuousSet, Integral
H = 60*60*24 # Time horizon in seconds
m = AbstractModel()
m.time = ContinuousSet(initialize=(0, H)) | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
BlocksThe microgrid is created by connecting units together, such as batteries, loads, renewable sources, etc. In the pyomo vocabulary, such a components is called a block. As a first step, the microgrid is constituted of a renewable power source (PV panel), a critical load, and a connection to the main grid.A quick d... | from batteries import AbsBatteryV0
from maingrids import AbsMainGridV0
from sources import AbsFixedPowerLoad, AbsFixedPowerSource
m.mg = AbsMainGridV0()
m.s = AbsFixedPowerSource()
m.l = AbsFixedPowerLoad() | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
Each block is described by a set of constrains, variables, parameter and expressions.One can print any pyomo object using the `pprint` method. Example : m.mg.pprint()One can access documentation of any object using the builtIn method `doc` or `help` function (for heritance). Pop-up documentation shortcut : `Shift... | @m.Constraint(m.time)
def power_balance(m, t):
return m.mg.p[t] + m.s.p[t] == m.l.p[t] | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
ObjectifAs a first hypothesis, we will only consider a fixed selling/buying price of energy $c$, such that : $$J = \int_{0}^{H} c.p_{mg}(t)$$.Pyomo allows you to make integrals over a continuous set as follow : | m.int = Integral(m.time, wrt=m.time, rule=lambda m, i: m.mg.inst_cost[i])
m.obj = Objective(expr=m.int) | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
Instantiate the problem, discretize it and solve it`m` is a pyomo Abstract Model, as we saw in the pyomo tutorial. Which meens that the structure of the problem is now completlty defined and may be used for different scenarios or cases. The fllowing steps consern :1. Loading data (scenario, predictions and sizing of t... | %run data/data_models.py
df_s[['P_pv', 'P_load_1']].plot(figsize=(15,3)) | /home/admin/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/datetimes.py:1172: UserWarning: Converting to PeriodArray/Index representation will drop timezone information.
"will drop timezone information.", UserWarning)
| BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
2. Problem InstantiationThe abstract model is instanciate by the previously definied data dictionnary, as follow : | inst = m.create_instance(data) | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
DiscretizationAfter instantiation, one can discretize the problem equation over the time horizon. In the folowing, we choose a number of finite element $nfe = 96$ i.e. every $15~ min$ for $H=1\ day$. | from pyomo.environ import TransformationFactory
inst = m.create_instance(data)
nfe = 60*60*24/(15*60)
TransformationFactory('dae.finite_difference').apply_to(inst, nfe=nfe) | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
SolvingThe problem is solve as follow : | opt = SolverFactory("glpk")
res = opt.solve(inst, load_solutions=True) | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
Post-Processing | from utils import pplot
index = pd.date_range(start = TSTART, end = TEND, periods = nfe+1)
pplot(inst.mg.p, inst.l.p, inst.s.p, index = index, marker='x', figsize=(10,5)) | _____no_output_____ | BSD-2-Clause-FreeBSD | PyomoTutorial/microgrid/Microgrid_problem_0.ipynb | ReinboldV/PyomoGallery |
Analyzing interstellar reddening and calculating synthetic photometry AuthorsKristen Larson, Lia Corrales, Stephanie T. Douglas, Kelle CruzInput from Emir Karamehmetoglu, Pey Lian Lim, Karl Gordon, Kevin Covey Learning Goals- Investigate extinction curve shapes- Deredden spectral energy distributions and spectra- Ca... | import pathlib
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import astropy.units as u
from astropy.table import Table
from dust_extinction.parameter_averages import CCM89, F99
from synphot import units, config
from synphot import SourceSpectrum,SpectralElement,Observation,ExtinctionModel1D
fr... | _____no_output_____ | BSD-3-Clause | tutorials/color-excess/color-excess.ipynb | jvictor42/astropy-tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.