markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
View the Circuit It's usually a good idea to view the ASCII diagram of your circuit to make sure it's doing what you want. This can be displayed by printing the circuit. | print(qnn) | 0: βββZββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
1: ββββΌβββββZββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
2: ββββΌββββββΌβββββZββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β
3: ββββΌββββββΌββββββΌβββββZββββββββββββββββββββββββββββββββββββββββββββββ
β β β β
4: ββββΌββββββΌββββββΌββββββΌβββββZββββββββββββββββββββββββββββββββββββββββ
β β β β β
5: ββββΌββββββΌββββββΌββββββΌββββββΌβββββZββββββββββββββββββββββββββββββββββ
β β β β β β
6: ββββΌββββββΌββββββΌββββββΌββββββΌββββββΌβββββZββββββββββββββββββββββββββββ
β β β β β β β
7: ββββΌββββββΌββββββΌββββββΌββββββΌββββββΌββββββΌβββββZββββββββββββββββββββββ
β β β β β β β β
8: ββββΌββββββΌββββββΌββββββΌββββββΌββββββΌββββββΌββββββΌβββββZββββββββββββββββ
β β β β β β β β β
r: βββX^wβββX^wβββX^wβββX^wβββX^wβββX^wβββX^wβββX^wβββX^wβββS^-1βββHβββ
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
You can experiment with adding more layers of $ZX$ gates (or adding other kinds of transformations!) to your QNN, but we can use this simplest kind of circuit to analyze a simple toy problem, which is what we will do next. A Toy Problem: Biased Coin FlipsAs a toy problem, let's get our quantum neuron to decide whether a coin is biased toward heads or toward tails based on a sequence of coin flips. To be specific, let's try to train a QNN to distinguish between a coin that yields "heads" with probability $p$, and one that yields "heads" with probability $1-p$. Without loss of generality, let's say that $p\leq 0.5$. We don't need a fancy QNN to come up with a winning strategy: given a series of coin flips, you guess $p$ if the majority of flips are "tails" and $1-p$ if the majority are "heads." But for purposes of illustration, let's do it the fancy way. To translate this problem into our QNN language, we need to encode the sequence of coin flips into a computational basis state. Let's associate $0$ with tails and $1$ with heads. So the sequence of coin flips becomes a sequence of $0$s and $1$s, and these define a computational basis state. We also need to define a convention for our labeling of the two coins. We'll say that the $p$ coin (majority tails) gets the label $-1$ and the $1-p$ coin (majority heads) gets the label $+1$. So when we measure $Y$ at the end of the computation we can say that the majority-vote of the $Y$ outcome is our predicted label. To be a little more nuanced (and to aid the formulation of the problem), let's say that the expectation value $\langle Y \rangle$ for a given input state defines our estimator for the label of that state. We're going to use that to define a loss function for training next. Define Loss Function Suppose we have a collection of $N$ (bitstring, label) pairs. A useful loss function to characterize the effectiveness of our QNN on this collection is$$\text{Loss} = \frac{1}{2N}\sum_{j=1}^n (1- \ell_j\langle Y \rangle_j),$$where $\ell_j$ is the label of the $j$th pair and $\langle Y \rangle_j$ is the expectation value of $Y$ on the readout qubit using the $j$th bitstring as input. If the network is perfect, the loss is equal to zero. If the network is maximally unsure about the labels (so that $\langle Y \rangle_j = 0$ for all $j$) then the loss is equal to $1/2$. And if the network gets everything wrong, then the loss is equal to $1$. We're going to train our network using this loss function, so next we'll write some functions to compute the loss. Another useful function to have around is the average classification error. Recall that our prescription was to execute the quantum circuit many times and take a majority vote to compute the predicted label. The majority vote for the readout is the same as $\text{sign}(\langle Y \rangle)$, so we can write a formula for the error in this procedure as$$\text{Error} = \frac{1}{2N}\sum_{j=1}^n \big(1- \ell_j\text{sign}\big(\langle Y \rangle_j\big)\big).$$This is not so useful as a loss function because it is not smooth and does not provide an incentive to make $|\langle Y \rangle|$ large, but it can be an informative quantity to compute.__Question__: Why would we want $|\langle Y \rangle|$ to be large? Solution When we implement this algorithm on the actual hardware, $\langle Y \rangle$ can only be estimated by repeatedly executing the circuit and measuring the result. The more measurements we make, the better our estimate of $\langle Y \rangle$ will be. Even if we are only interested in $\text{sign}\big(\langle Y \rangle\big)$, we will need to meake enough measurements to be sure that our estimate has the correct sign, and if $|\langle Y \rangle|$ is large then fewer measurements will be required to have high confidence in the sign.Furthermore, if the machine is noisy (which it will be), then the noise will induce some errors in our estimate of $\langle Y \rangle$. If $|\langle Y \rangle|$ is small then it's likely that the noise will lead to the wrong sign. Expectation ValueOur first function computes the expectation value of the readout qubit for our circuit given a specification of the initial state. Rather than a bitstring, we'll specify the initial state as an array of $0$s and $1$s. These are the outputs of the coin flips in our toy problem. We'll compute the expectation value exactly using the wavefunction for now. | def readout_expectation(state):
"""Takes in a specification of a state as an array of 0s and 1s
and returns the expectation value of Z on ther readout qubit.
Uses the XmonSimulator to calculate the wavefunction exactly."""
# A convenient representation of the state as an integer
state_num = int(np.sum(state*2**np.arange(len(state))))
resolver = cirq.ParamResolver(params)
simulator = cirq.Simulator()
# Specify an explicit qubit order so that we know which qubit is the readout
result = simulator.simulate(qnn, resolver, qubit_order=[readout]+data_qubits,
initial_state=state_num)
wf = result.final_state
# Becase we specified qubit order, the Z value of the readout is the most
# significant bit.
Z_readout = np.append(np.ones(2**INPUT_SIZE), -np.ones(2**INPUT_SIZE))
return np.sum(np.abs(wf)**2 * Z_readout) | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Loss and ErrorThe next functions take a list of states (each specified as an array of $0$s and $1$s as before) and a corresponding list of labels and computes the loss and error, respectively, of that list. | def loss(states, labels):
loss=0
for state, label in zip(states,labels):
loss += 1 - label*readout_expectation(state)
return loss/(2*len(states))
def classification_error(states, labels):
error=0
for state,label in zip(states,labels):
error += 1 - label*np.sign(readout_expectation(state))
return error/(2*len(states)) | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Generating Data For our toy problem we'll want to be able to generate a batch of data. Here is a helper function for that task: | def make_batch():
"""Generates a set of labels, then uses those labels to generate inputs.
label = -1 corresponds to majority 0 in the sate, label = +1 corresponds to
majority 1.
"""
np.random.seed(0) # For consistency in demo
labels = (-1)**np.random.choice(2, size=100) # Smaller batch sizes will speed up computation
states = []
for label in labels:
states.append(np.random.choice(2, size=INPUT_SIZE, p=[0.5-label*0.2,0.5+label*0.2]))
return states, labels
states, labels = make_batch() | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
TrainingNow we'll try to find the optimal weight to solve our toy problem. For illustration, we'll do both a brute force search of the paramter space as well as a stochastic gradient descent. Brute Force SearchLet's compute both the loss and error rate on a batch of data as a function of the shared weight between all the gates. | # Using cirq.Simulator with the EigenGate implementation of ZZ, this takes
# about 30s to run. Using the XmonSimulator took about 40 minutes the last
# time I tried it!
%%time
linspace = np.linspace(start=-1, stop=1, num=80)
train_losses = []
error_rates = []
for p in linspace:
params = {'w': p}
train_losses.append(loss(states, labels))
error_rates.append(classification_error(states, labels))
plt.plot(linspace, train_losses)
plt.xlabel('Weight')
plt.ylabel('Loss')
plt.title('Loss as a Function of Weight')
plt.show()
plt.plot(linspace, error_rates)
plt.xlabel('Weight')
plt.ylabel('Error Rate')
plt.title('Error Rate as a Function of Weight')
plt.show() | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
__Question__: Why are the loss and error functions periodic with period $1$ when the $ZX$ gate is periodic with period $2$? Solution This kind of "halving" of the periodicity of $\langle Y \rangle$ compared to the period of the gates itself is typical of qubit systems. We can analyze how it works mathematically in a simpler setting. Instead of the $ZX$ Gate, let's just imagine that we rotate the readout qubit around the $X$ axis by some fixed amout. This is the effective calculation for a single fixed data input.$$\begin{align}\langle Y \rangle &= \langle 0 |\exp(-i \pi w X) Y \exp(i \pi w X) |0 \rangle\\&= \langle 0 |\big(\cos \pi w - i X\sin \pi w \big) Y \big(\cos \pi w + i X \sin \pi w \big) |0 \rangle\\&= \langle 0 |\big(Y\cos 2\pi w +Z \sin 2\pi w \big) |0 \rangle\\&= \sin 2\pi w.\end{align}$$ Stochastic Gradient DescentTo train the network we'll use stochastic gradient descent. Note that this isn't necessarily a good idea since the loss function is far from convex, and there's a good chance we'll get stuck in very inefficient local minimum if we initialize the paramters randomly. But as an exercise we'll do it anyway. In the next section we'll discuss other ways to train these sorts of networks. We'll compute the gradient of the loss function using a symmetric finite-difference approximation: $f'(x) \approx (f(x + \epsilon) - f(x-\epsilon))/2\epsilon$. This is the most straightforward way to do it using the quantum computer. We'll also generate a new instance of the problem each time. | def stochastic_grad_loss():
"""Generates a new data point and computes the gradient of the loss
using that data point."""
# Randomly generate the data point.
label = (-1)**np.random.choice(2)
state = np.random.choice(2, size=INPUT_SIZE, p=[0.5-label*0.2,0.5+label*0.2])
# Compute the gradient using finite difference
eps = 10**-5 # Discretization of gradient. Try different values.
params['w'] -= eps
loss1 = loss([state],[label])
params['w'] += 2*eps
grad = (loss([state],[label])-loss1)/(2*eps)
params['w'] -= eps # Reset the parameter value
return grad | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
We can apply this function repeatedly to flow toward the minimum: | eta = 10**-4 # Learning rate. Try different values.
params = {'w': 0} # Initialize weight. Try different values.
for i in range(201):
if not i%25:
print('Step: {} Loss: {}'.format(i, loss(states, labels)))
grad = stochastic_grad_loss()
params['w'] += -eta*grad
print('Final Weight: {}'.format(params['w'])) | Step: 0 Loss: 0.5
Step: 25 Loss: 0.29664170142263174
Step: 50 Loss: 0.21596111725317313
Step: 75 Loss: 0.19353972657117993
Step: 100 Loss: 0.1930989919230342
Step: 125 Loss: 0.19318223176524044
Step: 150 Loss: 0.19358215024578385
Step: 175 Loss: 0.1965144828868506
Step: 200 Loss: 0.1930640292633325
Final Weight: -0.0443500901565141
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Use Sampling Instead of Calculating from the WavefunctionOn real hardware we will have to use sampling to find results instead of computing the exact wavefunction. Rewrite the `readout_expectation` function to compute the expectation value using sampling instead. Unlike with the wavefunction calculation, we also need to build our circuit in a way that accounts for the initial state (we are always assumed to start in the all $|0\rangle$ state) | def readout_expectation_sample(state):
"""Takes in a specification of a state as an array of 0s and 1s
and returns the expectation value of Z on ther readout qubit.
Uses the XmonSimulator to sample the final wavefunction."""
# We still need to resolve the parameters in the circuit.
resolver = cirq.ParamResolver(params)
# Make a copy of the QNN to avoid making changes to the global variable.
measurement_circuit = qnn.copy()
# Modify the measurement circuit to account for the desired input state.
# YOUR CODE HERE
# Add appropriate measurement gate(s) to the circuit.
# YOUR CODE HERE
simulator = cirq.google.XmonSimulator()
result = simulator.run(measurement_circuit, resolver, repetitions=10**6) # Try adjusting the repetitions
# Return the Z expectation value
return ((-1)**result.measurements['m']).mean() | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Solution | def readout_expectation_sample(state):
"""Takes in a specification of a state as an array of 0s and 1s
and returns the expectation value of Z on ther readout qubit.
Uses the XmonSimulator to sample the final wavefunction."""
# We still need to resolve the parameters in the circuit.
resolver = cirq.ParamResolver(params)
# Make a copy of the QNN to avoid making changes to the global variable.
measurement_circuit = qnn.copy()
# Modify the measurement circuit to account for the desired input state.
for i, qubit in enumerate(data_qubits):
if state[i]:
measurement_circuit.insert(0,cirq.X(qubit))
# Add appropriate measurement gate(s) to the circuit.
measurement_circuit.append(cirq.measure(readout, key='m'))
simulator = cirq.Simulator()
result = simulator.run(measurement_circuit, resolver, repetitions=10**6) # Try adjusting the repetitions
# Return the Z expectation value
return ((-1)**result.measurements['m']).mean() | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Comparison of Sampling with the Exact Wavefunction Just to illustrate the difference between sampling and using the wavefunction, try running the two methods several times on identical input: | state = [0,0,0,1,0,1,1,0,1] # Try different initial states.
params = {'w': 0.05} # Try different weights.
print("Exact expectation value: {}".format(readout_expectation(state)))
print("Estimates from sampling:")
for _ in range(5):
print(readout_expectation_sample(state)) | Exact expectation value: 0.3090169429779053
Estimates from sampling:
0.308354
0.306674
0.309026
0.310854
0.30854
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
As an exercise, try repeating some of the above calculations (e.g., the SGD optimization) using `readout_expectation_sample` in place of `readout_expectation`. How many repetitions should you use? How should the hyperparameters `eps` and `eta` be adjusted in response to the number of repetitions? Optimizing For HardwareThere are more issues to think about if you want to run your network on real hardware. First is the connectivity issue, and second is minimizing the number of two-qubit operations. Consider the Foxtail device: | print(cirq.google.Foxtail) | (0, 0)βββ(0, 1)βββ(0, 2)βββ(0, 3)βββ(0, 4)βββ(0, 5)βββ(0, 6)βββ(0, 7)βββ(0, 8)βββ(0, 9)βββ(0, 10)
β β β β β β β β β β β
β β β β β β β β β β β
(1, 0)βββ(1, 1)βββ(1, 2)βββ(1, 3)βββ(1, 4)βββ(1, 5)βββ(1, 6)βββ(1, 7)βββ(1, 8)βββ(1, 9)βββ(1, 10)
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
The qubits are arranged in two rows of eleven qubits each, and qubits can only communicate to their nearest neighbors along the horizontal and vertial connections. That does not mesh well with the QNN we designed, where all of the data qubits need to interact with the readout qubit. There is no *in-principle* restriction on the kinds of algorithms you are allowed to run. The solution to the connectivity problem is to make use of SWAP gates, which have the effect of exchanging the states of two (neighboring) qubits. It's equivalent to what you would get if you physically exchanged the positions of two of the qubits in the grid. The problem is that each SWAP operation is costly, so you want to avoid SWAPing as much as possible. We need to think carefully about our algorithm design to minimize the number of SWAPs performed as the circuit is executed.__Question__: How should we modify our QNN circuit so that it can runs efficiently on the Foxtail device? Solution One strategy is to move the readout qubit around as it talks to the other qubits. Suppose the readout qubit starts in the $(0,0)$ position. First it can interact with the qubits in the $(1,0)$ and $(0,1)$ positons like normal, then SWAP with the $(0,1)$ qubit. Now the readout qubit is in the $(0,1)$ position and can interact with the $(1,1)$ and $(0,2)$ qubits before SWAPing with the $(0,2)$ qubit. It continues down the line in this fashion.Let's code up this circuit: | qnn_fox = cirq.Circuit()
w = 0.2 # Want an explicit numerical weight for later
for i in range(10):
qnn_fox.append([ZXGate(w).on(cirq.GridQubit(1,i), cirq.GridQubit(0,i)),
ZXGate(w).on(cirq.GridQubit(0,i+1), cirq.GridQubit(0,i)),
cirq.SWAP(cirq.GridQubit(0,i), cirq.GridQubit(0,i+1))])
qnn_fox.append(ZXGate(w).on(cirq.GridQubit(1,10), cirq.GridQubit(0,10)))
qnn_fox.append([(cirq.S**-1)(cirq.GridQubit(0,10)),cirq.H(cirq.GridQubit(0,10)),
cirq.measure(cirq.GridQubit(0,10))])
print(qnn_fox) | (0, 0): ββββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β
(0, 1): βββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β
(0, 2): βββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β
(0, 3): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β
(0, 4): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β β
(0, 5): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β β β
(0, 6): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β β β β
(0, 7): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β β β β β
(0, 8): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββββββββββββββββββββββ
β β β β β β β β β β β
(0, 9): βββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββXβββββββΓββββββββββββββββββββββββββ
β β β β β β β β β β β β
(0, 10): ββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌβββββββZ^0.2βββΓβββXβββββββS^-1βββHβββMβββ
β β β β β β β β β β β
(1, 0): ββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β β β β β β β
(1, 1): ββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β β β β β β
(1, 2): ββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β β β β β
(1, 3): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β β β β
(1, 4): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β β β
(1, 5): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β β
(1, 6): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β β
(1, 7): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β β
(1, 8): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββ
β β
(1, 9): ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββΌββββββββββββββββββββββ
β
(1, 10): βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββZ^0.2ββββββββββββββββββ
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
As coded, this circuit still won't run on the Foxtail device. That's because the gates we've defined are not native gates. Cirq has a built-in method that will convert our gates to Xmon gates (which are native for the Foxtail device) and attempt to optimze the circuit by reducing the total number of gates: | cirq.google.optimized_for_xmon(qnn_fox, new_device=cirq.google.Foxtail, allow_partial_czs=True) | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
---- Data Library for Python---- Content layer - NewsThis notebook demonstrates how to retrieve News. Learn moreTo learn more about the Refinitiv Data Library for Python please join the Refinitiv Developer Community. By [registering](https://developers.refinitiv.com/iam/register) and [logging](https://developers.refinitiv.com/content/devportal/en_us/initCookie.html) into the Refinitiv Developer Community portal you will have free access to a number of learning materials like [Quick Start guides](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-library-for-python/quick-start), [Tutorials](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-library-for-python/learning), [Documentation](https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-library-for-python/docs) and much more. Getting Help and SupportIf you have any questions regarding using the API, please post them on the [Refinitiv Data Q&A Forum](https://community.developers.refinitiv.com/spaces/321/index.html). The Refinitiv Developer Community will be happy to help. Set the configuration file locationFor a better ease of use, you have the option to set initialization parameters of the Refinitiv Data Library in the _refinitiv-data.config.json_ configuration file. This file must be located beside your notebook, in your user folder or in a folder defined by the _RD_LIB_CONFIG_PATH_ environment variable. The _RD_LIB_CONFIG_PATH_ environment variable is the option used by this series of examples. The following code sets this environment variable. | import os
os.environ["RD_LIB_CONFIG_PATH"] = "../../../Configuration" | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Some Imports to start with | import refinitiv.data as rd
from refinitiv.data.content import news
from datetime import timedelta | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Open the data sessionThe open_session() function creates and open sessions based on the information contained in the refinitiv-data.config.json configuration file. Please edit this file to set the session type and other parameters required for the session you want to open. | rd.open_session('platform.rdp') | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Retrieve data Headlines Get headlines | response = news.headlines.Definition("Apple").get_data()
response.data.df | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Get headlines within a range of dates | response = news.headlines.Definition(
query="Refinitiv",
date_from="20.03.2021",
date_to=timedelta(days=-4),
count=3
).get_data()
response.data.df | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Get a limited number of headlines | response = news.headlines.Definition(query = "Google", count = 350).get_data()
response.data.df | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Story | response = news.story.Definition("urn:newsml:reuters.com:20211003:nNRAgvhyiu:1").get_data()
print(response.data.story.title, '\n')
print(response.data.story.content) | Google Doodle marks birthday of Spanish ocean scientist MarΓa de los Γngeles AlvariΓ±o GonzΓ‘lez
For best results when printing this announcement, please click on link below:
http://newsfile.refinitiv.com/getnewsfile/v1/story?guid=urn:newsml:reuters.com:20211003:nNRAgvhyiu&default-theme=true
The Google Doodle today (3 OCtober) celebrates the 105th birthday of
Spanish-American professor and marine research biologist MarΓa de los
Γngeles AlvariΓ±o GonzΓ‘lez, who is regarded as one of the most important
Spanish scientists of all time.
Born in 1916, her love of natural history began with her father's library and
deepened as she pursued coastline oceanography research.
Although the Spanish Institute of Oceanography (IEO) only accepted men at the
time, her university work impressed the organization so much that they
appointed her as a marine biologist in 1952.
Based in Vigo, she began her pioneering research on zooplankton, tiny
organisms that serve as the foundation of the oceanic food chain and
identified some species to be the best indicators of ocean health.
In 1953, the British Council awarded Γngeles AlvariΓ±o a fellowship that
resulted in her becoming the first woman to work as a scientist aboard a
British research vessel.
Following several expeditions, she furthered her studies in the United States
where she retired as one of the world's most prestigious marine biologists in
1987.
During her career she discovered 22 new species of zooplankton and published
over 100 scientific papers. Even today she is the only Spanish scientist of
1,000 in the "Encyclopedia of World Scientists," and a modern research vessel
in IEO's fleet bears her name.
Read More
AP News Digest 6:30 a.m.
(https://www.independent.co.uk/news/world/europe/joe-biden-communist-party-east-african-covid-child-b1931394.html)
La Palma volcano turns 'much more aggressive' and blows open new fissures
(https://www.independent.co.uk/news/world/europe/la-palma-volcano-eruption-fissures-b1931367.html)
How security fears for Rutte revealed power of Dutch drug gangs
(https://www.independent.co.uk/independentpremium/rutte-netherlands-drug-gangs-gangsters-b1931165.html)
Copyright Β© 2021 Independent.co.ukk. All rights reserved.
| Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Close the session | rd.close_session() | _____no_output_____ | Apache-2.0 | Examples/2-Content/2.03-News/EX-2.03.01-News.ipynb | Refinitiv-API-Samples/Example.DataLibrary.Python |
Statistic Inference- This is a Python base notebook- Using `rpy2` for R functionsWe saw some pattern in EDA, naturally, we would like to see if the different between feature are significantly related to the target. Import libaries | import rpy2
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
%load_ext rpy2.ipython
%%R
library(tidyverse)
library(broom)
library(GGally) | R[write to console]: ββ Attaching packages βββββββββββββββββββββββββββββββββββββββ tidyverse 1.3.1 ββ
R[write to console]: β ggplot2 3.3.5 β purrr 0.3.4
β tibble 3.1.6 β dplyr 1.0.7
β tidyr 1.1.4 β stringr 1.4.0
β readr 2.1.1 β forcats 0.5.1
R[write to console]: ββ Conflicts ββββββββββββββββββββββββββββββββββββββββββ tidyverse_conflicts() ββ
β dplyr::filter() masks stats::filter()
β dplyr::lag() masks stats::lag()
R[write to console]: Registered S3 method overwritten by 'GGally':
method from
+.gg ggplot2
| MIT | spotify_user_behaviour_predictor/4_Stat_Infer.ipynb | MacyChan/spotify-user-behaviour-predictor |
Reading the data CSVRead in the data CSV and store it as a pandas dataframe named `spotify_df`. | %%R
spotify_df <- read_csv("data/spotify_data.csv")
head(spotify_df) | R[write to console]: New names:
* `` -> ...1
| MIT | spotify_user_behaviour_predictor/4_Stat_Infer.ipynb | MacyChan/spotify-user-behaviour-predictor |
Regression Data Wrangle- Remove `song_title` and `artist` for relationship study by regression. As both of them are neither numerical nor categorical features. | %%R
spotify_df_num <- spotify_df[2:15]
head(spotify_df_num) | # A tibble: 6 Γ 14
acousticness danceability duration_ms energy instrumentalness key liveness
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.0102 0.833 204600 0.434 0.0219 2 0.165
2 0.199 0.743 326933 0.359 0.00611 1 0.137
3 0.0344 0.838 185707 0.412 0.000234 2 0.159
4 0.604 0.494 199413 0.338 0.51 5 0.0922
5 0.18 0.678 392893 0.561 0.512 5 0.439
6 0.00479 0.804 251333 0.56 0 8 0.164
# β¦ with 7 more variables: loudness <dbl>, mode <dbl>, speechiness <dbl>,
# tempo <dbl>, time_signature <dbl>, valence <dbl>, target <dbl>
| MIT | spotify_user_behaviour_predictor/4_Stat_Infer.ipynb | MacyChan/spotify-user-behaviour-predictor |
Set up regression model Here, I am interested in determining factors associated with `target`. In particular, I will use a Multiple Linear Regression (MLR) Model to study the relation between `target` and all other features. | %%R
ML_reg <- lm( target ~ ., data = spotify_df_num) |> tidy(conf.int = TRUE)
ML_reg<- ML_reg |>
mutate(Significant = p.value < 0.05) |>
mutate_if(is.numeric, round, 3)
ML_reg | # A tibble: 14 Γ 8
term estimate std.error statistic p.value conf.low conf.high Significant
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl>
1 (Interce⦠-0.313 0.206 -1.52 0.128 -0.717 0.09 FALSE
2 acoustic⦠-0.325 0.055 -5.92 0 -0.433 -0.217 TRUE
3 danceabi⦠0.415 0.078 5.33 0 0.262 0.568 TRUE
4 duration⦠0 0 4.08 0 0 0 TRUE
5 energy 0.09 0.093 0.974 0.33 -0.092 0.272 FALSE
6 instrume⦠0.268 0.044 6.05 0 0.181 0.354 TRUE
7 key 0.001 0.003 0.334 0.739 -0.005 0.007 FALSE
8 liveness 0.098 0.07 1.4 0.162 -0.039 0.236 FALSE
9 loudness -0.023 0.005 -4.81 0 -0.033 -0.014 TRUE
10 mode -0.035 0.022 -1.58 0.113 -0.078 0.008 FALSE
11 speechin⦠0.816 0.121 6.74 0 0.579 1.05 TRUE
12 tempo 0.001 0 1.95 0.052 0 0.002 FALSE
13 time_sig⦠-0.009 0.042 -0.205 0.838 -0.091 0.074 FALSE
14 valence 0.165 0.051 3.24 0.001 0.065 0.265 TRUE
| MIT | spotify_user_behaviour_predictor/4_Stat_Infer.ipynb | MacyChan/spotify-user-behaviour-predictor |
- We can see that a lot of features are statiscally correlated with target. They are listed in the table below. | %%R
ML_reg |>
filter(Significant == TRUE) |>
select(term) | # A tibble: 7 Γ 1
term
<chr>
1 acousticness
2 danceability
3 duration_ms
4 instrumentalness
5 loudness
6 speechiness
7 valence
| MIT | spotify_user_behaviour_predictor/4_Stat_Infer.ipynb | MacyChan/spotify-user-behaviour-predictor |
GGpairsBelow is the ggpair plots to visual the correlation between different features. | %%R
ggpairs(data = spotify_df_num) | _____no_output_____ | MIT | spotify_user_behaviour_predictor/4_Stat_Infer.ipynb | MacyChan/spotify-user-behaviour-predictor |
Migrating scripts from Framework Mode to Script ModeThis notebook focus on how to migrate scripts using Framework Mode to Script Mode. The original notebook using Framework Mode can be find here https://github.com/awslabs/amazon-sagemaker-examples/blob/4c2a93114104e0b9555d7c10aaab018cac3d7c04/sagemaker-python-sdk/tensorflow_distributed_mnist/tensorflow_local_mode_mnist.ipynb Set up the environment | import os
import subprocess
import sagemaker
from sagemaker import get_execution_role
sagemaker_session = sagemaker.Session()
role = get_execution_role() | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Download the MNIST dataset | import utils
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
data_sets = input_data.read_data_sets('data', dtype=tf.uint8, reshape=False, validation_size=5000)
utils.convert_to(data_sets.train, 'train', 'data')
utils.convert_to(data_sets.validation, 'validation', 'data')
utils.convert_to(data_sets.test, 'test', 'data') | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Upload the dataWe use the ```sagemaker.Session.upload_data``` function to upload our datasets to an S3 location. The return value inputs identifies the location -- we will use this later when we start the training job. | inputs = sagemaker_session.upload_data(path='data', key_prefix='data/mnist') | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Construct an entry point script for training On this example, we assume that you aready have a Framework Mode training script named `mnist.py`: | !pygmentize 'mnist.py' | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
The training script `mnist.py` include the Framework Mode functions ```model_fn```, ```train_input_fn```, ```eval_input_fn```, and ```serving_input_fn```. We need to create a entrypoint script that uses the functions above to create a ```tf.estimator```: | %%writefile train.py
import argparse
# import original framework mode script
import mnist
import tensorflow as tf
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# read hyperparameters as script arguments
parser.add_argument('--training_steps', type=int)
parser.add_argument('--evaluation_steps', type=int)
args, _ = parser.parse_known_args()
# creates a tf.Estimator using `model_fn` that saves models to /opt/ml/model
estimator = tf.estimator.Estimator(model_fn=mnist.model_fn, model_dir='/opt/ml/model')
# creates parameterless input_fn function required by the estimator
def input_fn():
return mnist.train_input_fn(training_dir='/opt/ml/input/data/training', params=None)
train_spec = tf.estimator.TrainSpec(input_fn, max_steps=args.training_steps)
# creates parameterless serving_input_receiver_fn function required by the exporter
def serving_input_receiver_fn():
return mnist.serving_input_fn(params=None)
exporter = tf.estimator.LatestExporter('Servo',
serving_input_receiver_fn=serving_input_receiver_fn)
# creates parameterless input_fn function required by the evaluation
def input_fn():
return mnist.eval_input_fn(training_dir='/opt/ml/input/data/training', params=None)
eval_spec = tf.estimator.EvalSpec(input_fn, steps=args.evaluation_steps, exporters=exporter)
# start training and evaluation
tf.estimator.train_and_evaluate(estimator=estimator, train_spec=train_spec, eval_spec=eval_spec) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Changes in the SageMaker TensorFlow estimatorWe need to create a TensorFlow estimator pointing to ```train.py``` as the entrypoint: | from sagemaker.tensorflow import TensorFlow
mnist_estimator = TensorFlow(entry_point='train.py',
dependencies=['mnist.py'],
role='SageMakerRole',
framework_version='1.13',
hyperparameters={'training_steps':10, 'evaluation_steps':10},
py_version='py3',
train_instance_count=1,
train_instance_type='local')
mnist_estimator.fit(inputs) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Deploy the trained model to prepare for predictionsThe deploy() method creates an endpoint (in this case locally) which serves prediction requests in real-time. | mnist_predictor = mnist_estimator.deploy(initial_instance_count=1, instance_type='local') | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Invoking the endpoint | import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
for i in range(10):
data = mnist.test.images[i].tolist()
predict_response = mnist_predictor.predict(data)
print("========================================")
label = np.argmax(mnist.test.labels[i])
print("label is {}".format(label))
print("prediction is {}".format(predict_response)) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
Clean-upDeleting the local endpoint when you're finished is important since you can only run one local endpoint at a time. | mnist_estimator.delete_endpoint() | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb | dleen/amazon-sagemaker-examples |
The Linnerud dataset is a multi-output regression dataset. It consists of three excercise (data) and three physiological (target) variables collected from twenty middle-aged men in a fitness club:physiological - CSV containing 20 observations on 3 physiological variables:Weight, Waist and Pulse.exercise - CSV containing 20 observations on 3 exercise variables:Chins, Situps and Jumps. To create a Regression model that would plot the relationship between the waistline and how many situps are accomplished we need to take both of the variables into separate 1 dimensional vectors, divide them into training and testing sets, train a linear regression model using train set and check its output on the test set | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, model_selection
X, y = datasets.load_linnerud(return_X_y=True)
print(X.shape)
print(X[0]) | (20, 3)
[ 5. 162. 60.]
| MIT | 2-Regression/1-Tools/linnerud.ipynb | pr0gmtc/ML-For-Beginners |
Taking Waist and Situps variables: | X = X[:, np.newaxis, 1]
y = y[:, np.newaxis, 1]
print(X.shape)
print(y.shape)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)
model = linear_model.LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.show() | _____no_output_____ | MIT | 2-Regression/1-Tools/linnerud.ipynb | pr0gmtc/ML-For-Beginners |
β [sanskrit-coders/indic_transliteration: Python package for indic script transliteration](https://github.com/sanskrit-coders/indic_transliteration)```pip install indic_transliterationpip install git+https://github.com/sanskrit-coders/indic_transliteration/@master ``` | from indic_transliteration import sanscript
from indic_transliteration.sanscript import SchemeMap, SCHEMES, transliterate
data = 'idam adbhutam'
print(transliterate(data, sanscript.HK, sanscript.TELUGU))
print(transliterate(data, sanscript.ITRANS, sanscript.DEVANAGARI))
scheme_map = SchemeMap(SCHEMES[sanscript.VELTHUIS], SCHEMES[sanscript.TELUGU])
print(transliterate(data, scheme_map=scheme_map))
# Dravidian language extension (ε°εΊ¦ει¨θΎΎη½ζ―θΌδΊΊ)
from indic_transliteration import xsanscript
# from indic_transliteration.xsanscript import SchemeMap, SCHEMES, transliterate
data = 'ΰ€
ΰ€Έΰ€― ΰ€ΰ€·ΰ€§ΰ€Ώΰ€ ΰ€ΰ₯ΰ€°ΰ€¨ΰ₯ΰ€₯ΰ€ΰ₯€ ΰ€ ΰ€ ΰ€―ΰ₯ΰ€ΰ₯ΰ€ΰ€ΰ₯?'
print(transliterate(data, xsanscript.DEVANAGARI, xsanscript.KANNADA)) | ΰ²
ΰ²Έΰ²― ΰ²ΰ²·ΰ²§ΰ²Ώΰ² ΰ²ΰ³ΰ²°ΰ²¨ΰ³ΰ²₯ΰ²ΰ₯€ ΰ² ΰ² ΰ²―ΰ³ΰ²ΰ³ΰ²ΰ²ΰ³?
| Apache-2.0 | notebook/procs-hi-transliteration.ipynb | samlet/stack |
--- Copyright 2018 Analytics Zoo Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Environment Preparation** **Install Java 8**Run the cell on the **Google Colab** to install jdk 1.8.**Note:** if you run this notebook on your computer, root permission is required when running the cell to install Java 8. (You may ignore this cell if Java 8 has already been set up in your computer). | # Install jdk8
!apt-get install openjdk-8-jdk-headless -qq > /dev/null
import os
# Set environment variable JAVA_HOME.
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
!update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
!java -version | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Install Analytics Zoo** [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/) is needed to prepare the Python environment for running this example. **Note**: The following code cell is specific for setting up conda environment on Colab; for general conda installation, please refer to the [install guide](https://docs.conda.io/projects/conda/en/latest/user-guide/install/) for more details. | import sys
# Get current python version
version_info = sys.version_info
python_version = f"{version_info.major}.{version_info.minor}.{version_info.micro}"
# Install Miniconda
!wget https://repo.continuum.io/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh
!chmod +x Miniconda3-4.5.4-Linux-x86_64.sh
!./Miniconda3-4.5.4-Linux-x86_64.sh -b -f -p /usr/local
# Update Conda
!conda install --channel defaults conda python=$python_version --yes
!conda update --channel defaults --all --yes
# Append to the sys.path
_ = (sys.path
.append(f"/usr/local/lib/python{version_info.major}.{version_info.minor}/site-packages"))
os.environ['PYTHONHOME']="/usr/local" | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
You can install the latest pre-release version using `pip install --pre --upgrade analytics-zoo[ray]`. | # Install latest pre-release version of Analytics Zoo
# Installing Analytics Zoo from pip will automatically install pyspark, bigdl, and their dependencies.
!pip install --pre --upgrade analytics-zoo[ray]
# Install python dependencies
!pip install torch==1.7.1 torchvision==0.8.2 | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Automated hyper-parameter search for PyTorch using Orca APIs**In this guide we will describe how to enable automated hyper-parameter search for PyTorch using Orca `AutoEstimator` in 5 simple steps. | # import necesary libraries and modules
from __future__ import print_function
import os
import argparse
from zoo.orca import init_orca_context, stop_orca_context
from zoo.orca import OrcaContext | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Step 1: Init Orca Context** | # recommended to set it to True when running Analytics Zoo in Jupyter notebook.
OrcaContext.log_output = True # (this will display terminal's stdout and stderr in the Jupyter notebook).
cluster_mode = "local"
if cluster_mode == "local":
init_orca_context(cores=4, memory="2g", init_ray_on_spark=True) # run in local mode
elif cluster_mode == "k8s":
init_orca_context(cluster_mode="k8s", num_nodes=2, cores=4, init_ray_on_spark=True) # run on K8s cluster
elif cluster_mode == "yarn":
init_orca_context(
cluster_mode="yarn-client", cores=4, num_nodes=2, memory="2g", init_ray_on_spark=True,
driver_memory="10g", driver_cores=1) # run on Hadoop YARN cluster | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
This is the only place where you need to specify local or distributed mode. View [Orca Context](https://analytics-zoo.readthedocs.io/en/latest/doc/Orca/Overview/orca-context.html) for more details.**Note**: You should export HADOOP_CONF_DIR=/path/to/hadoop/conf/dir when you run on Hadoop YARN cluster. **Step 2: Define the Model**You may define your model, loss and optimizer in the same way as in any standard PyTorch program. | import torch
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self, fc1_hidden_size=500):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(4*4*50, fc1_hidden_size)
self.fc2 = nn.Linear(fc1_hidden_size, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2, 2)
x = x.view(-1, 4*4*50)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=1)
criterion = nn.NLLLoss() | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
After defining your model, you need to define a *Model Creator Function* that returns an instance of your model, and a *Optimizer Creator Function* that returns a PyTorch optimizer. Note that both the *Model Creator Function* and the *Optimizer Creator Function* should take `config` as input and get the hyper-parameter values from `config`. | def model_creator(config):
model = LeNet(fc1_hidden_size=config["fc1_hidden_size"])
return model
def optim_creator(model, config):
return torch.optim.Adam(model.parameters(), lr=config["lr"]) | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Step 3: Define Dataset**You can define the train and validation datasets using *Data Creator Function* that has one parameter of `config` and returns a PyTorch `DataLoader`. | import torch
from torchvision import datasets, transforms
torch.manual_seed(0)
dir = './dataset'
test_batch_size = 640
def train_loader_creator(config):
train_loader = torch.utils.data.DataLoader(
datasets.MNIST(dir, train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=config["batch_size"], shuffle=True)
return train_loader
def test_loader_creator(config):
test_loader = torch.utils.data.DataLoader(
datasets.MNIST(dir, train=False, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=test_batch_size, shuffle=False)
return test_loader | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Step 4: Define search space**You should define a dictionary as your hyper-parameter search space. The keys are hyper-parameter names which should be the same with those in your creators, and you can specify how you want to sample each hyper-parameter in the values of the search space. See more about [automl.hp](https://analytics-zoo.readthedocs.io/en/latest/doc/PythonAPI/AutoML/automl.htmlorca-automl-hp). | from zoo.orca.automl import hp
search_space = {
"fc1_hidden_size": hp.choice([500, 600]),
"lr": hp.choice([0.001, 0.003]),
"batch_size": hp.choice([160, 320, 640]),
} | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
**Step 5: Automatically fit and search *with* Orca AutoEstimator** First, create an AutoEstimator. You can refer to [AutoEstimator API doc](https://analytics-zoo.readthedocs.io/en/latest/doc/PythonAPI/AutoML/automl.htmlorca-automl-auto-estimator) for more details. | from zoo.orca.automl.auto_estimator import AutoEstimator
auto_est = AutoEstimator.from_torch(model_creator=model_creator,
optimizer=optim_creator,
loss=criterion,
logs_dir="/tmp/zoo_automl_logs",
resources_per_trial={"cpu": 2},
name="lenet_mnist") | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
Next, use the auto estimator to fit and search for the best hyper-parameter set. | auto_est.fit(data=train_loader_creator,
validation_data=test_loader_creator,
search_space=search_space,
n_sampling=2,
epochs=1,
metric="accuracy") | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
Finally, you can get the best learned model and the best hyper-parameters. | best_model = auto_est.get_best_model().model # will change later
best_config = auto_est.get_best_config()
print(best_config) | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
You can use the best learned model and the best hyper-parameters as you want. Here, we demonstrate how to evaluate on the test dataset. | test_loader = test_loader_creator(best_config)
best_model.eval()
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = best_model(data)
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).sum().numpy()
accuracy = 100. * correct / len(test_loader.dataset)
print(f"accuracy is {accuracy}%") | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
You can find the accuracy of the best model has reached 98%. | # stop orca context when program finishes
stop_orca_context() | _____no_output_____ | Apache-2.0 | docs/docs/colab-notebook/orca/quickstart/autoestimator_pytorch_lenet_mnist.ipynb | EvelynQiang/analytics-zoo |
DL Neuromatch Academy: Week 1, Day 2, Tutorial 1 Gradients and AutoGrad__Content creators:__ Saeed Salehi, Vladimir Haltakov, Andrew Saxe__Content reviewers:__ Polina Turishcheva, Atnafu Lambebo, Yu-Fang Yang__Content editors:__ Anoop Kulkarni__Production editors:__ Khalid Almubarak, Spiros Chavlis ---Tutorial ObjectivesDay 2 Tutorial 1 will continue on buiding PyTorch skillset and motivate its core functionality, Autograd. In this notebook, we will cover the key concepts and ideas of:* Gradient descent* PyTorch Autograd* PyTorch nn module | #@markdown Tutorial slides
# you should link the slides for all tutorial videos here (we will store pdfs on osf)
from IPython.display import HTML
HTML('<iframe src="https://docs.google.com/presentation/d/1kfWWYhSIkczYfjebhMaqQILTCu7g94Q-o_ZcWb1QAKs/embed?start=false&loop=false&delayms=3000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>') | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
--- Setup | # Imports
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
import time
import random
from tqdm.notebook import tqdm, trange
#@title Figure settings
import ipywidgets as widgets # interactive display
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
#@title Plotting functions
def ex3_plot(epochs, losses, values, gradients):
f, (plot1, plot2, plot3) = plt.subplots(3, 1, sharex=True, figsize=(10, 7))
plot1.set_title("Cross Entropy Loss")
plot1.plot(np.linspace(1, epochs, epochs), losses, color='r')
plot2.set_title("First Parameter value")
plot2.plot(np.linspace(1, epochs, epochs), values, color='c')
plot3.set_title("First Parameter gradient")
plot3.plot(np.linspace(1, epochs, epochs), gradients, color='m')
plot3.set_xlabel("Epoch")
plt.show()
#@title Helper functions
seed = 1943 # McCulloch & Pitts (1943)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
--- Section 1: Gradient Descent AlgorithmSince the goal of most learning algorithms is **minimizing the risk (cost) function**, optimization is the soul of learning! The gradient descent algorithm, along with its variations such as stochastic gradient descent, is one of the most powerful and popular optimization methods used for deep learning. 1.1: Gradient Descent | #@title Video 1.1: Introduction
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="PFQeUDxQFls", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video
#@title Video 1.2: Gradient Descent
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="Z3dyRLR8GbM", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
Gradient Descent (introduced by Augustin-Louis Cauchy in 1847) is an **iterative method** to **minimize** a **continuous** and (ideally) **differentiable function** of **many variables**. DefinitionLet $f(\mathbf{w}): \mathbb{R}^d \rightarrow \mathbb{R}$ be a differentiable function. Gradient Descent is an iterative algorithm for minimizing the function $f$, starting with an initial value for variables $\mathbf{w}$, taking steps of size $\eta$ in the direction of the negative gradient at the current point to update the variables $\mathbf{w}$.$$ \mathbf{w}^{(t+1)} = \mathbf{w}^{(t)} - \eta \nabla f (\mathbf{w}^{(t)}) $$where $\eta > 0$ and $\nabla f (\mathbf{w})= \left( \frac{\delta f(\mathbf{w})}{\delta w_1}, ..., \frac{\delta f(\mathbf{w})}{\delta w_d} \right)$. Since negative gradients always point locally in the direction of steepest descent, the algorithm makes small steps at each point **towards** the minimum. Vanilla Algorithm---> *inputs*: initial guess $\mathbf{w}^{(0)}$, step size $\eta > 0$, number of steps $T$> *For* *t = 1, 2, ..., T* *do* \$\qquad$ $\mathbf{w}^{(t+1)} = \mathbf{w}^{(t)} - \eta \nabla f (\mathbf{w}^{(t)})$\*end*> *return*: $\mathbf{w}^{(t+1)}$---To be able to use this algorithm, we need to calculate the gradient of the loss with respect to the learnable parameters. 1.2: Calculating GradientsTo minimize the empirical risk (loss) function using gradient descent, we need to calculate the vector of partial derivatives:$$\dfrac{\partial Loss}{\partial \mathbf{w}} = \left[ \dfrac{\partial Loss}{\partial w_1}, \dfrac{\partial Loss}{\partial w_2} , ..., \dfrac{\partial Loss}{\partial w_d} \right]^{\top} $$Although PyTorch and other deep learning frameworks (e.g. JAX and TensorFlow) provide us with incredibly powerful and efficient algorithms for automatic differentiation, calculating few derivatives with hand would be fun. Exercise 1.21. Given $L(w_1, w_2) = w_1^2 - 2w_1 w_2$ find $\dfrac{\partial L}{\partial w_1}$ and $\dfrac{\partial L}{\partial w_1}$.2. Given $f(x) = sin(x)$ and $g(x) = \ln(x)$, find the derivative of their composite function $\dfrac{d (f \circ g)(x)}{d x}$ (*hint: chain rule*). **Chain rule**: For a composite function $F(x) = f(g(x)) \equiv (f \circ g)(x)$:$$F'(x) = f'(g(x)) \cdot g'(x)$$or differently denoted:$$ \frac{dF}{dx} = \frac{df}{dg} ~ \frac{dg}{dx} $$3. Given $f(x, y, z) = \tanh \left( \ln \left[1 + z \frac{2x}{sin(y)} \right] \right)$, how easy is it to derive $\dfrac{\partial f}{\partial x}$, $\dfrac{\partial f}{\partial y}$ and $\dfrac{\partial f}{\partial z}$? (*hint: you don't have to actually calculate them!*) 1.3: Computational Graphs and Backprop | #@title Video 1.3: Computational Graph
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="7c8iCHcVgVs", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
The last function in *Exercise 1.2* is an example of how overwhelming the derivation of gradients can get, as the number of variables and nested functions increases. This function is still extremely simple compared to the loss functions of modern neural networks. So how do PyTorch and similar frameworks approach such beasts? 1.3.1: Computational GraphsLetβs look at the function again:$$f(x, y, z) = \tanh \left(\ln \left[1 + z \frac{2x}{sin(y)} \right] \right)$$we can build a so-called computational graph (shown below) to break the original function to smaller and more approachable expressions. If this "reverse engineering" approach seems unintuitive and arbitrary, it's because it is! Usually, the graph is built first.Starting from $x$, $y$, and $z$ and following the arrows and expressions, you would see that our graph returns the same function as $f$. It does so by calculating intermediate variables $a,b,c,d,$ and $e$. This is called the **forward pass**.Now, letβs start from $f$, and work our way against the arrows while calculating the gradient of each expression as we go. This is called **backward pass**, which later inspires **backpropagation of errors**.Because we've split the computation into simple operations on intermediate variables, I hope you can appreciate how easy it now is to calculate the partial derivatives. Now we can use chain rule and simply calculate any gradient:$$ \dfrac{\partial f}{\partial x} = \dfrac{\partial f}{\partial e}~\dfrac{\partial e}{\partial d}~\dfrac{\partial d}{\partial c}~\dfrac{\partial c}{\partial a}~\dfrac{\partial a}{\partial x} = \left( 1-\tanh^2(e) \right) \cdot \frac{1}{d}\cdot z \cdot \frac{1}{b} \cdot 2$$Conveniently, the values for $e$, $b$, and $d$ are available to us from when we did the forward pass through the graph. That is, the partial derivatives have simple expressions in terms of the intermediate variables $a,b,c,d,e$ that we calculated and stored during the forward pass. Exercise 1.3For the function above, calculate the $\dfrac{\partial f}{\partial y}$ and $\dfrac{\partial f}{\partial z}$ using the computational graph and chain rule. For more: [Calculus on Computational Graphs: Backpropagation](https://colah.github.io/posts/2015-08-Backprop/) --- Section 2: PyTorch AutoGrad | #@title Video 2.1: Automatic Differentiation
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="h8B8Nlcz7yY", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
Deep learning frameworks such as PyTorch, JAX, and TensorFlow come with a very efficient and sophisticated set of algorithms, commonly known as Automatic differentiation. AutoGrad is PyTorch's automatic differentiation engine. Here we start by covering the essentials of AutoGrad, but you will learn more in the coming days. Section 2.1: Forward PropagationEverything starts with the forward propagation (pass). PyTorch plans the computational graph, as we declare the variables and operations, and it builds the graph when we call the backward pass. PyTorch rebuilds the graph every time we iterate or change it (or simply put, PyTorch uses a dynamic graph).Before we start our first example, let's recall gradient descent algorithm. In gradient descent algorithm, it is only required to have the gradient of our cost function with respect to variables which are accessible to us for updating (changing). These variables are often called "learnable parameters" or simply parameter in PyTorch. In the case of neural networks, weights and biases are often the learnable parameters. Exercise 2.1In PyTorch, we can set the optional argument `requires_grad` in tensors to `True`, so PyTorch would track every operation on them while configuring the computational graph. For this exercise, use the provided tensors to build the following graph. | class SimpleGraph:
def __init__(self, w=None, b=None):
"""Initializing the SimpleGraph
Args:
w (float): initial value for weight
b (float): initial value for bias
"""
if w is None:
self.w = torch.randn(1, requires_grad=True)
else:
self.w = torch.tensor([w], requires_grad=True)
if b is None:
self.b = torch.randn(1, requires_grad=True)
else:
self.b = torch.tensor([b], requires_grad=True)
def forward(self, x):
"""Forward pass
Args:
x (torch.Tensor): 1D tensor of features
Returns:
torch.Tensor: model predictions
"""
assert isinstance(x, torch.Tensor)
#################################################
## Implement the the forward pass to calculate prediction
## Note that prediction is not the loss, but the value after `tanh`
# Complete the function and remove or comment the line below
raise NotImplementedError("Forward Pass `forward`")
#################################################
prediction = ...
return prediction
def sq_loss(y_true, y_prediction):
"""L2 loss function
Args:
y_true (torch.Tensor): 1D tensor of target labels
y_true (torch.Tensor): 1D tensor of predictions
Returns:
torch.Tensor: L2-loss (squared error)
"""
assert isinstance(y_true, torch.Tensor)
assert isinstance(y_prediction, torch.Tensor)
#################################################
## Implement the L2-loss (squred error) given true label and prediction
# Complete the function and remove or comment the line below
raise NotImplementedError("Loss function `sq_loss`")
#################################################
loss = ...
return loss
# # Uncomment to run
# feature = torch.tensor([1]) # input tensor
# target = torch.tensor([7]) # target tensor
# simple_graph = SimpleGraph(-0.5, 0.5)
# print("initial weight = {} \ninitial bias = {}".format(simple_graph.w.item(),
# simple_graph.b.item()))
# prediction = simple_graph.forward(feature)
# square_loss = sq_loss(target, prediction)
# print("for x={} and y={}, prediction={} and L2 Loss = {}".format(feature.item(),
# target.item(),
# prediction.item(),
# square_loss.item())) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial1_Solution_b9fccdbe.py) It is important to appreciate the fact that PyTorch can follow our operations as we arbitrary go through classes and functions. 2.2 Backward PropagationHere is where all the magic lies. We can first look at the operations that PyTorch kept track of. Tensor property `grad_fn` keeps reference to backward propagation functions. | print('Gradient function for prediction =', prediction.grad_fn)
print('Gradient function for loss =', square_loss.grad_fn) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
Now let's kick off backward pass to calculate the gradients by calling the `.backward()` on the tensor we wish to initiate the backpropagation from. Often, `.backward()` is called on the loss, which is the last on the graph. Before doing that, let's calculate the loss gradients:$$\frac{\partial{loss}}{\partial{w}} = - 2 x (y_t - y_p)(1 - y_p^2)$$$$\frac{\partial{loss}}{\partial{b}} = - 2 (y_t - y_p)(1 - y_p^2)$$We can then compare it to PyTorch gradients, which can be obtained by calling `.grad` on tensors.**Important Notes*** Always keep in mind that PyTorch is tracking all the operations for tensors that require grad. To stop this tracking, we use `.detach()`.* PyTorch builds the graph only when `.backward()` is called and then it is set free. If you try calling `.backward()` after it is already called, you get the following error: *`Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling .backward() or autograd.grad() the first time.`** Learnable parameters are "contagious". If you recall from our computational graph, we need all the intermediate gradients to be able to use the chain rule. Therefore, we need to `.detach()` any tensor that was on the path of gradient flow (e.g. prediction tensor).* `.backward()` accumulates gradients in the leaves. For most of training methods, we call `.zero_grad()` on the loss or optimizer to zero `.grad` attributes (see [autograd.backward](https://pytorch.org/docs/stable/autograd.htmltorch.autograd.backward) for more). | # analytical gradients (remember detaching)
ana_dloss_dw = - 2 * feature * (target - prediction.detach())*(1 - prediction.detach()**2)
ana_dloss_db = - 2 * (target - prediction.detach())*(1 - prediction.detach()**2)
square_loss.backward() # first we should call the backward to build the graph
autograd_dloss_dw = simple_graph.w.grad
autograd_dloss_db = simple_graph.b.grad
print(ana_dloss_dw == autograd_dloss_dw)
print(ana_dloss_db == autograd_dloss_db) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
References and more:* [A GENTLE INTRODUCTION TO TORCH.AUTOGRAD](https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html)* [AUTOMATIC DIFFERENTIATION PACKAGE - TORCH.AUTOGRAD](https://pytorch.org/docs/stable/autograd.html)* [AUTOGRAD MECHANICS](https://pytorch.org/docs/stable/notes/autograd.html)* [AUTOMATIC DIFFERENTIATION WITH TORCH.AUTOGRAD](https://pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html) --- Section 3: PyTorch's Neural Net module (`nn.Module`) | #@title Video 3.1: Putting it together
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="rUChBWj9ihw", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
In this section we will focus on training the simple neural network model from yesterday. | #@title Generate the sample dataset
import sklearn.datasets
# Create a dataset of 256 points with a little noise
X_orig, y_orig = sklearn.datasets.make_moons(256, noise=0.1)
# Plot the dataset
plt.figure(figsize=(9, 7))
plt.scatter(X_orig[:,0], X_orig[:,1], s=40, c=y_orig)
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")
plt.show()
# Select the appropriate device (GPU or CPU)
device = "cuda" if torch.cuda.is_available() else "cpu"
# Convert the 2D points to a float tensor
X = torch.from_numpy(X_orig).type(torch.FloatTensor)
X = X.to(device)
# Convert the labels to a long interger tensor
y = torch.from_numpy(y_orig).type(torch.LongTensor)
y = y.to(device) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
Let's define the same simple neural network model as in Day 1. This time we will not define a `train` method, but instead implement it outside of the class so we can better inspect it. | # Simple neural network with a single hidden layer
class NaiveNet(nn.Module):
def __init__(self):
"""
Initializing the NaiveNet
"""
super(NaiveNet, self).__init__()
self.layers = nn.Sequential(
nn.Linear(2, 16),
nn.ReLU(),
nn.Linear(16, 2),
)
def forward(self, x):
"""Forward pass
Args:
x (torch.Tensor): 2D tensor of features
Returns:
torch.Tensor: model predictions
"""
return self.layers(x) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
PyTorch provides us with ready to use neural network building blocks, such as linear or recurrent layers, activation functions and loss functions, packed in the [`torch.nn`](https://pytorch.org/docs/stable/nn.html) module. If we build a neural network using the `torch.nn` layers, the weights and biases are already in `requires_grad` mode. Now let's prepare the training! We need 3 things for that:* **Model parameters** - Model parameters refer to all the learnable parameters' of the model which are accessible by calling `.parameters()` on the model. Please note that not all the `requires_grad` are seen as model parameters. To create a custom model parameter, you can use [`nn.Parameter`](https://pytorch.org/docs/stable/generated/torch.nn.parameter.Parameter.html) (*A kind of Tensor that is to be considered a module parameter*). When we create a new instace of our model, layer parameters are initialized using a uniform distribution (more on that in the coming tutorials and days).* **Loss function** - we need to define the loss that we are going to be optimizing. The cross entropy loss is suitable for classification problems.* **Optimizer** - the optimizer will perform the adaptation of the model parameters according to the chosen loss function. The optimizer takes the parameters of the model (often by calling `.parameters()` on the model) as its input to be adapted.You will learn more details about choosing the right loss function and optimizer later in the course. | # Create an instance of our network
naive_model = NaiveNet().to(device)
# Create a cross entropy loss function
cross_entropy_loss = nn.CrossEntropyLoss()
# Stochstic Gradient Descent optimizer with a learning rate of 1e-1
learning_rate = 1e-1
sgd_optimizer = torch.optim.SGD(naive_model.parameters(), lr=learning_rate) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
The training process in PyTorch is interactive - you can perform training iterations as you wish and inspect the results after each iteration. We encourage leaving the loss function outside the explicit forward pass function, and rather calculate it on the output (prediction).Let's perform one training iteration. You can run the cell multiple times and see how the parameters are being updated and the loss is reducing. We pick the parameters of the first neuron in the first layer. Please make sure you go through all the commands and discuss their purpose with the pod. | # Reset all gradients to 0
sgd_optimizer.zero_grad()
# Forward pass (Compute the output of the model on the data)
y_logits = naive_model(X)
# Compute the loss
loss = cross_entropy_loss(y_logits, y)
print('Loss:', loss.item())
# Perform backpropagation to build the graph and compute the gradients
loss.backward()
# `.parameters()` returns a generator
print('Gradients:', next(naive_model.parameters()).grad[0].detach().numpy())
# Print model's first learnable parameters
print('Parameters before:', next(naive_model.parameters())[0].detach().numpy())
# Optimizer takes a step in the steepest direction (negative of gradient)
# and "updates" the weights and biases of the network
sgd_optimizer.step()
# Print model's first learnable parameters
print('Parameters after: ', next(naive_model.parameters())[0].detach().numpy()) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
Exercise 3Following everything we learned so far, we ask you to complete the `train` function below. | def train(features, labels, model, loss_fun, optimizer, n_epochs):
"""Training function
Args:
features (torch.Tensor): features (input) with shape torch.Size([n_samples, 2])
labels (torch.Tensor): labels (targets) with shape torch.Size([n_samples, 2])
model (torch nn.Module): the neural network
loss_fun (function): loss function
optimizer(function): optimizer
n_epochs (int): number of training epochs
Returns:
list: record (evolution) of losses
list: record (evolution) of value of the first parameter
list: record (evolution) of gradient of the first parameter
"""
loss_record = [] # keeping recods of loss
par_values = [] # keeping recods of first parameter
par_grads = [] # keeping recods of gradient of first parameter
# we use `tqdm` methods for progress bar
epoch_range = trange(n_epochs, desc='loss: ', leave=True)
for i in epoch_range:
if loss_record:
epoch_range.set_description("loss: {:.4f}".format(loss_record[-1]))
epoch_range.refresh() # to show immediately the update
time.sleep(0.01)
#################################################
## Implement the missing parts of the training loop
# Complete the function and remove or comment the line below
raise NotImplementedError("Training setup `train`")
#################################################
... # Initialize gradients to 0
predictions = ... # Compute model prediction (output)
loss = ... # Compute the loss
... # Compute gradients (backward pass)
... # update parameters (optimizer takes a step)
loss_record.append(loss.item())
par_values.append(next(model.parameters())[0][0].item())
par_grads.append(next(model.parameters()).grad[0][0].item())
return loss_record, par_values, par_grads
# # Uncomment to run
# epochs = 5000
# losses, values, gradients = train(X, y,
# naive_model,
# cross_entropy_loss,
# sgd_optimizer,
# epochs)
# ex3_plot(epochs, losses, values, gradients) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D2_LinearDeepLearning/solutions/W1D2_Tutorial1_Solution_364cd4e2.py)*Example output:* | #@title Video 3.2: Wrap-up
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="zFmWs6doqhM", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial1.ipynb | haltakov/course-content-dl |
Classifying Hourly Timestamps into Day or Night | import pandas as pd
import numpy as np
import warnings
from df2gspread import df2gspread as d2g
warnings.simplefilter('ignore')
## Import Raw TTN Data from Google SpreadSheet
url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRlXVQ6c3fKWvtQlFRSRUs5TI3soU7EghlypcptOM8paKXcUH8HjYv90VoJBncuEKYIZGLq477xE58C/pub?gid=0&single=true&output=csv'
df_hourly = pd.read_csv(url,parse_dates = ['time'],infer_datetime_format = True,usecols = [0,3])
df_hourly.head()
## Cleaning and re-organizing the DataFrame
df_hourly.rename(columns={'time': 'TimeStamps'}, inplace=True)
df_hourly.rename(columns={'CarCount': 'VehicleCountperHour'}, inplace=True)
## Strip the Microseconds from the time column
df_hourly['TimeStamps'] = df_hourly['TimeStamps'].values.astype('datetime64[s]')
## Reorder the dataframe
df_hourly = df_hourly.reindex(['TimeStamps','VehicleCountperHour'], axis=1)
df_hourly.tail() | _____no_output_____ | MIT | DataWrangling/ClassifyingTimeStamps.ipynb | diliprk/SmartCityVisualization |
Importing SunTime Chart for adding Day or Night Classification Here we add Day or Night classification to Hourly Vehicle Count Data using sunrise and sunset times dataframe of Saarbrucken. These times were acquired from [timeanddate.com](https://www.timeanddate.com/sun/germany/saarbrucken) and the dataframe was manually created. | # Reading SunTime Chart of SaarbrΓΌcken
url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRJCZQkgUHTCcx-wvJOog87qq4EFiQ1W6T4akxLSpiqCb3KjYDf_43coltDGG0YcjjsDTxjeXE-O_NH/pub?gid=0&single=true&output=csv'
df_suntimes = pd.read_csv(url)
# Modified Sun Timings DataFrame
df_suntimes_mod = pd.DataFrame()
df_suntimes_mod['SunriseTimeStamp']= pd.to_datetime(df_suntimes['Date'] + ' ' + df_suntimes['Sunrise'])
df_suntimes_mod['SunsetTimeStamp']= pd.to_datetime(df_suntimes['Date'] + ' ' + df_suntimes['Sunset'])
# Querying values in the dataframe to selected dates
start_time = '2018-02-21 07:25:00'
df_suntimes_mod = df_suntimes_mod.loc[df_suntimes_mod.SunriseTimeStamp >= start_time,:]
end_time = '2018-02-25 18:15:00'
df_suntimes_mod = df_suntimes_mod.loc[df_suntimes_mod.SunriseTimeStamp <= end_time,:]
df_suntimes_mod = df_suntimes_mod.reset_index()
df_suntimes_mod = df_suntimes_mod.drop(['index'], 1)
df_suntimes_mod
## Creating a new Dataframe from original dataframe to classify Hourly TimeStamps as 'Day' or 'Night':
df_dn = df_hourly
## Set Everything to Day First
df_dn['DayorNight'] = 'Day'
## Manually fixing first day's night timestamps to 'Night'
night_index = (df_dn.loc[df_dn.TimeStamps <= (df_suntimes_mod['SunriseTimeStamp'][0]),:]).index
# Select Night Time Traffic Only from Sunset today to next day Sunrise
n_days = len(df_suntimes_mod['SunriseTimeStamp'])
for i,j in zip(range(n_days),range(1,n_days)):
start_time = df_suntimes_mod['SunsetTimeStamp'][i]
end_time = df_suntimes_mod['SunriseTimeStamp'][j]
data = df_dn[(df_dn['TimeStamps'] > start_time) & (df_dn['TimeStamps'] < end_time)]
night_index = night_index.append(data.index)
## Set all the Night TimeStamps to 'Night
df_dn['DayorNight'].iloc[night_index] = 'Night'
df_dn.head(15)
# Writing the file as csv
df_dn.to_csv('data/DayorNight.csv', date_format="%d/%m/%Y %H:%M:%S",index=False)
## Write pandas dataframe to a Google Sheet Using df2spread:
# Insert ID of Google Spreadsheet
spreadsheet = '1LTXIPNb7MX0qEOU_DbBKC-OwE080kyRvt-i_ejFM-Yg'
# Insert Sheet Name
wks_name = 'CleanedData'
d2g.upload(df_dn,spreadsheet,wks_name,col_names=True,clean=True) | _____no_output_____ | MIT | DataWrangling/ClassifyingTimeStamps.ipynb | diliprk/SmartCityVisualization |
Coding MatricesHere are a few exercises to get you started with coding matrices. The exercises start off with vectors and then get more challenging Vectors | ### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable v
v = [] | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
The v variable contains a Python list. This list could also be thought of as a 1x5 matrix with 1 row and 5 columns. How would you represent this list as a matrix? | ### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable mv
### The difference between a vector and a matrix in Python is that
### a matrix is a list of lists.
### Hint: See the last quiz on the previous page
mv = [[]] | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
How would you represent this vector in its vertical form with 5 rows and 1 column? When defining matrices in Python, each row is a list. So in this case, you have 5 rows and thus will need 5 lists.As an example, this is what the vector $$$$ would look like as a 1x2 matrix in Python: ```pythonmatrix1by2 = [ [5, 7]]```And here is what the same vector would look like as a 2x1 matrix:```pythonmatrix2by1 = [ [5], [7]]``` | ### TODO: Assign the vector <5, 10, 2, 6, 1> to the variable vT
### vT is a 5x1 matrix
vT = [] | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
Assigning Matrices to Variables | ### TODO: Assign the following matrix to the variable m
### 8 7 1 2 3
### 1 5 2 9 0
### 8 2 2 4 1
m = [[]] | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
Accessing Matrix Values | ### TODO: In matrix m, change the value
### in the second row last column from 0 to 5
### Hint: You do not need to rewrite the entire matrix
| _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
Looping through Matrices to do MathCoding mathematical operations with matrices can be tricky. Because matrices are lists of lists, you will need to use a for loop inside another for loop. The outside for loop iterates over the rows and the inside for loop iterates over the columns.Here is some pseudo code```pythonfor i in number of rows: for j in number of columns: mymatrix[i][j]```To figure out how many times to loop over the matrix, you need to know the number of rows and number of columns. If you have a variable with a matrix in it, how could you figure out the number of rows? How could you figure out the number of columns? The [len](https://docs.python.org/2/library/functions.htmllen) function in Python might be helpful. Scalar Multiplication | ### TODO: Use for loops to multiply each matrix element by 5
### Store the answer in the r variable. This is called scalar
### multiplication
###
### HINT: First write a for loop that iterates through the rows
### one row at a time
###
### Then write another for loop within the for loop that
### iterates through the columns
###
### If you used the variable i to represent rows and j
### to represent columns, then m[i][j] would give you
### access to each element in the matrix
###
### Because r is an empty list, you cannot directly assign
### a value like r[i][j] = m[i][j]. You might have to
### work on one row at a time and then use r.append(row).
r = [] | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
Printing Out a Matrix | ### TODO: Write a function called matrix_print()
### that prints out a matrix in
### a way that is easy to read.
### Each element in a row should be separated by a tab
### And each row should have its own line
### You can test our your results with the m matrix
### HINT: You can use a for loop within a for loop
### In Python, the print() function will be useful
### print(5, '\t', end = '') will print out the integer 5,
### then add a tab after the 5. The end = '' makes sure that
### the print function does not print out a new line if you do
### not want a new line.
### Your output should look like this
### 8 7 1 2 3
### 1 5 2 9 5
### 8 2 2 4 1
def matrix_print(matrix):
return
m = [
[8, 7, 1, 2, 3],
[1, 5, 2, 9, 5],
[8, 2, 2, 4, 1]
]
matrix_print(m) | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
Test Your Results | ### You can run these tests to see if you have the expected
### results. If everything is correct, this cell has no output
assert v == [5, 10, 2, 6, 1]
assert mv == [
[5, 10, 2, 6, 1]
]
assert vT == [
[5],
[10],
[2],
[6],
[1]]
assert m == [
[8, 7, 1, 2, 3],
[1, 5, 2, 9, 5],
[8, 2, 2, 4, 1]
]
assert r == [
[40, 35, 5, 10, 15],
[5, 25, 10, 45, 25],
[40, 10, 10, 20, 5]
] | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
Print Out Your Results | ### Run this cell to print out your answers
print(v)
print(mv)
print(vT)
print(m)
print(r) | _____no_output_____ | MIT | 4_6_Matrices_and_Transformation_of_State/2_matrices_in_python.ipynb | mustafa1adel/CVND_Localization_Exercises |
μμ 1======= μΌλ¬λκΈ° :**_κΌΌκΌΌνκ² μ½μ΄λ³΄κΈ° λ°λλλ€_*** `prettytable` λͺ¨λμ μ€μΉν΄μΌ μ€ν¬λ¦½νΈλ₯Ό μ€νν μ μμ. (μ€μΉ λ°©λ²: `pip install --user prettytable`) * `flights.db` νμΌμ΄ μμ μ© Jupyter notebookκ³Ό κ°μ λλ ν°λ¦¬μ μμ΄μΌ ν¨ (μλ€λ©΄ [μ¬κΈ°μ](http://open.gnu.ac.kr/lecslides/2018-2-DB/Assignments1/flights.db.zip) λ€μ΄ λ°κΈ°) μμΆμ ν΄μ ν΄μΌ ν¨. `flights.db.zip`μ΄ μλ κ³³μμ `unzip flights.db.zip`μΌλ‘ μμΆμ ν΄μ νλ©΄ λ¨* λ°μ΄ν°λ² μ΄μ€ `flights.db`λ₯Ό λ€μ΄ λ°μ ν κ°μ₯ μμ μ
μ λͺ
λ Ή μ€ννκΈ°* ν
μ€νΈ, λλ²κ·Έ, νμνκΈ° λ±μ μν΄μ μλ‘μ΄ μ
μ μμ±νλ κ²μ μ κ·Ή κΆμ₯ν¨* μ
μ μ€νμν€κ³ μ
μΌ νΈμ `In [*]:` μ΄ λ³΄μΈλ€λ©΄ _μ€ν μ€_ μ μλ―Έν¨ * **λ§μ½ μ
μ΄ μ€λ« λμ κ²°κ³Όλ₯Ό λ΄ λμ§ μκ³ λ©μΆ κ² κ°λ€λ©΄: SQL μ λ€μ μ°κ²°νλλ‘ python kernelμ λ€μ μμν΄μΌ ν¨** * 컀λμ λ€μ μμνλ λ°©λ²: "Kernel >> Restart & Clear Output", κ·Έλ¦¬κ³ μμ μ
λΆν° μλλ‘ νλμ© μ€ν ν¨ * λ€λ₯Έ λ²μ μ λ°μ΄ν°λ² μ΄μ€λ₯Ό λ‘λνκΈ° μν΄μλ λ§μ°¬κ°μ§λ₯Ό μλ‘μ΄ μ°κ²°μ λ§λ€μ΄μΌ ν¨* κΈ°μ΅νκΈ°: * `%sql [SQL μ§μλ¬Έ;]` μ _ν μ€μ§λ¦¬_ SQL μ§μλ¬Έμ μ¬μ© * `%%sql [SQL μ§μλ¬Έ;]` μ _μ¬λ¬ μ€μ§λ¦¬_ SQL μ§μλ¬Έμ μ¬μ©* `submit.py` μ μ€ννλ©΄ μ§μλ¬Έμ μ²λ¦¬νκ³ μΆλ ₯ν¨ * μ€νμ κ²°κ³Όλ `correct_output.txt` νμΌμ λμ μμ. * μ€ν κ²°κ³Όμ λΉκ΅λ₯Ό μνλ€λ©΄ `python sanity_check.py` μ μ€ννκ±°λ, λ€μμ λͺ
λ Ήμ μ€ννμ¬ κ²°κ³Όλ₯Ό μ»μ μ μμ `python submit.py > my_output; diff my_output correct_output.txt` ν°λ―Έλμμ μ
λ ₯ν΄μΌ ν¨ * **μμ λ‘ μμ±ν `submit.py` νμΌμ μλμ νμμ μ λμ μΌλ‘ λ°λΌμΌ ν¨.** νμμ΄λΌ ν¨μ: * 컬λΌμ μ΄λ¦μ `correct_output.txt` μ λμ μλ μ΄λ¦κ³Ό **λκ°μ μ΄λ¦**μ΄μ΄μΌ ν¨ * 컬λΌμ μμλ `correct_output.txt` μ λμ μλ μμμ **λκ°μ μμ**μ΄μ΄μΌ ν¨ μ μΆ λ°©λ²: * iPython notebook μ체λ₯Ό μ μΆνμ§ λ§ κ² * λμ μ, `submit.py` μ μμ±ν λ²νΈμ λ§κ² μ§μλ¬Έμ λ³΅μ¬ λΆμ¬ λ£κΈ° ν κ² * `%sql` λλ `%%sql` λͺ
λ Ήμ SQL λ¬Έμ ν¬ν¨μν€μ§ λ§ κ² * μ μΆν μ§μλ¬Έμ λκ°μ μ€ν€λ§μμ μμλ‘ μ νλ κ°μ λμμΌλ‘ μ€νμμΌ νκ°λ₯Ό ν κ²μ. κ·Έλ κΈ° λλ¬Έμ ν΄λ΅κ³Ό λκ°μ κ²°κ³Όκ° λμ€λλ‘ μμλ±μ μ¨μ μ‘°μνμ§ λ§κ² * **`submission_instructions.txt` μ μ€λͺ
λ λ°©λ²μΌλ‘ ν΄λ΅μ μ μΆν κ²**_μ¦κ²κ² μμν΄λ΄
μλ€!_ κ°μ: μ¬ν μΌμ μ§μ°------------------------μ¬ν μΌμ μ΄ μ§μ° λλ κ²λ§νΌ μ§μ¦ λλ μΌμ μμ΅λλ€. κ·Έλ μ§ μλμ?μ¬ν μΌμ μ΄ μ§μ°λμ§ μλλ‘ μ¬λ¬κ°μ§ μλ‘μ΄ λ°©λ²μ μ°Ύμλ΄
λλ€. μ΅κ·Όμ μ°Ύμ λ°μ΄ν°κ° μ μΌμ μ΄ μ§μ°λλμ§ μ΄μ μ 무μμ ν¬κΈ°ν μ§λ₯Ό μ μ€λͺ
ν΄μ£Όκ³ μμ΅λλ€. SQLμ μ¬μ©ν΄μ ν λ² κ·Έ μ΄μ λ€μ μμλ΄
μλ€. ---- μ΄ κ³Όμ μμλ 2017λ
7μμ μ¬κ°κΈ°μ μ§μ° μ 보μ μ 보λ₯Ό λ΄κ³ μμ΅λλ€. λ°μ΄ν°λ² μ΄μ€μ κΈ°λ³Έ 릴λ μ΄μ
μ λν μ 보λ₯Ό μμ λ΄
μλ€. | %%sql
SELECT *
FROM flight_delays
LIMIT 1; | * sqlite:///flights.db
Done.
| MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
κ΅μ₯ν λ§μ 컬λΌλ€μ΄ μλ κ²μ μ μ μλλ°, κ·Έλ¬λ©΄ λͺ μ€μ΄λ λ κΉμ? | %%sql
SELECT COUNT(*) AS num_rows
FROM flight_delays | * sqlite:///flights.db
Done.
| MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
λ°μ΄ν°μ μμ΄ μλΉν©λλ€! μκ³Ό 머리λ‘λ§ ν΄λ΅μ μ°Ύμ§ λͺ»ν κ² κ°κ΅°μ. λ°μ΄ν°λ² μ΄μ€μ λ λ§μ λ°μ΄ν°λ₯Ό λ£μ νμλ μκ² κ΅°μ. 컬λΌλ€μ΄ μ΄λ€ μλ―Έλ₯Ό κ°λμ§ μμ λ³΄λ €λ©΄ [μ΄ λ§ν¬](https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236)λ₯Ό λ°λΌκ°κΈ° λ°λλλ€. λͺ κ°μ μΆκ°μ μΈ ν
μ΄λΈλ€μ κ°μ΄ ν¬ν¨ν΄ λμμ΅λλ€. μ΄ ν
μ΄λΈλ€μ μ¬μ©νλ©΄ `airline_id`, `airport_id`, κ·Έλ¦¬κ³ `day_of_week` μ μ¬λμ΄ μ½κΈ° νΈν μ λ³΄λ‘ λ³νν μ μμ΅λλ€. μλμ μ
μ μ΄μ©νμ¬ `airlines`κ³Ό `weekdays` μ μ 보λ₯Ό νμΈν΄λ³΄κΈ° λ°λλλ€: | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ’μ΅λλ€. μ΄μ μμν΄λ΄
μλ€. SQL μ§μλ¬Έ μ§μλ¬Έ 1: ν곡νΈμ νκ· μ§μ° μκ°μ? ------------------------λ°μ΄ν°μ λν μ΄ν΄λ₯Ό λκΈ° μν΄, κ°λ¨ν μ§μλ¬Έμ μμ±ν΄λ΄
μλ€.μλμ μ
μ 2017λ
7μλμ λͺ¨λ ν곡νΈμ νκ· μ§μ°μκ°μ ꡬνλ μ§μλ¬Έμ μμ±ν΄λ΄
μλ€. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 2: κ°μ₯ κΈ΄ μ§μ° μκ°μ?------------------------νκ· μ 그리 ν¬μ§ μκ΅°μ. νμ§λ§ _μ΅μ₯_ μ§μ° μκ°μ μ΄λ»κ² λλμ?μλμ μ
μ 2017λ
7μλμ κ°μ₯ λ¦κ² λμ°©ν μκ°μ μ°Ύλ μ§μλ¬Έμ μμ±ν΄λ΄
μλ€. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 3: μ΄λ€ ν곡νΈμ νΌνλ κ²μ΄ μ μ 건κ°μ μ’μκΉμ?------------------------μ΄λ€ ν곡νΈμ΄ κ°μ₯ λ¦μλμ?μλμ μ
μ 2017λ
7μμ κ°μ₯ λ¦κ² λμ°©ν ν곡μ¬(`carrier`)μ νκ³΅νΈ λͺ
, μΆλ° λμ λͺ
, λμ°© λμ λͺ
, ν곡 μΌμ μ μΆλ ₯νλ μ§μλ¬Έμ μμ± λ°λλλ€. μμμ μ»μ μ 보λ₯Ό μ§μλ¬Έμ μ½μ
ν΄μ κ³μ°νμ§ λ§κ³ μ€μ²© μ§μλ¬Έμ μ°κΈ° λ°λλλ€. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 4: μ΄λ€ μμΌμ΄ μ¬ννκΈ° κ°μ₯ μμ’μ λ μΈκ°μ?------------------------νκΈ°κ° μμλμμΌλ λ¨Ό κ³³μΌλ‘ μ¬νμ ν μλ μμ§λ§, μΆμ₯μ κ°μΌνκ² μ§μ. λΉνκΈ°λ₯Ό νκΈ° κ°μ₯ μμ’μ λ μ λ¬΄μ¨ μμΌμΈκ°μ?μλμ μ
μ μμΌλ§λ€ νκ· μ§μ° μκ°μ΄ μ΄λ»κ² λλμ§ λ΄λ¦Όμ°¨μμΌλ‘ μ λ ¬νμ¬ κ²°κ³Όλ₯Ό μΆλ ₯νλλ‘ μ§μλ¬Έμ μμ±νκΈ° λ°λλλ€. μΆλ ₯ κ²°κ³Όμ μ€ν€λ§λ (`weekday_name`, `average_delay`)μ ννλ₯Ό κ°κ³ μμ΄μΌ ν©λλ€.**Note: μμΌμ IDλ₯Ό κ·Έλλ‘ μΆλ ₯νμ§ λ§κΈ° λ°λλλ€.** (Hint: `weekdays` ν
μ΄λΈμ μ¬μ©νμ¬ joinνμ¬ μμΌμ μ΄λ¦μ μΆλ ₯νλλ‘ ν©μλ€.) | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 5: SFOμμ μΆλ°νλ νκ³΅μ¬ μ€ μ§μ° μκ°μ΄ κ°μ₯ κΈ΄ ν곡μ¬λ μ΄λμ
λκΉ?------------------------μ΄λ€ μμΌμ νΌν΄μΌ ν μ§ μμμΌλ SFOμμ μΆλ°νλ νκ³΅μ¬ μ€ ν κ³³μ μ ν΄μΌ ν©λλ€. μ΄λλ‘ κ°μ§λ λ§νμ§ μμμΌλ, SFOμμ μΆλ°νλ λͺ¨λ ν곡μ¬μ ν곡νΈλ€μ νκ· μ§μ°μκ°μ κ΅¬ν΄ λ΄
μλ€.μλμ μ
μ 2017λ
7μμ SFOμμ μΆλ°ν κ° νκ³΅μ¬ λ³λ‘ λͺ¨λ ν곡νΈμ λν΄ νκ· μ§μ°μκ°μ λ΄λ¦Όμ°¨μμΌλ‘ ꡬνλ μ§μλ¬Έμ μμ±ν΄λ΄
μλ€.**Note: νκ³΅μ¬ IDλ₯Ό κ·Έλλ‘ μΆλ ₯νμ§ λ§μλ€.** (Hint: μ€μ²© μ§μλ¬ΈμΌλ‘ `airlines` ν
μ΄λΈμ join νμ¬ νκ³΅μ¬ μ΄λ¦μ μΆλ ₯ν©μλ€.) | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 6: ν곡μ¬λ€μ μ§μ° λΉμ¨μ μμ λ΄
μλ€------------------------μ§μ°λλ ν곡νΈμ΄ λ§μ΅λλ€. μ΄λ€ ν곡μ¬κ° μ§μ°μκ°μ΄ λ§μ μμλ΄
μλ€.μλμ μ
μ νκ· 10λΆ μ΄μ μ§μ°λλ ν곡νΈμ΄ μμλ ν곡μ¬λ€μ λΉμ¨μ ꡬν΄λ΄
μλ€. μ 체 ν곡μ¬μ μλ₯Ό μΈμ μ§μλ¬Έμ ν¬ν¨μν€μ§ λ§κΈ° λ°λλλ€. κ·Έλ¦¬κ³ μ§μλ¬Έμλ μ΅μν νλ μ΄μμ `HAVING` μ μ μ¬μ©ν©μλ€.Note: sqlite μ `COUNT(*)`λ μ μνμ 리ν΄νκΈ° λλ¬Έμ μ€μνμΌλ‘ κ²°κ³Όλ₯Ό μΆλ ₯νλ €λ©΄ μ΅μν ν λ² μ΄μ `SELECT CAST (COUNT(*) AS float)` λλ `COUNT(*)*1.0` μ μ μ¨μΌ ν©λλ€. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 7: μΆλ° μ§μ°μ΄ λμ°© μ§μ°μ μ΄λ€ μν₯μ λ―ΈμΉλμ?------------------------λΉνκΈ°κ° μ§μ° μΆλ°νλ©΄ λμ°© μκ°μ μΌλ§λ μν₯μ μ£Όλμ§ μκ³ μΆμ΅λλ€.[μν 곡λΆμ°](https://en.wikipedia.org/wiki/Covariance) μ λ λ³μ κ°μ λΆμ°λμ μΈ‘μ νμ¬ μκ΄κ΄κ³κ° μλμ§ μλ €μ£Όλ ν΅κ³μΉμ
λλ€. 곡λΆμ°μ΄ ν΄μλ‘ μκ΄κ΄κ³κ° λκ³ μμμΈ κ²½μ° μμκ΄κ΄κ³κ° μμ΅λλ€. μν 곡λΆμ°μ κ³μ° μμ λ€μκ³Ό κ°μ΅λλ€:$$Cov(X,Y) = \frac{1}{n-1} \sum_{i=1}^n (x_i-\hat{x})(y_i-\hat{y})$$μ΄ λ, $x_i$ λ $X$μ $i$λ²μ§Έ κ°μ΄κ³ , $y_i$λ $Y$μ $i$λ²μ§Έ κ°μ
λλ€. $X$ μ $Y$μ νκ· μ $\bar{x}$ κ³Ό $\bar{y}$μΌλ‘ νν νμμ΅λλ€.μλμ μ
μ λμ°© μ§μ°κ³Ό μΆλ° μ§μ° μκ°μ 곡λΆμ°μ ꡬνλ νλμ μ§μλ¬Έμ μμ± ν΄λ³΄κΈ° λ°λλλ€.*Note: [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) μΌλ‘ ꡬν μλ μμ΅λλ€. κ·Έ κ²°κ³Όλ μ κ·ν λμ΄ 1 λΆν° -1μ κ°μΌλ‘ μκ΄κ΄κ³λ₯Ό μλ € μ€λλ€. νμ§λ§, SQLiteλ λ£¨νΈ κ³μ° ν¨μκ° λ€μ΄ μμ§ μκΈ° λλ¬Έμ μ΄ κ³μ°μμ μΈ μ κ° μμ΅λλ€. λ€λ₯Έ 보νΈμ μΈ λ°μ΄ν°λ² μ΄μ€(PostgreSQLμ MySQL)μλ λ£¨νΈ κ³μ° ν¨μκ° κ΅¬νλμ΄ μμ΅λλ€.* | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 8: ν μ£Όκ° μλ§μ΄μμ΅λλ€...------------------------7μ μ΄λ€ ν곡μ¬μ λ§μ§λ§ ν μ£Ό(24μΌ μ΄ν)μ νκ· μ§μ° μκ°μ΄ κ·Έ μ΄μ μ£Ό(24μΌ μ΄μ )λ€μ νκ· μ§μ° μκ°λ³΄λ€ μ λμ μΌλ‘ κΈΈμλμ?μλμ μ
μ 1μΌλΆν° 23μΌκΉμ§μ νκ· μ§μ° μκ° λλΉ 24μΌ λΆν° 31μΌ μ¬μ΄μ νκ· μ§μ° μκ°μ΄ μ λμ μΌλ‘ κΈΈμλ ν곡μ¬μ μ΄λ¦μ μΆλ ₯νλ μ§μλ¬Έμ μμ±νκΈ° λ°λλλ€.Note: [sqliteμμ λ μ§ λ€λ£¨κΈ°](http://www.sqlite.org/lang_datefunc.html)μ λ°λΌ `day_of_month`μ μ¬μ©νμ¬ μ§μλ¬Έμ μμ±νλ κ²μ΄ νΈν κ²μ
λλ€.Note 2: μλ§ κ³Όμ μ€ κ°μ₯ μ΄λ €μ΄ μ§μλ¬Έμ΄ λ μλ μλλ°, μμ λ¨μλ‘ μ§μλ¬Έμ μμ±νμ¬ ν λΆλΆμ© ν΄κ²°νκ³ , κ·Έ μ§μλ¬Έμ ν©μ³μ μ΅μ’
μ§μλ¬Έμ μμ±νλ κ²μ΄ μ’μ΅λλ€.Hint: λ κ°μ νμ μ§μλ¬ΈμΌλ‘ κ³μ°ν μ μμ΅λλ€. νλμ μ§μλ¬Έμ΄ 24μΌ μ΄νμ νκ· λμ°© μκ°μ κ³μ°νκ³ , λ€λ₯Έ μ§μλ¬Έμ΄ 24μΌ μ΄μ μ λμ°© μκ°μ κ³μ°νκ³ , λ μ§μλ¬Έμ joinνμ¬ μ§μ° μκ°μ μ°¨λ₯Ό κ³μ°νλ©΄ λ©λλ€. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 9: μ§λ³΄μ μΈ κ·Έλ¦¬κ³ νλͺ
μ μΈ------------------------ν¬νΈλλ (PDX)μ μ μ§ (EUG)λ‘ κ°κΈ°λ₯Ό μνμ§λ§, ν λ²μ κ°κΈ°κ° μ½μ§ μκ΅°μ. μ°μ κ³ κ° λ§μΌλ¦¬μ§λ₯Ό μ±μ°κΈ° μν΄ κ°μ ν곡νΈμΌλ‘ κ° λμλ‘ μ΄λνκΈ°λ₯Ό μν©λλ€. SFO -> PDFμ SFO -> EUG λ‘ κ°λ κ°μ ν곡μ¬κ° μλμ§ μκ³ μΆμ΅λλ€.μλμ μ
μ 2017λ
7μμ SFO -> PDX κ³Ό SFO -> EUG μ μΆνν ν곡μ¬μ μ μΌν μ΄λ¦(μ€λ³΅ μμ ID κ° μλ)μ μΆλ ₯νλ νλμ SQL μ§μλ¬Έμ μμ±νκΈ° λ°λλλ€. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
μ§μλ¬Έ 10: νΌλ‘λμ λ±κ±°λ¦¬ κ°μ κ²°μ ------------------------μμΉ΄κ³ μμ μΊλ¦¬ν¬λμλ‘ μ΄λνλ €κ³ ν©λλ€. Midway (MDW) λλ O'Hare (ORD) μμ μνλμμ€μ½ (SFO), μ°νΈμΈ (SJC), μ€ν¬λλ (OAK)λ‘ λμ°©νλ©΄ μ’κ²μ΅λλ€. λ§μ½ μ΄ λ² λ¬μ΄ 7μμ΄λΌκ³ νλ©΄ μμΉ΄κ³ μμ νμ§ μκ° 14μμ μΆλ°νλ κ²½λ‘ μ€ μ§μ° μκ°μ΄ κ°μ₯ μ§§μ κ²½λ‘κ° μ΄λ€ κ²μ
λκΉ?μλμ μ
μ MDW λλ ORD μμ νμ§ μκ° 14μ(`crs_dep_time`)μ μΆλ°νκ³ SFO, SJC, λλ OAKμ λμ°©νλ ν곡νΈλ€μ νκ· μ§μ° μκ°μ ꡬνλ νλμ μ§μλ¬Έμ μμ±νκΈ° λ°λλλ€. μΆλ°κ³Ό λμ°© 곡νμ Group byλ‘ λ¬Άκ³ μ§μ° μκ°μ λ΄λ¦Όμ°¨μμΌλ‘ μΆλ ₯νκΈ° λ°λλλ€.Note: `crs_dep_time` νλλ μ μ νμ κ°κ³ μμΌλ©° hhmm (e.g. 4:15pm μ 1615 μ) νμ λ°λ¦. | %%sql
| _____no_output_____ | MIT | Assignments1/HW1.ipynb | resourceful/lecture_db |
303 Build NN QuicklyView more, visit my tutorial page: https://morvanzhou.github.io/tutorials/My Youtube Channel: https://www.youtube.com/user/MorvanZhou | import torch
import torch.nn.functional as F
# replace following class code with an easy sequential network
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
def forward(self, x):
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
return x
net1 = Net(1, 10, 1)
# easy and fast way to build your network
net2 = torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1)
)
print(net1) # net1 architecture
print(net2) # net2 architecture | Net(
(hidden): Linear(in_features=1, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=1, bias=True)
)
Sequential(
(0): Linear(in_features=1, out_features=10, bias=True)
(1): ReLU()
(2): Linear(in_features=10, out_features=1, bias=True)
)
| MIT | tutorial-contents-notebooks/303_build_nn_quickly.ipynb | harrywang/PyTorch-Tutorial |
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); Generating C code for the right-hand-side of the scalar wave equation, in ***curvilinear*** coordinates, using a reference metric formalism Author: Zach Etienne Formatting improvements courtesy Brandon Clark[comment]: (Abstract: TODO)**Notebook Status:** Validated **Validation Notes:** This tutorial notebook has been confirmed to be self-consistent with its corresponding NRPy+ module, as documented [below](code_validation). In addition, all expressions have been validated against a trusted code (the [original SENR/NRPy+ code](https://bitbucket.org/zach_etienne/nrpy)). NRPy+ Source Code for this module: [ScalarWaveCurvilinear/ScalarWaveCurvilinear_RHSs.py](../edit/ScalarWaveCurvilinear/ScalarWaveCurvilinear_RHSs.py)[comment]: (Introduction: TODO) Table of Contents$$\label{toc}$$This notebook is organized as follows0. [Preliminaries](prelim): Reference Metrics and Picking Best Coordinate System to Solve the PDE1. [Example](example): The scalar wave equation in spherical coordinates1. [Step 1](contracted_christoffel): Contracted Christoffel symbols $\hat{\Gamma}^i = \hat{g}^{ij}\hat{\Gamma}^k_{ij}$ in spherical coordinates, using NRPy+1. [Step 2](rhs_scalarwave_spherical): The right-hand side of the scalar wave equation in spherical coordinates, using NRPy+1. [Step 3](code_validation): Code Validation against `ScalarWaveCurvilinear.ScalarWaveCurvilinear_RHSs` NRPy+ Module1. [Step 5](latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file Preliminaries: Reference Metrics and Picking Best Coordinate System to Solve the PDE \[Back to [top](toc)\]$$\label{prelim}$$Recall from [NRPy+ tutorial notebook on the Cartesian scalar wave equation](Tutorial-ScalarWave.ipynb), the scalar wave equation in 3D Cartesian coordinates is given by$$\partial_t^2 u = c^2 \nabla^2 u \text{,}$$where $u$ (the amplitude of the wave) is a function of time and Cartesian coordinates in space: $u = u(t,x,y,z)$ (spatial dimension as-yet unspecified), and subject to some initial condition$$u(0,x,y,z) = f(x,y,z),$$with suitable (sometimes approximate) spatial boundary conditions.To simplify this equation, let's first choose units such that $c=1$. Alternative wave speeds can be constructedby simply rescaling the time coordinate, with the net effect being that the time $t$ is replaced with time in dimensions of space; i.e., $t\to c t$:$$\partial_t^2 u = \nabla^2 u.$$As we learned in the [NRPy+ tutorial notebook on reference metrics](Tutorial-Reference_Metric.ipynb), reference metrics are a means to pick the best coordinate system for the PDE we wish to solve. However, to take advantage of reference metrics requires first that we generalize the PDE. In the case of the scalar wave equation, this involves first rewriting in [Einstein notation](https://en.wikipedia.org/wiki/Einstein_notation) (with implied summation over repeated indices) via$$(-\partial_t^2 + \nabla^2) u = \eta^{\mu\nu} u_{,\ \mu\nu} = 0,$$where $u_{,\mu\nu} = \partial_\mu \partial_\nu u$, and $\eta^{\mu\nu}$ is the contravariant flat-space metric tensor with components $\text{diag}(-1,1,1,1)$.Next we apply the "comma-goes-to-semicolon rule" and replace $\eta^{\mu\nu}$ with $\hat{g}^{\mu\nu}$ to generalize the scalar wave equation to an arbitrary reference metric $\hat{g}^{\mu\nu}$:$$\hat{g}^{\mu\nu} u_{;\ \mu\nu} = \hat{\nabla}_{\mu} \hat{\nabla}_{\nu} u = 0,$$where $\hat{\nabla}_{\mu}$ denotes the [covariant derivative](https://en.wikipedia.org/wiki/Covariant_derivative) with respect to the reference metric basis vectors $\hat{x}^{\mu}$, and $\hat{g}^{\mu \nu} \hat{\nabla}_{\mu} \hat{\nabla}_{\nu} u$ is the covariant[D'Alembertian](https://en.wikipedia.org/wiki/D%27Alembert_operator) of $u$.For example, suppose we wish to model a short-wavelength wave that is nearly spherical. In this case, if we were to solve the wave equation PDE in Cartesian coordinates, we would in principle need high resolution in all three cardinal directions. If instead we chose spherical coordinates centered at the center of the wave, we might need high resolution only in the radial direction, with only a few points required in the angular directions. Thus choosing spherical coordinates would be far more computationally efficient than modeling the wave in Cartesian coordinates.Let's now expand the covariant scalar wave equation in arbitrary coordinates. Since the covariant derivative of a scalar is equivalent to its partial derivative, we have\begin{align}0 &= \hat{g}^{\mu \nu} \hat{\nabla}_{\mu} \hat{\nabla}_{\nu} u \\&= \hat{g}^{\mu \nu} \hat{\nabla}_{\mu} \partial_{\nu} u.\end{align}$\partial_{\nu} u$ transforms as a one-form under covariant differentiation, so we have$$\hat{\nabla}_{\mu} \partial_{\nu} u = \partial_{\mu} \partial_{\nu} u - \hat{\Gamma}^\tau_{\mu\nu} \partial_\tau u,$$where $$\hat{\Gamma}^\tau_{\mu\nu} = \frac{1}{2} \hat{g}^{\tau\alpha} \left(\partial_\nu \hat{g}_{\alpha\mu} + \partial_\mu \hat{g}_{\alpha\nu} - \partial_\alpha \hat{g}_{\mu\nu} \right)$$are the [Christoffel symbols](https://en.wikipedia.org/wiki/Christoffel_symbols) associated with the reference metric $\hat{g}_{\mu\nu}$.Then the scalar wave equation is written:$$0 = \hat{g}^{\mu \nu} \left( \partial_{\mu} \partial_{\nu} u - \hat{\Gamma}^\tau_{\mu\nu} \partial_\tau u\right).$$Define the contracted Christoffel symbols:$$\hat{\Gamma}^\tau = \hat{g}^{\mu\nu} \hat{\Gamma}^\tau_{\mu\nu}.$$Then the scalar wave equation is given by$$0 = \hat{g}^{\mu \nu} \partial_{\mu} \partial_{\nu} u - \hat{\Gamma}^\tau \partial_\tau u.$$The reference metrics we adopt satisfy$$\hat{g}^{t \nu} = -\delta^{t \nu},$$where $\delta^{t \nu}$ is the [Kronecker delta](https://en.wikipedia.org/wiki/Kronecker_delta). Therefore the scalar wave equation in curvilinear coordinates can be written\begin{align}0 &= \hat{g}^{\mu \nu} \partial_{\mu} \partial_{\nu} u - \hat{\Gamma}^\tau \partial_\tau u \\&= -\partial_t^2 u + \hat{g}^{i j} \partial_{i} \partial_{j} u - \hat{\Gamma}^i \partial_i u \\\implies \partial_t^2 u &= \hat{g}^{i j} \partial_{i} \partial_{j} u - \hat{\Gamma}^i \partial_i u,\end{align}where repeated Latin indices denote implied summation over *spatial* components only. This module implements the bottom equation for arbitrary reference metrics satisfying $\hat{g}^{t \nu} = -\delta^{t \nu}$. To gain an appreciation for what NRPy+ accomplishes automatically, let's first work out the scalar wave equation in spherical coordinates by hand: Example: The scalar wave equation in spherical coordinates \[Back to [top](toc)\]$$\label{example}$$For example, the spherical reference metric is written$$\hat{g}_{\mu\nu} = \begin{pmatrix}-1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & r^2 & 0 \\ 0 & 0 & 0 & r^2 \sin^2 \theta \\\end{pmatrix}.$$Since the inverse of a diagonal matrix is simply the inverse of the diagonal elements, we can write $$\hat{g}^{\mu\nu} = \begin{pmatrix}-1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & \frac{1}{r^2} & 0 \\ 0 & 0 & 0 & \frac{1}{r^2 \sin^2 \theta} \\\end{pmatrix}.$$The scalar wave equation in these coordinates can thus be written\begin{align}0 &= \hat{g}^{\mu \nu} \partial_{\mu} \partial_{\nu} u - \hat{\Gamma}^\tau \partial_\tau u \\&= \hat{g}^{tt} \partial_t^2 u + \hat{g}^{rr} \partial_r^2 u + \hat{g}^{\theta\theta} \partial_\theta^2 u + \hat{g}^{\phi\phi} \partial_\phi^2 u - \hat{\Gamma}^\tau \partial_\tau u \\&= -\partial_t^2 u + \partial_r^2 u + \frac{1}{r^2} \partial_\theta^2u + \frac{1}{r^2 \sin^2 \theta} \partial_\phi^2 u - \hat{\Gamma}^\tau \partial_\tau u\\\implies \partial_t^2 u &= \partial_r^2 u + \frac{1}{r^2} \partial_\theta^2u + \frac{1}{r^2 \sin^2 \theta} \partial_\phi^2 u - \hat{\Gamma}^\tau \partial_\tau u\end{align}The contracted Christoffel symbols $\hat{\Gamma}^\tau$ can then be computed directly from the metric $\hat{g}_{\mu\nu}$.It can be shown (exercise to the reader) that the only nonzerocomponents of $\hat{\Gamma}^\tau$ in static spherical polar coordinates aregiven by\begin{align}\hat{\Gamma}^r &= -\frac{2}{r} \\\hat{\Gamma}^\theta &= -\frac{\cos\theta}{r^2 \sin\theta}.\end{align}Thus we have found the Laplacian in spherical coordinates is simply:\begin{align}\nabla^2 u &= \partial_r^2 u + \frac{1}{r^2} \partial_\theta^2 u + \frac{1}{r^2 \sin^2 \theta} \partial_\phi^2 u - \hat{\Gamma}^\tau \partial_\tau u\\&= \partial_r^2 u + \frac{1}{r^2} \partial_\theta^2 u + \frac{1}{r^2 \sin^2 \theta} \partial_\phi^2 u + \frac{2}{r} \partial_r u + \frac{\cos\theta}{r^2 \sin\theta} \partial_\theta u\end{align}(cf. http://mathworld.wolfram.com/SphericalCoordinates.html; though note that they defined the angle $\phi$ as $\theta$ and $\theta$ as $\phi$.) Step 1: Contracted Christoffel symbols $\hat{\Gamma}^i = \hat{g}^{ij}\hat{\Gamma}^k_{ij}$ in spherical coordinates, using NRPy+ \[Back to [top](toc)\]$$\label{contracted_christoffel}$$Let's next use NRPy+ to derive the contracted Christoffel symbols$$\hat{g}^{ij} \hat{\Gamma}^k_{ij}$$in spherical coordinates, where $i\in\{1,2,3\}$ and $j\in\{1,2,3\}$ are spatial indices.As discussed in the [NRPy+ tutorial notebook on reference metrics](Tutorial-Reference_Metric.ipynb), several reference-metric-related quantities in spherical coordinates are computed in NRPy+ (provided the parameter **`reference_metric::CoordSystem`** is set to **`"Spherical"`**), including the inverse spatial spherical reference metric $\hat{g}^{ij}$ and the Christoffel symbols from this reference metric $\hat{\Gamma}^{i}_{jk}$. | import sympy as sp
import NRPy_param_funcs as par
import indexedexp as ixp
import reference_metric as rfm
# reference_metric::CoordSystem can be set to Spherical, SinhSpherical, SinhSphericalv2,
# Cylindrical, SinhCylindrical, SinhCylindricalv2, etc.
# See reference_metric.py and NRPy+ tutorial notebook on
# reference metrics for full list and description of how
# to extend.
par.set_parval_from_str("reference_metric::CoordSystem","Spherical")
par.set_parval_from_str("grid::DIM",3)
rfm.reference_metric()
contractedGammahatU = ixp.zerorank1()
for k in range(3):
for i in range(3):
for j in range(3):
contractedGammahatU[k] += rfm.ghatUU[i][j] * rfm.GammahatUDD[k][i][j]
for k in range(3):
print("contracted GammahatU["+str(k)+"]:")
sp.pretty_print(sp.simplify(contractedGammahatU[k]))
if k<2:
print("\n\n") | contracted GammahatU[0]:
-2
βββ
xxβ
contracted GammahatU[1]:
-1
βββββββββββββ
2
xxβ β
tan(xxβ)
contracted GammahatU[2]:
0
| BSD-2-Clause | Tutorial-ScalarWaveCurvilinear.ipynb | Steve-Hawk/nrpytutorial |
Step 2: The right-hand side of the scalar wave equation in spherical coordinates, using NRPy+ \[Back to [top](toc)\]$$\label{rhs_scalarwave_spherical}$$Following our [implementation of the scalar wave equation in Cartesian coordinates](Tutorial-ScalarWave.ipynb), we will introduce a new variable $v=\partial_t u$ that will enable us to split the second time derivative into two first-order time derivatives:\begin{align}\partial_t u &= v \\\partial_t v &= \hat{g}^{ij} \partial_{i} \partial_{j} u - \hat{\Gamma}^i \partial_i u.\end{align}Adding back the sound speed $c$, we have a choice of a single factor of $c$ multiplying both right-hand sides, or a factor of $c^2$ multiplying the second equation only. We'll choose the latter:\begin{align}\partial_t u &= v \\\partial_t v &= c^2 \left(\hat{g}^{ij} \partial_{i} \partial_{j} u - \hat{\Gamma}^i \partial_i u\right).\end{align}Now let's generate the C code for the finite-difference representations of the right-hand sides of the above "time evolution" equations for $u$ and $v$. Since the right-hand side of $\partial_t v$ contains implied sums over $i$ and $j$ in the first term, and an implied sum over $k$ in the second term, we'll find it useful to split the right-hand side into two parts\begin{equation}\partial_t v = c^2 \left({\underbrace {\textstyle \hat{g}^{ij} \partial_{i} \partial_{j} u}_{\text{Part 1}}} {\underbrace {\textstyle -\hat{\Gamma}^i \partial_i u}_{\text{Part 2}}}\right),\end{equation}and perform the implied sums in two pieces: | import NRPy_param_funcs as par
import indexedexp as ixp
import grid as gri
import finite_difference as fin
import reference_metric as rfm
from outputC import *
# The name of this module ("scalarwave") is given by __name__:
thismodule = __name__
# Step 0: Read the spatial dimension parameter as DIM.
DIM = par.parval_from_str("grid::DIM")
# Step 1: Set the finite differencing order to 4.
par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER",4)
# Step 2a: Reset the gridfunctions list; below we define the
# full complement of gridfunctions needed by this
# tutorial. This line of code enables us to re-run this
# tutorial without resetting the running Python kernel.
gri.glb_gridfcs_list = []
# Step 2b: Register gridfunctions that are needed as input
# to the scalar wave RHS expressions.
uu, vv = gri.register_gridfunctions("EVOL",["uu","vv"])
# Step 3a: Declare the rank-1 indexed expression \partial_{i} u,
# Derivative variables like these must have an underscore
# in them, so the finite difference module can parse the
# variable name properly.
uu_dD = ixp.declarerank1("uu_dD")
# Step 3b: Declare the rank-2 indexed expression \partial_{ij} u,
# which is symmetric about interchange of indices i and j
# Derivative variables like these must have an underscore
# in them, so the finite difference module can parse the
# variable name properly.
uu_dDD = ixp.declarerank2("uu_dDD","sym01")
# Step 4: Define the C parameter wavespeed. The `wavespeed`
# variable is a proper SymPy variable, so it can be
# used in below expressions. In the C code, it acts
# just like a usual parameter, whose value is
# specified in the parameter file.
wavespeed = par.Cparameters("REAL",thismodule,"wavespeed", 1.0)
# Step 5: Define right-hand sides for the evolution.
uu_rhs = vv
# Step 5b: The right-hand side of the \partial_t v equation
# is given by:
# \hat{g}^{ij} \partial_i \partial_j u - \hat{\Gamma}^i \partial_i u.
# ^^^^^^^^^^^^ PART 1 ^^^^^^^^^^^^^^^^ ^^^^^^^^^^ PART 2 ^^^^^^^^^^^
vv_rhs = 0
for i in range(DIM):
# PART 2:
vv_rhs -= contractedGammahatU[i]*uu_dD[i]
for j in range(DIM):
# PART 1:
vv_rhs += rfm.ghatUU[i][j]*uu_dDD[i][j]
vv_rhs *= wavespeed*wavespeed
# Step 6: Generate C code for scalarwave evolution equations,
# print output to the screen (standard out, or stdout).
fin.FD_outputC("stdout",
[lhrh(lhs=gri.gfaccess("rhs_gfs","uu"),rhs=uu_rhs),
lhrh(lhs=gri.gfaccess("rhs_gfs","vv"),rhs=vv_rhs)]) | {
/*
* NRPy+ Finite Difference Code Generation, Step 1 of 2: Read from main memory and compute finite difference stencils:
*/
/*
* Original SymPy expressions:
* "[const double uu_dD0 = invdx0*(-2*uu_i0m1_i1_i2/3 + uu_i0m2_i1_i2/12 + 2*uu_i0p1_i1_i2/3 - uu_i0p2_i1_i2/12),
* const double uu_dD1 = invdx1*(-2*uu_i0_i1m1_i2/3 + uu_i0_i1m2_i2/12 + 2*uu_i0_i1p1_i2/3 - uu_i0_i1p2_i2/12),
* const double uu_dDD00 = invdx0**2*(-5*uu/2 + 4*uu_i0m1_i1_i2/3 - uu_i0m2_i1_i2/12 + 4*uu_i0p1_i1_i2/3 - uu_i0p2_i1_i2/12),
* const double uu_dDD11 = invdx1**2*(-5*uu/2 + 4*uu_i0_i1m1_i2/3 - uu_i0_i1m2_i2/12 + 4*uu_i0_i1p1_i2/3 - uu_i0_i1p2_i2/12),
* const double uu_dDD22 = invdx2**2*(-5*uu/2 + 4*uu_i0_i1_i2m1/3 - uu_i0_i1_i2m2/12 + 4*uu_i0_i1_i2p1/3 - uu_i0_i1_i2p2/12)]"
*/
const double uu_i0_i1_i2m2 = in_gfs[IDX4(UUGF, i0,i1,i2-2)];
const double uu_i0_i1_i2m1 = in_gfs[IDX4(UUGF, i0,i1,i2-1)];
const double uu_i0_i1m2_i2 = in_gfs[IDX4(UUGF, i0,i1-2,i2)];
const double uu_i0_i1m1_i2 = in_gfs[IDX4(UUGF, i0,i1-1,i2)];
const double uu_i0m2_i1_i2 = in_gfs[IDX4(UUGF, i0-2,i1,i2)];
const double uu_i0m1_i1_i2 = in_gfs[IDX4(UUGF, i0-1,i1,i2)];
const double uu = in_gfs[IDX4(UUGF, i0,i1,i2)];
const double uu_i0p1_i1_i2 = in_gfs[IDX4(UUGF, i0+1,i1,i2)];
const double uu_i0p2_i1_i2 = in_gfs[IDX4(UUGF, i0+2,i1,i2)];
const double uu_i0_i1p1_i2 = in_gfs[IDX4(UUGF, i0,i1+1,i2)];
const double uu_i0_i1p2_i2 = in_gfs[IDX4(UUGF, i0,i1+2,i2)];
const double uu_i0_i1_i2p1 = in_gfs[IDX4(UUGF, i0,i1,i2+1)];
const double uu_i0_i1_i2p2 = in_gfs[IDX4(UUGF, i0,i1,i2+2)];
const double vv = in_gfs[IDX4(VVGF, i0,i1,i2)];
const double tmpFD0 = (1.0/12.0)*uu_i0m2_i1_i2;
const double tmpFD1 = -1.0/12.0*uu_i0p2_i1_i2;
const double tmpFD2 = (1.0/12.0)*uu_i0_i1m2_i2;
const double tmpFD3 = -1.0/12.0*uu_i0_i1p2_i2;
const double tmpFD4 = -5.0/2.0*uu;
const double uu_dD0 = invdx0*(tmpFD0 + tmpFD1 - 2.0/3.0*uu_i0m1_i1_i2 + (2.0/3.0)*uu_i0p1_i1_i2);
const double uu_dD1 = invdx1*(tmpFD2 + tmpFD3 - 2.0/3.0*uu_i0_i1m1_i2 + (2.0/3.0)*uu_i0_i1p1_i2);
const double uu_dDD00 = ((invdx0)*(invdx0))*(-tmpFD0 + tmpFD1 + tmpFD4 + (4.0/3.0)*uu_i0m1_i1_i2 + (4.0/3.0)*uu_i0p1_i1_i2);
const double uu_dDD11 = ((invdx1)*(invdx1))*(-tmpFD2 + tmpFD3 + tmpFD4 + (4.0/3.0)*uu_i0_i1m1_i2 + (4.0/3.0)*uu_i0_i1p1_i2);
const double uu_dDD22 = ((invdx2)*(invdx2))*(tmpFD4 + (4.0/3.0)*uu_i0_i1_i2m1 - 1.0/12.0*uu_i0_i1_i2m2 + (4.0/3.0)*uu_i0_i1_i2p1 - 1.0/12.0*uu_i0_i1_i2p2);
/*
* NRPy+ Finite Difference Code Generation, Step 2 of 2: Evaluate SymPy expressions and write to main memory:
*/
/*
* Original SymPy expressions:
* "[rhs_gfs[IDX4(UUGF, i0, i1, i2)] = vv,
* rhs_gfs[IDX4(VVGF, i0, i1, i2)] = wavespeed**2*(2*uu_dD0/xx0 + uu_dD1*sin(2*xx1)/(2*xx0**2*sin(xx1)**2) + uu_dDD00 + uu_dDD11/xx0**2 + uu_dDD22/(xx0**2*sin(xx1)**2))]"
*/
const double tmp0 = (1.0/((xx0)*(xx0)));
const double tmp1 = tmp0/((sin(xx1))*(sin(xx1)));
rhs_gfs[IDX4(UUGF, i0, i1, i2)] = vv;
rhs_gfs[IDX4(VVGF, i0, i1, i2)] = ((wavespeed)*(wavespeed))*(tmp0*uu_dDD11 + (1.0/2.0)*tmp1*uu_dD1*sin(2*xx1) + tmp1*uu_dDD22 + 2*uu_dD0/xx0 + uu_dDD00);
}
| BSD-2-Clause | Tutorial-ScalarWaveCurvilinear.ipynb | Steve-Hawk/nrpytutorial |
Step 3: Code Validation against `ScalarWaveCurvilinear.ScalarWaveCurvilinear_RHSs` NRPy+ Module \[Back to [top](toc)\]$$\label{code_validation}$$Here, as a code validation check, we verify agreement in the SymPy expressions for the RHSs of the Curvilinear Scalar Wave equation (i.e., uu_rhs and vv_rhs) between1. this tutorial and 2. the NRPy+ [ScalarWaveCurvilinear.ScalarWaveCurvilinear_RHSs](../edit/ScalarWaveCurvilinear/ScalarWaveCurvilinear_RHSs.py) module.By default, we analyze the RHSs in Spherical coordinates, though other coordinate systems may be chosen. | # Step 7: We already have SymPy expressions for uu_rhs and vv_rhs in
# terms of other SymPy variables. Even if we reset the list
# of NRPy+ gridfunctions, these *SymPy* expressions for
# uu_rhs and vv_rhs *will remain unaffected*.
#
# Here, we will use the above-defined uu_rhs and vv_rhs to
# validate against the same expressions in the
# ScalarWaveCurvilinear/ScalarWaveCurvilinear module,
# to ensure consistency between the tutorial and the
# module itself.
#
# Reset the list of gridfunctions, as registering a gridfunction
# twice will spawn an error.
gri.glb_gridfcs_list = []
# Step 8: Call the ScalarWaveCurvilinear_RHSs() function from within the
# ScalarWaveCurvilinear/ScalarWaveCurvilinear_RHSs.py module,
# which should do exactly the same as in Steps 1-6 above.
import ScalarWaveCurvilinear.ScalarWaveCurvilinear_RHSs as swcrhs
swcrhs.ScalarWaveCurvilinear_RHSs()
# Step 9: Consistency check between the tutorial notebook above
# and the ScalarWaveCurvilinear_RHSs() function from within the
# ScalarWaveCurvilinear/ScalarWaveCurvilinear_RHSs.py module.
print("Consistency check between ScalarWaveCurvilinear tutorial and NRPy+ module:")
print("uu_rhs - swcrhs.uu_rhs: "+str(sp.simplify(uu_rhs - swcrhs.uu_rhs))+"\t\t (should be zero)")
print("vv_rhs - swcrhs.vv_rhs: "+str(sp.simplify(vv_rhs - swcrhs.vv_rhs))+"\t\t (should be zero)") | Consistency check between ScalarWaveCurvilinear tutorial and NRPy+ module:
uu_rhs - swcrhs.uu_rhs: 0 (should be zero)
vv_rhs - swcrhs.vv_rhs: 0 (should be zero)
| BSD-2-Clause | Tutorial-ScalarWaveCurvilinear.ipynb | Steve-Hawk/nrpytutorial |
Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename[Tutorial-ScalarWaveCurvilinear.pdf](Tutorial-ScalarWaveCurvilinear.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.) | !jupyter nbconvert --to latex --template latex_nrpy_style.tplx --log-level='WARN' Tutorial-ScalarWaveCurvilinear.ipynb
!pdflatex -interaction=batchmode Tutorial-ScalarWaveCurvilinear.tex
!pdflatex -interaction=batchmode Tutorial-ScalarWaveCurvilinear.tex
!pdflatex -interaction=batchmode Tutorial-ScalarWaveCurvilinear.tex
!rm -f Tut*.out Tut*.aux Tut*.log | [pandoc warning] Duplicate link reference `[comment]' "source" (line 23, column 1)
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
| BSD-2-Clause | Tutorial-ScalarWaveCurvilinear.ipynb | Steve-Hawk/nrpytutorial |
Find the top rooms ignited and the top materials in those rooms that were first ignited | import psycopg2
import pandas as pd
from IPython.display import display
conn = psycopg2.connect(service='nfirs')
pd.options.display.max_rows = 1000
df = pd.read_sql_query("select * from codelookup where fieldid = 'PROP_USE' and length(code_value) = 3 order by code_value", conn)['code_value']
codes = list(df.values) | _____no_output_____ | MIT | sources/nfirs/scripts/popular-room-ignitions.ipynb | tbuffington7/data |
By property use type (batch by property type) | # Create a CSV for each property use type
q = """SELECT x.prop_use,
area_orig,
first_ign,
x.civ_inj,
x.civ_death,
x.flame_sprd,
x.item_sprd,
x.cnt
FROM
( SELECT *,
row_number() over (partition BY area_orig
ORDER BY area_orig, w.cnt DESC, first_ign, w.flame_sprd,w.item_sprd, w.civ_death, w.civ_inj DESC) row_num
FROM
(SELECT distinct bf.area_orig,
bf.first_ign,
bf.prop_use,
bf.flame_sprd,
bf.item_sprd,
COALESCE(bf.oth_death, 0) as civ_death,
COALESCE(bf.oth_inj,0) as civ_inj,
count(*) OVER ( PARTITION BY bf.area_orig, bf.first_ign, bf.flame_sprd, bf.item_sprd, COALESCE(bf.oth_death, 0)+COALESCE(bf.oth_inj,0) ) AS cnt,
row_number() OVER ( PARTITION BY bf.area_orig, bf.first_ign, bf.flame_sprd, bf.item_sprd, COALESCE(bf.oth_death, 0)+COALESCE(bf.oth_inj,0) ) AS row_numbers
FROM joint_buildingfires bf
WHERE bf.area_orig IN
( SELECT area_orig
FROM joint_buildingfires
WHERE prop_use = %(use)s
AND area_orig != 'UU'
AND extract(year from inc_date) > 2011
GROUP BY area_orig
ORDER BY count(1) DESC LIMIT 8)
AND bf.prop_use = %(use)s
AND bf.first_ign != 'UU'
AND extract(year from inc_date) > 2011
ORDER BY area_orig,
first_ign ) w
WHERE w.row_numbers = 1) x
ORDER BY area_orig,
x.cnt DESC,
first_ign
"""
# for c in codes[1:2]:
# df = pd.read_sql_query(q, conn, params=dict(use=c))
# display(df)
for c in codes:
df = pd.read_sql_query(q, conn, params=dict(use=c))
df.to_csv('/tmp/{}.csv'.format(c))
# Testing/sanity checks
q = """SELECT bf.prop_use, bf.area_orig,
bf.first_ign,
bf.flame_sprd,
COALESCE(bf.oth_death, 0) + COALESCE(bf.oth_inj,0) as civ_inj_death,
count(*) OVER ( PARTITION BY bf.area_orig, bf.first_ign, bf.flame_sprd, COALESCE(bf.oth_death, 0)+COALESCE(bf.oth_inj,0) ) AS cnt,
row_number() OVER ( PARTITION BY bf.area_orig, bf.first_ign, bf.flame_sprd, COALESCE(bf.oth_death, 0)+COALESCE(bf.oth_inj,0) ) AS row_numbers
FROM buildingfires bf
WHERE bf.area_orig IN
( SELECT area_orig
FROM buildingfires
WHERE prop_use = %(use)s
AND area_orig != 'UU'
GROUP BY area_orig
ORDER BY count(1) DESC LIMIT 8)
AND bf.prop_use = %(use)s
AND bf.first_ign != 'UU'
ORDER BY area_orig,
first_ign,
cnt desc"""
pd.read_sql_query(q, conn, params=dict(use='100'))
q = """
select count(1)
from joint_buildingfires
where prop_use='100'
and area_orig = '00'
and first_ign = '00'
and COALESCE(oth_death, 0) + COALESCE(oth_inj, 0) = 0
and flame_sprd = 'N'
"""
pd.read_sql_query(q, conn)
# Sanity checks
q = """
select area_orig, first_ign, count(1)
from joint_buildingfires
where area_orig != 'UU'
and first_ign != 'UU'
group by area_orig, first_ign
order by count desc
"""
pd.read_sql_query(q, conn)
# More sanity checks, including civ death/inj + flame spread
q = """
select area_orig, first_ign, flame_sprd, COALESCE(oth_death, 0)+COALESCE(oth_inj,0) as civ_death_inj, count(1)
from joint_buildingfires
where area_orig != 'UU'
and first_ign != 'UU'
group by area_orig, first_ign, flame_sprd, civ_death_inj
order by count desc"""
pd.read_sql_query(q, conn)
# For grouped propety usage only 6 most popular ignition sources
q = """
--
SELECT area_orig,
first_ign,
x.cnt
FROM
( SELECT *,
row_number() over (partition BY area_orig
ORDER BY area_orig, w.cnt DESC, first_ign) row_num
FROM
(SELECT bf.area_orig,
bf.first_ign,
count(*) OVER ( PARTITION BY bf.area_orig, bf.first_ign ) AS cnt,
row_number() OVER ( PARTITION BY bf.area_orig, bf.first_ign ) AS row_numbers
FROM joint_buildingfires bf
WHERE bf.area_orig IN
( SELECT area_orig
FROM joint_buildingfires
WHERE prop_use in ('120', '121', '122', '123', '124', '129')
AND area_orig != 'UU'
GROUP BY area_orig
ORDER BY count(1) DESC LIMIT 8)
AND bf.prop_use in ('120', '121', '122', '123', '124', '129')
AND bf.first_ign != 'UU'
ORDER BY area_orig,
first_ign ) w
WHERE w.row_numbers = 1) x
WHERE x.row_num < 7
ORDER BY area_orig,
x.cnt DESC,
first_ign
"""
df = pd.read_sql_query(q, conn)
display(df)
# Pull all from buildingfires to CSV
q = """
select prop_use, area_orig, first_ign, oth_inj, oth_death, flame_sprd
from joint_buildingfires"""
df = pd.read_sql_query(q, conn)
df.to_csv('/tmp/buildingfires.csv') | _____no_output_____ | MIT | sources/nfirs/scripts/popular-room-ignitions.ipynb | tbuffington7/data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.