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
![image.png](data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCABNAI0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD7LrzPT/i1p958WpvAy2O2NZHgjvjPw8yrkptxxyGXOeorrfiDr0XhnwbqmuyEFrW3Zogf4pDwg/FiK+WW8OajpHw10T4lwM51E6w0zuTyU3fu2P1dG/77r2crwNLEQlKr192P+J6/16niZpj6uHnGNLp70v8ACnY+gP2hfiafhR4AXxUNGGr5vYrX7P8AafJ++GO7dtbpt6Y710Hwx8baL8QPBVh4q0Gbfa3aZaNj88Eg+/G47Mp4/IjgivC/25dVt9b/AGY9P1i0IMF5qVnOnPQMkhx+HT8K84+Gt/q/7OmseF9du5bm7+HXjfTrSa6Yjd9humiUs3Hdck/7UeRyUrx3FxbT3R7UZKSTWzPozQvjRp+q/HrVPhPHol3HeafE8j3rTKY3Coj8L1/jH5VN+0Z8XLP4Q+DrbWpdN/tW7vLsW1tZ/aPJ3/KWdi21sBQB26kV4d8Npobj/goV4puYJUlhlsZHjkRgyupt4CGBHUEHOaZ8W7WD42/te2Pw8lkaTQPDVhMLwoxwJSm52/B2hT/gJpDPqD4aeLbLxx4C0bxZp6eXBqdqk3lltxifo6E9yrAr+Fcd8IvjNp/xD8beKfDFpol3Yy+HpWilmlmVlmIlePIA5HKZ5ryv9gjxDeadbeKvhRrRKaj4fv3lijbqEL7JVHsJFB/7aVmfsV/8l7+Lv/X6/wD6VzUAeufDf456d4p+Kmr/AA41Pw/e+H9d00SYS5nR1nMZG4IV/wBkhx6rk1j+Pf2kNM0D4jap4J0TwnqniW90q2ee9ks5kVY/LQvIvIJJUYB/2jt61xX7bXhTUPC+r6J8cvCMyWesaTcRW962B+8BJWJyP4sZMbDurDsK3P2Gvh22j+Crj4i60/2nX/FJM4mc7nS2LEjJ/vO2Xb/gPpQBiN+2ZpiXq2T/AA38RrdPysBlQSN9F25PQ16T4d+OVpq0XhJpPC+p2UniMkJHPIoa3xcND8wIyc7d3HY15N49z/w8U8Jcn/jyj7/9O9xXffG8Z+PfgEHPL24/8ma78uw8K9ZxntZv7k2efmVedCipw3ul97Ol+O/x48I/CdYbTUkuNT1q4TzINNtSN+zON7seEUkEDqT2B5rkPhB+0u/jX4g6d4O1f4fap4duNUEjWc0s+9HCIznIZEOMKeRnnFec/s8WFr4+/bA8f+JvE0aXlzo885sYZhuETLP5MbYP9xFwPQkHrX2HdWFndTW01xbQzS2snmwO6BmifBBZSeVOCRx2JrgPQPn/AMdftQ22m+Pb3wn4K8Cax40n01mW+msnIVChw+wKjlgp4LHAyOM9a9b+EHjyy+I/ge18U2Gm6hp0M7vH5N7HtcMh2tgjhlzkbh6HoQRXyVc6b8Vf2Z/iN4k8T6X4dTxF4S1SUyT3IUsvlb2dd7L80LruIJIKnPfjH1N8C/iXoHxR8FLr+hQyWnlymC7s5cb7eYAMVyOGBDAhh1z2OQADvaKKKAPF/wBpaHxDrseieE9D0u+uI7m4E11PHAzRJztQMwGAASzHPoKgv/2edCXSp0tNb1p7pYW8lZJU8oyAHbkbemcd69b8Wa7Y+GfDOpeIdT837FptrJdT+Um5tiAk4Hc4HSvD/wDhsH4Qf89Nf/8ABd/9lXpU80r0aUKVF8qV/m/M8yplVCtVlUqrmb/BeR5n8T9H8a6v+y5N4RHhXXZr/TtegeCBLCVnaBlkJ2gDJCtuyR03CvoTRPAmneL/ANnXQvBfivT5Ujl0G0hmjkTbNbSrCuGAPKujD9CDxmuH/wCGwfhB/wA9Nf8A/Bd/9nR/w2D8IP8Anpr/AP4Lv/s65MTX9vVlVta+tjrwtD6vRjSve3U8V+BXgrxj8JP2gtefVtF1PUxo+h3rWs9vaySJfKqKYVjIByWAAC9RyO1aXwJ/ZsvfiFpus+MfiVd+J/D+rX2oyFIYlFvLID8zyOJEJwXYgdPu19g+BvEll4v8K2HiTTre9gsr+LzbdbuLypGQk7W25OARyPUEGsP4mfFfwH8OrcP4r8QW1nO67orRMy3Eg9RGuWx7nA96wOg+aLD4Xa98Df2m/C+p+E7HxH4g8NahGIb+7+ztO0SysY5RK0agAKdkgyOg9qwPh5rXxM+E/wAXPH2r6f8ACTxF4gh1jUZ1R1tZ40CrcSMHVhGwYENXo+qftseB4rpo9O8K+IbuJTgSSNFFu9wNzfrW/wCC/wBr74Wa3cpa6sNW8PSM20SXsAeHP+/GWx9SAKAD9omTxP8AED9kz7XH4T1O21vUHtJpNIjgklnhInGVK7Q3AGTwK9I/Zzsb3Tfgb4PsNRtJ7O7g0uJJoJ4ykkbDOQynkH2Ndpo+p6frGmw6lpV9bX1lOu+G4t5RJHIPUMODVugD5a8beGvEU/7efhjxDBoOqS6PDaRrLfpaubdD5E4wZMbRyQOvcV23xi0fV7741+Cb+z0u9uLW3aHz54oGZIsXGTuYDA455r2+vLfih8fvhl8PbmSx1nXRdanGcPYaennzIfRsEKh9mYGunCYl4apzpX0a+9WOXF4VYmnyN21T+53PGvjF8P8A4h/C7403Pxi+FmmPrNlqJZtV02KMyMC+DKCi/MyMQHDLkq3bGM9P8Lfjl8R/iH8RNH0aL4Y3vh7RQZG1W9uEllAxE+xQzIgQF9vqx6cVhy/tteDhORF4N8QPDn77Swq2P93J/nXe/Dv9qP4UeLrqKxk1S40C9lICRatGIkZs4wJQSn5kVzHUeZ678aPjT4Th8R+D/G3wzudc1O8edNNvbGFzaGOTKqoCo3mxjPHIbHDc816B+xF8N9d+H/wyu5PEts9lqWsXgufsj/fgiVAqBx2Y/MSOwIB5yK94jdJUDowZWAKlTkEHvT6ACiiigDO8T6Jp/iPw7qGg6rG0thqFu9tcIrlC0bghgCORweorxv8A4ZM+Cv8A0L99/wCDSf8A+Kr3WigD548T/sz/AAE8OeHr/XtX0e9t7Cwge4uJDqk/yooJP8XJ7AdyQK+TvgL8OrT4sfG37Dp+mSWHheCdr27h8xnMForfLCXPJZuEz15Y9q9s/wCCgfxSMstr8K9FnJOUutYMZySesMBx+Dkf7nvXtP7JXwvX4Z/C2CO/gEevattvNTLDDRkj5Ifoinn/AGi1AGH+1f8AGyD4TeGrbw74ZW3/AOElvoMWqBQUsIB8olK9M8YRenBJ4GD4P8CP2cPEXxXc+PPiNrGoWmm6g3noWbfe6gCfvlnzsQ9iQSR0AGDXN+HbZvjz+13I+ps02l3OoyTSqScCxt87Y/YMqqv1cmvsXxn8YNF8F+NIvCtzo84tIIo/PuYjgQKy5GyMDLALjp9ADitqGHqV5ONNXaV/kjGviKdCKlUdk3b5kWi/s2/BjS7NbdPBNndEDDS3c0szt7ks3H4AVy3xD/ZJ+F+v2UreH7a58MagV/dy2srSw7u26Jycj/dKmtL4gWvjH4oabKnh+8sbDSbVopEia4Ia5ZwSN8qEqNqFG2DIBcZYkYHf/Dx9V0SztfCfiO7W71C3tVe3uxuxdRjAYZPJeMkA+qlG7kBypQVFVFPVvbqvMmNabrSpuGiW/R+R8PeHNf8AiR+y38Tzouro93otwwkmtUcm2voc482En7kg9eCCMMCK+/8Awj4g0vxT4asPEOi3K3OnX8CzwSDup7EdiDkEdiCK8q/bF8C2fjb4I6tdJCj6locbajZSryRsGZUz6Mgbj1C+leG/sY/FSXw38GfiBYXcnmDw5aNq2no/I+dWBT6eYEP1c1gdBv8A7ZHx/wBS07VZvhn4BupYr7iLVL+3JMqM3/LvERyG5G5hyM7Rg5qh8Dv2P473T4dc+KV3dJNOBIukW0mxkzz++k5O71Vends8Vx/7CHg8eNfi/qnjXXs3v9igXW6UZ8y9mZtrn1IxI312ntX35QB5Xb/s7fBiC1FsngHTGQDG52ld/wDvotn9a8v+LX7HfhHU9PnvPh/dT6DqagtHazytNaSn+6S2XT65Ye1fUlFAHwT+zr8ZPFHwf8cH4afEn7TFosdwLZkujl9Lc9HU94TkEgcYIZe4P3qjK6B0YMpGQQcgivkj/gop4CtZ/DWlfEK0hRL20nWwvWUYMkL7jGW/3WBH0f2FeofsW+L7jxd8BdKe9mM15pMj6ZM7NksIsGMn/tmyD8KAPaKKKKACuP8AjL470/4c/DvVPFeobX+yx7baAnBnnbiOMfU9fQAntXYV8Cftj+PL/wCJ/wAXrH4b+FN15Z6Zdi0ijiORc37nY7fRfuA9vnPQ0AM/Y+8Cah8VPjFf/EbxXuvLLTLv7bPJIPlub5zuRPov3yO2EHQ197ajG8un3EURw7xOq/UggVynwV8Baf8ADf4c6Z4Usdjtbx77qcDH2i4bmST8TwPRQB2rsz0oA/PH9gaRLL9oh7a7+WeXS7uBFbr5gZGI+uEavqP4mfEbRNB+KVvpdz4ITWL23hULdLGrXJMikqkK7SW6469SQPf5U+Omkav8Df2nk8V6TARaTXx1fTichJUdj50BPbBZ0I67WU96+5/h94g8JfEPw/pnjXREtLwSR4jleJTPav8AxRMeqMpOCM+44INdGGq06Um6kbqzW9jmxVKpVilTlZ3T2ueK2ngHVPEngKSztdestLa3uUuJbRpz9luFkDFZncEjzASY+OP3RB3EAjubvwbq91pGk+DLfxhqkl/Y2yzXF4oj2Wi7GRQp2eZmTLIAWzsDk/w5vfGH4TW3jCIXWj3EWmam0gNwW3eTcqM8uinG8E5DYzyQfbr/AIe+GYfCfhe10lZ2up40BuLl87pnwBnkk4AAUDsqgdq3lXthIRU9U27W2879fQ540b4ucnDRxSvffyt09TzTw94M1D4b/Bzxy3iLVbe5il065l8qJmMcarA4J+bHLZGeOw618W/BCxu7r4ffFiW3VikXhdN+P+vuF/8A0GN/1r6R/bz+L1jp3hiX4ZaJdLLquobW1Qxtn7Nbg7hGx7O5A47KDn7wrT/Yt+FCWPwN1e48RWpSTxnEwkjZcMLIoyR/i293Hsy1zYivPEVHUnuzrw9CGHpqnDZHN/8ABNO7tzpPjWxDKLhbi0lI7lCsgH6g/nX2BX5u/CHxHqX7O/7Q15pniSOUWCSNp+phVPzwMQY7hB3AwrjuVJHU1+jGk6hZarp1vqOnXUN3Z3MaywzwuGSRCMhgR1BrE2LVFFITigDwr9u+5gg/Zx1iKYgPc3dpFDnu4mV+P+Ao1cr/AME4baeP4R67cuCIZtccR577YYgT+teT/twfFWHx74vsPAXhSX+0NP0q4PmyW/zi6vW+QKmPvBASoI6szY4AJ+t/2dvArfDv4Q6J4ZnC/bo4jPfEHObiQ7nGe+0kLn0WgD0GiiigDyD9rH4or8M/hdc3FlOE17VN1ppig/MjEfPN9EXn/eKjvX5//Bz4iXPw38ajxZbaLYaxqEcTpAb4uRCz8NINpBLYyMn+8a/Vi5s7W5Km4t4Ziv3TJGGx9M1F/ZWm/wDQPtP+/C/4UAfDn/DbXjv/AKFLw3+c/wD8XR/w2147/wChS8N/nP8A/F19x/2Vpv8A0D7T/vwv+FH9lab/ANA+0/78L/hQB4b4bsdP/ad/Z7tb3xjp9tp17NcT/ZJ7IEm0kjcoHXeSSCB8yk4I9OCPmS+8NfHD9mzxLPqWkm5OlO3zXltEZ7C6QdPNT+Bsf3sMOcHvX6K28EVvH5cMaRoOiooUfkKe6hlKsAQRggjrQB8UaH+3BqkVqE1rwDZ3VwF5ktNRaFSf91kfH51znjP9rX4m+MlOieC9Eh0OS5yi/Yle7vGz2RsYB9wufQivs/VPhl8O9UnNxqPgbw1dzE5Mkulwlj9Tt5rW0Dwz4d0BCmhaFpelKRgiztI4c/8AfIFAHx3+zv8Asta3qutxeMPizFLFb+b9oXSrh99xdyZzuuDztUnkqTubvgdftiKNIkWONVVFACqBgADsKcKKAPF/2mfgNpXxZ0qO9tJotN8T2cZW1vWX5JU5PlS45K56MOVJPUEg/JmgeL/jl+zhqTaNfWNxFpPmEizv4zNYyknlopFOFJ6/Kw68jNfo3UN5a295bvb3UEU8LjDRyIGVh7g8GgD40tv247lbIrcfDqF7oDG6PVyqE/Qxk/rXBeMvjz8ZfjNK/hbwtpk1naXI2SWWixO8sintJMeQvrjaMda+3J/hV8NJ7n7TN8P/AAs82c7zpMOc/wDfNdNpGk6ZpFr9l0rTrOwt/wDnlbQLEn5KAKAPm39lX9mdfBF5B4x8ceRc+IYxus7KMh4rEn+Mt0eX0xwvYk4I+nqKKACiiigD/9k=)--- 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