markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
We apply another type of normalization to 0-1 just for the purposes of plotting the image. If we didn't do this, the range of our values would be somewhere between -1 and 1, and matplotlib would not be able to interpret the entire range of values. By rescaling our -1 to 1 valued images to 0-1, we can visualize it better.
norm_imgs_show = (norm_imgs - np.min(norm_imgs)) / (np.max(norm_imgs) - np.min(norm_imgs)) plt.figure(figsize=(10, 10)) plt.imshow(utils.montage(norm_imgs_show, 'normalized.png'))
session-1/session-1.ipynb
goddoe/CADL
apache-2.0
<a name="part-five---convolve-the-dataset"></a> Part Five - Convolve the Dataset <a name="instructions-4"></a> Instructions Using tensorflow, we'll attempt to convolve your dataset with one of the kernels we created during the lesson, and then in the next part, we'll take the sum of the convolved output to use for sorting. You should use the function utils.gabor to create an edge detector. You can also explore with the utils.gauss2d kernel. What you must figure out is how to reshape your kernel to be 4-dimensional: K_H, K_W, C_I, and C_O, corresponding to the kernel's height and width (e.g. 16), the number of input channels (RGB = 3 input channels), and the number of output channels, (1). <a name="code-4"></a> Code <h3><font color='red'>TODO! COMPLETE THIS SECTION!</font></h3>
# First build 3 kernels for each input color channel ksize = ... kernel = np.concatenate([utils.gabor(ksize)[:, :, np.newaxis] for i in range(3)], axis=2) # Now make the kernels into the shape: [ksize, ksize, 3, 1]: kernel_4d = ... assert(kernel_4d.shape == (ksize, ksize, 3, 1))
session-1/session-1.ipynb
goddoe/CADL
apache-2.0
We'll Perform the convolution with the 4d tensor in kernel_4d. This is a ksize x ksize x 3 x 1 tensor, where each input color channel corresponds to one filter with 1 output. Each filter looks like:
plt.figure(figsize=(5, 5)) plt.imshow(kernel_4d[:, :, 0, 0], cmap='gray') plt.imsave(arr=kernel_4d[:, :, 0, 0], fname='kernel.png', cmap='gray')
session-1/session-1.ipynb
goddoe/CADL
apache-2.0
Perform the convolution with the 4d tensors: <h3><font color='red'>TODO! COMPLETE THIS SECTION!</font></h3>
convolved = utils.convolve(... convolved_show = (convolved - np.min(convolved)) / (np.max(convolved) - np.min(convolved)) print(convolved_show.shape) plt.figure(figsize=(10, 10)) plt.imshow(utils.montage(convolved_show[..., 0], 'convolved.png'), cmap='gray')
session-1/session-1.ipynb
goddoe/CADL
apache-2.0
What we've just done is build a "hand-crafted" feature detector: the Gabor Kernel. This kernel is built to respond to particular orientation: horizontal edges, and a particular scale. It also responds equally to R, G, and B color channels, as that is how we have told the convolve operation to work: use the same kernel for every input color channel. When we work with deep networks, we'll see how we can learn the convolution kernels for every color channel, and learn many more of them, in the order of 100s per color channel. That is really where the power of deep networks will start to become obvious. For now, we've seen just how difficult it is to get at any higher order features of the dataset. We've really only picked out some edges! <a name="part-six---sort-the-dataset"></a> Part Six - Sort the Dataset <a name="instructions-5"></a> Instructions Using tensorflow, we'll attempt to organize your dataset. We'll try sorting based on the mean value of each convolved image's output to use for sorting. To do this, we could calculate either the sum value (tf.reduce_sum) or the mean value (tf.reduce_mean) of each image in your dataset and then use those values, e.g. stored inside a variable values to sort your images using something like tf.nn.top_k and sorted_imgs = np.array([imgs[idx_i] for idx_i in idxs]) prior to creating the montage image, m = montage(sorted_imgs, "sorted.png") and then include this image in your zip file as <b>sorted.png</b> <a name="code-5"></a> Code <h3><font color='red'>TODO! COMPLETE THIS SECTION!</font></h3>
# Create a set of operations using tensorflow which could # provide you for instance the sum or mean value of every # image in your dataset: # First flatten our convolved images so instead of many 3d images, # we have many 1d vectors. # This should convert our 4d representation of N x H x W x C to a # 2d representation of N x (H*W*C) flattened = tf.reshape(convolved... assert(flattened.get_shape().as_list() == [100, 10000]) # Now calculate some statistics about each of our images values = tf.reduce_sum(flattened, axis=1) # Then create another operation which sorts those values # and then calculate the result: idxs_op = tf.nn.top_k(values, k=100)[1] idxs = sess.run(idxs_op) # Then finally use the sorted indices to sort your images: sorted_imgs = np.array([imgs[idx_i] for idx_i in idxs]) # Then plot the resulting sorted dataset montage: # Make sure we have a 100 x 100 x 100 x 3 dimension array assert(sorted_imgs.shape == (100, 100, 100, 3)) plt.figure(figsize=(10, 10)) plt.imshow(utils.montage(sorted_imgs, 'sorted.png'))
session-1/session-1.ipynb
goddoe/CADL
apache-2.0
What does your sorting reveal? Could you imagine the same sorting over many more images reveal the thing your dataset sought to represent? It is likely that the representations that you wanted to find hidden within "higher layers", i.e., "deeper features" of the image, and that these "low level" features, edges essentially, are not very good at describing the really interesting aspects of your dataset. In later sessions, we'll see how we can combine the outputs of many more convolution kernels that have been assembled in a way that accentuate something very particular about each image, and build a sorting that is much more intelligent than this one! <a name="assignment-submission"></a> Assignment Submission Now that you've completed all 6 parts, we'll create a zip file of the current directory using the code below. This code will make sure you have included this completed ipython notebook and the following files named exactly as: <pre> session-1/ session-1.ipynb dataset.png mean.png std.png normalized.png kernel.png convolved.png sorted.png libs/ utils.py </pre> You'll then submit this zip file for your first assignment on Kadenze for "Assignment 1: Datasets/Computing with Tensorflow"! If you have any questions, remember to reach out on the forums and connect with your peers or with me. <b>To get assessed, you'll need to be a premium student.</b> If you aren't already enrolled as a student, register now at http://www.kadenze.com/ and join the #CADL community to see what your peers are doing! https://www.kadenze.com/courses/creative-applications-of-deep-learning-with-tensorflow/info Then remember to complete the remaining parts of Assignemnt 1 on Kadenze!: * Comment on 1 student's open-ended arrangement (Part 6) in the course gallery titled "Creating a Dataset/ Computing with Tensorflow". Think about what images they've used in their dataset and how the arrangement reflects what could be represented by that data. * Finally make a forum post in the forum for this assignment "Creating a Dataset/ Computing with Tensorflow". - Including a link to an artist making use of machine learning to organize data or finding representations within large datasets - Tell a little about their work (min 20 words). - Comment on at least 2 other student's forum posts (min 20 words) Make sure your notebook is named "session-1" or else replace it with the correct name in the list of files below:
utils.build_submission('session-1.zip', ('dataset.png', 'mean.png', 'std.png', 'normalized.png', 'kernel.png', 'convolved.png', 'sorted.png', 'session-1.ipynb'))
session-1/session-1.ipynb
goddoe/CADL
apache-2.0
Shor's algorithm <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://quantumai.google/cirq/tutorials/shor"><img src="https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png" />View on QuantumAI</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/shor.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/shor.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/github_logo_1x.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/shor.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/download_icon_1x.png" />Download notebook</a> </td> </table> This tutorial presents a pedagogical demonstration of Shor's algorithm. It is a modified and expanded version of this Cirq example.
"""Install Cirq.""" try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") """Imports for the notebook.""" import fractions import math import random import numpy as np import sympy from typing import Callable, List, Optional, Sequence, Union import cirq
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
Order finding Factoring an integer $n$ can be reduced to finding the period of the <i>modular exponential function</i> (to be defined). Finding this period can be accomplished (with high probability) by finding the <i>order</i> of a randomly chosen element of the multiplicative group modulo $n$. Let $n$ be a positive integer and $$ \mathbb{Z}n := {x \in \mathbb{Z}+ : x < n \text{ and } \text{gcd}(x, n) = 1} $$ be the multiplicative group modulo $n$. Given $x \in \mathbb{Z}_n$, compute the smallest positive integer $r$ such that $x^r \text{ mod } n = 1$. It can be shown from group/number theory that: (1) Such an integer $r$ exists. (Note that $g^{|G|} = 1_G$ for any group $G$ with cardinality $|G|$ and element $g \in G$, but it's possible that $r < |G|$.) (2) If $n = pq$ for primes $p$ and $q$, then $|\mathbb{Z}_n| = \phi(n) = (p - 1) (q - 1)$. (The function $\phi$ is called Euler's totient function.) (3) The modular exponential function $$ f_x(z) := x^z \mod n $$ is periodic with period $r$ (the order of the element $x \in \mathbb{Z}_n$). That is, $f_x(z + r) = f_x(z)$. (4) If we know the period of the modular exponential function, we can (with high probability) figure out $p$ and $q$ -- that is, factor $n$. As a refresher, we can visualize the elements of some multiplicative groups $\mathbb{Z}_n$ for integers $n$ via the following simple function.
"""Function to compute the elements of Z_n.""" def multiplicative_group(n: int) -> List[int]: """Returns the multiplicative group modulo n. Args: n: Modulus of the multiplicative group. """ assert n > 1 group = [1] for x in range(2, n): if math.gcd(x, n) == 1: group.append(x) return group
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
For example, the multiplicative group modulo $n = 15$ is shown below.
"""Example of a multiplicative group.""" n = 15 print(f"The multiplicative group modulo n = {n} is:") print(multiplicative_group(n))
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
One can check that this set of elements indeed forms a group (under ordinary multiplication). Classical order finding A function for classically computing the order $r$ of an element $x \in \mathbb{Z}_n$ is provided below. This function simply computes the sequence $$ x^2 \text{ mod } n $$ $$ x^3 \text{ mod } n $$ $$ x^4 \text{ mod } n $$ $$ \vdots $$ until an integer $r$ is found such that $x^r = 1 \text{ mod } n$. Since $|\mathbb{Z}_n| = \phi(n)$, this algorithm for order finding has time complexity $O(\phi(n))$ which is inefficient. (Roughly $O(2^{L / 2})$ where $L$ is the number of bits in $n$.)
"""Function for classically computing the order of an element of Z_n.""" def classical_order_finder(x: int, n: int) -> Optional[int]: """Computes smallest positive r such that x**r mod n == 1. Args: x: Integer whose order is to be computed, must be greater than one and belong to the multiplicative group of integers modulo n (which consists of positive integers relatively prime to n), n: Modulus of the multiplicative group. Returns: Smallest positive integer r such that x**r == 1 mod n. Always succeeds (and hence never returns None). Raises: ValueError when x is 1 or not an element of the multiplicative group of integers modulo n. """ # Make sure x is both valid and in Z_n. if x < 2 or x >= n or math.gcd(x, n) > 1: raise ValueError(f"Invalid x={x} for modulus n={n}.") # Determine the order. r, y = 1, x while y != 1: y = (x * y) % n r += 1 return r
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
An example of computing $r$ for a given $x \in \mathbb{Z}_n$ and given $n$ is shown in the code block below.
"""Example of (classically) computing the order of an element.""" n = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14]. x = 8 r = classical_order_finder(x, n) # Check that the order is indeed correct. print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}")
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
The quantum part of Shor's algorithm is order finding, but done via a quantum circuit, which we'll discuss below. Quantum order finding Quantum order finding is essentially quantum phase estimation with unitary $U$ that computes the modular exponential function $f_x(z)$ for some randomly chosen $x \in \mathbb{Z}_n$. The full details of how $U$ is computed in terms of elementary gates can be complex to unravel, especially on a first reading. In this tutorial, we'll use arithmetic operations in Cirq which can implement such a unitary $U$ without fully delving into the details of elementary gates. Below we first show an example of a simple arithmetic operation in Cirq (addition) then discuss the operation we care about (modular exponentiation). Quantum arithmetic operations in Cirq Here we discuss an example of defining an arithmetic operation in Cirq, namely modular addition. This operation adds the value of the input register into the target register. More specifically, this operation acts on two qubit registers as $$ |a\rangle_i |b\rangle_t \mapsto |a\rangle_i |a + b \text{ mod } N_t \rangle_t . $$ Here, the subscripts $i$ and $t$ denote <i>i</i>nput and <i>t</i>arget register, respectively, and $N_t$ is the dimension of the target register. To define this operation, called Adder, we inherit from cirq.ArithmeticOperation and override the four methods shown below. The main method is the apply method which defines the arithmetic. Here, we simply state the expression as $a + b$ instead of the more accurate $a + b \text{ mod } N_t$ above -- the cirq.ArithmeticOperation class is able to deduce what we mean by simply $a + b$ since the operation must be reversible.
"""Example of defining an arithmetic (quantum) operation in Cirq.""" class Adder(cirq.ArithmeticOperation): """Quantum addition.""" def __init__(self, target_register, input_register): self.input_register = input_register self.target_register = target_register def registers(self): return self.target_register, self.input_register def with_registers(self, *new_registers): return Adder(*new_registers) def apply(self, target_value, input_value): return target_value + input_value
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
Now that we have the operation defined, we can use it in a circuit. The cell below creates two qubit registers, then sets the first register to be $|10\rangle$ (in binary) and the second register to be $|01\rangle$ (in binary) via $X$ gates. Then, we use the Adder operation, then measure all the qubits. Since $10 + 01 = 11$ (in binary), we expect to measure $|11\rangle$ in the target register every time. Additionally, since we do not alter the input register, we expect to measure $|10\rangle$ in the input register every time. In short, the only bitstring we expect to measure is $1011$.
"""Example of using an Adder in a circuit.""" # Two qubit registers. qreg1 = cirq.LineQubit.range(2) qreg2 = cirq.LineQubit.range(2, 4) # Define the circuit. circ = cirq.Circuit( cirq.ops.X.on(qreg1[0]), cirq.ops.X.on(qreg2[1]), Adder(input_register=qreg1, target_register=qreg2), cirq.measure_each(*qreg1), cirq.measure_each(*qreg2) ) # Display it. print("Circuit:\n") print(circ) # Print the measurement outcomes. print("\n\nMeasurement outcomes:\n") print(cirq.sample(circ, repetitions=5).data)
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
In the output of this code block, we first see the circuit which shows the initial $X$ gates, the Adder operation, then the final measurements. Next, we see the measurement outcomes which are all the bitstring $1011$ as expected. It is also possible to see the unitary of the adder operation, which we do below. Here, we set the target register to be two qubits in the zero state, i.e. $|00\rangle$. We specify the input register as the integer one which corresponds to the qubit register $|01\rangle$.
"""Example of the unitary of an Adder operation.""" cirq.unitary( Adder(target_register=cirq.LineQubit.range(2), input_register=1) ).real
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
We can understand this unitary as follows. The $i$th column of the unitary is the state $|i + 1 \text{ mod } 4\rangle$. For example, if we look at the $0$th column of the unitary, we see the state $|i + 1 \text{ mod } 4\rangle = |0 + 1 \text{ mod } 4\rangle = |1\rangle$. If we look at the $1$st column of the unitary, we see the state $|i + 1 \text{ mod } 4\rangle = |1 + 1 \text{ mod } 4\rangle = |2\rangle$. Similarly for the last two columns. Modular exponential arithmetic operation We can define the modular exponential arithmetic operation in a similar way to the simple addition arithmetic operation, shown below. For the purposes of understanding Shor's algorithm, the most important part of the following code block is the apply method which defines the arithmetic operation.
"""Defines the modular exponential operation used in Shor's algorithm.""" class ModularExp(cirq.ArithmeticOperation): """Quantum modular exponentiation. This class represents the unitary which multiplies base raised to exponent into the target modulo the given modulus. More precisely, it represents the unitary V which computes modular exponentiation x**e mod n: V|y⟩|e⟩ = |y * x**e mod n⟩ |e⟩ 0 <= y < n V|y⟩|e⟩ = |y⟩ |e⟩ n <= y where y is the target register, e is the exponent register, x is the base and n is the modulus. Consequently, V|y⟩|e⟩ = (U**e|y)|e⟩ where U is the unitary defined as U|y⟩ = |y * x mod n⟩ 0 <= y < n U|y⟩ = |y⟩ n <= y """ def __init__( self, target: Sequence[cirq.Qid], exponent: Union[int, Sequence[cirq.Qid]], base: int, modulus: int ) -> None: if len(target) < modulus.bit_length(): raise ValueError(f'Register with {len(target)} qubits is too small ' f'for modulus {modulus}') self.target = target self.exponent = exponent self.base = base self.modulus = modulus def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]: return self.target, self.exponent, self.base, self.modulus def with_registers( self, *new_registers: Union[int, Sequence['cirq.Qid']], ) -> cirq.ArithmeticOperation: if len(new_registers) != 4: raise ValueError(f'Expected 4 registers (target, exponent, base, ' f'modulus), but got {len(new_registers)}') target, exponent, base, modulus = new_registers if not isinstance(target, Sequence): raise ValueError( f'Target must be a qubit register, got {type(target)}') if not isinstance(base, int): raise ValueError( f'Base must be a classical constant, got {type(base)}') if not isinstance(modulus, int): raise ValueError( f'Modulus must be a classical constant, got {type(modulus)}') return ModularExp(target, exponent, base, modulus) def apply(self, *register_values: int) -> int: assert len(register_values) == 4 target, exponent, base, modulus = register_values if target >= modulus: return target return (target * base**exponent) % modulus def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs, ) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 for qubit in args.known_qubits: if qubit in self.target: if t == 0: if isinstance(self.exponent, Sequence): e_str = 'e' else: e_str = str(self.exponent) wire_symbols.append( f'ModularExp(t*{self.base}**{e_str} % {self.modulus})') else: wire_symbols.append('t' + str(t)) t += 1 if isinstance(self.exponent, Sequence) and qubit in self.exponent: wire_symbols.append('e' + str(e)) e += 1 return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols))
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
In the apply method, we see that we evaluate (target * base**exponent) % modulus. The target and the exponent depend on the values of the respective qubit registers, and the base and modulus are constant -- namely, the modulus is $n$ and the base is some $x \in \mathbb{Z}_n$. The total number of qubits we will use is $3 (L + 1)$ where $L$ is the number of bits needed to store the integer $n$ to factor. The size of the unitary which implements the modular exponential is thus $4^{3(L + 1)}$. For a modest $n = 15$, the unitary requires storing $2^{30}$ floating point numbers in memory which is out of reach of most current standard laptops.
"""Create the target and exponent registers for phase estimation, and see the number of qubits needed for Shor's algorithm. """ n = 15 L = n.bit_length() # The target register has L qubits. target = cirq.LineQubit.range(L) # The exponent register has 2L + 3 qubits. exponent = cirq.LineQubit.range(L, 3 * L + 3) # Display the total number of qubits to factor this n. print(f"To factor n = {n} which has L = {L} bits, we need 3L + 3 = {3 * L + 3} qubits.")
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
As with the simple adder operation, this modular exponential operation has a unitary which we can display (memory permitting) as follows.
"""See (part of) the unitary for a modular exponential operation.""" # Pick some element of the multiplicative group modulo n. x = 5 # Display (part of) the unitary. Uncomment if n is small enough. # cirq.unitary(ModularExp(target, exponent, x, n))
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
Using the modular exponentional operation in a circuit The quantum part of Shor's algorithm is just phase estimation with the unitary $U$ corresponding to the modular exponential operation. The following cell defines a function which creates the circuit for Shor's algorithm using the ModularExp operation we defined above.
"""Function to make the quantum circuit for order finding.""" def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit: """Returns quantum circuit which computes the order of x modulo n. The circuit uses Quantum Phase Estimation to compute an eigenvalue of the unitary U|y⟩ = |y * x mod n⟩ 0 <= y < n U|y⟩ = |y⟩ n <= y Args: x: positive integer whose order modulo n is to be found n: modulus relative to which the order of x is to be found Returns: Quantum circuit for finding the order of x modulo n """ L = n.bit_length() target = cirq.LineQubit.range(L) exponent = cirq.LineQubit.range(L, 3 * L + 3) return cirq.Circuit( cirq.X(target[L - 1]), cirq.H.on_each(*exponent), ModularExp(target, exponent, x, n), cirq.qft(*exponent, inverse=True), cirq.measure(*exponent, key='exponent'), )
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
Using this function, we can visualize the circuit for a given $x$ and $n$ as follows.
"""Example of the quantum circuit for period finding.""" n = 15 x = 7 circuit = make_order_finding_circuit(x, n) print(circuit)
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
As previously described, we put the exponent register into an equal superposition via Hadamard gates. The $X$ gate on the last qubit in the target register is used for phase kickback. The modular exponential operation performs the sequence of controlled unitaries in phase estimation, then we apply the inverse quantum Fourier transform to the exponent register and measure to read out the result. To illustrate the measurement results, we can sample from a smaller circuit. (Note that in practice we would never run Shor's algorithm with $n = 6$ because it is even. This is just an example to illustrate the measurement outcomes.)
"""Measuring Shor's period finding circuit.""" circuit = make_order_finding_circuit(x=5, n=6) res = cirq.sample(circuit, repetitions=8) print("Raw measurements:") print(res) print("\nInteger in exponent register:") print(res.data)
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
We interpret each measured bitstring as an integer, but what do these integers tell us? In the next section we look at how to classically post-process to interpret them. Classical post-processing The integer we measure is close to $s / r$ where $r$ is the order of $x \in \mathbb{Z}_n$ and $0 \le s < r$ is an integer. We use the continued fractions algorithm to determine $r$ from $s / r$ then return it if the order finding circuit succeeded, else we return None.
def process_measurement(result: cirq.Result, x: int, n: int) -> Optional[int]: """Interprets the output of the order finding circuit. Specifically, it determines s/r such that exp(2πis/r) is an eigenvalue of the unitary U|y⟩ = |xy mod n⟩ 0 <= y < n U|y⟩ = |y⟩ n <= y then computes r (by continued fractions) if possible, and returns it. Args: result: result obtained by sampling the output of the circuit built by make_order_finding_circuit Returns: r, the order of x modulo n or None. """ # Read the output integer of the exponent register. exponent_as_integer = result.data["exponent"][0] exponent_num_bits = result.measurements["exponent"].shape[1] eigenphase = float(exponent_as_integer / 2**exponent_num_bits) # Run the continued fractions algorithm to determine f = s / r. f = fractions.Fraction.from_float(eigenphase).limit_denominator(n) # If the numerator is zero, the order finder failed. if f.numerator == 0: return None # Else, return the denominator if it is valid. r = f.denominator if x**r % n != 1: return None return r
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
The next code block shows an example of creating an order finding circuit, executing it, then using the classical postprocessing function to determine the order. Recall that the quantum part of the algorithm succeeds with some probability. If the order is None, try re-running the cell a few times.
"""Example of the classical post-processing.""" # Set n and x here n = 6 x = 5 print(f"Finding the order of x = {x} modulo n = {n}\n") measurement = cirq.sample(circuit, repetitions=1) print("Raw measurements:") print(measurement) print("\nInteger in exponent register:") print(measurement.data) r = process_measurement(measurement, x, n) print("\nOrder r =", r) if r is not None: print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}")
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
You should see that the order of $x = 5$ in $\mathbb{Z}_6$ is $r = 2$. Indeed, $5^2 \text{ mod } 6 = 25 \text{ mod } 6 = 1$. Quantum order finder We can now define a streamlined function for the quantum version of order finding using the functions we have previously written. The quantum order finder below creates the circuit, executes it, and processes the measurement result.
def quantum_order_finder(x: int, n: int) -> Optional[int]: """Computes smallest positive r such that x**r mod n == 1. Args: x: integer whose order is to be computed, must be greater than one and belong to the multiplicative group of integers modulo n (which consists of positive integers relatively prime to n), n: modulus of the multiplicative group. """ # Check that the integer x is a valid element of the multiplicative group # modulo n. if x < 2 or n <= x or math.gcd(x, n) > 1: raise ValueError(f'Invalid x={x} for modulus n={n}.') # Create the order finding circuit. circuit = make_order_finding_circuit(x, n) # Sample from the order finding circuit. measurement = cirq.sample(circuit) # Return the processed measurement result. return process_measurement(measurement, x, n)
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
This completes our quantum implementation of an order finder, and the quantum part of Shor's algorithm. The complete factoring algorithm We can use this quantum order finder (or the classical order finder) to complete Shor's algorithm. In the following code block, we add a few pre-processing steps which: (1) Check if $n$ is even, (2) Check if $n$ is prime, (3) Check if $n$ is a prime power, all of which can be done efficiently with a classical computer. Additionally, we add the last necessary post-processing step which uses the order $r$ to compute a non-trivial factor $p$ of $n$. This is achieved by computing $y = x^{r / 2} \text{ mod } n$ (assuming $r$ is even), then computing $p = \text{gcd}(y - 1, n)$.
"""Functions for factoring from start to finish.""" def find_factor_of_prime_power(n: int) -> Optional[int]: """Returns non-trivial factor of n if n is a prime power, else None.""" for k in range(2, math.floor(math.log2(n)) + 1): c = math.pow(n, 1 / k) c1 = math.floor(c) if c1**k == n: return c1 c2 = math.ceil(c) if c2**k == n: return c2 return None def find_factor( n: int, order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder, max_attempts: int = 30 ) -> Optional[int]: """Returns a non-trivial factor of composite integer n. Args: n: Integer to factor. order_finder: Function for finding the order of elements of the multiplicative group of integers modulo n. max_attempts: number of random x's to try, also an upper limit on the number of order_finder invocations. Returns: Non-trivial factor of n or None if no such factor was found. Factor k of n is trivial if it is 1 or n. """ # If the number is prime, there are no non-trivial factors. if sympy.isprime(n): print("n is prime!") return None # If the number is even, two is a non-trivial factor. if n % 2 == 0: return 2 # If n is a prime power, we can find a non-trivial factor efficiently. c = find_factor_of_prime_power(n) if c is not None: return c for _ in range(max_attempts): # Choose a random number between 2 and n - 1. x = random.randint(2, n - 1) # Most likely x and n will be relatively prime. c = math.gcd(x, n) # If x and n are not relatively prime, we got lucky and found # a non-trivial factor. if 1 < c < n: return c # Compute the order r of x modulo n using the order finder. r = order_finder(x, n) # If the order finder failed, try again. if r is None: continue # If the order r is even, try again. if r % 2 != 0: continue # Compute the non-trivial factor. y = x**(r // 2) % n assert 1 < y < n c = math.gcd(y - 1, n) if 1 < c < n: return c print(f"Failed to find a non-trivial factor in {max_attempts} attempts.") return None
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
The function find_factor uses the quantum_order_finder by default, in which case it is executing Shor's algorithm. As previously mentioned, due to the large memory requirements for classically simulating this circuit, we cannot run Shor's algorithm for $n \ge 15$. However, we can use the classical order finder as a substitute.
"""Example of factoring via Shor's algorithm (order finding).""" # Number to factor n = 184573 # Attempt to find a factor p = find_factor(n, order_finder=classical_order_finder) q = n // p print("Factoring n = pq =", n) print("p =", p) print("q =", q) """Check the answer is correct.""" p * q == n
docs/tutorials/shor.ipynb
quantumlib/Cirq
apache-2.0
Manifold Learning One weakness of PCA is that it cannot detect non-linear features. A set of algorithms known as Manifold Learning have been developed to address this deficiency. A canonical dataset used in Manifold learning is the S-curve:
from sklearn.datasets import make_s_curve X, y = make_s_curve(n_samples=1000) from mpl_toolkits.mplot3d import Axes3D ax = plt.axes(projection='3d') ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=y) ax.view_init(10, -60);
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
This is a 2-dimensional dataset embedded in three dimensions, but it is embedded in such a way that PCA cannot discover the underlying data orientation:
from sklearn.decomposition import PCA X_pca = PCA(n_components=2).fit_transform(X) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y);
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
Manifold learning algorithms, however, available in the sklearn.manifold submodule, are able to recover the underlying 2-dimensional manifold:
from sklearn.manifold import Isomap iso = Isomap(n_neighbors=15, n_components=2) X_iso = iso.fit_transform(X) plt.scatter(X_iso[:, 0], X_iso[:, 1], c=y);
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
Manifold learning on the digits data We can apply manifold learning techniques to much higher dimensional datasets, for example the digits data that we saw before:
from sklearn.datasets import load_digits digits = load_digits() fig, axes = plt.subplots(2, 5, figsize=(10, 5), subplot_kw={'xticks':(), 'yticks': ()}) for ax, img in zip(axes.ravel(), digits.images): ax.imshow(img, interpolation="none", cmap="gray")
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
We can visualize the dataset using a linear technique, such as PCA. We saw this already provides some intuition about the data:
# build a PCA model pca = PCA(n_components=2) pca.fit(digits.data) # transform the digits data onto the first two principal components digits_pca = pca.transform(digits.data) colors = ["#476A2A", "#7851B8", "#BD3430", "#4A2D4E", "#875525", "#A83683", "#4E655E", "#853541", "#3A3120","#535D8E"] plt.figure(figsize=(10, 10)) plt.xlim(digits_pca[:, 0].min(), digits_pca[:, 0].max() + 1) plt.ylim(digits_pca[:, 1].min(), digits_pca[:, 1].max() + 1) for i in range(len(digits.data)): # actually plot the digits as text instead of using scatter plt.text(digits_pca[i, 0], digits_pca[i, 1], str(digits.target[i]), color = colors[digits.target[i]], fontdict={'weight': 'bold', 'size': 9}) plt.xlabel("first principal component") plt.ylabel("second principal component");
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
Using a more powerful, nonlinear techinque can provide much better visualizations, though. Here, we are using the t-SNE manifold learning method:
from sklearn.manifold import TSNE tsne = TSNE(random_state=42) # use fit_transform instead of fit, as TSNE has no transform method: digits_tsne = tsne.fit_transform(digits.data) plt.figure(figsize=(10, 10)) plt.xlim(digits_tsne[:, 0].min(), digits_tsne[:, 0].max() + 1) plt.ylim(digits_tsne[:, 1].min(), digits_tsne[:, 1].max() + 1) for i in range(len(digits.data)): # actually plot the digits as text instead of using scatter plt.text(digits_tsne[i, 0], digits_tsne[i, 1], str(digits.target[i]), color = colors[digits.target[i]], fontdict={'weight': 'bold', 'size': 9})
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
t-SNE has a somewhat longer runtime that other manifold learning algorithms, but the result is quite striking. Keep in mind that this algorithm is purely unsupervised, and does not know about the class labels. Still it is able to separate the classes very well (though the classes four, one and nine have been split into multiple groups). <div class="alert alert-success"> <b>EXERCISE</b>: <ul> <li> Compare the results of applying isomap to the digits dataset to the results of PCA and t-SNE. Which result do you think looks best? </li> <li> Given how well t-SNE separated the classes, one might be tempted to use this processing for classification. Try training a K-nearest neighbor classifier on digits data transformed with t-SNE, and compare to the accuracy on using the dataset without any transformation. </li> </ul> </div>
# %load solutions/21A_isomap_digits.py # %load solutions/21B_tsne_classification.py
notebooks/21.Unsupervised_learning-Non-linear_dimensionality_reduction.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
1 - Problem Statement 1.1 - Dataset and Preprocessing Run the following cell to read the dataset of dinosaur names, create a list of unique characters (such as a-z), and compute the dataset and vocabulary size.
data = open('dinos.txt', 'r').read() data= data.lower() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size))
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
The characters are a-z (26 characters) plus the "\n" (or newline character), which in this assignment plays a role similar to the &lt;EOS&gt; (or "End of sentence") token we had discussed in lecture, only here it indicates the end of the dinosaur name rather than the end of a sentence. In the cell below, we create a python dictionary (i.e., a hash table) to map each character to an index from 0-26. We also create a second python dictionary that maps each index back to the corresponding character character. This will help you figure out what index corresponds to what character in the probability distribution output of the softmax layer. Below, char_to_ix and ix_to_char are the python dictionaries.
char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) } ix_to_char = { i:ch for i,ch in enumerate(sorted(chars)) } print(ix_to_char)
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
1.2 - Overview of the model Your model will have the following structure: Initialize parameters Run the optimization loop Forward propagation to compute the loss function Backward propagation to compute the gradients with respect to the loss function Clip the gradients to avoid exploding gradients Using the gradients, update your parameter with the gradient descent update rule. Return the learned parameters <img src="images/rnn.png" style="width:450;height:300px;"> <caption><center> Figure 1: Recurrent Neural Network, similar to what you had built in the previous notebook "Building a RNN - Step by Step". </center></caption> At each time-step, the RNN tries to predict what is the next character given the previous characters. The dataset $X = (x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, ..., x^{\langle T_x \rangle})$ is a list of characters in the training set, while $Y = (y^{\langle 1 \rangle}, y^{\langle 2 \rangle}, ..., y^{\langle T_x \rangle})$ is such that at every time-step $t$, we have $y^{\langle t \rangle} = x^{\langle t+1 \rangle}$. 2 - Building blocks of the model In this part, you will build two important blocks of the overall model: - Gradient clipping: to avoid exploding gradients - Sampling: a technique used to generate characters You will then apply these two functions to build the model. 2.1 - Clipping the gradients in the optimization loop In this section you will implement the clip function that you will call inside of your optimization loop. Recall that your overall loop structure usually consists of a forward pass, a cost computation, a backward pass, and a parameter update. Before updating the parameters, you will perform gradient clipping when needed to make sure that your gradients are not "exploding," meaning taking on overly large values. In the exercise below, you will implement a function clip that takes in a dictionary of gradients and returns a clipped version of gradients if needed. There are different ways to clip gradients; we will use a simple element-wise clipping procedure, in which every element of the gradient vector is clipped to lie between some range [-N, N]. More generally, you will provide a maxValue (say 10). In this example, if any component of the gradient vector is greater than 10, it would be set to 10; and if any component of the gradient vector is less than -10, it would be set to -10. If it is between -10 and 10, it is left alone. <img src="images/clip.png" style="width:400;height:150px;"> <caption><center> Figure 2: Visualization of gradient descent with and without gradient clipping, in a case where the network is running into slight "exploding gradient" problems. </center></caption> Exercise: Implement the function below to return the clipped gradients of your dictionary gradients. Your function takes in a maximum threshold and returns the clipped versions of your gradients. You can check out this hint for examples of how to clip in numpy. You will need to use the argument out = ....
### GRADED FUNCTION: clip def clip(gradients, maxValue): ''' Clips the gradients' values between minimum and maximum. Arguments: gradients -- a dictionary containing the gradients "dWaa", "dWax", "dWya", "db", "dby" maxValue -- everything above this number is set to this number, and everything less than -maxValue is set to -maxValue Returns: gradients -- a dictionary with the clipped gradients. ''' dWaa, dWax, dWya, db, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['db'], gradients['dby'] ### START CODE HERE ### # clip to mitigate exploding gradients, loop over [dWax, dWaa, dWya, db, dby]. (≈2 lines) for gradient in [dWax, dWaa, dWya, db, dby]: np.clip(gradient, -maxValue, maxValue, out = gradient) ### END CODE HERE ### gradients = {"dWaa": dWaa, "dWax": dWax, "dWya": dWya, "db": db, "dby": dby} return gradients np.random.seed(3) dWax = np.random.randn(5,3)*10 dWaa = np.random.randn(5,5)*10 dWya = np.random.randn(2,5)*10 db = np.random.randn(5,1)*10 dby = np.random.randn(2,1)*10 gradients = {"dWax": dWax, "dWaa": dWaa, "dWya": dWya, "db": db, "dby": dby} gradients = clip(gradients, 10) print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2]) print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1]) print("gradients[\"dWya\"][1][2] =", gradients["dWya"][1][2]) print("gradients[\"db\"][4] =", gradients["db"][4]) print("gradients[\"dby\"][1] =", gradients["dby"][1])
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Expected output: <table> <tr> <td> **gradients["dWaa"][1][2] ** </td> <td> 10.0 </td> </tr> <tr> <td> **gradients["dWax"][3][1]** </td> <td> -10.0 </td> </td> </tr> <tr> <td> **gradients["dWya"][1][2]** </td> <td> 0.29713815361 </td> </tr> <tr> <td> **gradients["db"][4]** </td> <td> [ 10.] </td> </tr> <tr> <td> **gradients["dby"][1]** </td> <td> [ 8.45833407] </td> </tr> </table> 2.2 - Sampling Now assume that your model is trained. You would like to generate new text (characters). The process of generation is explained in the picture below: <img src="images/dinos3.png" style="width:500;height:300px;"> <caption><center> Figure 3: In this picture, we assume the model is already trained. We pass in $x^{\langle 1\rangle} = \vec{0}$ at the first time step, and have the network then sample one character at a time. </center></caption> Exercise: Implement the sample function below to sample characters. You need to carry out 4 steps: Step 1: Pass the network the first "dummy" input $x^{\langle 1 \rangle} = \vec{0}$ (the vector of zeros). This is the default input before we've generated any characters. We also set $a^{\langle 0 \rangle} = \vec{0}$ Step 2: Run one step of forward propagation to get $a^{\langle 1 \rangle}$ and $\hat{y}^{\langle 1 \rangle}$. Here are the equations: $$ a^{\langle t+1 \rangle} = \tanh(W_{ax} x^{\langle t \rangle } + W_{aa} a^{\langle t \rangle } + b)\tag{1}$$ $$ z^{\langle t + 1 \rangle } = W_{ya} a^{\langle t + 1 \rangle } + b_y \tag{2}$$ $$ \hat{y}^{\langle t+1 \rangle } = softmax(z^{\langle t + 1 \rangle })\tag{3}$$ Note that $\hat{y}^{\langle t+1 \rangle }$ is a (softmax) probability vector (its entries are between 0 and 1 and sum to 1). $\hat{y}^{\langle t+1 \rangle}_i$ represents the probability that the character indexed by "i" is the next character. We have provided a softmax() function that you can use. Step 3: Carry out sampling: Pick the next character's index according to the probability distribution specified by $\hat{y}^{\langle t+1 \rangle }$. This means that if $\hat{y}^{\langle t+1 \rangle }_i = 0.16$, you will pick the index "i" with 16% probability. To implement it, you can use np.random.choice. Here is an example of how to use np.random.choice(): python np.random.seed(0) p = np.array([0.1, 0.0, 0.7, 0.2]) index = np.random.choice([0, 1, 2, 3], p = p.ravel()) This means that you will pick the index according to the distribution: $P(index = 0) = 0.1, P(index = 1) = 0.0, P(index = 2) = 0.7, P(index = 3) = 0.2$. Step 4: The last step to implement in sample() is to overwrite the variable x, which currently stores $x^{\langle t \rangle }$, with the value of $x^{\langle t + 1 \rangle }$. You will represent $x^{\langle t + 1 \rangle }$ by creating a one-hot vector corresponding to the character you've chosen as your prediction. You will then forward propagate $x^{\langle t + 1 \rangle }$ in Step 1 and keep repeating the process until you get a "\n" character, indicating you've reached the end of the dinosaur name.
# GRADED FUNCTION: sample def sample(parameters, char_to_ix, seed): """ Sample a sequence of characters according to a sequence of probability distributions output of the RNN Arguments: parameters -- python dictionary containing the parameters Waa, Wax, Wya, by, and b. char_to_ix -- python dictionary mapping each character to an index. seed -- used for grading purposes. Do not worry about it. Returns: indices -- a list of length n containing the indices of the sampled characters. """ # Retrieve parameters and relevant shapes from "parameters" dictionary Waa, Wax, Wya, by, b = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters['by'], parameters['b'] vocab_size = by.shape[0] n_a = Waa.shape[1] ### START CODE HERE ### # Step 1: Create the one-hot vector x for the first character (initializing the sequence generation). (≈1 line) x = np.zeros((vocab_size, 1)) # Step 1': Initialize a_prev as zeros (≈1 line) a_prev = np.zeros((n_a, 1)) # Create an empty list of indices, this is the list which will contain the list of indices of the characters to generate (≈1 line) indices = [] # Idx is a flag to detect a newline character, we initialize it to -1 idx = -1 # Loop over time-steps t. At each time-step, sample a character from a probability distribution and append # its index to "indices". We'll stop if we reach 50 characters (which should be very unlikely with a well # trained model), which helps debugging and prevents entering an infinite loop. counter = 0 newline_character = char_to_ix['\n'] while (idx != newline_character and counter != 50): # Step 2: Forward propagate x using the equations (1), (2) and (3) a = np.tanh(np.dot(Waa, a_prev) + np.dot(Wax, x) + b) z = np.dot(Wya, a) + by y = softmax(z) # for grading purposes np.random.seed(counter+seed) # Step 3: Sample the index of a character within the vocabulary from the probability distribution y idx = np.random.choice([i for i in range(vocab_size)], p = y.ravel()) # Append the index to "indices" indices.append(idx) # Step 4: Overwrite the input character as the one corresponding to the sampled index. x = np.zeros((vocab_size, 1)) x[idx] = 1 # Update "a_prev" to be "a" a_prev = a # for grading purposes seed += 1 counter +=1 ### END CODE HERE ### if (counter == 50): indices.append(char_to_ix['\n']) return indices np.random.seed(2) _, n_a = 20, 100 Wax, Waa, Wya = np.random.randn(n_a, vocab_size), np.random.randn(n_a, n_a), np.random.randn(vocab_size, n_a) b, by = np.random.randn(n_a, 1), np.random.randn(vocab_size, 1) parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "b": b, "by": by} indices = sample(parameters, char_to_ix, 0) print("Sampling:") print("list of sampled indices:", indices) print("list of sampled characters:", [ix_to_char[i] for i in indices])
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Expected output: <table> <tr> <td> **list of sampled indices:** </td> <td> [12, 17, 24, 14, 13, 9, 10, 22, 24, 6, 13, 11, 12, 6, 21, 15, 21, 14, 3, 2, 1, 21, 18, 24, <br> 7, 25, 6, 25, 18, 10, 16, 2, 3, 8, 15, 12, 11, 7, 1, 12, 10, 2, 7, 7, 11, 5, 6, 12, 25, 0, 0] </td> </tr><tr> <td> **list of sampled characters:** </td> <td> ['l', 'q', 'x', 'n', 'm', 'i', 'j', 'v', 'x', 'f', 'm', 'k', 'l', 'f', 'u', 'o', <br> 'u', 'n', 'c', 'b', 'a', 'u', 'r', 'x', 'g', 'y', 'f', 'y', 'r', 'j', 'p', 'b', 'c', 'h', 'o', <br> 'l', 'k', 'g', 'a', 'l', 'j', 'b', 'g', 'g', 'k', 'e', 'f', 'l', 'y', '\n', '\n'] </td> </tr> </table> 3 - Building the language model It is time to build the character-level language model for text generation. 3.1 - Gradient descent In this section you will implement a function performing one step of stochastic gradient descent (with clipped gradients). You will go through the training examples one at a time, so the optimization algorithm will be stochastic gradient descent. As a reminder, here are the steps of a common optimization loop for an RNN: Forward propagate through the RNN to compute the loss Backward propagate through time to compute the gradients of the loss with respect to the parameters Clip the gradients if necessary Update your parameters using gradient descent Exercise: Implement this optimization process (one step of stochastic gradient descent). We provide you with the following functions: ```python def rnn_forward(X, Y, a_prev, parameters): """ Performs the forward propagation through the RNN and computes the cross-entropy loss. It returns the loss' value as well as a "cache" storing values to be used in the backpropagation.""" .... return loss, cache def rnn_backward(X, Y, parameters, cache): """ Performs the backward propagation through time to compute the gradients of the loss with respect to the parameters. It returns also all the hidden states.""" ... return gradients, a def update_parameters(parameters, gradients, learning_rate): """ Updates parameters using the Gradient Descent Update Rule.""" ... return parameters ```
# GRADED FUNCTION: optimize def optimize(X, Y, a_prev, parameters, learning_rate = 0.01): """ Execute one step of the optimization to train the model. Arguments: X -- list of integers, where each integer is a number that maps to a character in the vocabulary. Y -- list of integers, exactly the same as X but shifted one index to the left. a_prev -- previous hidden state. parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a) Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a) b -- Bias, numpy array of shape (n_a, 1) by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1) learning_rate -- learning rate for the model. Returns: loss -- value of the loss function (cross-entropy) gradients -- python dictionary containing: dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x) dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a) dWya -- Gradients of hidden-to-output weights, of shape (n_y, n_a) db -- Gradients of bias vector, of shape (n_a, 1) dby -- Gradients of output bias vector, of shape (n_y, 1) a[len(X)-1] -- the last hidden state, of shape (n_a, 1) """ ### START CODE HERE ### # Forward propagate through time (≈1 line) loss, cache = rnn_forward(X, Y, a_prev, parameters) # Backpropagate through time (≈1 line) gradients, a = rnn_backward(X, Y, parameters, cache) # Clip your gradients between -5 (min) and 5 (max) (≈1 line) gradients = clip(gradients, 5) # Update parameters (≈1 line) parameters = update_parameters(parameters, gradients, learning_rate) ### END CODE HERE ### return loss, gradients, a[len(X)-1] np.random.seed(1) vocab_size, n_a = 27, 100 a_prev = np.random.randn(n_a, 1) Wax, Waa, Wya = np.random.randn(n_a, vocab_size), np.random.randn(n_a, n_a), np.random.randn(vocab_size, n_a) b, by = np.random.randn(n_a, 1), np.random.randn(vocab_size, 1) parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "b": b, "by": by} X = [12,3,5,11,22,3] Y = [4,14,11,22,25, 26] loss, gradients, a_last = optimize(X, Y, a_prev, parameters, learning_rate = 0.01) print("Loss =", loss) print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2]) print("np.argmax(gradients[\"dWax\"]) =", np.argmax(gradients["dWax"])) print("gradients[\"dWya\"][1][2] =", gradients["dWya"][1][2]) print("gradients[\"db\"][4] =", gradients["db"][4]) print("gradients[\"dby\"][1] =", gradients["dby"][1]) print("a_last[4] =", a_last[4])
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Expected output: <table> <tr> <td> **Loss ** </td> <td> 126.503975722 </td> </tr> <tr> <td> **gradients["dWaa"][1][2]** </td> <td> 0.194709315347 </td> <tr> <td> **np.argmax(gradients["dWax"])** </td> <td> 93 </td> </tr> <tr> <td> **gradients["dWya"][1][2]** </td> <td> -0.007773876032 </td> </tr> <tr> <td> **gradients["db"][4]** </td> <td> [-0.06809825] </td> </tr> <tr> <td> **gradients["dby"][1]** </td> <td>[ 0.01538192] </td> </tr> <tr> <td> **a_last[4]** </td> <td> [-1.] </td> </tr> </table> 3.2 - Training the model Given the dataset of dinosaur names, we use each line of the dataset (one name) as one training example. Every 100 steps of stochastic gradient descent, you will sample 10 randomly chosen names to see how the algorithm is doing. Remember to shuffle the dataset, so that stochastic gradient descent visits the examples in random order. Exercise: Follow the instructions and implement model(). When examples[index] contains one dinosaur name (string), to create an example (X, Y), you can use this: python index = j % len(examples) X = [None] + [char_to_ix[ch] for ch in examples[index]] Y = X[1:] + [char_to_ix["\n"]] Note that we use: index= j % len(examples), where j = 1....num_iterations, to make sure that examples[index] is always a valid statement (index is smaller than len(examples)). The first entry of X being None will be interpreted by rnn_forward() as setting $x^{\langle 0 \rangle} = \vec{0}$. Further, this ensures that Y is equal to X but shifted one step to the left, and with an additional "\n" appended to signify the end of the dinosaur name.
# GRADED FUNCTION: model def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus ix_to_char -- dictionary that maps the index to a character char_to_ix -- dictionary that maps a character to an index num_iterations -- number of iterations to train the model for n_a -- number of units of the RNN cell dino_names -- number of dinosaur names you want to sample at each iteration. vocab_size -- number of unique characters found in the text, size of the vocabulary Returns: parameters -- learned parameters """ # Retrieve n_x and n_y from vocab_size n_x, n_y = vocab_size, vocab_size # Initialize parameters parameters = initialize_parameters(n_a, n_x, n_y) # Initialize loss (this is required because we want to smooth our loss, don't worry about it) loss = get_initial_loss(vocab_size, dino_names) # Build list of all dinosaur names (training examples). with open("dinos.txt") as f: examples = f.readlines() examples = [x.lower().strip() for x in examples] # Shuffle list of all dinosaur names np.random.seed(0) np.random.shuffle(examples) # Initialize the hidden state of your LSTM a_prev = np.zeros((n_a, 1)) # Optimization loop for j in range(num_iterations): ### START CODE HERE ### # Use the hint above to define one training example (X,Y) (≈ 2 lines) index = j % len(examples) X = [None] + [char_to_ix[ch] for ch in examples[index]] Y = X[1:] + [char_to_ix['\n']] # Perform one optimization step: Forward-prop -> Backward-prop -> Clip -> Update parameters # Choose a learning rate of 0.01 curr_loss, gradients, a_prev = optimize(X, Y, a_prev, parameters) ### END CODE HERE ### # Use a latency trick to keep the loss smooth. It happens here to accelerate the training. loss = smooth(loss, curr_loss) # Every 2000 Iteration, generate "n" characters thanks to sample() to check if the model is learning properly if j % 2000 == 0: print('Iteration: %d, Loss: %f' % (j, loss) + '\n') # The number of dinosaur names to print seed = 0 for name in range(dino_names): # Sample indices and print them sampled_indices = sample(parameters, char_to_ix, seed) print_sample(sampled_indices, ix_to_char) seed += 1 # To get the same result for grading purposed, increment the seed by one. print('\n') return parameters
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Run the following cell, you should observe your model outputting random-looking characters at the first iteration. After a few thousand iterations, your model should learn to generate reasonable-looking names.
parameters = model(data, ix_to_char, char_to_ix)
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Conclusion You can see that your algorithm has started to generate plausible dinosaur names towards the end of the training. At first, it was generating random characters, but towards the end you could see dinosaur names with cool endings. Feel free to run the algorithm even longer and play with hyperparameters to see if you can get even better results. Our implemetation generated some really cool names like maconucon, marloralus and macingsersaurus. Your model hopefully also learned that dinosaur names tend to end in saurus, don, aura, tor, etc. If your model generates some non-cool names, don't blame the model entirely--not all actual dinosaur names sound cool. (For example, dromaeosauroides is an actual dinosaur name and is in the training set.) But this model should give you a set of candidates from which you can pick the coolest! This assignment had used a relatively small dataset, so that you could train an RNN quickly on a CPU. Training a model of the english language requires a much bigger dataset, and usually needs much more computation, and could run for many hours on GPUs. We ran our dinosaur name for quite some time, and so far our favoriate name is the great, undefeatable, and fierce: Mangosaurus! <img src="images/mangosaurus.jpeg" style="width:250;height:300px;"> 4 - Writing like Shakespeare The rest of this notebook is optional and is not graded, but we hope you'll do it anyway since it's quite fun and informative. A similar (but more complicated) task is to generate Shakespeare poems. Instead of learning from a dataset of Dinosaur names you can use a collection of Shakespearian poems. Using LSTM cells, you can learn longer term dependencies that span many characters in the text--e.g., where a character appearing somewhere a sequence can influence what should be a different character much much later in ths sequence. These long term dependencies were less important with dinosaur names, since the names were quite short. <img src="images/shakespeare.jpg" style="width:500;height:400px;"> <caption><center> Let's become poets! </center></caption> We have implemented a Shakespeare poem generator with Keras. Run the following cell to load the required packages and models. This may take a few minutes.
from __future__ import print_function from keras.callbacks import LambdaCallback from keras.models import Model, load_model, Sequential from keras.layers import Dense, Activation, Dropout, Input, Masking from keras.layers import LSTM from keras.utils.data_utils import get_file from keras.preprocessing.sequence import pad_sequences from shakespeare_utils import * import sys import io
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
To save you some time, we have already trained a model for ~1000 epochs on a collection of Shakespearian poems called "The Sonnets". Let's train the model for one more epoch. When it finishes training for an epoch---this will also take a few minutes---you can run generate_output, which will prompt asking you for an input (&lt;40 characters). The poem will start with your sentence, and our RNN-Shakespeare will complete the rest of the poem for you! For example, try "Forsooth this maketh no sense " (don't enter the quotation marks). Depending on whether you include the space at the end, your results might also differ--try it both ways, and try other inputs as well.
print_callback = LambdaCallback(on_epoch_end=on_epoch_end) model.fit(x, y, batch_size=128, epochs=1, callbacks=[print_callback]) # Run this cell to try with different inputs without having to re-train the model generate_output()
Course 5/Dinosaurus Island Character level language model final v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Introduction The HyperModel class in KerasTuner provides a convenient way to define your search space in a reusable object. You can override HyperModel.build() to define and hypertune the model itself. To hypertune the training process (e.g. by selecting the proper batch size, number of training epochs, or data augmentation setup), you can override HyperModel.fit(), where you can access: The hp object, which is an instance of keras_tuner.HyperParameters The model built by HyperModel.build() A basic example is shown in the "tune model training" section of Getting Started with KerasTuner. Tuning the custom training loop In this guide, we will subclass the HyperModel class and write a custom training loop by overriding HyperModel.fit(). For how to write a custom training loop with Keras, you can refer to the guide Writing a training loop from scratch. First, we import the libraries we need, and we create datasets for training and validation. Here, we just use some random data for demonstration purposes.
import keras_tuner import tensorflow as tf from tensorflow import keras import numpy as np x_train = np.random.rand(1000, 28, 28, 1) y_train = np.random.randint(0, 10, (1000, 1)) x_val = np.random.rand(1000, 28, 28, 1) y_val = np.random.randint(0, 10, (1000, 1))
guides/ipynb/keras_tuner/custom_tuner.ipynb
keras-team/keras-io
apache-2.0
Then, we subclass the HyperModel class as MyHyperModel. In MyHyperModel.build(), we build a simple Keras model to do image classification for 10 different classes. MyHyperModel.fit() accepts several arguments. Its signature is shown below: python def fit(self, hp, model, x, y, validation_data, callbacks=None, **kwargs): The hp argument is for defining the hyperparameters. The model argument is the model returned by MyHyperModel.build(). x, y, and validation_data are all custom-defined arguments. We will pass our data to them by calling tuner.search(x=x, y=y, validation_data=(x_val, y_val)) later. You can define any number of them and give custom names. The callbacks argument was intended to be used with model.fit(). KerasTuner put some helpful Keras callbacks in it, for example, the callback for checkpointing the model at its best epoch. We will manually call the callbacks in the custom training loop. Before we can call them, we need to assign our model to them with the following code so that they have access to the model for checkpointing. py for callback in callbacks: callback.model = model In this example, we only called the on_epoch_end() method of the callbacks to help us checkpoint the model. You may also call other callback methods if needed. If you don't need to save the model, you don't need to use the callbacks. In the custom training loop, we tune the batch size of the dataset as we wrap the NumPy data into a tf.data.Dataset. Note that you can tune any preprocessing steps here as well. We also tune the learning rate of the optimizer. We will use the validation loss as the evaluation metric for the model. To compute the mean validation loss, we will use keras.metrics.Mean(), which averages the validation loss across the batches. We need to return the validation loss for the tuner to make a record.
class MyHyperModel(keras_tuner.HyperModel): def build(self, hp): """Builds a convolutional model.""" inputs = keras.Input(shape=(28, 28, 1)) x = keras.layers.Flatten()(inputs) x = keras.layers.Dense( units=hp.Choice("units", [32, 64, 128]), activation="relu" )(x) outputs = keras.layers.Dense(10)(x) return keras.Model(inputs=inputs, outputs=outputs) def fit(self, hp, model, x, y, validation_data, callbacks=None, **kwargs): # Convert the datasets to tf.data.Dataset. batch_size = hp.Int("batch_size", 32, 128, step=32, default=64) train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch( batch_size ) validation_data = tf.data.Dataset.from_tensor_slices(validation_data).batch( batch_size ) # Define the optimizer. optimizer = keras.optimizers.Adam( hp.Float("learning_rate", 1e-4, 1e-2, sampling="log", default=1e-3) ) loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) # The metric to track validation loss. epoch_loss_metric = keras.metrics.Mean() # Function to run the train step. @tf.function def run_train_step(images, labels): with tf.GradientTape() as tape: logits = model(images) loss = loss_fn(labels, logits) # Add any regularization losses. if model.losses: loss += tf.math.add_n(model.losses) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) # Function to run the validation step. @tf.function def run_val_step(images, labels): logits = model(images) loss = loss_fn(labels, logits) # Update the metric. epoch_loss_metric.update_state(loss) # Assign the model to the callbacks. for callback in callbacks: callback.model = model # Record the best validation loss value best_epoch_loss = float("inf") # The custom training loop. for epoch in range(2): print(f"Epoch: {epoch}") # Iterate the training data to run the training step. for images, labels in train_ds: run_train_step(images, labels) # Iterate the validation data to run the validation step. for images, labels in validation_data: run_val_step(images, labels) # Calling the callbacks after epoch. epoch_loss = float(epoch_loss_metric.result().numpy()) for callback in callbacks: # The "my_metric" is the objective passed to the tuner. callback.on_epoch_end(epoch, logs={"my_metric": epoch_loss}) epoch_loss_metric.reset_states() print(f"Epoch loss: {epoch_loss}") best_epoch_loss = min(best_epoch_loss, epoch_loss) # Return the evaluation metric value. return best_epoch_loss
guides/ipynb/keras_tuner/custom_tuner.ipynb
keras-team/keras-io
apache-2.0
Now, we can initialize the tuner. Here, we use Objective("my_metric", "min") as our metric to be minimized. The objective name should be consistent with the one you use as the key in the logs passed to the 'on_epoch_end()' method of the callbacks. The callbacks need to use this value in the logs to find the best epoch to checkpoint the model.
tuner = keras_tuner.RandomSearch( objective=keras_tuner.Objective("my_metric", "min"), max_trials=2, hypermodel=MyHyperModel(), directory="results", project_name="custom_training", overwrite=True, )
guides/ipynb/keras_tuner/custom_tuner.ipynb
keras-team/keras-io
apache-2.0
We start the search by passing the arguments we defined in the signature of MyHyperModel.fit() to tuner.search().
tuner.search(x=x_train, y=y_train, validation_data=(x_val, y_val))
guides/ipynb/keras_tuner/custom_tuner.ipynb
keras-team/keras-io
apache-2.0
Finally, we can retrieve the results.
best_hps = tuner.get_best_hyperparameters()[0] print(best_hps.values) best_model = tuner.get_best_models()[0] best_model.summary()
guides/ipynb/keras_tuner/custom_tuner.ipynb
keras-team/keras-io
apache-2.0
Calculate the Nonredundant Read Fraction (NRF) SAM format example: SRR585264.8766235 0 1 4 15 35M * 0 0 CTTAAACAATTATTCCCCCTGCAAACATTTTCAAT GGGGGGGGGGGGGGGGGGGGGGFGGGGGGGGGGGG XT:A:U NM:i:1 X0:i:1 X1:i:6 XM:i:1 XO:i:0 XG:i:0 MD:Z:8T26 Import the required modules
import subprocess import matplotlib.pyplot as plt import random import numpy as np
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Make figures prettier and biger
plt.style.use('ggplot') figsize(10,5)
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Parse the SAM file and extract the unique start coordinates. First store the file name in the variable
file = "/ngschool/chip_seq/bwa/input.sorted.bam"
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Next we read the file using samtools. From each read we need to store the flag, chromosome name and start coordinate.
p = subprocess.Popen(["samtools", "view", "-q10", "-F260", file], stdout=subprocess.PIPE) coords = [] for line in p.stdout: flag, ref, start = line.decode('utf-8').split()[1:4] coords.append([flag, ref, start]) coords[:3]
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
What is the total number of our unique reads?
len(coords)
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Randomly sample the coordinates to get 1M for NRF calculations
random.seed(1234) sample = random.sample(coords, 1000000) len(sample)
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
How many of those coordinates are unique? (We will use the set python object which only the unique items.)
uniqueStarts = {'watson': set(), 'crick': set()} for coord in sample: flag, ref, start = coord if int(flag) & 16: uniqueStarts['crick'].add((ref, start)) else: uniqueStarts['watson'].add((ref, start))
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
How many on the Watson strand?
len(uniqueStarts['watson'])
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
And on the Crick?
len(uniqueStarts['crick'])
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Calculate the NRF
NRF_input = (len(uniqueStarts['watson']) + len(uniqueStarts['crick']))*1.0/len(sample) print(NRF_input)
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Lets create a function from what we did above and apply it to all of our files! To use our function on the real sequencing datasets (not only on a small subset) we need to optimize our method a bit- we will use python module called numpy.
def calculateNRF(filePath, pickSample=True, sampleSize=10000000, seed=1234): p = subprocess.Popen(['samtools', 'view', '-q10', '-F260', filePath], stdout=subprocess.PIPE) coordType = np.dtype({'names': ['flag', 'ref', 'start'], 'formats': ['uint16', 'U10', 'uint32']}) coordArray = np.empty(10000000, dtype=coordType) i = 0 for line in p.stdout: if i >= len(coordArray): coordArray = np.append(coordArray, np.empty(1000000, dtype=coordType), axis=0) fg, rf, st = line.decode('utf-8').split()[1:4] coordArray[i] = np.array((fg, rf, st), dtype=coordType) i += 1 coordArray = coordArray[:i] sample = coordArray if pickSample and len(coordArray) > sampleSize: np.random.seed(seed) sample = np.random.choice(coordArray, sampleSize, replace=False) uniqueStarts = {'watson': set(), 'crick': set()} for read in sample: flag, ref, start = read if flag & 16: uniqueStarts['crick'].add((ref, start)) else: uniqueStarts['watson'].add((ref, start)) NRF = (len(uniqueStarts['watson']) + len(uniqueStarts['crick']))*1.0/len(sample) return NRF
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Calculate the NRF for the chip-seq sample
NRF_chip = calculateNRF("/ngschool/chip_seq/bwa/sox2_chip.sorted.bam", sampleSize=1000000) print(NRF_chip)
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Plot the NRF!
plt.bar([0,2],[NRF_input, NRF_chip], width=1) plt.xlim([-0.5,3.5]), plt.xticks([0.5, 2.5], ['Input', 'ChIP']) plt.xlabel('Sample') plt.ylabel('NRF') plt.ylim([0, 1.25]), plt.yticks(np.arange(0, 1.2, 0.2)) plt.plot((-0.5,3.5), (0.8,0.8), 'red', linestyle='dashed') plt.show()
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Calculate the Signal Extraction Scaling Load the results from the coverage calculations
countList = [] with open('/ngschool/chip_seq/bedtools/input_coverage.bed', 'r') as covFile: for line in covFile: countList.append(int(line.strip('\n').split('\t')[3])) countList[0:6] countList[-15:]
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Lets see where do our reads align to the genome. Plot the distribution of tags along the genome.
plt.plot(range(len(countList)), countList) plt.xlabel('Bin number') plt.ylabel('Bin coverage') plt.xlim([0, len(countList)]) plt.show()
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Now sort the list- order the windows based on the tag count
countList.sort() countList[0:6]
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Sum all the aligned tags
countSum = sum(countList) countSum
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Calculate the summaric fraction of tags along the ordered windows.
countFraction = [] for i, count in enumerate(countList): if i == 0: countFraction.append(count*1.0 / countSum) else: countFraction.append((count*1.0 / countSum) + countFraction[i-1])
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Look at the last five items of the list:
countFraction[-5:]
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Calculate the number of windows.
winNumber = len(countFraction) winNumber
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Calculate what fraction of a whole is the position of each window.
winFraction = [] for i in range(winNumber): winFraction.append(i*1.0 / winNumber)
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Look at the last five items of our new list:
winFraction[-5:]
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Now prepare the function!
def calculateSES(filePath): countList = [] with open(filePath, 'r') as covFile: for line in covFile: countList.append(int(line.strip('\n').split('\t')[3])) plt.plot(range(len(countList)), countList) plt.xlabel('Bin number') plt.ylabel('Bin coverage') plt.xlim([0, len(countList)]) plt.show() countList.sort() countSum = sum(countList) countFraction = [] for i, count in enumerate(countList): if i == 0: countFraction.append(count*1.0 / countSum) else: countFraction.append((count*1.0 / countSum) + countFraction[i-1]) winNumber = len(countFraction) winFraction = [] for i in range(winNumber): winFraction.append(i*1.0 / winNumber) return [winFraction, countFraction]
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Use our function to calculate the signal extraction scaling for the Sox2 ChIP sample:
chipSes = calculateSES("/ngschool/chip_seq/bedtools/sox2_chip_coverage.bed")
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
Now we can plot the calculated fractions for both the input and ChIP sample:
plt.plot(winFraction, countFraction, label='input') plt.plot(chipSes[0], chipSes[1], label='Sox2 ChIP') plt.ylim([0,1]) plt.xlabel('Ordered window franction') plt.ylabel('Genome coverage fraction') plt.legend(loc='best') plt.show()
jupyter/ndolgikh/.ipynb_checkpoints/NGSchool_python-checkpoint.ipynb
NGSchool2016/ngschool2016-materials
gpl-3.0
The data contains one event per row and has 5 variables: user_id: Identifier for each user. event_timestamp: The time each event happened. lat: The latitude of the user when the event occurred. lon: The longitude of the user when the event occurred. event_type: The type of event that occurred: login, level, buy_coins and megapack. Basic differences between apply and transform Suppose we wanted to count the number of events for each user. Both functions can do this, but in different ways. Let's try it first with apply.
apply_ex = data.groupby('user_id').apply(len) print(apply_ex.head())
posts/product_data_071317.ipynb
dtrimarco/blog
mit
The output here is a pandas Series with each user_id as the index and the count of the number of events as values. Now to try the same thing with transform.
transform_ex = data.groupby('user_id').transform(len) print(transform_ex.head())
posts/product_data_071317.ipynb
dtrimarco/blog
mit
What the heck happened here? This odd DataFrame highlights a key difference: apply by default returns an object with one element per group and transform returns an object of the exact same size as the input object. Unless specified, it operates column by column in order. How about we clean this up a bit and create a new column in our original DataFrame that contains the total event count for each group in it.
data['event_count'] = data.groupby('user_id')['user_id'].transform(len) print(data.head(7))
posts/product_data_071317.ipynb
dtrimarco/blog
mit
Much better. All we had to do was assign to the new event_count column and then specify the ['user_id'] column after the groupby statement. Whether you would prefer to have this additional column of repeating values depends on what you intend to do with the data afterwards. Let's assume this is acceptable. Now for something a bit more involved. Custom Functions Say we didn't have Google Analytics or Mixpanel implemented into our app and wanted to assign a monetary value to each event. Of course, we could loop through the entire DataFrame, but this can be very inefficient with a lot of data. Let's try it using a custom function.
def add_value(x): if x == 'buy_coins': y = 1.00 elif x == 'megapack': y = 10.00 else: y=0.0 return y
posts/product_data_071317.ipynb
dtrimarco/blog
mit
Here we've defined a very simple custom function that assigns values to each of the four event types. Now to apply it to our data.
data['event_value'] = data['event_type'].apply(add_value) print(data.head(7))
posts/product_data_071317.ipynb
dtrimarco/blog
mit
A Convenience Function
def plotDecisionBoundary(model, X, y): fig = plt.figure() ax = fig.add_subplot(111) padding = 0.6 resolution = 0.0025 colors = ['royalblue','forestgreen','ghostwhite'] # Calculate the boundaris x_min, x_max = X[:, 0].min(), X[:, 0].max() y_min, y_max = X[:, 1].min(), X[:, 1].max() x_range = x_max - x_min y_range = y_max - y_min x_min -= x_range * padding y_min -= y_range * padding x_max += x_range * padding y_max += y_range * padding # Create a 2D Grid Matrix. The values stored in the matrix # are the predictions of the class at at said location xx, yy = np.meshgrid(np.arange(x_min, x_max, resolution), np.arange(y_min, y_max, resolution)) # What class does the classifier say? Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the contour map cs = plt.contourf(xx, yy, Z, cmap=plt.cm.terrain) # Plot the test original points as well... for label in range(len(np.unique(y))): indices = np.where(y == label) plt.scatter(X[indices, 0], X[indices, 1], c=colors[label], label=str(label), alpha=0.8) p = model.get_params() plt.axis('tight') plt.title('K = ' + str(p['n_neighbors']))
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
The Assignment Load up the dataset into a variable called X. Check .head and dtypes to make sure you're loading your data properly--don't fail on the 1st step!
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Copy the wheat_type series slice out of X, and into a series called y. Then drop the original wheat_type column from the X:
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Do a quick, "ordinal" conversion of y. In actuality our classification isn't ordinal, but just as an experiment...
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Do some basic nan munging. Fill each row's nans with the mean of the feature:
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Split X into training and testing data sets using train_test_split(). Use 0.33 test size, and use random_state=1. This is important so that your answers are verifiable. In the real world, you wouldn't specify a random_state:
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Create an instance of SKLearn's Normalizer class and then train it using its .fit() method against your training data. The reason you only fit against your training data is because in a real-world situation, you'll only have your training data to train with! In this lab setting, you have both train+test data; but in the wild, you'll only have your training data, and then unlabeled data you want to apply your models to.
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
With your trained pre-processor, transform both your training AND testing data. Any testing data has to be transformed with your preprocessor that has ben fit against your training data, so that it exist in the same feature-space as the original data used to train your models.
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Just like your preprocessing transformation, create a PCA transformation as well. Fit it against your training data, and then project your training and testing features into PCA space using the PCA model's .transform() method. This has to be done because the only way to visualize the decision boundary in 2D would be if your KNN algo ran in 2D as well:
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Create and train a KNeighborsClassifier. Start with K=9 neighbors. Be sure train your classifier against the pre-processed, PCA- transformed training data above! You do not, of course, need to transform your labels.
# .. your code here .. # I hope your KNeighbors classifier model from earlier was named 'knn' # If not, adjust the following line: plotDecisionBoundary(knn, X_train, y_train)
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Display the accuracy score of your test data/labels, computed by your KNeighbors model. You do NOT have to run .predict before calling .score, since .score will take care of running your predictions for you automatically.
# .. your code here ..
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
Bonus Instead of the ordinal conversion, try and get this assignment working with a proper Pandas get_dummies for feature encoding. You might have to update some of the plotDecisionBoundary() code.
plt.show()
Module5/Module5 - Lab5.ipynb
authman/DAT210x
mit
<a id='step2'></a> 2. Specify all variables for the module and scene Below find a list of all of the possible parameters for makeModule. scene and simulation parameters are also organized below. This simulation will be a complete simulation in terms of parameters that you can modify. The below routine creates a HEXAGONAL torque tube, for a 2-UP configuration of a specific module size. Parameters for the module, the torque tube, and the scene are below. This is being run with gendaylit, for one specific timestamp
simulationname = 'tutorial_4' ## SceneDict Parameters gcr = 0.33 # ground cover ratio, = module_height / pitch albedo = 0.28 #'concrete' # ground albedo hub_height = 2.35 # we could also pass clearance_height. azimuth_ang = 90 # Modules will be facing East. lat = 37.5 lon = -77.6 nMods = 4 # doing a smaller array for better visualization on this example. nRows = 2 # MakeModule Parameters module_type='test-module' x = 1.996 # landscape, sinze x > y. Remember that orientation has been deprecated. y = 0.991 tilt = 10 numpanels = 2 # doing a 2-up system! # Gaps: xgap = 0.05 # distance between modules in the row. ygap = 0.15 # distance between the 2 modules along the collector slope. zgap = 0.175 # if there is a torquetube, this is the distance between the torquetube and the modules. # If there is not a module, zgap is the distance between the module and the axis of rotation (relevant for # tracking systems. # TorqueTube Parameters tubetype = 'Hex' diameter = 0.15 material = 'Metal_Grey' # IT's NOT GRAY, IT's GREY.
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step3'></a> 3. Create the Radiance Object and generate the Sky
demo = bifacial_radiance.RadianceObj(simulationname, path=str(testfolder)) # Create a RadianceObj 'object' demo.setGround(albedo) # input albedo number or material name like 'concrete'. To see options, run this without any input. epwfile = demo.getEPW(lat,lon) # pull TMY data for any global lat/lon metdata = demo.readWeatherFile(epwfile, coerce_year=2001) # read in the EPW weather data from above timestamp = metdata.datetime.index(pd.to_datetime('2001-06-17 13:0:0 -5')) # Make this timezone aware, use -5 for EST. demo.gendaylit(timestamp) # Mid-day, June 17th
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step4'></a> 4. Calculating tracker angle/geometry for a specific timestamp This trick is useful if you are trying to use the fixed-tilt steps in bifacial_radiance to model a tracker for one specific point in time (if you take a picture of a tracker, it looks fixed, right? Well then). We assigned a 10 degree tilt at the beginning, but if we were to model a tracker as a fixed-tilt element because we are interested in only one point in time, this routine will tell us what tilt to use. Please note that to model a tracker as fixed tilt, we suggest passing a hub_height, otherwise you will have to calculate the clearance_height manually. <div class="alert alert-warning"> Details: you might have noticed in the previoust tutorial looking at the tracker dictionary, but the way that bifacial_radiance handles tracking: If the tracker is N-S axis azimuth, the surface azimuth of the modules will be set to 90 always, with a tilt that is either positive (for the early morning, facing East), or negative (for the afternoon, facing west). </div>
# Some tracking parameters that won't be needed after getting this angle: axis_azimuth = 180 axis_tilt = 0 limit_angle = 60 backtrack = True tilt = demo.getSingleTimestampTrackerAngle(metdata, timestamp, gcr, axis_azimuth, axis_tilt,limit_angle, backtrack) print ("\n NEW Calculated Tilt: %s " % tilt)
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step5'></a> 5. Making the Module & the Scene, Visualize and run Analysis
# Making module with all the variables module = demo.makeModule(name=module_type,x=x,y=y,bifi=1, zgap=zgap, ygap=ygap, xgap=xgap, numpanels=numpanels) module.addTorquetube(diameter=diameter, material=material, tubetype=tubetype, visible=True, axisofrotation=True) # create a scene with all the variables. # Specifying the pitch automatically with the collector width (sceney) returned by the module object. # Height has been deprecated as an input. pass clearance_height or hub_height in the scenedict. sceneDict = {'tilt':tilt,'pitch': np.round(module.sceney / gcr,3), 'hub_height':hub_height,'azimuth':azimuth_ang, 'module_type':module_type, 'nMods': nMods, 'nRows': nRows} scene = demo.makeScene(module=module, sceneDict=sceneDict) #makeScene creates a .rad file of the Scene octfile = demo.makeOct(demo.getfilelist()) # makeOct combines all of the ground, sky and object files into a .oct file.
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
At this point you should be able to go into a command window (cmd.exe) and check the geometry. It should look like the image at the beginning of the journal. Example: rvu -vf views\front.vp -e .01 -pe 0.02 -vp -2 -12 14.5 tutorial_4.oct
## Comment the line below to run rvu from the Jupyter notebook instead of your terminal. ## Simulation will stop until you close the rvu window #!rvu -vf views\front.vp -e .01 tutorial_4.oct
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
And then proceed happily with your analysis:
analysis = bifacial_radiance.AnalysisObj(octfile, demo.name) # return an analysis object including the scan dimensions for back irradiance sensorsy = 200 # setting this very high to see a detailed profile of the irradiance, including #the shadow of the torque tube on the rear side of the module. frontscan, backscan = analysis.moduleAnalysis(scene, modWanted = 2, rowWanted = 1, sensorsy = 200) frontDict, backDict = analysis.analysis(octfile, demo.name, frontscan, backscan) # compare the back vs front irradiance # print('"Annual" bifacial ratio average: %0.3f' %( sum(analysis.Wm2Back) / sum(analysis.Wm2Front) ) ) # See comment below of why this line is commented out.
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step6'></a> 6. Calculate Bifacial Ratio (clean results) Although we could calculate a bifacial ratio average at this point, this value would be misleading, since some of the sensors generated will fall on the torque tube, the sky, and/or the ground since we have torquetube and ygap in the scene. To calculate the real bifacial ratio average, we must use the clean routines.
resultFile='results/irr_tutorial_4.csv' results_loaded = bifacial_radiance.load.read1Result(resultFile) print("Printing the dataframe containing the results just calculated in %s: " % resultFile) results_loaded print("Looking at only 1 sensor in the middle -- position 100 out of the 200 sensors sampled:") results_loaded.loc[100]
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
As an example, we can see above that sensor 100 falls in the hextube, and in the sky. We need to remove this to calculate the real bifacial_gain from the irradiance falling into the modules. To do this we use cleanResult form the load.py module in bifacial_radiance. This finds the invalid materials and sets the irradiance values for those materials to NaN This might take some time in the current version.
# Cleaning Results: # remove invalid materials and sets the irradiance values to NaN clean_results = bifacial_radiance.load.cleanResult(results_loaded) print("Sampling the same location as before to see what the results are now:") clean_results.loc[100] print('CORRECT Annual bifacial ratio average: %0.3f' %( clean_results['Wm2Back'].sum() / clean_results['Wm2Front'].sum() )) print ("\n(If we had not done the cleaning routine, the bifacial ratio would have been ", \ "calculated to %0.3f <-- THIS VALUE IS WRONG)" %( sum(analysis.Wm2Back) / sum(analysis.Wm2Front) ))
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
<a id='step7'></a> 7. Add Custom Elements to your Scene Example: Marker at 0,0 position This shows how to add a custom element, in this case a Cube, that will be placed in the center of your already created scene to mark the 0,0 location. This can be added at any point after makeScene has been run once. Notice that if this extra element is in the scene and the analysis sensors fall on this element, they will measure irradiance at this element and no the modules. We are going to create a "MyMarker.rad" file in the objects folder, right after we make the Module. This is a prism (so we use 'genbox'), that is black from the ground.rad list of materials ('black') We are naming it 'CenterMarker' Its sides are going to be 0.5x0.5x0.5 m and We are going to leave its bottom surface coincident with the plane z=0, but going to center on X and Y.
name='MyMarker' text='! genbox black CenterMarker 0.1 0.1 4 | xform -t -0.05 -0.05 0' customObject = demo.makeCustomObject(name,text)
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
This should have created a MyMarker.rad object on your objects folder. But creating the object does not automatically adds it to the seen. So let's now add the customObject to the Scene. We are not going to translate it or anything because we want it at the center, but you can pass translation, rotation, and any other XFORM command from Radiance. I am passing a rotation 0 because xform has to have something (I think) otherwise it gets confused.
demo.appendtoScene(scene.radfiles, customObject, '!xform -rz 0') # makeOct combines all of the ground, sky and object files into a .oct file. octfile = demo.makeOct(demo.getfilelist())
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
appendtoScene appended to the Scene.rad file the name of the custom object we created and the xform transformation we included as text. Then octfile merged this new scene with the ground and sky files. At this point you should be able to go into a command window (cmd.exe) and check the geometry, and the marker should be there. Example: #### rvu -vf views\front.vp -e .01 tutorial_4.oct
## Comment the line below to run rvu from the Jupyter notebook instead of your terminal. ## Simulation will stop until you close the rvu window #!rvu -vf views\front.vp -e .01 tutorial_4.oct
docs/tutorials/4 - Medium Level Example - Debugging your Scene with Custom Objects (Fixed Tilt 2-up with Torque Tube + CLEAN Routine + CustomObject).ipynb
NREL/bifacial_radiance
bsd-3-clause
Lorenz Attractor - 3D line and point plotting demo Lorenz attractor is a 3D differential equation that we will use to demonstrate mayavi's 3D plotting ability. We will look at some ways to make plotting lots of data more efficient.
# setup parameters for Lorenz equations sigma=10 beta=8/3. rho=28 def lorenz(x, t, ): dx = np.zeros(3) dx[0] = -sigma*x[0] + sigma*x[1] dx[1] = rho*x[0] - x[1] - x[0]*x[2] dx[2] = -beta*x[2] + x[0]*x[1] return dx # solve for a specific particle # initial condition y0 = np.ones(3) + .01 # time steps to compute location n_time = 20000 t = np.linspace(0,200,n_time) # solve the ODE y = odeint( lorenz, y0, t ) y.shape
code_examples/python_mayavi/mayavi_intermediate.ipynb
thehackerwithin/berkeley
bsd-3-clause