markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
So you can iterate the values and their frequencies like this:
for val in sorted(hist.Values()): print(val, hist[val])
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Or you can use the Items method:
for val, freq in hist.Items(): print(val, freq)
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
thinkplot is a wrapper for matplotlib that provides functions that work with the objects in thinkstats2. For example Hist plots the values and their frequencies as a bar graph. Config takes parameters that label the x and y axes, among other things.
import thinkplot thinkplot.Hist(hist) thinkplot.Config(xlabel='value', ylabel='frequency')
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
As an example, I'll replicate some of the figures from the book. First, I'll load the data from the pregnancy file and select the records for live births.
download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/nsfg.py") download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemPreg.dct") download( "https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemPreg.dat.gz" ) import nsfg preg = nsfg.ReadFemPreg() live = preg[preg....
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Here's the histogram of birth weights in pounds. Notice that Hist works with anything iterable, including a Pandas Series. The label attribute appears in the legend when you plot the Hist.
hist = thinkstats2.Hist(live.birthwgt_lb, label='birthwgt_lb') thinkplot.Hist(hist) thinkplot.Config(xlabel='Birth weight (pounds)', ylabel='Count')
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Before plotting the ages, I'll apply floor to round down:
ages = np.floor(live.agepreg) hist = thinkstats2.Hist(ages, label='agepreg') thinkplot.Hist(hist) thinkplot.Config(xlabel='years', ylabel='Count')
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
As an exercise, plot the histogram of pregnancy lengths (column prglngth). Hist provides smallest, which select the lowest values and their frequencies.
for weeks, freq in hist.Smallest(10): print(weeks, freq)
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Use Largest to display the longest pregnancy lengths. From live births, we can select first babies and others using birthord, then compute histograms of pregnancy length for the two groups.
firsts = live[live.birthord == 1] others = live[live.birthord != 1] first_hist = thinkstats2.Hist(firsts.prglngth, label='first') other_hist = thinkstats2.Hist(others.prglngth, label='other')
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
We can use width and align to plot two histograms side-by-side.
width = 0.45 thinkplot.PrePlot(2) thinkplot.Hist(first_hist, align='right', width=width) thinkplot.Hist(other_hist, align='left', width=width) thinkplot.Config(xlabel='weeks', ylabel='Count', xlim=[27, 46])
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Series provides methods to compute summary statistics:
mean = live.prglngth.mean() var = live.prglngth.var() std = live.prglngth.std()
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Here are the mean and standard deviation:
mean, std
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
As an exercise, confirm that std is the square root of var: Here's are the mean pregnancy lengths for first babies and others:
firsts.prglngth.mean(), others.prglngth.mean()
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
And here's the difference (in weeks):
firsts.prglngth.mean() - others.prglngth.mean()
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
This functon computes the Cohen effect size, which is the difference in means expressed in number of standard deviations:
def CohenEffectSize(group1, group2): """Computes Cohen's effect size for two groups. group1: Series or DataFrame group2: Series or DataFrame returns: float if the arguments are Series; Series if the arguments are DataFrames """ diff = group1.mean() - group2.mean() var...
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Compute the Cohen effect size for the difference in pregnancy length for first babies and others. Exercises Using the variable totalwgt_lb, investigate whether first babies are lighter or heavier than others. Compute Cohen’s effect size to quantify the difference between the groups. How does it compare to the differe...
download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemResp.dct") download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemResp.dat.gz") resp = nsfg.ReadFemResp()
code/chap02ex.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Import and load MNIST dataset (Preprocessing) Dataloader are powerful instruments, which help you to prepare your data. E.g. you can shuffle your data, transform data (standardize/normalize), divide it into batches, ... For more information see https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader <br>...
batch_size_train = 60000 # Samples per Training Batch batch_size_test = 10000 # just create one large test dataset (MNIST test dataset has 10.000 Samples) # Get Training and Test Dataset with a Dataloader train_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('./files/', train=True, download...
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Plot 8 random images
plt.figure(figsize=(16,2)) for k in range(8): plt.subplot(1,8,k+1) plt.imshow(x_train[np.random.randint(x_train.shape[0])], interpolation='nearest', cmap='binary') plt.xticks(()) plt.yticks(())
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Specify Autoencoder As explained in the lecture, we are using Stochstic Quantization. This means for the training process (def forward), we employ stochastic quantization in forward path but during back-propagation, we consider the quantization device as being non-existent (.detach()). While validating and testing, use...
# target compression rate bit_per_image = 24 # BSC error probability Pe = 0.05 hidden_encoder_1 = 500 hidden_encoder_2 = 250 hidden_encoder_3 = 100 hidden_encoder = [hidden_encoder_1, hidden_encoder_2, hidden_encoder_3] hidden_decoder_1 = 100 hidden_decoder_2 = 250 hidden_decoder_3 = 500 hidden_decoder = [hidden_dec...
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Helper function to get a random mini-batch of images
def get_batch(x, batch_size): idxs = np.random.randint(0, x.shape[0], (batch_size)) return torch.stack([torch.reshape(x[k], (-1,)) for k in idxs])
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Perform the training
batch_size = 250 model = Autoencoder(hidden_encoder, hidden_decoder, image_size, bit_per_image) model.to(device) # Mean Squared Error loss loss_fn = nn.MSELoss() # Adam Optimizer optimizer = optim.Adam(model.parameters()) print('Start Training') # Training loop for it in range(25000): # Original pa...
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Evaluation Compare sent and received images
valid_images = model.test(x_test_flat.to(device), Pe).detach().cpu().numpy() valid_binary = 0.5*(1 - model.binarizer(model.encoder(x_test_flat.to(device)))).detach().cpu().numpy() # from bipolar (BPSK) to binary # show 8 images and their reconstructed versions plt.figure(figsize=(16,4)) idxs = np.random.randint(x_te...
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Generate 8 arbitary images just by sampling random bit strings
random_data = 1-2*np.random.randint(2,size=(8,bit_per_image)) generated_images = model.decoder(torch.Tensor(random_data).to(device)).detach().cpu().numpy() plt.figure(figsize=(16,2)) for k in range(8): plt.subplot(1,8,k+1) plt.imshow(np.reshape(generated_images[k],(image_size,image_size)), interpolation='neares...
mloc/ch4_Autoencoders/Autoencoder_Compression_Binarizer.ipynb
kit-cel/lecture-examples
gpl-2.0
Time to build the network Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes. The network has two layers, a hid...
class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes # Initialize we...
first-neural-network/Your_first_neural_network.ipynb
kimegitee/deep-learning
mit
Training the network Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se...
import sys ### Set the hyperparameters here ### epochs = 2000 learning_rate = 0.01 hidden_nodes = 25 output_nodes = 4 N_i = train_features.shape[1] network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate) losses = {'train':[], 'validation':[]} for e in range(epochs): # Go through a random batch of...
first-neural-network/Your_first_neural_network.ipynb
kimegitee/deep-learning
mit
Thinking about your results Answer these questions about your results. How well does the model predict the data? Where does it fail? Why does it fail where it does? Your answer below The model captures well the patterns during a normal week, including the relative winding down in the weekends and the daily spikes in th...
import unittest inputs = [0.5, -0.2, 0.1] targets = [0.4] test_w_i_h = np.array([[0.1, 0.4, -0.3], [-0.2, 0.5, 0.2]]) test_w_h_o = np.array([[0.3, -0.1]]) class TestMethods(unittest.TestCase): ########## # Unit tests for data loading ########## def test_data_path(self...
first-neural-network/Your_first_neural_network.ipynb
kimegitee/deep-learning
mit
Use Reset
import resnet50 from resnet50 import Resnet50 # omit the last dense layer, so that we don't have to do model.pop # before we finetune the model to suit our purpose rn0 = Resnet50(include_top=False).model rn0.output_shape[1:]
deeplearning1/nbs/try-resnet.ipynb
yingchi/fastai-notes
apache-2.0
```py from utils.py def get_classes(path): batches = get_batches(path+'train', shuffle=False, batch_size=1) val_batches = get_batches(path+'valid', shuffle=False, batch_size=1) test_batches = get_batches(path+'test', shuffle=False, batch_size=1) return (val_batches.classes, batches.classes, onehot(val_b...
batches = get_batches(path+'train', shuffle=False, batch_size=batch_size) val_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False) # labels are the one-hot encoded version of classes (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filenames) = get_classes(path) ...
deeplearning1/nbs/try-resnet.ipynb
yingchi/fastai-notes
apache-2.0
py def save_array(fname, arr): c=bcolz.carray(arr, rootdir=fname, mode='w') c.flush()
save_array(model_path + 'trn_rn0_conv.bc', trn_features) save_array(model_path + 'val_rn0_conv.bc', val_features) trn_features = load_array(model_path + 'trn_rn0_conv.bc') val_features = load_array(model_path + 'val_rn0_conv.bc')
deeplearning1/nbs/try-resnet.ipynb
yingchi/fastai-notes
apache-2.0
FC net
def get_fc_layers(p): return [ BatchNormalization(axis=1, input_shape=rn0.output_shape[1:]), Flatten(), Dropout(p), Dense(1024, activation='relu'), BatchNormalization(), Dropout(p/2), Dense(1024, activation='relu'), BatchNormalization(), Dropou...
deeplearning1/nbs/try-resnet.ipynb
yingchi/fastai-notes
apache-2.0
Global average pooling
def get_ap_layers(p): return [ GlobalAveragePooling2D(input_shape=rn0.output_shape[1:]), Dropout(p), Dense(2, activation='softmax') ] model = Sequential(get_ap_layers(0.2)) model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(trn_features, t...
deeplearning1/nbs/try-resnet.ipynb
yingchi/fastai-notes
apache-2.0
Use Resnet Large
rn1 = Resnet50(include_top=False, size=(400, 400)).model rn1.output_shape[1:] batches = get_batches(path+'train', shuffle=False, batch_size=batch_size, target_size=(400, 400)) val_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False, target_size=(400,...
deeplearning1/nbs/try-resnet.ipynb
yingchi/fastai-notes
apache-2.0
Implementing an Earley Parser A Grammar for Grammars Earley's algorithm has two inputs: - a grammar $G$ and - a string $s$. It then checks whether the string $s$ can be parsed with the given grammar. In order to input the grammar in a natural way, we first have to develop a parser for grammars. An example grammar that ...
!type simple.g !cat simple.g
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
We use <span style="font-variant:small-caps;">Antlr</span> to develop a parser for this Grammar. The pure grammar to parse this type of grammar is stored in the file Pure.g4.
!type Pure.g4 !cat Pure.g4
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The annotated grammar is stored in the file Grammar.g4.
!type Grammar.g4 !cat -n Grammar.g4
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The class Grammar represents a context free grammar. It stores a list of the rules of the grammar. Each grammar rule of the form $$ a \rightarrow \beta $$ is stored as the tuple $(a,) + \beta$. The start symbol is assumed to be the variable on the left hand side of the first rule. To distinguish syntactical variables...
class Grammar(): def __init__(self, Rules): self.mRules = Rules
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The class EarleyParser implements the parsing algorithm of Jay Earley. The class maintains the following member variables: - mGrammar is the grammar that is used to parse the given token string. - mString is the list of tokens and literals that has to be parsed. As a hack, the first element of this list in None. The...
class EarleyParser(): def __init__(self, grammar, TokenList): self.mGrammar = grammar self.mString = [None] + TokenList # hack so mString[1] is the first token self.mStateList = [set() for i in range(len(TokenList)+1)] print('Grammar:\n') print(self.mGrammar) ...
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The method parse implements Earley's algorithm. For all states $Q_1$, $\cdots$, $Q_n$ we proceed as follows: - We apply the completion operation followed by the prediction operation. This is done until no more states are added to $Q_i$. (The inner while loop is not necessary if the grammar does not contain $\vare...
def parse(self): "run Earley's algorithm" n = len(self.mString) - 1 # mString[0] = None for i in range(0, n+1): if i + 1 <= n: next_token = self.mString[i+1] else: next_token = 'EOF' print('_' * 80) print(f'next token = {next_token}') print('_'...
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The function test takes two arguments. - file is the name of a file containing a grammar, - word is a string that should be parsed. word is first tokenized. Then the resulting token list is parsed using Earley's algorithm.
def test(file, word): Rules = parse_grammar(file) grammar = Grammar(Rules) TokenList = tokenize(word) ep = EarleyParser(grammar, TokenList) ep.parse() test('simple.g', '1 * 2 + 3')
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
The command below cleans the directory.
!del GrammarLexer.* GrammarParser.* Grammar.tokens GrammarListener.py Grammar.interp !rmdir /S /Q __pycache__ !dir /B !rm GrammarLexer.* GrammarParser.* Grammar.tokens GrammarListener.py Grammar.interp !rm -r __pycache__ !ls
ANTLR4-Python/Earley-Parser/Earley-Parser.ipynb
karlstroetmann/Formal-Languages
gpl-2.0
Use Fairing to build docker image
import os import sys import fairing from fairing.builders import append from fairing.builders import cluster from fairing.deployers import job from fairing.preprocessors.converted_notebook import ConvertNotebookPreprocessorWithFire # Setting up google container repositories (GCR) for storing output containers # You ca...
Label_Microservice/notebooks/Training_Pipeline.ipynb
kubeflow/code-intelligence
mit
Build Docker image We use builders in Kubeflow Fairing to build docker images. We use ClusterBuilder to builds a docker image in a Kubernetes cluster and AppendBuilder to append a new layer tarball. We also include preprocessor as a parameter to send the processed inputs to docker build.
preprocessor = ConvertNotebookPreprocessorWithFire('RepoMLP', notebook_file='repo_mlp.ipynb') if not preprocessor.input_files: preprocessor.input_files = set() input_files = ['../../py/label_microservice/mlp.py', '../../py/label_microservice/repo_config.py', '../../py/code_intelligenc...
Label_Microservice/notebooks/Training_Pipeline.ipynb
kubeflow/code-intelligence
mit
Build pipeline Kubeflow Pipelines builds reusable end-to-end machine learning workflows. Define the pipeline as a Python function. "@kfp.dsl.pipeline" is a required decoration including name and description properties. We define two steps for our training pipelines, including scrapping issues and training model, both o...
import kfp import kfp.components as comp import kfp.gcp as gcp import kfp.dsl as dsl import kfp.compiler as compiler # need to modify it if build a new one target_image = 'gcr.io/issue-label-bot-dev/training/fairing-job:5350A3D3' @dsl.pipeline( name='Training pipeline', description='A pipeline that loads embedd...
Label_Microservice/notebooks/Training_Pipeline.ipynb
kubeflow/code-intelligence
mit
Compile the pipeline We compile our pipeline to an intermediate representation, which is a YAML file compressed in a zip file.
pipeline_func = train_pipeline pipeline_filename = pipeline_func.__name__ + '.pipeline.zip' compiler.Compiler().compile(pipeline_func, pipeline_filename)
Label_Microservice/notebooks/Training_Pipeline.ipynb
kubeflow/code-intelligence
mit
Submit the pipeline for execution We upload our created pipeline, the zip file, and run it. Then, we can see the pipeline and experiments on Kubeflow UI.
EXPERIMENT_NAME = 'TrainModel' client = kfp.Client() experiment = client.create_experiment(EXPERIMENT_NAME) #Specify pipeline argument values arguments = {'owner': '', 'repo': ''} #Submit a pipeline run run_name = pipeline_func.__name__ + ' run' run_result = client.run_pipeline(experiment.id, run_name, pipeline_file...
Label_Microservice/notebooks/Training_Pipeline.ipynb
kubeflow/code-intelligence
mit
Post-training float16 quantization <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lite/performance/post_training_float16_quant"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blan...
import logging logging.getLogger("tensorflow").setLevel(logging.DEBUG) import tensorflow as tf from tensorflow import keras import numpy as np import pathlib
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
For the example, you trained the model for just a single epoch, so it only trains to ~96% accuracy. Convert to a TensorFlow Lite model Using the TensorFlow Lite Converter, you can now convert the trained model into a TensorFlow Lite model. Now load the model using the TFLiteConverter:
converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert()
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
To instead quantize the model to float16 on export, first set the optimizations flag to use default optimizations. Then specify that float16 is the supported type on the target platform:
converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_types = [tf.float16]
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
Finally, convert the model like usual. Note, by default the converted model will still use float input and outputs for invocation convenience.
tflite_fp16_model = converter.convert() tflite_model_fp16_file = tflite_models_dir/"mnist_model_quant_f16.tflite" tflite_model_fp16_file.write_bytes(tflite_fp16_model)
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
Note how the resulting file is approximately 1/2 the size.
!ls -lh {tflite_models_dir}
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
Run the TensorFlow Lite models Run the TensorFlow Lite model using the Python TensorFlow Lite Interpreter. Load the model into the interpreters
interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file)) interpreter.allocate_tensors() interpreter_fp16 = tf.lite.Interpreter(model_path=str(tflite_model_fp16_file)) interpreter_fp16.allocate_tensors()
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
Test the models on one image
test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32) input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] interpreter.set_tensor(input_index, test_image) interpreter.invoke() predictions = interpreter.get_tensor(output_index) import m...
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
Repeat the evaluation on the float16 quantized model to obtain:
# NOTE: Colab runs on server CPUs. At the time of writing this, TensorFlow Lite # doesn't have super optimized server CPU kernels. For this reason this may be # slower than the above float interpreter. But for mobile CPUs, considerable # speedup can be observed. print(evaluate_model(interpreter_fp16))
site/en-snapshot/lite/performance/post_training_float16_quant.ipynb
tensorflow/docs-l10n
apache-2.0
If your qutip version is lower than 4.4.1 please run the following cell
from qutip.qip.models.spinchain import CircularSpinChain from qutip.qip.models.spinchain import LinearSpinChain
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Otherwise please run this cell
from qutip.qip.device import CircularSpinChain, LinearSpinChain from qutip.qip.noise import RandomNoise
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Hamiltonian: $\displaystyle H = - \frac{1}{2}\sum_n^N h_n \sigma_z(n) - \frac{1}{2} \sum_n^{N-1} [ J_x^{(n)} \sigma_x(n) \sigma_x(n+1) + J_y^{(n)} \sigma_y(n) \sigma_y(n+1) +J_z^{(n)} \sigma_z(n) \sigma_z(n+1)]$ The linear and circular spin chain models employing the nearest neighbor interaction can be implemented usin...
N = 3 qc = QubitCircuit(N) qc.add_gate("CNOT", targets=[0], controls=[2])
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The non-adjacent interactions are broken into a series of adjacent ones by the program automatically.
U_ideal = gate_sequence_product(qc.propagators()) U_ideal
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Circular Spin Chain Model Implementation
p1 = CircularSpinChain(N, correct_global_phase=True) U_list = p1.run(qc) U_physical = gate_sequence_product(U_list) U_physical.tidyup(atol=1e-5) (U_ideal - U_physical).norm()
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The results obtained from the physical implementation agree with the ideal result.
p1.qc0.gates
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The gates are first convert to gates with adjacent interactions moving in the direction with the least number of qubits in between.
p1.qc1.gates
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
They are then converted into the basis [ISWAP, RX, RZ]
p1.qc2.gates
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The time for each applied gate:
p1.get_full_tlist()
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The pulse can be plotted as:
p1.plot_pulses();
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Linear Spin Chain Model Implementation
p2 = LinearSpinChain(N, correct_global_phase=True) U_list = p2.run(qc) U_physical = gate_sequence_product(U_list) U_physical.tidyup(atol=1e-5) (U_ideal - U_physical).norm()
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The results obtained from the physical implementation agree with the ideal result.
p2.qc0.gates
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The gates are first convert to gates with adjacent interactions moving in the direction with the least number of qubits in between.
p2.qc1.gates
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
They are then converted into the basis [ISWAP, RX, RZ]
p2.qc2.gates
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The time for each applied gate:
p2.get_full_tlist()
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The pulse can be plotted as:
p2.plot_pulses();
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Numerical simulation From QuTiP 4.5, we also add the possibility to allow numerical simulation of SpinChain-based quantum computing. One needs only to add an option analytical=False in run_state to use one of the QuTiP solvers to simulate the state evolution instead of direct matrix product. Under numerical simulation,...
from qutip import basis, fidelity N = 1 plus_state = (basis(2,0) + basis(2,1)).unit() qc = QubitCircuit(N=N) qc.add_gate("SNOT", targets=0) processor = LinearSpinChain(N=N) processor.load_circuit(qc) end_state = processor.run_state(init_state=basis(2, 0), analytical=False).states[-1] fidelity(end_state, plus_state) p...
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
As the control noise is coherent noise, the result of this noise is still a pure state. Therefore, we can visualize it on a Bloch sphere.
from qutip.bloch import Bloch b = Bloch() b.add_states([end_state, plus_state]) b.make_sphere()
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Software versions:
from qutip.ipynbtools import version_table version_table()
examples/spin-chain-model.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
Here an Operator instance is created for our Hamiltonian. In this case the paulis are from an Ising Hamiltonian translated from the max cut problem. We load a small sample instance of the maxcut problem.
w = maxcut.parse_gset_format('sample.maxcut') qubitOp, offset = maxcut.get_maxcut_qubitops(w) algo_input = get_input_instance('EnergyInput') algo_input.qubit_op = qubitOp
community/aqua/optimization/maxcut.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
We also offer a function to generate a random graph as a input.
if True: np.random.seed(8123179) w = maxcut.random_graph(4, edge_prob=0.5, weight_range=10) qubitOp, offset = maxcut.get_maxcut_qubitops(w) algo_input.qubit_op = qubitOp print(w)
community/aqua/optimization/maxcut.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Here we test for the presence of algorithms we want to use in this notebook. If Aqua is installed correctly ExactEigensolver and VQE will always be found. CPLEX.Ising is dependent on IBM CPLEX being installed (see introduction above). CPLEX is not required but if installed then this notebook will demonstrate the CPLEX....
to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] operational_algos = [] for algo in to_be_tested_algos: try: get_algorithm_instance(algo) operational_algos.append(algo) except: print("{} is unavailable and will be skipped.".format(algo)) print(operational_algos)
community/aqua/optimization/maxcut.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
We can now use the Operator without regard to how it was created. First we need to prepare the configuration params to invoke the algorithm. Here we will use the ExactEigensolver first to return the smallest eigenvalue. Backend is not required since this is computed classically not using quantum computation. We then ad...
if 'ExactEigensolver' not in operational_algos: print("ExactEigensolver is not in operational algorithms.") else: algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_inpu...
community/aqua/optimization/maxcut.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Note: IBM CPLEX is an optional installation addition for Aqua. If installed then the Aqua CPLEX.Ising algorithm will be able to be used. If not, then solving this problem using this particular algorithm will simply be skipped. We change the configuration parameters to solve it with the CPLEX backend. The CPLEX backend...
if 'CPLEX.Ising' not in operational_algos: print("CPLEX.Ising is not in operational algorithms.") else: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, a...
community/aqua/optimization/maxcut.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Now we want VQE and so change it and add its other configuration parameters. VQE also needs and optimizer and variational form. While we can omit them from the dictionary, such that defaults are used, here we specify them explicitly so we can set their parameters as we desire.
if 'VQE' not in operational_algos: print("VQE is not in operational algorithms.") else: algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': ...
community/aqua/optimization/maxcut.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Let's set up a synthetic data-set just to show that the COBRA estimator is scikit-learn compatible.
# setting up our random data-set rng = np.random.RandomState(1) # D1 = train machines; D2 = create COBRA; D3 = calibrate epsilon, alpha; D4 = testing n_features = 20 D1, D2, D3, D4 = 200, 200, 200, 200 D = D1 + D2 + D3 + D4 X = rng.uniform(-1, 1, D * n_features).reshape(D, n_features) Y = np.power(X[:,1], 2) + np.powe...
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Similar to other scikit-learn estimators, we set up our machine by creating an object and then fitting it. Since we are not passing an Epsilon value, we pass data to find an optimal epsilon value while instantiating our object. The optimal epsilon is found through the scikit-learn CVGridSearch. The grid_points paramet...
cobra = Cobra() cobra.set_epsilon(X_epsilon=X_eps, y_epsilon=Y_eps, grid_points=5) cobra.epsilon cobra.fit(X_train, Y_train)
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
We now see if our object can fit into the scikit-learn pipeline and GridSearch - and it can!
from sklearn.utils.estimator_checks import check_estimator check_estimator(Cobra) #passes
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Exponentially Weighted Average Aggregate Let us also demonstrate the EWA predictor. You can read more about it over here in the paper by A. Dalalyan and A. B. Tsybakov.
ewa = Ewa() ewa.set_beta(X_beta=X_eps, y_beta=Y_eps)
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
If we fit EWA without passing beta, we perform a CV to find the optimal beta.
ewa.fit(X_train, Y_train) check_estimator(Ewa) #passes
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
EWA assigns weights to each machine based on it's MSE. We can check the weights of each machine with the plot_machine_weights method.
ewa.plot_machine_weights() ewa.machine_weight_
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Like the Cobra estimator, Ewa is also a scikit-learn compatible estimator. It also fits into the Visualisation class, like demonstrated in the notebook. Predicting? Like the other scikit-learn predictors, we estimate on data by simply using the predict() method.
query = X_test[0].reshape(1, -1) cobra.predict(query) ewa.predict(query)
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Why pycobra? There are scikit-learn estimators which already perform well in basic regression tasks - why use pycobra? The Cobra estimator has the advantage of a theoretical bound on its performance - this means it is supposed to perform at least as well as the estimators used to create it, up to a remainder term which...
from sklearn import datasets from sklearn.metrics import accuracy_score bc = datasets.load_breast_cancer() X = bc.data[:-20] y = bc.target[:-20] X_test = bc.data[-20:] y_test = bc.target[-20:] from pycobra.classifiercobra import ClassifierCobra check_estimator(ClassifierCobra) cc = ClassifierCobra() cc.fit(X, y) cc...
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Let's see how it works in a practical case.
cc_diag = Diagnostics(cc, X_test, y_test) cc_diag.load_errors() cc_diag.machine_error
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Quite well! Real-world datasets We have demonstrated in the regression notebook how pycobra works on synthetic data-sets. Let's see pycobra in action on some scikit-learn regression datasets.
diabetes = datasets.load_diabetes() diabetes_X_train = diabetes.data[:-40] diabetes_X_test = diabetes.data[-20:] # part of the data to find an appropriate epsilon diabetes_X_eps = diabetes.data[-40:-20] diabetes_y_train = diabetes.target[:-40] diabetes_y_test = diabetes.target[-20:] diabetes_y_eps = diabetes.target[-...
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
We're unaware of what epsilon value to choose for our data-sets so by passing X_eps and y_eps we can get an idea of what might be a good epsilon value.
COBRA_diabetes = Cobra() COBRA_diabetes.set_epsilon(X_epsilon=diabetes_X_eps, y_epsilon=diabetes_y_eps, grid_points=50) COBRA_diabetes.fit(diabetes_X_train, diabetes_y_train)
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Predicting using the COBRA predictor is again similar to using a scikit-learn estimator.
COBRA_diabetes.predict(diabetes_X_test)
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Let's compare our MSEs using the diagnostics class now.
cobra_diagnostics = Diagnostics(COBRA_diabetes, diabetes_X_test, diabetes_y_test, load_MSE=True) cobra_diagnostics.machine_MSE
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
Let us similarily use COBRA on the Boston housing data set.
boston = datasets.load_boston() boston_X_train = boston.data[:-40] boston_X_test = boston.data[-20:] boston_X_eps = boston.data[-40:-20] boston_y_train = boston.target[:-40] boston_y_test = boston.target[-20:] boston_y_eps = boston.target[-40:-20] COBRA_boston = Cobra() COBRA_boston.set_epsilon(X_epsilon=boston_X_ep...
docs/notebooks/pycobra.ipynb
bhargavvader/pycobra
mit
PhIP-Seq kinetics computations Reaction summary IP reaction (1 mL) * IgG * MW of IgG = 150 kDa * 2 µg IgG = 13.3 pmol = 8.03e12 molecules * 13.3 nM in the reaction * Phage * 100k particles per clone on average * Add ~1e10 total particles per mL reaction * 5k - 50k of each clone per reaction ...
df = pd.read_csv('/Users/laserson/lasersonlab/larman/libraries/T7-Pep_InputCountsComplete46M.csv', header=None, index_col=0) counts = df.values.ravel() sns.distplot(counts)
notebooks/phip_modeling/phip-kinetic-computations.ipynb
laserson/phip-stat
apache-2.0
(min, 10%ile, 50%ile, 90%ile, max)
iles = (counts.min(), sp.stats.scoreatpercentile(counts, 10), sp.stats.scoreatpercentile(counts, 50), sp.stats.scoreatpercentile(counts, 90), counts.max()) iles cov = sum(counts) cov
notebooks/phip_modeling/phip-kinetic-computations.ipynb
laserson/phip-stat
apache-2.0
And the same values as frequencies
tuple([float(val) / cov for val in iles]) counts.mean(), counts.std() (18. / cov) * 1e10 (229. / cov) * 1e10 (counts > 0).sum() counts.shape def equil_conc(total_antibody, total_phage, Kd): s = total_antibody + total_phage + Kd bound = 0.5 * (s - np.sqrt(s * s - 4 * total_antibody * total_phage)) equi...
notebooks/phip_modeling/phip-kinetic-computations.ipynb
laserson/phip-stat
apache-2.0
It's most important to ensure we get maximal phage capture, and this seems to be independent of the total phage concentration. Let's instead explore the fraction phage bound as a function of the antibody concentration and Kd
antibody_concentrations = np.logspace(-15, -3, num=25) Kds = np.logspace(-15, -6, num=19) antibody_labels = ['{:.1e}'.format(c) for c in antibody_concentrations] Kd_labels = ['{:.1e}'.format(c) for c in Kds] phage_concentration = 2e-15 frac_antibody_bound = np.zeros((len(antibody_concentrations), len(Kds))) frac_phag...
notebooks/phip_modeling/phip-kinetic-computations.ipynb
laserson/phip-stat
apache-2.0
Implementation: Data Exploration Let's begin by investigating the dataset to determine how many students we have information on, and learn about the graduation rate among these students. In the code cell below, you will need to compute the following: - The total number of students, n_students. - The total number of fea...
# TODO: Calculate number of students n_students = None # TODO: Calculate number of features n_features = None # TODO: Calculate passing students n_passed = None # TODO: Calculate failing students n_failed = None # TODO: Calculate graduation rate grad_rate = None # Print the results print "Total number of students:...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit
Preparing the Data In this section, we will prepare the data for modeling, training and testing. Identify feature and target columns It is often the case that the data you obtain contains non-numeric features. This can be a problem, as most machine learning algorithms expect numeric data to perform computations with. R...
# Extract feature columns feature_cols = list(student_data.columns[:-1]) # Extract target column 'passed' target_col = student_data.columns[-1] # Show the list of columns print "Feature columns:\n{}".format(feature_cols) print "\nTarget column: {}".format(target_col) # Separate the data into feature data and target...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit
Preprocess Feature Columns As you can see, there are several non-numeric columns that need to be converted! Many of them are simply yes/no, e.g. internet. These can be reasonably converted into 1/0 (binary) values. Other columns, like Mjob and Fjob, have more than two values, and are known as categorical variables. The...
def preprocess_features(X): ''' Preprocesses the student data and converts non-numeric binary variables into binary (0/1) variables. Converts categorical variables into dummy variables. ''' # Initialize new output DataFrame output = pd.DataFrame(index = X.index) # Investigate each feature ...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit
Implementation: Training and Testing Data Split So far, we have converted all categorical features into numeric values. For the next step, we split the data (both features and corresponding labels) into training and test sets. In the following code cell below, you will need to implement the following: - Randomly shuffl...
# TODO: Import any additional functionality you may need here # TODO: Set the number of training points num_train = None # Set the number of testing points num_test = X_all.shape[0] - num_train # TODO: Shuffle and split the dataset into the number of training and testing points above X_train = None X_test = None y_t...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit
Training and Evaluating Models In this section, you will choose 3 supervised learning models that are appropriate for this problem and available in scikit-learn. You will first discuss the reasoning behind choosing these three models by considering what you know about the data and each model's strengths and weaknesses....
def train_classifier(clf, X_train, y_train): ''' Fits a classifier to the training data. ''' # Start the clock, train the classifier, then stop the clock start = time() clf.fit(X_train, y_train) end = time() # Print the results print "Trained model in {:.4f} seconds".format(end - s...
Machine learning Nanodegree/student_intervention/student_intervention.ipynb
isamu-isozaki/Machine-Learning
mit