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 |
|---|---|---|---|---|---|
Create the ensemble of neural networks. All networks use the same TensorFlow graph that was defined above. For each neural network the TensorFlow weights and variables are initialized to random values and then optimized. The variables are then saved to disk so they can be reloaded later.You may want to skip this comput... | if True:
# For each of the neural networks.
for i in range(num_networks):
print("Neural network: {0}".format(i))
# Create a random training-set. Ignore the validation-set.
x_train, y_train, _, _ = random_training_set()
# Initialize the variables of the TensorFlow graph.
... | Neural network: 0
Optimization Iteration: 1, Training Batch Accuracy: 6.2%
Optimization Iteration: 101, Training Batch Accuracy: 87.5%
Optimization Iteration: 201, Training Batch Accuracy: 92.2%
Optimization Iteration: 301, Training Batch Accuracy: 92.2%
Optimization Iteration: 401, Training Batch... | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-functions for calculating and predicting classificationsThis function calculates the predicted labels of images, that is, for each image it calculates a vector of length 10 indicating which of the 10 classes the image is.The calculation is done in batches because it might use too much RAM otherwise. If your com... | # Split the data-set in batches of this size to limit RAM usage.
batch_size = 256
def predict_labels(images):
# Number of images.
num_images = len(images)
# Allocate an array for the predicted labels which
# will be calculated in batches and filled into this array.
pred_labels = np.zeros(shape=(nu... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Calculate a boolean array whether the predicted classes for the images are correct. | def correct_prediction(images, labels, cls_true):
# Calculate the predicted labels.
pred_labels = predict_labels(images=images)
# Calculate the predicted class-number for each image.
cls_pred = np.argmax(pred_labels, axis=1)
# Create a boolean array whether each image is correctly classified.
... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Calculate a boolean array whether the images in the test-set are classified correctly. | def test_correct():
return correct_prediction(images = data.test.images,
labels = data.test.labels,
cls_true = data.test.cls) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Calculate a boolean array whether the images in the validation-set are classified correctly. | def validation_correct():
return correct_prediction(images = data.validation.images,
labels = data.validation.labels,
cls_true = data.validation.cls) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-functions for calculating the classification accuracyThis function calculates the classification accuracy given a boolean array whether each image was correctly classified. E.g. `classification_accuracy([True, True, False, False, False]) = 2/5 = 0.4` | def classification_accuracy(correct):
# When averaging a boolean array, False means 0 and True means 1.
# So we are calculating: number of True / len(correct) which is
# the same as the classification accuracy.
return correct.mean() | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Calculate the classification accuracy on the test-set. | def test_accuracy():
# Get the array of booleans whether the classifications are correct
# for the test-set.
correct = test_correct()
# Calculate the classification accuracy and return it.
return classification_accuracy(correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Calculate the classification accuracy on the original validation-set. | def validation_accuracy():
# Get the array of booleans whether the classifications are correct
# for the validation-set.
correct = validation_correct()
# Calculate the classification accuracy and return it.
return classification_accuracy(correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Results and analysis Function for calculating the predicted labels for all the neural networks in the ensemble. The labels are combined further below. | def ensemble_predictions():
# Empty list of predicted labels for each of the neural networks.
pred_labels = []
# Classification accuracy on the test-set for each network.
test_accuracies = []
# Classification accuracy on the validation-set for each network.
val_accuracies = []
# For each ... | Network: 0, Accuracy on Validation-Set: 0.9948, Test-Set: 0.9893
Network: 1, Accuracy on Validation-Set: 0.9936, Test-Set: 0.9880
Network: 2, Accuracy on Validation-Set: 0.9958, Test-Set: 0.9893
Network: 3, Accuracy on Validation-Set: 0.9938, Test-Set: 0.9889
Network: 4, Accuracy on Validation-Set: 0.9938, Test-Set: 0.... | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Summarize the classification accuracies on the test-set for the neural networks in the ensemble. | print("Mean test-set accuracy: {0:.4f}".format(np.mean(test_accuracies)))
print("Min test-set accuracy: {0:.4f}".format(np.min(test_accuracies)))
print("Max test-set accuracy: {0:.4f}".format(np.max(test_accuracies))) | Mean test-set accuracy: 0.9889
Min test-set accuracy: 0.9880
Max test-set accuracy: 0.9893
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The predicted labels of the ensemble is a 3-dim array, the first dim is the network-number, the second dim is the image-number, the third dim is the classification vector. | pred_labels.shape | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Ensemble predictions There are different ways to calculate the predicted labels for the ensemble. One way is to calculate the predicted class-number for each neural network, and then select the class-number with most votes. But this requires a large number of neural networks relative to the number of classes.The metho... | ensemble_pred_labels = np.mean(pred_labels, axis=0)
ensemble_pred_labels.shape | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The ensemble's predicted class number is then the index of the highest number in the label, which is calculated using argmax as usual. | ensemble_cls_pred = np.argmax(ensemble_pred_labels, axis=1)
ensemble_cls_pred.shape | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Boolean array whether each of the images in the test-set was correctly classified by the ensemble of neural networks. | ensemble_correct = (ensemble_cls_pred == data.test.cls) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Negate the boolean array so we can use it to lookup incorrectly classified images. | ensemble_incorrect = np.logical_not(ensemble_correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Best neural networkNow we find the single neural network that performed best on the test-set.First list the classification accuracies on the test-set for all the neural networks in the ensemble. | test_accuracies | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The index of the neural network with the highest classification accuracy. | best_net = np.argmax(test_accuracies)
best_net | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The best neural network's classification accuracy on the test-set. | test_accuracies[best_net] | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Predicted labels of the best neural network. | best_net_pred_labels = pred_labels[best_net, :, :] | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The predicted class-number. | best_net_cls_pred = np.argmax(best_net_pred_labels, axis=1) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Boolean array whether the best neural network classified each image in the test-set correctly. | best_net_correct = (best_net_cls_pred == data.test.cls) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Boolean array whether each image is incorrectly classified. | best_net_incorrect = np.logical_not(best_net_correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Comparison of ensemble vs. the best single network The number of images in the test-set that were correctly classified by the ensemble. | np.sum(ensemble_correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The number of images in the test-set that were correctly classified by the best neural network. | np.sum(best_net_correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Boolean array whether each image in the test-set was correctly classified by the ensemble and incorrectly classified by the best neural network. | ensemble_better = np.logical_and(best_net_incorrect,
ensemble_correct) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Number of images in the test-set where the ensemble was better than the best single network: | ensemble_better.sum() | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Boolean array whether each image in the test-set was correctly classified by the best single network and incorrectly classified by the ensemble. | best_net_better = np.logical_and(best_net_correct,
ensemble_incorrect) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Number of images in the test-set where the best single network was better than the ensemble. | best_net_better.sum() | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-functions for plotting and printing comparisons Function for plotting images from the test-set and their true and predicted class-numbers. | def plot_images_comparison(idx):
plot_images(images=data.test.images[idx, :],
cls_true=data.test.cls[idx],
ensemble_cls_pred=ensemble_cls_pred[idx],
best_cls_pred=best_net_cls_pred[idx]) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Function for printing the predicted labels. | def print_labels(labels, idx, num=1):
# Select the relevant labels based on idx.
labels = labels[idx, :]
# Select the first num labels.
labels = labels[0:num, :]
# Round numbers to 2 decimal points so they are easier to read.
labels_rounded = np.round(labels, 2)
# Print the rounded la... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Function for printing the predicted labels for the ensemble of neural networks. | def print_labels_ensemble(idx, **kwargs):
print_labels(labels=ensemble_pred_labels, idx=idx, **kwargs) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Function for printing the predicted labels for the best single network. | def print_labels_best_net(idx, **kwargs):
print_labels(labels=best_net_pred_labels, idx=idx, **kwargs) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Function for printing the predicted labels of all the neural networks in the ensemble. This only prints the labels for the first image. | def print_labels_all_nets(idx):
for i in range(num_networks):
print_labels(labels=pred_labels[i, :, :], idx=idx, num=1) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Examples: Ensemble is better than the best networkPlot examples of images that were correctly classified by the ensemble and incorrectly classified by the best single network. | plot_images_comparison(idx=ensemble_better) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The ensemble's predicted labels for the first of these images (top left image): | print_labels_ensemble(idx=ensemble_better, num=1) | [[ 0. 0. 0. 0.76 0. 0. 0. 0. 0.23 0. ]]
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The best network's predicted labels for the first of these images: | print_labels_best_net(idx=ensemble_better, num=1) | [[ 0. 0. 0. 0.21 0. 0. 0. 0. 0.79 0. ]]
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The predicted labels of all the networks in the ensemble, for the first of these images: | print_labels_all_nets(idx=ensemble_better) | [[ 0. 0. 0. 0.21 0. 0. 0. 0. 0.79 0. ]]
[[ 0. 0. 0. 0.96 0. 0.01 0. 0. 0.03 0. ]]
[[ 0. 0. 0. 0.99 0. 0. 0. 0. 0.01 0. ]]
[[ 0. 0. 0. 0.88 0. 0. 0. 0. 0.12 0. ]]
[[ 0. 0. 0. 0.76 0. 0.01 0. 0. 0.22 0. ]]
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Examples: Best network is better than ensembleNow plot examples of images that were incorrectly classified by the ensemble but correctly classified by the best single network. | plot_images_comparison(idx=best_net_better) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The ensemble's predicted labels for the first of these images (top left image): | print_labels_ensemble(idx=best_net_better, num=1) | [[ 0.5 0. 0. 0. 0. 0.05 0.45 0. 0. 0. ]]
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The best single network's predicted labels for the first of these images: | print_labels_best_net(idx=best_net_better, num=1) | [[ 0.3 0. 0. 0. 0. 0.15 0.56 0. 0. 0. ]]
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The predicted labels of all the networks in the ensemble, for the first of these images: | print_labels_all_nets(idx=best_net_better) | [[ 0.3 0. 0. 0. 0. 0.15 0.56 0. 0. 0. ]]
[[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[ 0.19 0. 0. 0. 0. 0. 0.81 0. 0. 0. ]]
[[ 0.15 0. 0. 0. 0. 0.12 0.72 0. 0. 0. ]]
[[ 0.85 0. 0. 0. 0. 0. 0.14 0. 0. 0. ]]
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Close TensorFlow Session We are now done using TensorFlow, so we close the session to release its resources. | # This has been commented out in case you want to modify and experiment
# with the Notebook without having to restart it.
# session.close() | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
_Speech Processing Labs 2020: Signals: Module 1_ | ## Run this first!
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import cmath
from math import floor
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
plt.style.use('ggplot')
## some helper functions:
from dspMisc import * | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
4 The Discrete Fourier Transform Learning Outcomes* Understand the DFT equation: what input does it take and what outputs does it produce. Need to know* Topic Videos: Series Expansion, Fourier Analysis, Frequency Domain* Vector operations: dot product* [Digital Signals: Sampling sinusoids](./sp-m1-3-sampling-sinusoids... | ## plot complex numbers in the DFT[1] equation
N=16
## make an array of N steps: 0,...,N
nsteps = np.array(range(N))
tsteps = 2*np.pi*nsteps/N
Tmin = np.min(tsteps)
Tmax = np.max(tsteps)
## Corresponding complex numbers z[n] = e^{j 2 pi n/N}
zn_k1 = np.exp(-1j*2*np.pi*nsteps/N)
## Plot the phasor corresponding to D... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
What this animation shows is that for $k=1$, the $e^{-j\varphi}$ terms in the DFT represent $N$ evenly space samples around the unit circle aka one period of a sinusoid. So, The term $x[n] e^{-j2\pi n/N}$ represents multiplying the $n$th step around the unit circle with the $n$th input value. Exercise (optional)We saw... |
## Make the background and plot the k=1 phasor
X_k1, Y_k1, fig, phasor, iproj, rproj = plot_phasor_static(zn_k1, tsteps, plot_real=True, plot_imag=True)
## Now, let's say our input x looks like this square wave:
xn = np.array([-1]*8 + [1]*8)
## Exercise: Try some other inputs later
#xn = np.array([-1, -1,-1,-1, 1, ... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
In the plot above, you can see that: * The grey dots show our samples from the $k=1$ phasor (top left), and projected imaginary component, i.e. the sine in the DFT sum (top right), and the projected real component, i.e. the cosine (bottom left) * The blue dots show our input sequence (top right and bottom left)* the ye... | ## The dot product: sum all the elementwise multiplications
dft_1_real = np.sum(real_xn_zn)
dft_1_imag = np.sum(imag_xn_zn)
print("* projection and then two separate products: DFT[k] = %f + i%f" %(dft_1_real, dft_1_imag))
## check these are the same!
dft_1 = np.sum(xn*zn_k1)
print("* one dot product and then project... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
Exercise: Change the inputWhat happens when we change the input `xn` so that:* it has a different period* exactly matches the sine component of the k=1 phasor* is out of phase with the sine component of the k=1 phasor* has a different magnitude* something else ...There are some commented out options that you can try i... | ## Let's generate our DFT[1] phasor for an input of N=16 points:
N=16
## make an array of N steps: 0,...,N
nsteps = np.array(range(N))
tsteps = 2*np.pi*nsteps/N
## The k=1 phasor:
zn_k1 = np.exp(-1j*tsteps) | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
Now let's create an input that's the same as the sine component of the DFT[1] phasor, but shifted by $\pi/3$ radians. | ## Plot the DFT[1] phasor
X_k1, Y_k1, fig, phasor, iproj, rproj = plot_phasor_static(zn_k1, tsteps, plot_real=False, plot_imag=True)
## Now, for the input let's use a phase shifted version of the sine component of our phasor, zn (defined above)
# Remember that multiplying a complex number by e^{j theta} rotates it by ... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
In the plot above, you should see the input (in blue) is the same as the sine component of the $k=1$ phasor but *phase shifted*. By multiplying everything by $e^{j\pi/3}$ _delays_ the our $-sin(\theta)$ function by $\pi/3$ seconds (in this example we're assuming that it takes $\theta$ seconds to travel $\theta$ degrees... | ## Elementwise multiplication of the input and the k=1 phasor
xn_times_zn = xn * zn_k1
## Add it all up to get the dot product
dft_1 = np.sum(xn_times_zn)
print("DFT[1] = %f + i%f" %(dft_1.real, dft_1.imag))
print("in polar coordinates: magnitude=%f, phase=%f" %cmath.polar(dft_1))
## Plot the sequence of multiplica... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
The result of the DFT is 6.93 + j4, which in polar coordinates has a magnitude=8 and phase angle=0.52 * Non-zero magnitude means that the input has a frequency component that matches the frequency of the $k=1$ phasor* Non-zero phase means that the input is like the $k=1$ phasor in frequency, but starting from a differ... | ## Plot the input from above and the equivalent cos and sin function based on DFT phase output.
_, _, fig, phasor, iproj, rproj = plot_phasor_static(zn_k1, tsteps, plot_real=False, plot_imag=True)
#fig, phasor, iproj, rproj = create_phasor_iproj_bkg(Tmin, Tmax, ymax=1.5)
#phasor.scatter(zn_real_k1, zn_imag_k1)
## O... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
In the plot above, you should see:* the DFT[1] phasor in grey, i.e. $-\sin(t)$* Our phase shifted input in blue* The phase shift determined by DFT[1] applied as a cosine wave: $\cos(t + \pi/6)$ in red* Our phase shifted input generated directly using the `np.sin` function: $-\sin(t-\pi/3)$ in greenYou should see is tha... | ## Plot the phasor and sinusoid for different values of k
## Number of samples
N=16
## DFT output we're looking at: a sinusoid with k times the freq of the k=1 phasor
k=15
## indices of points in sample
nsteps = np.array(range(N))
## times of samples
tsteps = 2*np.pi*nsteps/N
## N sample values of the kth DFT phas... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
Notes 4.3 The full DFTNow that we've seen what happens when we calculate the individual DFT components, lets do the whole thing!We need1. **Input:** a sequence of $N$ samples1. generate $N$ phasors, with $N$ sampled points1. generate $N$ dot products between the input and the phasors1. **Output:** $N$ complex numbers... | ## 1) Input: -sin(t-pi/3) as above
N=16
nsteps = np.array(range(N))
theta_step = 2*np.pi/N
theta_steps = theta_step * nsteps
## set the phase shift
phase_in = np.pi/3
## set the input as -sin with phase shift
x = -np.sin(theta_steps-phase_in)
## Plot the input x
fig, tdom = plt.subplots(figsize=(16, 4))
tdom.scatte... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
You should see the input (16 points), `x`, plotted in magenta Generate phasorsLet's use some functions to generate all the DFT phasors in one go: | ## 2) Generate the phasors
# Given a sequence length N, return dictionary representing N DFT outputs
# the kth element of the return dictionary contains the complex numbers sampled around the unit circle after
# N steps, their real and imaginary parts, and the angles of those complex numbers (magnitude is always 1)
de... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
You should see in the plots above that phasors $k > N/2$ repeat the frequencies we see for $k < N/2$. For example, the $k=1$ phasor is equivalent in frequency to the $k=15$ phasor! Calculate dot products (i.e. input and phasor correlations) | ## 3) Get the dot products for each for each phasor and the input
def get_dft_outputs(x, phasors):
DFT = []
## Go through our list of N phasors
for k, phasor in phasors.items():
## Do the dot product between the input and each phasor sequence
DFT.append(np.sum(x * phasor['zs']... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
Get the output magnitudes and phasesNow we convert the results of the dot products we just calculated into polar form to get magnitudes and phases. We can then plot them! | ## convert to polar coordinates to get magnitude and phase
dft_polar = [cmath.polar(z) for z in dft]
mags = [m for m, _ in dft_polar]
phases = [ph if mag > 0.00001 else 0 for mag,ph in dft_polar]
## we need to put a condition into the phase calculation because phase is calculated by
## a ratio of the imaginary comp... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
How do we interpret the magnitude and phase graphs? The top plot shows the magnitude response of the DFT with respect to our input. The bottom plot shows the phase respose. The magnitude plot shows positive magnitudes for the 1st and the N-1th DFT components, and zero for all the rest. This means that the input is a... | ## Plot the actual DFT outputs as complex numbers on the complex plane
## For the example above, we can see that most of the outputs are at (0,0), i.e. not contribution
## but we get positive magnitudes for the 1st and 15th component, with the same
## magnitude by 'mirrored' phase angle:
ymax=(N/2) + 2
fig, ax = plt... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
You can see from this plot that all but two of the DFT outputs have zero magnitude. The two that have non-zero magnitude are the 1st and 15th components. You can see that they have the same magnitude, but mirror each other in phase (they are complex conjugates). This symmetry is something you see a lot of in digital ... | ## 1) Input: -sin(t-pi/3) as above
nsteps = np.array(range(N))
theta_step = 2*np.pi/N
theta_steps = theta_step * nsteps
Tmin = np.min(theta_steps)
Tmax = np.max(theta_steps)
phase_in = np.pi/3
x = -np.sin(theta_steps-phase_in)
fig, tdom = plt.subplots(figsize=(16, 4))
tdom.scatter(tsteps, x, color='magenta')
tdom.p... | _____no_output_____ | MIT | signals/sp-m1-4-discrete-fourier-transform.ipynb | Ahmed-H-N/uoe_speech_processing_course |
Scalable Recommendation with Poisson Factorization - Computation Statistics Project 1 The following notebook is an example of the use of the implementation of the mean-field variational algorithm for approximate posterior inference for the Hierarchical Poisson Factorization, by Gopalan et al. (2013). The variational i... | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.special
import scipy.stats
import sklearn.metrics
from hpf_vi import hpf_vi
from sklearn.metrics import mean_squared_error | _____no_output_____ | MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
The dataset is a sparse matrix of 0 and 1, which represents the interaction between users and items.The matrix contains clusters of similar users in terms of items consumed. There are more than 1700 users and approximately 17000 items. | ratings = pd.read_pickle("ratings_df.pkl")
ratings = np.array(ratings) | _____no_output_____ | MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
As one can read in the documentation of **hpf_vi**, the algorithm stops either when the difference between two subsequent log-likelihood is smaller than a tolerance value (which can be changed) or after a user-defined number of iterations.In the following code, a function that splits training and testing data is define... | def train_val_split(data, valid_dim=0.2):
'''
Creating two additional objects, i.e. training and validation set, which can be used in the fitting process
Parameters:
data = np.array
valid_dim = float
'''
if valid_dim >= 1:
raise ValueError("valid_dim mu... | _____no_output_____ | MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
We can now fit the model using the variational inference algorithm. Note that the specification of a validation set is optional. | model = hpf_vi() # instantiating the model
model.fit(train = train, valid = valid, tol = 1, iterations = 100) | /content/hpf_vi.py:180: RuntimeWarning: divide by zero encountered in log
self.logprod = np.log(self.prod)
| MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
As one can see in the next graph, the log-likelihood, as expected, tends to a higher value, until one of the two stopping criteria is met.Recall that the log-likelihood is the following:$$p(y) = \prod_{u,i}\frac{(\theta_u^T\beta_i)^{y_{u,i}}\cdot e ^{-\theta_u^T\beta_i}}{y_{u,i}!} = \prod_{u,i:\;y_{u,i} > 0} \frac{(\th... | fig, ax = plt.subplots(figsize=(9,5))
ax.plot(model.ll[1:model.its]) # trimming the loglik computed on the random initialization
ax.set_xlabel("Epochs")
ax.set_ylabel("- Loglikelihood") | _____no_output_____ | MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
The **fit** method will generate a sequence of Mean Squared Errors for both the training and, if provided, the validation set. This second parameter can be used, as suggested by the authors, as a stopping criterion for the algorithm. Nevertheless, we opt for the in-sample log-likelihood.In the following, a graph of the... | fig, ax = plt.subplots(figsize=(9, 5))
ax.plot(model.mse_train[1:model.its],label="Training set MSE")
ax.plot(model.mse_valid[1:model.its], label="Validation set MSE")
ax.set_xlabel("Epochs")
ax.set_ylabel("MSE")
ax.legend(); | _____no_output_____ | MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
Recommendations can now be made thanks to the estimated parameter. The method **recommend** suggests, for each user, the items that obtained the highest score. Plotting some results In the following, we can qualitatively assess the in-sample performance of the model by comparing the actual vs predicted observations fo... | fig, ax = plt.subplots(figsize=(14, 10), nrows=3)
for u,i in enumerate([1,100,1000]):
ax[u].plot(model.predicted[i]/model.predicted[i].max(), label = "Prediction")
ax[u].plot(ratings[i], label = "Actual observations")
ax[u].set_xlabel("Item")
ax[u].set_ylabel("Interaction")
ax[u].set_yticklabels([]... | _____no_output_____ | MIT | Variational Inference for Hierarchical Poisson Factorization/HPF_notebook.ipynb | leonardoruggieri/Computational-Statistics-PhD |
Importing necessary libraries. | from tensorflow.keras.layers import Input, Dense, Flatten
from keras import Model
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.models import Sequential | _____no_output_____ | MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
As we are using VGG16 architecture, it expects the size of 224 by 224(Although, you can set your own size). We will set image size. | image_size = [224, 224]
vgg = VGG16(input_shape = image_size + [3], weights = 'imagenet', include_top = False) | Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5
58892288/58889256 [==============================] - 1s 0us/step
| MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
The first argument is the shape of input image plus **3**(as image is colured[RBG], for black_and_white add **1**).The second one is the weights eqaul to imagenet. And,as we know it gives 1000 outputs. Third one excludes the top layer. | for layer in vgg.layers:
layer.trainable = False | _____no_output_____ | MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
Some of the layers of VGG16 are already trained. To train them again is not a good practice. Thereby making it False | from glob import glob
folders = glob('/kaggle/input/tomato/New Plant Diseases Dataset(Augmented)/train/*')
folders
| _____no_output_____ | MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
Flattening the output layer | x = Flatten()(vgg.output)
prediction = Dense(len(folders), activation = 'softmax')(x)
model = Model(inputs = vgg.input, outputs = prediction)
model.summary() | Model: "functional_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 224, 224, 3)] 0
__________________________________... | MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
Compiling the model | model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy']) | _____no_output_____ | MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
Generating more images | from keras.preprocessing.image import ImageDataGenerator
train_data_gen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)
test_data_gen = ImageDataGenerator(rescale = 1./255)
train_set = train_data_gen.flow_from_directory('/kaggle/input/tomato/New Plant Diseases Dataset... | Found 4585 images belonging to 10 classes.
| MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
Fitting the model | mod = model.fit_generator(
train_set,
validation_data=test_set,
epochs=10,
steps_per_epoch=len(train_set),
validation_steps=len(test_set)
)
import matplotlib.pyplot as plt
plt.plot(mod.history['loss'], label='train loss')
plt.plot(mod.history['val_loss'], label='val loss')
plt.legend()
plt.show()
plt.plot(m... | _____no_output_____ | MIT | Machine Learning/Models/4-tomato-diesease-prediction.ipynb | TusharVerma015/Ds-Algo-HacktoberFest-1 |
Lecture 8: Fitting Generalized Linear Models (Part II) | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('talk')
sns.set_style('white')
%matplotlib inline | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Objectives+ Maximum Posterior Estimate+ Bayesian Linear Regression+ Evidence Approximation+ Automatic Relevance Determination ReadingsBefore coming to class, please read the following:+ [Ch. 3 of Bishop, 2006](http://www.amazon.com/Pattern-Recognition-Learning-Information-Statistics/dp/0387310738)+ [Ohio State Univer... | # Linear Basis
class LinearBasis(object):
"""
Represents a 1D linear basis.
"""
def __init__(self):
self.num_basis = 2 # The number of basis functions
def __call__(self, x):
"""
``x`` should be a 1D array.
"""
return [1., x[0]]
# We need a generic functio... | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
We will use the motorcycle data set of lecture 7. | data = np.loadtxt('motor.dat')
X = data[:, 0][:, None]
Y = data[:, 1] | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Probabilistic Regression - Version 2+ We wish to model the data using some **fixed** basis/features:$$y(\mathbf{x};\mathbf{w}) = \sum_{j=1}^{m} w_{j}\phi_{j}(\mathbf{x}) = \mathbf{w^{T}\boldsymbol{\phi}(\mathbf{x})}$$+ We *model the measurement process* using a **likelihood** function:$$\mathbf{y}_{1:n} | \mathbf{x}_{... | import scipy.linalg
ell = 2.
alpha = 5
sigma = 20.28
Xc = np.linspace(0, 60, 20)
phi = RadialBasisFunctions(Xc, ell)
Phi = compute_design_matrix(X, phi)
A = np.dot(Phi.T, Phi) / sigma ** 2. + alpha * np.eye(Phi.shape[1])
L = scipy.linalg.cho_factor(A)
w_MPE = scipy.linalg.cho_solve(L, np.dot(Phi.T, Y))
print 'w_MPE:'
p... | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Hands-on+ Experiment with different alphas.+ When are we underfitting?+ When are we overfitting?+ Which one (if any) gives you the best fit? Issues with Maximum Posterior Estimate+ How many basis functions should I use?+ Which basis functions should I use?+ How do I pick the parameters of the basis functions, e.g., t... | import scipy.linalg
ell = 2.
alpha = 0.001
sigma = 20.28
Xc = np.linspace(0, 60, 20)
phi = RadialBasisFunctions(Xc, ell)
Phi = compute_design_matrix(X, phi)
A = np.dot(Phi.T, Phi) / sigma ** 2. + alpha * np.eye(Phi.shape[1])
L = scipy.linalg.cho_factor(A)
m = scipy.linalg.cho_solve(L, np.dot(Phi.T, Y) / sigma ** 2) # ... | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Sampling Posterior Models+ We can actually sample models (functions) from the posterior. Here is how: + Sample a $\mathbf{w}$ from $p(\mathbf{w}|\mathbf{x}_{1:n},\mathbf{y}_{1:n}, \sigma, \alpha)$. + Look at the sampled model: $$ y(\mathbf{x};\mathbf{w}) = \mathbf{w}^T\boldsymbol{\phi}(\mathbf{x}). $$ | # We have m, S, X_p, and Phi_p from before
fig, ax = plt.subplots()
ax.plot(X, Y, 'x', markeredgewidth=2, label='Observations')
for i in xrange(10):
w = np.random.multivariate_normal(m, S)
Y_p_s = np.dot(Phi_p, w)
ax.plot(X_p, Y_p_s, color=sns.color_palette()[2], linewidth=0.5);
ax.set_xlabel('$x$')
ax.set_... | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Issues with Bayesian Linear Regression+ How many basis functions should I use?+ Which basis functions should I use?+ How do I pick the parameters of the basis functions, e.g., the lengthscale $\ell$ of the RBFs, $\alpha$, etc.?+ Hands-on+ Experiment with different alphas, ells, and sigmas.+ When are we underfitting?+... | from sklearn.linear_model import BayesianRidge
ell = 2.
Xc = np.linspace(0, 60, 50)
phi = RadialBasisFunctions(Xc, ell)
Phi = compute_design_matrix(X, phi)
regressor = BayesianRidge()
regressor.fit(Phi, Y)
# They are using different names:
sigma = np.sqrt(1. / regressor.alpha_)
print 'best sigma:', sigma
alpha = regres... | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Issues with Bayesian Linear Regression+ How many basis functions should I use?+ Which basis functions should I use? Hands-on+ Try the evidence approximation with the Fourier basis.+ Try the evidence approximation with the Step function basis. Probabilistic Regression - Version 5 - Automatic Relevance Determination+ ... | from sklearn.linear_model import ARDRegression
ell = 2.
Xc = np.linspace(0, 60, 50)
phi = RadialBasisFunctions(Xc, ell)
Phi = compute_design_matrix(X, phi)
regressor = ARDRegression()
regressor.fit(Phi, Y)
# They are using different names:
sigma = np.sqrt(1. / regressor.alpha_)
print 'best sigma:', sigma
alpha = regres... | _____no_output_____ | MIT | handouts/handout_08.ipynb | bdlafleur/uq-course |
Optimization of a Dissipative Quantum Gate | # NBVAL_IGNORE_OUTPUT
%load_ext watermark
import sys
import os
import qutip
import numpy as np
import scipy
import matplotlib
import matplotlib.pylab as plt
import krotov
import copy
from functools import partial
from itertools import product
%watermark -v --iversions | Python implementation: CPython
Python version : 3.7.6
IPython version : 7.19.0
matplotlib: 3.3.3
scipy : 1.3.1
numpy : 1.17.2
krotov : 1.2.1
qutip : 4.5.0
sys : 3.7.6 (default, Jan 6 2020, 00:53:52)
[Clang 11.0.0 (clang-1100.0.33.16)]
| BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
$\newcommand{tr}[0]{\operatorname{tr}}\newcommand{diag}[0]{\operatorname{diag}}\newcommand{abs}[0]{\operatorname{abs}}\newcommand{pop}[0]{\operatorname{pop}}\newcommand{aux}[0]{\text{aux}}\newcommand{int}[0]{\text{int}}\newcommand{opt}[0]{\text{opt}}\newcommand{tgt}[0]{\text{tgt}}\newcommand{init}[0]{\text{init}}\newco... | if sys.platform != 'linux':
krotov.parallelization.set_parallelization(use_loky=True)
from krotov.parallelization import parallel_map | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The two-transmon system We consider the Hamiltonian from Eq (17) in the paper, in the rotating wave approximation, together with spontaneous decay and dephasing of each qubit. Alltogether, we define the Liouvillian as follows: | def two_qubit_transmon_liouvillian(
ω1, ω2, ωd, δ1, δ2, J, q1T1, q2T1, q1T2, q2T2, T, Omega, n_qubit
):
from qutip import tensor, identity, destroy
b1 = tensor(identity(n_qubit), destroy(n_qubit))
b2 = tensor(destroy(n_qubit), identity(n_qubit))
H0 = (
(ω1 - ωd - δ1 / 2) * b1.dag() * b1
... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
We will use internal units GHz and ns. Values in GHz contain an implicit factor 2π, and MHz and μs are converted to GHz and ns, respectively: | GHz = 2 * np.pi
MHz = 1e-3 * GHz
ns = 1
μs = 1000 * ns | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
This implicit factor $2 \pi$ is because frequencies ($\nu$) convert to energies as $E = h \nu$, but our propagation routines assume a unit $\hbar = 1$ for energies. Thus, the factor $h / \hbar = 2 \pi$. We will use the same parameters as those given in Table 2 of the paper: | ω1 = 4.3796 * GHz # qubit frequency 1
ω2 = 4.6137 * GHz # qubit frequency 2
ωd = 4.4985 * GHz # drive frequency
δ1 = -239.3 * MHz # anharmonicity 1
δ2 = -242.8 * MHz # anharmonicity 2
J = -2.3 * MHz # effective qubit-qubit coupling
q1T1 = 38.0 * μs # decay time for qubit 1
q2T1 = 32.0 * μs # decay time for... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
While in the original paper, each transmon was cut off at 6 levels, here we truncate at 5 levels. This makes the propagation faster, while potentially introducing a slightly larger truncation error. | n_qubit = 5 # number of transmon levels to consider | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
In the Liouvillian, note the control being split up into a separate real and imaginary part. As a guess control we use a real-valued constant pulse with an amplitude of 35 MHz, acting over 400 ns, with a switch-on and switch-off in the first 20 ns (see plot below) | def Omega(t, args):
E0 = 35.0 * MHz
return E0 * krotov.shapes.flattop(t, 0, T, t_rise=(20 * ns), func='sinsq') | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The imaginary part start out as zero: | def ZeroPulse(t, args):
return 0.0 | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
We can now instantiate the Liouvillian: | L = two_qubit_transmon_liouvillian(
ω1, ω2, ωd, δ1, δ2, J, q1T1, q2T1, q1T2, q2T2, T, Omega, n_qubit
) | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The guess pulse looks as follows: | def plot_pulse(pulse, tlist, xlimit=None):
fig, ax = plt.subplots()
if callable(pulse):
pulse = np.array([pulse(t, None) for t in tlist])
ax.plot(tlist, pulse/MHz)
ax.set_xlabel('time (ns)')
ax.set_ylabel('pulse amplitude (MHz)')
if xlimit is not None:
ax.set_xlim(xlimit)
plt... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Optimization objectives Our target gate is $\Op{O} = \sqrt{\text{iSWAP}}$: | SQRTISWAP = qutip.Qobj(np.array(
[[1, 0, 0, 0],
[0, 1 / np.sqrt(2), 1j / np.sqrt(2), 0],
[0, 1j / np.sqrt(2), 1 / np.sqrt(2), 0],
[0, 0, 0, 1]]),
dims=[[2, 2], [2, 2]]
) | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The key idea explored in the paper is that a set of three density matrices is sufficient to track the optimization$$\begin{align}\Op{\rho}_1 &= \sum_{i=1}^{d} \frac{2 (d-i+1)}{d (d+1)} \ketbra{i}{i} \\\Op{\rho}_2 &= \sum_{i,j=1}^{d} \frac{1}{d} \ketbra{i}{j} \\\Op{\rho}_3 &= \sum_{i=1}^{d} \frac{1}{d} \ketbra{... | ket00 = qutip.ket((0, 0), dim=(n_qubit, n_qubit))
ket01 = qutip.ket((0, 1), dim=(n_qubit, n_qubit))
ket10 = qutip.ket((1, 0), dim=(n_qubit, n_qubit))
ket11 = qutip.ket((1, 1), dim=(n_qubit, n_qubit))
basis = [ket00, ket01, ket10, ket11] | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The three density matrices play different roles in the optimization, and, as shown in the paper, convergence may improve significantly by weighing the states relatively to each other. For this example, we place a strong emphasis on the optimization $\Op{\rho}_1 \rightarrow \Op{O}^\dagger \Op{\rho}_1 \Op{O}$, by a facto... | weights = np.array([20, 1, 1], dtype=np.float64)
weights *= len(weights) / np.sum(weights) # manual normalization
weights /= np.array([0.3, 1.0, 0.25]) # purities | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The `krotov.gate_objectives` routine can initialize the density matrices $\Op{\rho}_1$, $\Op{\rho}_2$, $\Op{\rho}_3$ automatically, via the parameter `liouville_states_set`. Alternatively, we could also use the `'full'` basis of 16 matrices or the extended set of $d+1 = 5$ pure-state density matrices. | objectives = krotov.gate_objectives(
basis,
SQRTISWAP,
L,
liouville_states_set='3states',
weights=weights,
normalize_weights=False,
)
objectives | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
The use of `normalize_weights=False` is because we have included the purities in the weights, as discussed above. Dynamics under the Guess Pulse For numerical efficiency, both for the analysis of the guess/optimized controls, we will use a stateful density matrix propagator: A true physical measure for the success of ... | full_liouville_basis = [psi * phi.dag() for (psi, phi) in product(basis, basis)] | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
We propagate these under the guess control: | def propagate_guess(initial_state):
return objectives[0].mesolve(
tlist,
rho0=initial_state,
).states[-1]
full_states_T = parallel_map(
propagate_guess, values=full_liouville_basis,
)
print("F_avg = %.3f" % krotov.functionals.F_avg(full_states_T, basis, SQRTISWAP)) | F_avg = 0.344
| BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Note that we use $F_{T,\text{re}}$, not $F_{\text{avg}}$ to steer the optimization, as the Krotov boundary condition $\frac{\partial F_{\text{avg}}}{\partial \rho^\dagger}$ would be non-trivial. Before doing the optimization, we can look the population dynamics under the guess pulse. For this purpose we propagate the p... | rho00, rho01, rho10, rho11 = [qutip.ket2dm(psi) for psi in basis]
def propagate_guess_for_expvals(initial_state):
return objectives[0].propagate(
tlist,
propagator=krotov.propagators.DensityMatrixODEPropagator(),
rho0=initial_state,
e_ops=[rho00, rho01, rho10, rho11]
)
def plot_p... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Optimization We now define the optimization parameters for the controls, the Krotov step size $\lambda_a$ and the update-shape that will ensure that the pulse switch-on and switch-off stays intact. | pulse_options = {
L[i][1]: dict(
lambda_a=1.0,
update_shape=partial(
krotov.shapes.flattop, t_start=0, t_stop=T, t_rise=(20 * ns))
)
for i in [1, 2]
} | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Then we run the optimization for 2000 iterations | opt_result = krotov.optimize_pulses(
objectives,
pulse_options,
tlist,
propagator=krotov.propagators.DensityMatrixODEPropagator(reentrant=True),
chi_constructor=krotov.functionals.chis_re,
info_hook=krotov.info_hooks.print_table(J_T=krotov.functionals.J_T_re),
iter_stop=3,
) | iter. J_T ∑∫gₐ(t)dt J ΔJ_T ΔJ secs
0 1.22e-01 0.00e+00 1.22e-01 n/a n/a 17
1 7.49e-02 2.26e-02 9.75e-02 -4.67e-02 -2.41e-02 48
2 7.41e-02 3.98e-04 7.45e-02 -8.12e-04 -4.14e-04 35
3 7.33e-02 3.70e-04 7.37e-02 -7.55e-04 -3.85e... | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
(this takes a while)... | dumpfile = "./3states_opt_result.dump"
if os.path.isfile(dumpfile):
opt_result = krotov.result.Result.load(dumpfile, objectives)
else:
opt_result = krotov.optimize_pulses(
objectives,
pulse_options,
tlist,
propagator=krotov.propagators.DensityMatrixODEPropagator(reentrant=True),
... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.