markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Train Deep Learning model and validate on test set
from h2o.estimators.deepwater import H2ODeepWaterEstimator model = H2ODeepWaterEstimator( distribution="multinomial", activation="rectifier", mini_batch_size=128, hidden=[1024,1024], hidden_dropout_ratios=[0.5,0.5], ## for better generalization input_dropout_ratio=0.1, sparse=True, ## can result in speedup for sparse data epochs=10) ## need more epochs for a better model model.train( x=x, y=y, training_frame=train_df, validation_frame=test_df ) model.scoring_history() model.model_performance(train=True) # training metrics model.model_performance(valid=True) # validation metrics
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Inspect the model in Flow It is highly recommended to use Flow to visualize the model training process and to inspect the model before using it for further steps. Using Crossvalidation If the value specified for nfolds is a positive integer, N-fold cross-validation is performed on the training frame and the cross-validation metrics are computed and stored as model output. To disable cross-validation, use nfolds=0, which is the default value. Advanced users can also specify a fold column that defines the holdout fold associated with each row. By default, the holdout fold assignment is random. H2O supports other schemes such as round-robin assignment using the modulo operator. Perform 3-fold cross-validation on training_frame
model_crossvalidated = H2ODeepWaterEstimator( distribution="multinomial", activation="rectifier", mini_batch_size=128, hidden=[1024,1024], hidden_dropout_ratios=[0.5,0.5], input_dropout_ratio=0.1, sparse=True, epochs=10, nfolds=3 ) model_crossvalidated.train( x=x, y=y, training_frame=train_df )
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Extracting and Handling the Results We can now extract the parameters of our model, examine the scoring process, and make predictions on new data.
# View specified parameters of the Deep Learning model model_crossvalidated.params; # Examine the trained model model_crossvalidated
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Note: The validation error is based on the parameter score_validation_samples, which can be used to sample the validation set (by default, the entire validation set is used).
## Validation error of the original model (using a train/valid split) model.mean_per_class_error(valid=True) ## Training error of the model trained on 100% of the data model_crossvalidated.mean_per_class_error(train=True) ## Estimated generalization error of the cross-validated model model_crossvalidated.mean_per_class_error(xval=True)
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Clearly, the model parameters aren't tuned perfectly yet, as 4-5% test set error is rather large.
#ls ../../h2o-docs/src/booklets/v2_2015/source/images/
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Predicting Once we have a satisfactory model (as determined by the validation or crossvalidation metrics), use the h2o.predict() command to compute and store predictions on new data for additional refinements in the interactive data science process.
predictions = model_crossvalidated.predict(test_df) predictions.describe()
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Variable Importance Variable importance allows us to view the absolute and relative predictive strength of each feature in the prediction task. Each H2O algorithm class has its own methodology for computing variable importance. You can enable the variable importance, by setting the variable_importances parameter to True. H2O’s Deep Learning uses the Gedeon method Gedeon, 1997, which is disabled by default since it can be slow for large networks. If variable importance is a top priority in your analysis, consider training a Distributed Random Forest (DRF) model and compare the generated variable importances.
# Train Deep Learning model and validate on test set and save the variable importances from h2o.estimators.deeplearning import H2ODeepLearningEstimator ## H2ODeepWaterEstimator doesn't yet have variable importances model_variable_importances = H2ODeepLearningEstimator( distribution="multinomial", activation="RectifierWithDropout", ## shortcut for hidden_dropout_ratios=[0.5,0.5,0.5] hidden=[32,32,32], ## smaller number of neurons to be fast enough on the CPU input_dropout_ratio=0.1, sparse=True, epochs=1, ## not interested in a good model here variable_importances=True) ## this is not yet implemented for DeepWaterEstimator model_variable_importances.train( x=x, y=y, training_frame=train_df, validation_frame=test_df) # Retrieve the variable importance import pandas as pd pd.DataFrame(model_variable_importances.varimp()) model_variable_importances.varimp_plot(num_of_features=20)
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Model Comparison with Grid Search Grid search provides more subtle insights into the model tuning and selection process by inspecting and comparing our trained models after the grid search process is complete. To learn when and how to select different parameter configurations in a grid search, refer to Parameters for parameter descriptions and configurable values. There are different strategies to explore the hyperparameter combinatorial space: Cartesian Search: test every single combination Random Search: sample combinations Cartesian Search In this example, two different network topologies and two different learning rates are specified. This grid search model trains all 4 different models (all possible combinations of these parameters); other parameter combinations can be specified for a larger space of models. Note that the models will most likely converge before the default value of epochs, since early stopping is enabled.
from h2o.grid.grid_search import H2OGridSearch hyper_parameters = { "hidden":[[200,200,200],[300,300]], "learning_rate":[1e-3,5e-3], } model_grid = H2OGridSearch(H2ODeepWaterEstimator, hyper_params=hyper_parameters) model_grid.train( x=x, y=y, distribution="multinomial", epochs=50, ## might stop earlier since we enable early stopping below training_frame=train_df, validation_frame=test_df, score_interval=2, ## score no more than every 2 seconds score_duty_cycle=0.5, ## score up to 50% of the time - to enable early stopping score_training_samples=1000, ## use a subset of the training frame for faster scoring score_validation_samples=1000, ## use a subset of the validation frame for faster scoring stopping_rounds=3, stopping_tolerance=0.05, stopping_metric="misclassification", sparse = True, mini_batch_size=256 ) # print model grid search results model_grid for gmodel in model_grid: print gmodel.model_id + " mean per class error: " + str(gmodel.mean_per_class_error()) import pandas as pd grid_results = pd.DataFrame([[m.model_id, m.mean_per_class_error(valid=True)] for m in model_grid]) grid_results
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Random Grid Search If the search space is too large you can let the GridSearch algorithm select the parameter, by sampling from the parameter space. Just specify how many models (and/or how much training time) you want, and provide a seed to make the random selection deterministic.
hyper_parameters = { "hidden":[[1000,1000],[2000]], "learning_rate":[s*1e-3 for s in range(30,100)], "momentum_start":[s*1e-3 for s in range(0,900)], "momentum_stable":[s*1e-3 for s in range(900,1000)], } search_criteria = {"strategy":"RandomDiscrete", "max_models":10, "max_runtime_secs":100, "seed":123456} model_grid_random_search = H2OGridSearch(H2ODeepWaterEstimator, hyper_params=hyper_parameters, search_criteria=search_criteria) model_grid_random_search.train( x=x, y=y, distribution="multinomial", epochs=50, ## might stop earlier since we enable early stopping below training_frame=train_df, validation_frame=test_df, score_interval=2, ## score no more than every 2 seconds score_duty_cycle=0.5, ## score up to 50% of the wall clock time - scoring is needed for early stopping score_training_samples=1000, ## use a subset of the training frame for faster scoring score_validation_samples=1000, ## use a subset of the validation frame for faster scoring stopping_rounds=3, stopping_tolerance=0.05, stopping_metric="misclassification", sparse = True, mini_batch_size=256) grid_results = pd.DataFrame([[m.model_id, m.mean_per_class_error(valid=True)] for m in model_grid_random_search]) grid_results
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Model Checkpoints H2O supporst model checkpoints. You can store the state of training and resume it later. Checkpointing can be used to reload existing models that were saved to disk in a previous session. To resume model training, use checkpoint model keys (model id) to incrementally train a specific model using more iterations, more data, different data, and so forth. To further train the initial model, use it (or its key) as a checkpoint argument for a new model. To improve this initial model, start from the previous model and add iterations by building another model, specifying checkpoint=previous model id, and changing train samples per iteration, target ratio comm to comp, or other parameters. Many parameters can be changed between checkpoints, especially those that affect regularization or performance tuning. You can use GridSearch with checkpoint restarts to scan a broader range of hyperparameter combinations.
# Re-start the training process on a saved DL model using the ‘checkpoint‘ argument model_checkpoint = H2ODeepWaterEstimator( checkpoint=model.model_id, activation="rectifier", distribution="multinomial", mini_batch_size=128, hidden=[1024,1024], hidden_dropout_ratios=[0.5,0.5], input_dropout_ratio=0.1, sparse=True, epochs=20) ## previous model had 10 epochs, so we need to only train for 10 more to get to 20 epochs model_checkpoint.train( x=x, y=y, training_frame=train_df, validation_frame=test_df) model_checkpoint.scoring_history()
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Specify a model and a file path. The default path is the current working directory.
model_path = h2o.save_model( model = model, #path = "/tmp/mymodel", force = True) print model_path !ls -lah $model_path
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
After restarting H2O, you can load the saved model by specifying the host and model file path. Note: The saved model must be the same version used to save the model.
# Load model from disk saved_model = h2o.load_model(model_path)
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
You can also use the following commands to retrieve a model from its H2O key. This is useful if you have created an H2O model using the web interface and want to continue the modeling process in another language, for example R.
# Retrieve model by H2O key model = h2o.get_model(model_id=model_checkpoint._id) model
examples/deeplearning/notebooks/deeplearning_mnist_introduction.ipynb
mathemage/h2o-3
apache-2.0
Communities are just as important in the social structure of novels as they are in real-world social structures. They're also just as obvious - it's easy to think of a tight cluster of characters in your favourite novel which are isolated from the rest of the story. Visually, they're also quite apparent. Refer back to the Dursley's little clique which we saw back in notebook 3. However, NetworkX's clique finding algorithm isn't ideal - it enumerates all cliques, giving us plenty of overlapping cliques which aren't that descriptive of the existing communities. In mathematical terms, we want to maximise the modularity of the whole graph at once. A cleaner solution to our problem is the python implementation of louvain community detection given here by Thomas Aynaud.
import community
05 - Cliques and Communities.ipynb
harrisonpim/bookworm
mit
This implementation of louvain modularity is a very smart piece of maths, first given by Blondel et al in Fast unfolding of communities in large networks. If you're not a mathematical reader, just skip over this section and go straight to the results. If you are interested in the maths, it goes roughly like this: We want to calculate a value Q between -1 and 1 for a partition of our graph, where $Q$ denotes the modularity of the network. Modularity is a comparative measure of the density within the communities in question and the density between them. A high modularity indicates a good splitting. Through successive, gradual changes to our labelling of nodes and close monitoring of the value of $Q$, we can optimise our partition(s). $Q$ and its change for each successve optimisation epoch ($\Delta Q$) are calculated in two stages, as follows. $$ Q = \frac{1}{2m} \sum_{ij} \left[\ A_{ij}\ \frac{k_i k_j}{2m}\ \right]\ \delta(c_i, c_j) $$ $m$ is the sum of all of the edge weights in the graph $A_{ij}$ represents the edge weight between nodes $i$ and $j$ $k_{i}$ and $k_{j}$ are the sum of the weights of the edges attached to nodes $i$ and $j$, respectively $\delta$ is the delta function. $c_{i}$ and $c_{j}$ are the communities of the nodes First, each node in the network is assigned to its own community. Then for each node $i$, the change in modularity is calculated by removing $i$ from its own community and moving it into the community of each neighbor $j$ of $i$: $$ \Delta Q = \left[\frac{\sum_{in} +\ k_{i,in}}{2m} - \left(\frac{\sum_{tot} +\ k_{i}}{2m}\right)^2 \right] - \left[ \frac{\sum_{in}}{2m} - \left(\frac{\sum_{tot}}{2m}\right)^2 - \left(\frac{k_{i}}{2m}\right)^2 \right] $$ $\sum_{in}$ is sum of all the weights of the links inside the community $i$ is moving into $k_{i,in}$ is the sum of the weights of the links between $i$ and other nodes in the community $m$ is the sum of the weights of all links in the network $\Sigma _{tot}$ is the sum of all the weights of the links to nodes in the community $k_{i}$ is the weighted degree of $i$ Once this value is calculated for all communities that $i$ is connected to, $i$ is placed into the community that resulted in the greatest modularity increase. If no increase is possible, $i$ remains in its original community. This process is applied repeatedly and sequentially to all nodes until no modularity increase can occur. Once this local maximum of modularity is hit, we move on to the second stage. All of the nodes in the same community are grouped to create a new network, where nodes are the communities from the previous phase. Links between nodes within communities are represented by self loops on these new community nodes, and links from multiple nodes in the same community to a node in a different community are represented by weighted edges. The first stage is then applied to this new weighted network, and the process repeats. Actually doing the thing Let's load in a book and try applying python-louvain's implementation of this algorithm to it:
book = nx.from_pandas_dataframe(bookworm('data/raw/hp_chamber_of_secrets.txt'), source='source', target='target') partitions = community.best_partition(book) values = [partitions.get(node) for node in book.nodes()] nx.draw(book, cmap=plt.get_cmap("RdYlBu"), node_color=values, with_labels=True)
05 - Cliques and Communities.ipynb
harrisonpim/bookworm
mit
Sweet - that works nicely. We can wrap this up neatly into a single function call
def draw_with_communities(book): ''' draw a networkx graph with communities partitioned and coloured according to their louvain modularity Parameters ---------- book : nx.Graph (required) the book graph to be visualised ''' partitions = community.best_partition(book) values = [partitions.get(node) for node in book.nodes()] nx.draw(book, cmap=plt.get_cmap("RdYlBu"), node_color=values, with_labels=True) book = nx.from_pandas_dataframe(bookworm('data/raw/fellowship_of_the_ring.txt'), source='source', target='target') draw_with_communities(book)
05 - Cliques and Communities.ipynb
harrisonpim/bookworm
mit
1-D series
s = pd.Series([3, 5, 67, 2, 4]) s s.name = "OneDArray" s s.index s.values s.sum() s.min() s.count() s * 3 s.sort_values() s.value_counts() s.abs?
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
DataFrame
eu = pd.read_csv('data/eu_revolving_loans.csv', header=[1,2,3], index_col=0, skiprows=1) eu.tail(4) eu.index eu.columns eu.shape eu.min(axis=1) eu.min() eu * 3 %pylab inline eu.plot(legend=False)
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
Data types: dtypes DataFrame is built on Numpy -- and uses the same data type representations.
eu.dtypes
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
converting types If you try to "cast" the value for Slovenia, you will get an error eu['Slovenia'].astype('float') This is due to an empty "n/a" value. missing values Let's re-read the dataset setting expected "na" values:
eu = pd.read_csv('data/eu_revolving_loans.csv', header=[1,2,3], index_col=0, skiprows=1, na_values=['-']) eu.dtypes
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
Filtering with Pandas
trade = pd.read_csv('data/ext_lt_intratrd.tsv', sep='\t') trade.dtypes trade.columns # expect an key error below due to extra spaces in names trade['2013'] new_cols = dict([(col, col.strip()) for col in trade.columns]) new_cols trade.rename(columns=new_cols) trade = trade.rename(columns=new_cols) trade['2013'] # selecting row 3 trade.ix[3] # selecting all rows where column index = 0 trade.ix[:,0] # split out the column with index 0 & assign to new column 'geo' # representing the country 2 letter code trade['geo'] = trade.ix[:,0].map(lambda row: row.split(',')[-1]) trade['geo'].head() trade['geo'].isin(['UK', 'DE']) trade[trade['geo'].isin(['UK', 'DE'])] # boolean selecting with more complex boolean expressions # - find all countries where there are continuous growth from 2012-2014 trade[(trade['2014'] > trade['2013']) & (trade['2013'] > trade['2012'])] # create a column that represents those with increase from 2012 - 2013 trade['2013inc'] = trade['2013'] > trade['2012'] trade['2013inc'].head()
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
Creating a new index not on the values but on the 2 letter geo-code column
trade = trade.set_index('geo') # now filter based on the geo column trade.loc['DE']
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
Row index with "iloc" method
# now filter based on row index for the top 100 rows trade.iloc[:100]
lecture03.numpy.pandas/lecture03.pandas.ipynb
philmui/datascience2016fall
mit
Loading events from a Noddy history In the current set-up of pynoddy, we always start with a pre-defined Noddy history loaded from a file, and then change aspects of the history and the single events. The first step is therefore to load the history file and to extract the single geological events. This is done automatically as default when loading the history file into the History object:
import sys, os import matplotlib.pyplot as plt # adjust some settings for matplotlib from matplotlib import rcParams # print rcParams rcParams['font.size'] = 15 # determine path of repository to set paths corretly below repo_path = os.path.realpath('../..') sys.path.append(repo_path) import pynoddy import pynoddy.history import pynoddy.events import pynoddy.output # reload(pynoddy) # Change to sandbox directory to store results os.chdir(os.path.join(repo_path, 'sandbox')) # Path to exmaple directory in this repository example_directory = os.path.join(repo_path,'examples') # Compute noddy model for history file history = 'simple_two_faults.his' history_ori = os.path.join(example_directory, history) output_name = 'noddy_out' # reload(pynoddy.history) # reload(pynoddy.events) H1 = pynoddy.history.NoddyHistory(history_ori) # Before we do anything else, let's actually define the cube size here to # adjust the resolution for all subsequent examples H1.change_cube_size(100) # compute model - note: not strictly required, here just to ensure changed cube size H1.write_history(history) pynoddy.compute_model(history, output_name)
docs/notebooks/3-Events.ipynb
flohorovicic/pynoddy
gpl-2.0
Changing aspects of geological events So what we now want to do, of course, is to change aspects of these events and to evaluate the effect on the resulting geological model. Parameters can directly be updated in the properties dictionary:
H1 = pynoddy.history.NoddyHistory(history_ori) # get the original dip of the fault dip_ori = H1.events[3].properties['Dip'] # add 10 degrees to dip add_dip = -20 dip_new = dip_ori + add_dip # and assign back to properties dictionary: H1.events[3].properties['Dip'] = dip_new # H1.events[2].properties['Dip'] = dip_new1 new_history = "dip_changed" new_output = "dip_changed_out" H1.write_history(new_history) pynoddy.compute_model(new_history, new_output) # load output from both models NO1 = pynoddy.output.NoddyOutput(output_name) NO2 = pynoddy.output.NoddyOutput(new_output) # create basic figure layout fig = plt.figure(figsize = (15,5)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) NO1.plot_section('y', position=0, ax = ax1, colorbar=False, title="Dip = %.0f" % dip_ori, savefig=True, fig_filename ="tmp.eps") NO2.plot_section('y', position=1, ax = ax2, colorbar=False, title="Dip = %.0f" % dip_new) plt.show()
docs/notebooks/3-Events.ipynb
flohorovicic/pynoddy
gpl-2.0
Let's import dependencies first.
import os, sys import time import nnabla as nn from nnabla.ext_utils import get_extension_context import nnabla.functions as F import nnabla.parametric_functions as PF import nnabla.solvers as S import numpy as np import functools import nnabla.utils.save as save from utils.neu.checkpoint_util import save_checkpoint, load_checkpoint from utils.neu.save_nnp import save_nnp
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
We then define a data iterator for Cifar-10. When called, it'll also download the dataset, and pass the samples to the network during training.
from contextlib import contextmanager import struct import tarfile import zlib import errno from nnabla.logger import logger from nnabla.utils.data_iterator import data_iterator from nnabla.utils.data_source import DataSource from nnabla.utils.data_source_loader import download, get_data_home class Cifar10DataSource(DataSource): ''' Get data directly from cifar10 dataset from Internet(yann.lecun.com). ''' def _get_data(self, position): image = self._images[self._indexes[position]] label = self._labels[self._indexes[position]] return (image, label) def __init__(self, train=True, shuffle=False, rng=None): super(Cifar10DataSource, self).__init__(shuffle=shuffle, rng=rng) self._train = train data_uri = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" logger.info('Getting labeled data from {}.'.format(data_uri)) r = download(data_uri) # file object returned with tarfile.open(fileobj=r, mode="r:gz") as fpin: # Training data if train: images = [] labels = [] for member in fpin.getmembers(): if "data_batch" not in member.name: continue fp = fpin.extractfile(member) data = np.load(fp, encoding="bytes", allow_pickle=True) images.append(data[b"data"]) labels.append(data[b"labels"]) self._size = 50000 self._images = np.concatenate( images).reshape(self._size, 3, 32, 32) self._labels = np.concatenate(labels).reshape(-1, 1) # Validation data else: for member in fpin.getmembers(): if "test_batch" not in member.name: continue fp = fpin.extractfile(member) data = np.load(fp, encoding="bytes", allow_pickle=True) images = data[b"data"] labels = data[b"labels"] self._size = 10000 self._images = images.reshape(self._size, 3, 32, 32) self._labels = np.array(labels).reshape(-1, 1) r.close() logger.info('Getting labeled data from {}.'.format(data_uri)) self._size = self._labels.size self._variables = ('x', 'y') if rng is None: rng = np.random.RandomState(313) self.rng = rng self.reset() def reset(self): if self._shuffle: self._indexes = self.rng.permutation(self._size) else: self._indexes = np.arange(self._size) super(Cifar10DataSource, self).reset() @property def images(self): """Get copy of whole data with a shape of (N, 1, H, W).""" return self._images.copy() @property def labels(self): """Get copy of whole label with a shape of (N, 1).""" return self._labels.copy() def data_iterator_cifar10(batch_size, train=True, rng=None, shuffle=True, with_memory_cache=False, with_file_cache=False): ''' Provide DataIterator with :py:class:`Cifar10DataSource` with_memory_cache and with_file_cache option's default value is all False, because :py:class:`Cifar10DataSource` is able to store all data into memory. ''' return data_iterator(Cifar10DataSource(train=train, shuffle=shuffle, rng=rng), batch_size, rng, with_memory_cache, with_file_cache) def categorical_error(pred, label): pred_label = pred.argmax(1) return (pred_label != label.flat).mean()
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
We now define our neural network. In this example, we employ a slightly modified architecture based on ResNet. We are also performing data augmentation here.
def resnet23_prediction(image, test=False, ncls=10, nmaps=64, act=F.relu): """ Construct ResNet 23 """ # Residual Unit def res_unit(x, scope_name, dn=False): C = x.shape[1] with nn.parameter_scope(scope_name): # Conv -> BN -> Nonlinear with nn.parameter_scope("conv1"): h = PF.convolution(x, C // 2, kernel=(1, 1), pad=(0, 0), with_bias=False) h = PF.batch_normalization(h, batch_stat=not test) h = act(h) # Conv -> BN -> Nonlinear with nn.parameter_scope("conv2"): h = PF.convolution(h, C // 2, kernel=(3, 3), pad=(1, 1), with_bias=False) h = PF.batch_normalization(h, batch_stat=not test) h = act(h) # Conv -> BN with nn.parameter_scope("conv3"): h = PF.convolution(h, C, kernel=(1, 1), pad=(0, 0), with_bias=False) h = PF.batch_normalization(h, batch_stat=not test) # Residual -> Nonlinear h = act(F.add2(h, x, inplace=True)) # Maxpooling if dn: h = F.max_pooling(h, kernel=(2, 2), stride=(2, 2)) return h # Conv -> BN -> Nonlinear with nn.parameter_scope("conv1"): # Preprocess if not test: image = F.image_augmentation(image, contrast=1.0, angle=0.25, flip_lr=True) image.need_grad = False h = PF.convolution(image, nmaps, kernel=(3, 3), pad=(1, 1), with_bias=False) h = PF.batch_normalization(h, batch_stat=not test) h = act(h) h = res_unit(h, "conv2", False) # -> 32x32 h = res_unit(h, "conv3", True) # -> 16x16 h = res_unit(h, "conv4", False) # -> 16x16 h = res_unit(h, "conv5", True) # -> 8x8 h = res_unit(h, "conv6", False) # -> 8x8 h = res_unit(h, "conv7", True) # -> 4x4 h = res_unit(h, "conv8", False) # -> 4x4 h = F.average_pooling(h, kernel=(4, 4)) # -> 1x1 pred = PF.affine(h, ncls) return pred
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
Define our loss function, which in this case is the mean of softmax cross entropy, computed from the predictions and the labels.
def loss_function(pred, label): loss = F.mean(F.softmax_cross_entropy(pred, label)) return loss
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
We are almost ready to start training! Let's define some hyper-parameters for the training.
n_train_samples = 50000 batch_size = 64 bs_valid = 64 #batch size for validation extension_module = 'cudnn' ctx = get_extension_context( extension_module) nn.set_default_context(ctx) prediction = functools.partial( resnet23_prediction, ncls=10, nmaps=64, act=F.relu)
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
We then create our training and validation graphs. Note that labels are not provided for validation.
# Create training graphs test = False image_train = nn.Variable((batch_size, 3, 32, 32)) label_train = nn.Variable((batch_size, 1)) pred_train = prediction(image_train, test) loss_train = loss_function(pred_train, label_train) input_image_train = {"image": image_train, "label": label_train} # Create validation graph test = True image_valid = nn.Variable((bs_valid, 3, 32, 32)) pred_valid = prediction(image_valid, test) input_image_valid = {"image": image_valid}
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
Let's also define our solver. We employ Adam in this example, but other solvers can be used too. Let's also define monitor variables to keep track of the progress during training. Note that, if you want to load previously saved weight parameters, you can load it using load_checkpoint.
# Solvers solver = S.Adam() solver.set_parameters(nn.get_parameters()) start_point = 0 # If necessary, load weights and solver state info from specified checkpoint file. # start_point = load_checkpoint(specified_checkpoint, solver) # Create monitor from nnabla.monitor import Monitor, MonitorSeries, MonitorTimeElapsed monitor = Monitor('tmp.monitor') monitor_loss = MonitorSeries("Training loss", monitor, interval=10) monitor_err = MonitorSeries("Training error", monitor, interval=10) monitor_time = MonitorTimeElapsed("Training time", monitor, interval=10) monitor_verr = MonitorSeries("Test error", monitor, interval=1)
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
We define data iterator variables separately for training and validation, using the data iterator we defined earlier. Note that the second argument is different for each variable, depending whether it is for training or validation.
# Data Iterator tdata = data_iterator_cifar10(batch_size, True) vdata = data_iterator_cifar10(batch_size, False) # save intermediate weights if you need #contents = save_nnp({'x': image_valid}, {'y': pred_valid}, batch_size) #save.save(os.path.join('tmp.monitor', # '{}_epoch0_result.nnp'.format('cifar10_resnet23')), contents)
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
We are good to go now! Start training, get a coffee, and watch how the training loss and test error decline as the training proceeds.
max_iter = 40000 val_iter = 100 model_save_interval = 10000 model_save_path = 'tmp.monitor' # Training-loop for i in range(start_point, max_iter): # Validation if i % int(n_train_samples / batch_size) == 0: ve = 0. for j in range(val_iter): image, label = vdata.next() input_image_valid["image"].d = image pred_valid.forward() ve += categorical_error(pred_valid.d, label) ve /= val_iter monitor_verr.add(i, ve) if int(i % model_save_interval) == 0: # save checkpoint file save_checkpoint(model_save_path, i, solver) # Forward/Zerograd/Backward image, label = tdata.next() input_image_train["image"].d = image input_image_train["label"].d = label loss_train.forward() solver.zero_grad() loss_train.backward() # Solvers update solver.update() e = categorical_error( pred_train.d, input_image_train["label"].d) monitor_loss.add(i, loss_train.d.copy()) monitor_err.add(i, e) monitor_time.add(i) nn.save_parameters(os.path.join(model_save_path, 'params_%06d.h5' % (max_iter))) # save_nnp_lastepoch contents = save_nnp({'x': image_valid}, {'y': pred_valid}, batch_size) save.save(os.path.join(model_save_path, '{}_result.nnp'.format('cifar10_resnet23')), contents)
tutorial/cifar10_classification.ipynb
sony/nnabla
apache-2.0
Target Densities Recall that we expect with the current target selection algorithms (which will be tested extensively during Survey Validation) to obtain spectra of, on average, 120 tracer QSOs/deg2 (i.e., QSOs at z<2.1), 50 Lya QSOs/deg2 (i.e., QSOs at z>2.1), and 90 contaminants/deg2. Very roughly, approximately two-thirds of these contaminants will be stars and the remainder will be intermediate-redshift galaxies. However, a more detailed analyis of the Galactic and extragalactic objects expected to contaminate QSO target selection is clearly needed. Brief recap: how do we generate spectra for (mock) QSO targets? Start with cosmological mocks which have RA, Dec, and redshift: Tracer QSOs: DarkSky/v1.0.1 Lya QSOs: london/v4.2.0 The two mocks are stiched together precisely at z=1.8 (including RSD) to avoid double-counting. Use desisim.templates.SIMQSO to generate (continuum) spectra at the input redshift. Under the hood, we draw from the BOSS/DR9 QSO luminosity function to get the apparent (normalization) magnitude of each QSO (accounting for the K-correction) and to synthesize (noiseless) grzW1W2 photometry. We perturb the photometry given the depth of our imaging and iteratively apply the latest target selection criteria (using color-cuts, not random forest) until we achieve the desired target density. For the Lya QSOs target selection cuts are applied after Lya forest, BALs, etc. are included. Finally, we write out targets.fits and truth.fits files (and spectra) with all the relevant catalog and ancillary data.
from desitarget.mock.mockmaker import QSOMaker, LYAMaker QSO = QSOMaker() data_tracer = QSO.read(only_coords=True, zmax_qso=1.8) qso_density = QSO.mock_density(QSO.default_mockfile)
projects/desi/lya/18dec19/mock-contaminants-qso.ipynb
moustakas/impy
gpl-2.0
Note that in general all the cosmological mocks are oversampled, so we have to subsample by a constant fraction in order to preserve the large-scale structure signal. For example, we downsample the DarkSky/QSO mock by an average factor of 0.35 from 340/deg2 to 120/deg2.
log.info(QSO.default_mockfile) log.info('Average density = {:.3f} QSO/deg2'.format(qso_density)) QSO.qamock_sky(data_tracer) LYA = LYAMaker() mockfile = os.path.join(os.getenv('DESI_ROOT'), 'mocks', 'lya_forest', 'london', 'v4.2.0', 'master.fits') data_lya = LYA.read(mockfile=mockfile, only_coords=True, zmax_qso=1.8) lya_density = LYA.mock_density(mockfile) log.info(mockfile) log.info('Average density = {:.3f} LYa QSO/deg2'.format(lya_density)) LYA.qamock_sky(data_lya)
projects/desi/lya/18dec19/mock-contaminants-qso.ipynb
moustakas/impy
gpl-2.0
Contaminants: a wish list. To properly include contaminants into our spectral simulations we need (for the kinds of objects that pass DESI/QSO target selection criteria): The correct redshift distribution (for extragalactic contaminants). A sensible spatial distribution (should not be random, since stellar contamination will vary with Galactic latitude). An optical luminosity function or, at the very least, a roughly correct apparent magnitude-redshift distribution. Spectral templates (so the correct multiband colors can be synthesized). Fulfilling this wish-list will require non-negligible dedicated effort, with input from the Lya and Target Selection Working Groups. Alternatively, Survey Validation should provide all the necessary observations. Contaminants: current status. Briefly, in the current version of select_mock_targets we use the following inputs. Extragalactic contaminants: Use the Buzzard/v1.6 mock (flux-limited to roughly r=24) for spatial coordinates and redshifts. Use the desisim/BGS templates (see, e.g., this notebook), as representative of the full range of spectral shapes spanned by galaxies. (But note: these templates were trained on spectra of galaxies only down to I&lt;20.5.) For speed, pre-select the templates (at a given redshift) that will pass QSO color-cuts and drawn from this subset of templates with uniform probability. Normalize each spectrum in the r-band using the QSO apparent magnitude distribution measured in DR7.1 (see this notebook). (Note: doing this ignores the correlation between redshift and apparent magnitude.) Galactic / stellar contaminants: Use the MWS/v0.0.6 and MWS-Superfaint/v0.0.6 mocks (flux-limited to r=23.5) to get spatial coordinates and radial velocities. Use the desisim/STAR templates (see this notebook). As for extragalactic contaminants, we pre-select the stellar templates that will pass QSO color-cuts and normalize to the appropriate QSO r-band magnitude distribution. Preliminary results. Some preliminary results can be viewed by navigating to targets-qa/QSO.html, which is based on spectral simulations (of all target classes, including contaminants) of 240k targets spanning 10 DESI tiles (roughly 40 deg2) generated as part of the 18.12 software release. Target density The final target density is close to the nominal density (OK given variations in large-scale structure), but would be nice to confirm over a larger footprint.
from IPython.display import Image, HTML, display Image('histo-QSO.png')
projects/desi/lya/18dec19/mock-contaminants-qso.ipynb
moustakas/impy
gpl-2.0
Redshift distribution and apparent magnitude vs redshift relation. Overall the final redshift distribution is not terrible, given the simple assumptions used. Not clear whether the "expected" dn/dz in desimodel/data/targets/nz_QSO.dat includes contaminants or not. Need to test whether the redshift distribution of the extragalactic contaminants is sensible. Too few Lya QSOs in the simulations? Or perhaps an issue with nz_QSO.dat? Need to check that the apparent magnitude-redshift relation matches data.
display(HTML("<table><tr><td><img src='mock-nz-QSO.png'></td><td><img src='mock-zvmag-QSO.png'></td></tr></table>"))
projects/desi/lya/18dec19/mock-contaminants-qso.ipynb
moustakas/impy
gpl-2.0
Operational intensity of differential operation We consder differential operation on a vector $u$ at a given point in 3D with a 1D stencil size $k$ (number of points in the stencil) for every order, the subindex $i$ represent the dimension number $1$ for z, $2$ for $x$ and 3 for $y$, First order : $ \frac{d u}{dx_i} $ Second order : $ \frac{d^2 u}{dx_i^2} $ Second order cross derivative $ \frac{d^2 u}{dx_i dx_j} $
# Arithmetic operations k = symbols('k') s = symbols('s') # 1D stencil # multiplication addition AI_dxi = k + 1 + k - 1 AI_dxxi = k + 1 + k - 1 AI_dxxij = 2*k + 2*k-1 # square stencil (all uses the same stencil mask) # multiplication addition AI_dxis = k**2 + k**2 - 1 AI_dxxis = k**2 + k**2 - 1 AI_dxxijs = k**2 + k**2 - 1 # I/O operations # load IO_dxi = k IO_dxxi = k IO_dxxij = 2*k IO_square = k**2 # Operational intensity in single precision print(AI_dxi/(4*IO_dxi)) print(AI_dxxi/(4*IO_dxxi)) print(AI_dxxij/(4*IO_dxxij)) print(AI_dxis/(4*IO_square)) print(AI_dxxis/(4*IO_square)) print(AI_dxxijs/(4*IO_square)) OI_dxi = lambdify(k,AI_dxi/(4*IO_dxi)) OI_dxxi = lambdify(k,AI_dxxi/(4*IO_dxxi)) OI_dxxij = lambdify(k,AI_dxxij/(4*IO_dxxij)) OI_dxis = lambdify(k,AI_dxis/(4*IO_dxxij)) OI_dxxis = lambdify(k,AI_dxxis/(4*IO_dxxij)) OI_dxxijs = lambdify(k,AI_dxxijs/(4*IO_dxxij))
OP_high.ipynb
opesci/notebooks
bsd-3-clause
Operational intensity of wave equations We now consider geophysical wave equations to obtain the theoretical expression of the operational intensity. We write directly the expression of a single time step as a function of differential operators. An operation on a wavefield is counted only once as we consider the minimum of arithmetic operations required. Acoustic isotropic $ u(x,y,z,t+dt) = dt^2 v^2(x,y,z) ( 2 u(x,y,z,t) + u(x,y,z,t-dt) + \nabla^2 u(x,y,z,t) +q ) $ VTI $ p(x,y,z,t+dt) = dt^2 v^2(x,y,z) \left( 2 p(x,y,z,t) + p(x,y,z,t-dt) +(1+2\epsilon)(\frac{d^2 p(x,t)}{dx^2}+\frac{d^2 p(x,t)}{dyx^2}) + \sqrt{(1+2\delta)} \frac{d^2 r(x,t)}{dz^2} + q \right) $ $ r(x,y,z,t+dt) = dt^2 v^2(x,y,z) \left( 2 r(x,y,z,t) + r(x,y,z,t-dt) +\sqrt{(1+2\delta)}(\frac{d^2 p(x,t)}{dx^2}+ \frac{d^2 p(x,t)}{dy^2}) + \frac{d^2 r(x,t)}{dz^2} + q \right) $ TTI $ p(x,y,z,t+dt) = dt^2 v^2(x,y,z) \left( 2 p(x,y,z,t) + p(x,y,z,t-dt) + (1+2\epsilon) (G_{\bar{x}\bar{x}} + G_{\bar{y}\bar{y}}) p(x,y,z,t) + \sqrt{(1+2\delta)} G_{\bar{z}\bar{z}} r(x,y,z,t) + q \right) $ $ r(x,y,z,t+dt) = dt^2 v^2(x,y,z) \left( 2 r(x,y,z,t) + r(x,y,z,t-dt) + \sqrt{(1+2\delta)}(G_{\bar{x}\bar{x}} + G_{\bar{y}\bar{y}}) p(x,y,z,t) + G_{\bar{z}\bar{z}} r(x,y,z) +q \right) $ where $ \begin{cases} G_{\bar{x}\bar{x}} & = cos(\phi)^2 cos(\theta)^2 \frac{d^2}{dx^2} +sin(\phi)^2 cos(\theta)^2 \frac{d^2}{dy^2}+ sin(\theta)^2 \frac{d^2}{dz^2} + sin(2\phi) cos(\theta)^2 \frac{d^2}{dx dy} - sin(\phi) sin(2\theta) \frac{d^2}{dy dz} -cos(\phi) sin(2\theta) \frac{d^2}{dx dz} \ G_{\bar{y}\bar{y}} & = sin(\phi)^2 \frac{d^2}{dx^2} +cos(\phi)^2 \frac{d^2}{dy^2} - sin(2\phi)^2 \frac{d^2}{dx dy}\ G_{\bar{z}\bar{z}} & = cos(\phi)^2 sin(\theta)^2 \frac{d^2}{dx^2} +sin(\phi)^2 sin(\theta)^2 \frac{d^2}{dy^2}+ cos(\theta)^2 \frac{d^2}{dz^2} + sin(2\phi) sin(\theta)^2 \frac{d^2}{dx dy} + sin(\phi) sin(2\theta) \frac{d^2}{dy dz} +cos(\phi) sin(2\theta) \frac{d^2}{dx dz} \ \end{cases} $
# Arithmetic # dxi dxxi dxxij multiplications additions duplicates AI_acou = 0*AI_dxi + 3*AI_dxxi + 0*AI_dxxij + 3 + 5 - 2 * 2 AI_vti = 2 * ( 0*AI_dxi + 3*AI_dxxi + 0*AI_dxxij + 5 + 5 - 2 ) AI_tti = 2 * ( 0*AI_dxi + 3*AI_dxxi + 3*AI_dxxij + 44 + 17 - 8 ) AI_acoums = 0*AI_dxi + 3*s*AI_dxxi + 0*AI_dxxij + 3*s + 5*s - 2 * 2 *s AI_vtims = 2 * ( 0*AI_dxi + 3*s*AI_dxxi + 0*AI_dxxij + 5*s + 5*s - 2*s ) AI_ttims = 2 * ( 0*AI_dxi + 3*s*AI_dxxi + 3*s*AI_dxxij + 44*s + 17*s - 8*s ) AI_acous = 0*AI_dxis + 3*AI_dxxis + 0*AI_dxxijs + 3 + 5 - 2 * 2 AI_vtis = 2 * ( 0*AI_dxis + 3*AI_dxxis + 0*AI_dxxijs + 5 + 5 - 2 * 2 ) AI_ttis = 2 * ( 0*AI_dxis + 3*AI_dxxis + 3*AI_dxxijs + 44 + 17 - 3*k**2 ) # I/O operations , the full domain of size N is in cache for best case scenario # IO_acou = 4 * N IO_vti = 9 * N IO_tti = 15 * N IO_acoums = 3 * s * N + N IO_vtims = 6 * s * N + 3 * N IO_ttims = 6 * s * N + 9 * N IO_acous = 4 * N IO_vtis = 9 * N IO_ttis = 15 * N print(simplify(N*AI_acou/(4*IO_acou))) print(simplify(N*AI_vti/(4*IO_vti))) print(simplify(N*AI_tti/(4*IO_tti))) print(simplify(N*AI_acoums/(4*IO_acoums))) print(simplify(N*AI_vtims/(4*IO_vtims))) print(simplify(N*AI_ttims/(4*IO_ttims))) print(simplify(N*AI_acous/(4*IO_acous))) print(simplify(N*AI_vtis/(4*IO_vtis))) print(simplify(N*AI_ttis/(4*IO_ttis))) OI_acou = lambdify(k,N*AI_acou/(4*IO_acou)) OI_vti = lambdify(k,N*AI_vti/(4*IO_vti)) OI_tti = lambdify(k,N*AI_tti/(4*IO_tti)) OI_acoums = lambdify((k,s),N*AI_acoums/(4*IO_acoums)) OI_vtims = lambdify((k,s),N*AI_vtims/(4*IO_vtims)) OI_ttims = lambdify((k,s),N*AI_ttims/(4*IO_ttims)) OI_acous = lambdify(k,N*AI_acous/(4*IO_acous)) OI_vtis = lambdify(k,N*AI_vtis/(4*IO_vtis)) OI_ttis = lambdify(k,N*AI_ttis/(4*IO_ttis)) print(limit(OI_acou(k),k,51)) print(limit(OI_vti(k),k,51)) print(limit(OI_tti(k),k,51)) print(limit(OI_acoums(3,s),s,128)) print(limit(OI_vtims(3,s),s,128)) print(limit(OI_ttims(3,s),s,128)) print(limit(OI_acous(k),k,51)) print(limit(OI_vtis(k),k,51)) print(limit(OI_ttis(k),k,51)) kk=[3,5,7,9,11,13,15,17,19,21,23,25,27,29,31] ss=[2,4,8,16,32,64] OI_wave=np.zeros((15,6)) OI_wavems=np.zeros((15,6,3)) OI=np.zeros((15,3)) for i in range(0,15): OI_wave[i,0]=OI_acou(kk[i]) OI_wave[i,1]=OI_vti(kk[i]) OI_wave[i,2]=OI_tti(kk[i]) OI_wave[i,3]=OI_acous(kk[i]) OI_wave[i,4]=OI_vtis(kk[i]) OI_wave[i,5]=OI_ttis(kk[i]) OI[i,0]=OI_dxi(kk[i]) OI[i,1]=OI_dxxi(kk[i]) OI[i,2]=OI_dxxij(kk[i]) for j in range(0,6): OI_wavems[i,j,0]=OI_acoums(kk[i],ss[j]) OI_wavems[i,j,1]=OI_vtims(kk[i],ss[j]) OI_wavems[i,j,2]=OI_ttims(kk[i],ss[j]) import matplotlib.pyplot as plt fig = plt.figure() plt.hold("off") acou = plt.plot(OI_wave[:,0],label='acou') # this is how you'd plot a single line... vti = plt.plot(OI_wave[:,1],label='vti') # this is how you'd plot a single line... tti = plt.plot(OI_wave[:,2],label='tti') # this is how you'd plot a single line... fig = plt.figure() plt.hold("off") acou = plt.plot(OI_wave[:,3],label='acous') # this is how you'd plot a single line... vti = plt.plot(OI_wave[:,4],label='vtis') # this is how you'd plot a single line... tti = plt.plot(OI_wave[:,5],label='ttis') # this is how you'd plot a single line... fig = plt.figure() plt.hold("off") acou = plt.plot(OI_wavems[:,2,0],label='acous') # this is how you'd plot a single line... vti = plt.plot(OI_wavems[:,2,1],label='vtis') # this is how you'd plot a single line... tti = plt.plot(OI_wavems[:,2,2],label='ttis') # this is how you'd plot a single line... fig = plt.figure() plt.hold("off") acou = plt.plot(OI_wavems[:,5,0],label='acous') # this is how you'd plot a single line... vti = plt.plot(OI_wavems[:,5,1],label='vtis') # this is how you'd plot a single line... tti = plt.plot(OI_wavems[:,5,2],label='ttis') # this is how you'd plot a single line... plt.show()
OP_high.ipynb
opesci/notebooks
bsd-3-clause
Vertex client library: AutoML text classification model for batch prediction <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_text_classification_batch.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_text_classification_batch.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> </table> <br/><br/><br/> Overview This tutorial demonstrates how to use the Vertex client library for Python to create text classification models and do batch prediction using Google Cloud's AutoML. Dataset The dataset used for this tutorial is the Happy Moments dataset from Kaggle Datasets. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. Objective In this tutorial, you create an AutoML text classification model from a Python script, and then do a batch prediction using the Vertex client library. You can alternatively create and deploy models using the gcloud command-line tool or online using the Google Cloud Console. The steps performed include: Create a Vertex Dataset resource. Train the model. View the model evaluation. Make a batch prediction. There is one key difference between using batch prediction and using online prediction: Prediction Service: Does an on-demand prediction for the entire set of instances (i.e., one or more data items) and returns the results in real-time. Batch Prediction Service: Does a queued (batch) prediction for the entire set of instances in the background and stores the results in a Cloud Storage bucket when ready. Costs This tutorial uses billable components of Google Cloud (GCP): Vertex AI Cloud Storage Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Installation Install the latest version of Vertex client library.
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/automl/showcase_automl_text_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Tutorial Now you are ready to start creating your own AutoML text classification model. Set up clients The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server. You will use different clients in this tutorial for different steps in the workflow. So set them all up upfront. Dataset Service for Dataset resources. Model Service for Model resources. Pipeline Service for training. Job Service for batch prediction and custom training.
# client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_dataset_client(): client = aip.DatasetServiceClient(client_options=client_options) return client def create_model_client(): client = aip.ModelServiceClient(client_options=client_options) return client def create_pipeline_client(): client = aip.PipelineServiceClient(client_options=client_options) return client def create_job_client(): client = aip.JobServiceClient(client_options=client_options) return client clients = {} clients["dataset"] = create_dataset_client() clients["model"] = create_model_client() clients["pipeline"] = create_pipeline_client() clients["job"] = create_job_client() for client in clients.items(): print(client)
notebooks/community/gapic/automl/showcase_automl_text_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Model deployment for batch prediction Now deploy the trained Vertex Model resource you created for batch prediction. This differs from deploying a Model resource for on-demand prediction. For online prediction, you: Create an Endpoint resource for deploying the Model resource to. Deploy the Model resource to the Endpoint resource. Make online prediction requests to the Endpoint resource. For batch-prediction, you: Create a batch prediction job. The job service will provision resources for the batch prediction request. The results of the batch prediction request are returned to the caller. The job service will unprovision the resoures for the batch prediction request. Make a batch prediction request Now do a batch prediction to your deployed model. Get test item(s) Now do a batch prediction to your Vertex model. You will use arbitrary examples out of the dataset as a test items. Don't be concerned that the examples were likely used in training the model -- we just want to demonstrate how to make a prediction.
test_items = ! gsutil cat $IMPORT_FILE | head -n2 if len(test_items[0]) == 3: _, test_item_1, test_label_1 = str(test_items[0]).split(",") _, test_item_2, test_label_2 = str(test_items[1]).split(",") else: test_item_1, test_label_1 = str(test_items[0]).split(",") test_item_2, test_label_2 = str(test_items[1]).split(",") print(test_item_1, test_label_1) print(test_item_2, test_label_2)
notebooks/community/gapic/automl/showcase_automl_text_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make batch prediction request Now that your batch of two test items is ready, let's do the batch request. Use this helper function create_batch_prediction_job, with the following parameters: display_name: The human readable name for the prediction job. model_name: The Vertex fully qualified identifier for the Model resource. gcs_source_uri: The Cloud Storage path to the input file -- which you created above. gcs_destination_output_uri_prefix: The Cloud Storage path that the service will write the predictions to. parameters: Additional filtering parameters for serving prediction results. The helper function calls the job client service's create_batch_prediction_job metho, with the following parameters: parent: The Vertex location root path for Dataset, Model and Pipeline resources. batch_prediction_job: The specification for the batch prediction job. Let's now dive into the specification for the batch_prediction_job: display_name: The human readable name for the prediction batch job. model: The Vertex fully qualified identifier for the Model resource. dedicated_resources: The compute resources to provision for the batch prediction job. machine_spec: The compute instance to provision. Use the variable you set earlier DEPLOY_GPU != None to use a GPU; otherwise only a CPU is allocated. starting_replica_count: The number of compute instances to initially provision, which you set earlier as the variable MIN_NODES. max_replica_count: The maximum number of compute instances to scale to, which you set earlier as the variable MAX_NODES. model_parameters: Additional filtering parameters for serving prediction results. Note, text models do not support additional parameters. input_config: The input source and format type for the instances to predict. instances_format: The format of the batch prediction request file: jsonl only supported. gcs_source: A list of one or more Cloud Storage paths to your batch prediction requests. output_config: The output destination and format for the predictions. prediction_format: The format of the batch prediction response file: jsonl only supported. gcs_destination: The output destination for the predictions. dedicated_resources: The compute resources to provision for the batch prediction job. machine_spec: The compute instance to provision. Use the variable you set earlier DEPLOY_GPU != None to use a GPU; otherwise only a CPU is allocated. starting_replica_count: The number of compute instances to initially provision. max_replica_count: The maximum number of compute instances to scale to. In this tutorial, only one instance is provisioned. This call is an asychronous operation. You will print from the response object a few select fields, including: name: The Vertex fully qualified identifier assigned to the batch prediction job. display_name: The human readable name for the prediction batch job. model: The Vertex fully qualified identifier for the Model resource. generate_explanations: Whether True/False explanations were provided with the predictions (explainability). state: The state of the prediction job (pending, running, etc). Since this call will take a few moments to execute, you will likely get JobState.JOB_STATE_PENDING for state.
BATCH_MODEL = "happydb_batch-" + TIMESTAMP def create_batch_prediction_job( display_name, model_name, gcs_source_uri, gcs_destination_output_uri_prefix, parameters=None, ): if DEPLOY_GPU: machine_spec = { "machine_type": DEPLOY_COMPUTE, "accelerator_type": DEPLOY_GPU, "accelerator_count": DEPLOY_NGPU, } else: machine_spec = { "machine_type": DEPLOY_COMPUTE, "accelerator_count": 0, } batch_prediction_job = { "display_name": display_name, # Format: 'projects/{project}/locations/{location}/models/{model_id}' "model": model_name, "model_parameters": json_format.ParseDict(parameters, Value()), "input_config": { "instances_format": IN_FORMAT, "gcs_source": {"uris": [gcs_source_uri]}, }, "output_config": { "predictions_format": OUT_FORMAT, "gcs_destination": {"output_uri_prefix": gcs_destination_output_uri_prefix}, }, "dedicated_resources": { "machine_spec": machine_spec, "starting_replica_count": MIN_NODES, "max_replica_count": MAX_NODES, }, } response = clients["job"].create_batch_prediction_job( parent=PARENT, batch_prediction_job=batch_prediction_job ) print("response") print(" name:", response.name) print(" display_name:", response.display_name) print(" model:", response.model) try: print(" generate_explanation:", response.generate_explanation) except: pass print(" state:", response.state) print(" create_time:", response.create_time) print(" start_time:", response.start_time) print(" end_time:", response.end_time) print(" update_time:", response.update_time) print(" labels:", response.labels) return response IN_FORMAT = "jsonl" OUT_FORMAT = "jsonl" # [jsonl] response = create_batch_prediction_job( BATCH_MODEL, model_to_deploy_id, gcs_input_uri, BUCKET_NAME, None )
notebooks/community/gapic/automl/showcase_automl_text_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a variable of the true number of deaths of an event
deaths = 6
python/while_statements.ipynb
tpin3694/tpin3694.github.io
mit
Create a variable that is denotes if the while loop should keep running
running = True
python/while_statements.ipynb
tpin3694/tpin3694.github.io
mit
while running is True
while running: # Create a variable that randomly create a integer between 0 and 10. guess = random.randint(0,10) # if guess equals deaths, if guess == deaths: # then print this print('Correct!') # and then also change running to False to stop the script running = False # else if guess is lower than deaths elif guess < deaths: # then print this print('No, it is higher.') # if guess is none of the above else: # print this print('No, it is lower')
python/while_statements.ipynb
tpin3694/tpin3694.github.io
mit
Overview of "fast" mode The fast mode simulation was first introduced in pvfactors v1.0.2. It relies on a mathematical simplification (see Theory section of the documentation) of the problem that assumes that we already know the irradiance incident on all front PV row surfaces and ground surfaces (for instance using the Perez model). In this mode, we therefore only calculate view factors from PV row back surfaces to the other ones assuming that back surfaces don't see each other. This way we do not need to solve a linear system of equations anymore for "ordered" PV arrays. This is an approximation compared to the "full" mode, since we're not calculating the impact of the multiple reflections on the PV array surfaces. But the initial results show that it still provides a very reasonable estimate of back surface incident irradiance values. Get timeseries inputs
def import_data(fp): """Import 8760 data to run pvfactors simulation""" tz = 'US/Arizona' df = pd.read_csv(fp, index_col=0) df.index = pd.DatetimeIndex(df.index).tz_convert(tz) return df df = import_data(filepath) df_inputs = df.iloc[:24, :] # Plot the data f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 3)) df_inputs[['dni', 'dhi']].plot(ax=ax1) df_inputs[['solar_zenith', 'solar_azimuth']].plot(ax=ax2) df_inputs[['surface_tilt', 'surface_azimuth']].plot(ax=ax3) plt.show() # Use a fixed albedo albedo = 0.2
docs/tutorials/Run_fast_simulations.ipynb
SunPower/pvfactors
bsd-3-clause
Run "fast" simulations with the PVEngine The PVEngine can be used to easily run fast mode simulations, using its run_fast_mode() method. In order to run the fast mode, the users need to specify which PV row to look at for calculating back surface incident irradiance. The way this is done is by specifying the index of the PV row either at initialiatization, or in the run_fast_mode() method. Optionally, a specific segment index can also be passed to the PV Engine to calculate the irradiance only for a segment of a PV row's back surface.
# Import PVEngine and OrderedPVArray from pvfactors.engine import PVEngine from pvfactors.geometry import OrderedPVArray # Instantiate PV array pvarray = OrderedPVArray.init_from_dict(pvarray_parameters) # Create PV engine, and specify the index of the PV row for fast mode fast_mode_pvrow_index = 1 # look at the middle PV row eng = PVEngine(pvarray, fast_mode_pvrow_index=fast_mode_pvrow_index) # Fit PV engine to the timeseries data eng.fit(df_inputs.index, df_inputs.dni, df_inputs.dhi, df_inputs.solar_zenith, df_inputs.solar_azimuth, df_inputs.surface_tilt, df_inputs.surface_azimuth, albedo)
docs/tutorials/Run_fast_simulations.ipynb
SunPower/pvfactors
bsd-3-clause
A report function needs to be passed to the run_fast_mode() method in order to return calculated values. The report function will need to rely on the pvarray's ts_pvrows attribute in order to get the calculated outputs.
# Create a function to build the report: the function will get the total incident irradiance on the back # of the middle PV row def fn_report(pvarray): return {'total_inc_back': (pvarray.ts_pvrows[fast_mode_pvrow_index] .back.list_segments[0].get_param_weighted('qinc'))} # Run timeseries simulations report = eng.run_fast_mode(fn_build_report=fn_report) # make a dataframe out of the report df_report = pd.DataFrame(report, index=df_inputs.index) # and plot the results f, ax = plt.subplots(figsize=(10, 3)) df_report.plot(ax=ax) plt.show()
docs/tutorials/Run_fast_simulations.ipynb
SunPower/pvfactors
bsd-3-clause
Run "fast" simulations using run_timeseries_engine() The same thing can be done more rapidly using the run_timeseries_engine() function.
# Choose center row (index 1) for the fast simulation fast_mode_pvrow_index = 1 # Create a function to build the report: the function will get the total incident irradiance on the back # of the middle PV row def fn_report(pvarray): return {'total_inc_back': (pvarray.ts_pvrows[fast_mode_pvrow_index] .back.list_segments[0].get_param_weighted('qinc'))} # import function to run simulations in parallel from pvfactors.run import run_timeseries_engine # run simulations report = run_timeseries_engine( fn_report, pvarray_parameters, df_inputs.index, df_inputs.dni, df_inputs.dhi, df_inputs.solar_zenith, df_inputs.solar_azimuth, df_inputs.surface_tilt, df_inputs.surface_azimuth, albedo, fast_mode_pvrow_index=fast_mode_pvrow_index) # this will trigger fast mode calculation # make a dataframe out of the report df_report = pd.DataFrame(report, index=df_inputs.index) f, ax = plt.subplots(figsize=(10, 3)) df_report.plot(ax=ax) plt.show()
docs/tutorials/Run_fast_simulations.ipynb
SunPower/pvfactors
bsd-3-clause
Example 1 Create pandas DataFrame
event_vocabulary = DataFrame([['Harv', 'sagedus'], ['tugev peavalu', 'sümptom']], columns=['term', 'type'])
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
or file event vocabulary.csv in csv format: term,type Harv,sagedus tugev peavalu,sümptom
event_vocabulary = read_csv('data/event vocabulary.csv')
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
or list of dicts
event_vocabulary = [{'term': 'harv', 'type': 'sagedus'}, {'term': 'tugev peavalu', 'type': 'sümptom'}]
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
There must be one key (column) called term in event_vocabulary. That refers to the strings searched from the text. Other keys (type in this example) are optional. No key may have name start, end, wstart_raw, wend_raw, cstart, wstart, or bstart. Create Text object, EventTagger object and find the list of events.
text = Text('Tugev peavalu esineb valimis harva.') event_tagger = EventTagger(event_vocabulary, search_method='ahocorasick', case_sensitive=False, conflict_resolving_strategy='ALL', return_layer=True) event_tagger.tag(text)
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
The attributes start and end show at which character the event starts and ends.<br> The attributes wstart_raw (word start raw) and wend_raw (word end raw) show at which word the event starts and ends.<br> The attributes cstart (char start) and wstart (word start) are like start and wstart_raw but are calculated as if all the events consist of one char.<br> The bstart (block start) attribute is is like wstart_raw but is calculated as if all the events and the gaps betveen the events (if exist) consist of one word. There is a gap between the events A and B if wend_raw of A &lt; wstart_raw of B. The cstart, wstart and bstart attributes are calculated only if there is no overlapping events in the text. Use conflict_resolving_strategy='MAX' or conflict_resolving_strategy='MIN' to remove overlaps. | | Tugev peavalu | esineb valimis | harv a. | |------------|-----------------|----------------|-------- | | start | 0 | | 29 | | end | 13 | | 33 | | wstart_raw | 0 | | 4 | | wend_raw | 2 | | 5 | | cstart | 0 | | 17 | | wstart | 0 | | 3 | | bstart | 0 | | 2 | The search_method is either 'ahocorasick' or 'naive'. 'naive' is slower in general but does not depend on pyahocorasic package. The conflict_resolving_strategy is either 'ALL', 'MIN' or 'MAX' (see the next example). The events in output are ordered by start and end. The defaults are: python search_method='naive' # for Python &lt; 3 search_method='ahocorasick' # for Python &gt;= 3 case_sensitive=True conflict_resolving_strategy='MAX' return_layer=False layer_name='events' Example 2
event_vocabulary = [ {'term': 'kaks', 'value': 2, 'type': 'väike'}, {'term': 'kümme', 'value': 10, 'type': 'keskmine'}, {'term': 'kakskümmend', 'value': 20, 'type': 'suur'}, {'term': 'kakskümmend kaks', 'value': 22, 'type': 'suur'} ] text = Text('kakskümmend kaks')
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
conflict_resolving_strategy='ALL' returns all events.
event_tagger = EventTagger(event_vocabulary, search_method='naive', conflict_resolving_strategy='ALL', return_layer=True) event_tagger.tag(text)
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
conflict_resolving_strategy='MAX' returns all the events that are not contained by any other event.
event_tagger = EventTagger(event_vocabulary, search_method='naive', conflict_resolving_strategy='MAX', return_layer=True) event_tagger.tag(text)
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
conflict_resolving_strategy='MIN' returns all the events that don't contain any other event.
event_tagger = EventTagger(event_vocabulary, search_method='naive', conflict_resolving_strategy='MIN', return_layer=True) event_tagger.tag(text)
docs/EventTagger.ipynb
estnltk/episode-miner
gpl-2.0
To select all the fellows you can use
fellows = models.Claimant.objects.filter(fellow=True) fellows
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
Remember that the Claimant table can have entries that aren't fellows and because of it we need to use .filter(selected=True). Basic (Pandas Part) You can use Pandas with Django.
from django_pandas.io import read_frame fellows = read_frame(fellows.values()) fellows
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
When converting a Django QuerySet into a Pandas DataFrame you will need to as the previous example because so far Pandas can't process Django QuerySets by default.
expenses = read_frame(Expense.objects.all()) expenses expenses.sum() expenses["amount_authorized_for_payment"].sum()
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
Pandas table as CSV and as Data URIs For the report, we need to Pandas table as CSV encoded inside data URIs so users can download the CSV file without querying the server.
from base64 import b64encode csv = fellows.to_csv( header=True, index=False ) b64encode(csv.encode())
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
The output of b64encode can be included in &lt;a download="fellows.csv" href="data:application/octet-stream;charset=utf-16le;base64,{{ b64encode_output | safe }}"&gt;Download the data as CSV.&lt;/a&gt; so that user can download the data. Basic (Tagulous) We use Tagulous as a tag library.
funds = models.Fund.objects.all() read_frame(funds)
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
Get a list of all tags:
funds[0].activity.all()
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
You can loop over each tag:
for tag in funds[0].activity.all(): print(tag.name)
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
Filter for a specific tag:
models.Fund.objects.filter(activity="ssi2/fellowship")
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
You can query for part of the name of the tag:
models.Fund.objects.filter(activity__name__contains="fellowship") for fund in models.Fund.objects.filter(activity__name__contains="fellowship"): print("{} - {}".format(fund, fund.activity.all()))
lowfat/reports/101.ipynb
softwaresaved/fat
bsd-3-clause
Noise <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://quantumai.google/cirq/noisy_simulation"><img src="https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png" />View on QuantumAI</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/noisy_simulation.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/quantumlib/Cirq/blob/master/docs/noisy_simulation.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/github_logo_1x.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/Cirq/docs/noisy_simulation.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/download_icon_1x.png" />Download notebook</a> </td> </table>
try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.")
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
For simulation, it is useful to have Gate objects that enact noisy quantum evolution. Cirq supports modeling noise via operator sum representations of noise (these evolutions are also known as quantum operations or quantum dynamical maps). This formalism models evolution of the density matrix $\rho$ via $$ \rho \rightarrow \sum_{k = 1}^{m} A_k \rho A_k^\dagger $$ where $A_k$ are known as Kraus operators. These operators are not necessarily unitary but must satisfy the trace-preserving property $$ \sum_k A_k^\dagger A_k = I . $$ A channel with $m = 1$ unitary Kraus operator is called coherent (and is equivalent to a unitary gate operation), otherwise the channel is called incoherent. For a given noisy channel, Kraus operators are not necessarily unique. For more details on these operators, see John Preskill's lecture notes. Common channels Cirq defines many commonly used quantum channels in ops/common_channels.py. For example, the single-qubit bit-flip channel $$ \rho \rightarrow (1 - p) \rho + p X \rho X $$ with parameter $p = 0.1$ can be created as follows.
import cirq """Get a single-qubit bit-flip channel.""" bit_flip = cirq.bit_flip(p=0.1)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
To see the Kraus operators of a channel, the cirq.kraus protocol can be used. (See the protocols guide.)
for i, kraus in enumerate(cirq.kraus(bit_flip)): print(f"Kraus operator {i + 1} is:\n", kraus, end="\n\n")
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
As mentioned, all channels are subclasses of cirq.Gates. As such, they can act on qubits and be used in circuits in the same manner as gates.
"""Example of using channels in a circuit.""" # See the number of qubits a channel acts on. nqubits = bit_flip.num_qubits() print(f"Bit flip channel acts on {nqubits} qubit(s).\n") # Apply the channel to each qubit in a circuit. circuit = cirq.Circuit( bit_flip.on_each(cirq.LineQubit.range(3)) ) print(circuit)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Channels can even be controlled.
"""Example of controlling a channel.""" # Get the controlled channel. controlled_bit_flip = bit_flip.controlled(num_controls=1) # Use it in a circuit. circuit = cirq.Circuit( controlled_bit_flip(*cirq.LineQubit.range(2)) ) print(circuit)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
In addition to the bit-flip channel, other common channels predefined in Cirq are shown below. Definitions of these channels can be found in their docstrings - e.g., help(cirq.depolarize). cirq.phase_flip cirq.phase_damp cirq.amplitude_damp cirq.depolarize cirq.asymmetric_depolarize cirq.reset For example, the asymmetric depolarizing channel is defined by $$ \rho \rightarrow (1-p_x-p_y-p_z) \rho + p_x X \rho X + p_y Y \rho Y + p_z Z \rho Z $$ and can be instantiated as follows.
"""Get an asymmetric depolarizing channel.""" depo = cirq.asymmetric_depolarize( p_x=0.10, p_y=0.05, p_z=0.15, ) circuit = cirq.Circuit( depo.on_each(cirq.LineQubit(0)) ) print(circuit)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
The kraus and mixture protocols We have seen the cirq.kraus protocol which returns the Kraus operators of a channel. Some channels have the interpretation of randomly applying a single unitary Kraus operator $U_k$ with probability $p_k$, namely $$ \rho \rightarrow \sum_k p_k U_k \rho U_k^\dagger {\rm ~where~} \sum_k p_k =1 {\rm ~and~ U_k U_k^\dagger= I}. $$ For example, the bit-flip channel from above $$ \rho \rightarrow (1 - p) \rho + p X \rho X $$ can be interpreted as doing nothing (applying identity) with probability $1 - p$ and flipping the bit (applying $X$) with probability $p$. Channels with these interpretations support the cirq.mixture protocol. This protocol returns the probabilities and unitary Kraus operators of the channel.
"""Example of using the mixture protocol.""" for prob, kraus in cirq.mixture(bit_flip): print(f"With probability {prob}, apply\n", kraus, end="\n\n")
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Channels that do not have this interpretation do not support the cirq.mixture protocol. Such channels apply Kraus operators with probabilities that depend on the state $\rho$. An example of a channel which does not support the mixture protocol is the amplitude damping channel with parameter $\gamma$ defined by Kraus operators $$ M_0 = \begin{bmatrix} 1 & 0 \cr 0 & \sqrt{1 - \gamma} \end{bmatrix} \text{and } M_1 = \begin{bmatrix} 0 & \sqrt{\gamma} \cr 0 & 0 \end{bmatrix} . $$
"""The amplitude damping channel is an example of a channel without a mixture.""" channel = cirq.amplitude_damp(0.1) if cirq.has_mixture(channel): print(f"Channel {channel} has a _mixture_ or _unitary_ method.") else: print(f"Channel {channel} does not have a _mixture_ or _unitary_ method.")
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
To summarize: Every Gate in Cirq supports the cirq.kraus protocol. If magic method _kraus_ is not defined, cirq.kraus looks for _mixture_ then for _unitary_. A subset of channels which support cirq.kraus also support the cirq.mixture protocol. If magic method _mixture_ is not defined, cirq.mixture looks for _unitary_. A subset of channels which support cirq.mixture also support the cirq.unitary protocol. For concrete examples, consider cirq.X, cirq.BitFlipChannel, and cirq.AmplitudeDampingChannel which are all subclasses of cirq.Gate. cirq.X defines the _unitary_ method. As a result, it supports the cirq.unitary protocol, the cirq.mixture protocol, and the cirq.kraus protocol. cirq.BitFlipChannel defines the _mixture_ method but not the _unitary_ method. As a result, it only supports the cirq.mixture protocol and the cirq.kraus protocol. cirq.AmplitudeDampingChannel defines the _kraus_ method, but not the _mixture_ method or the _unitary_ method. As a result, it only supports the cirq.kraus protocol. Custom channels There are two configurable channel types for channels not defined in cirq.ops.common_channels: MixedUnitaryChannel and KrausChannel. MixedUnitaryChannel takes a list of (probability, unitary) tuples and uses it to define the _mixture_ method. KrausChannel takes a list of Kraus operators and uses it to define the _channel method. Both types also accept a measurement key as an optional parameter. This key will be used to store the index of the selected unitary or Kraus operator in the measurement results. An example of each type is shown below.
import numpy as np q0 = cirq.LineQubit(0) # This is equivalent to a bit-flip error with probability 0.1. mix = [ (0.9, np.array([[1, 0], [0, 1]], dtype=np.complex64)), (0.1, np.array([[0, 1], [1, 0]], dtype=np.complex64)), ] bit_flip_mix = cirq.MixedUnitaryChannel(mix) # This is equivalent to an X-basis measurement. ops = [ np.array([[1, 1], [1, 1]]) * 0.5, np.array([[1, -1], [-1, 1]]) * 0.5, ] x_meas = cirq.KrausChannel(ops, key='x') # These circuits have the same behavior. circuit = cirq.Circuit( bit_flip_mix.on(q0), cirq.H(q0), x_meas.on(q0), ) equiv_circuit = cirq.Circuit( cirq.bit_flip(0.1).on(q0), cirq.H(q0), # Measure in x-basis cirq.H(q0), cirq.measure(q0, key='x'), cirq.H(q0), )
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Alternatively, users can define their own channel types. Defining custom channels is similar to defining custom gates. A minimal example for defining the channel $$ \rho \mapsto (1 - p) \rho + p Y \rho Y $$ is shown below.
"""Minimal example of defining a custom channel.""" class BitAndPhaseFlipChannel(cirq.SingleQubitGate): def __init__(self, p: float) -> None: self._p = p def _mixture_(self): ps = [1.0 - self._p, self._p] ops = [cirq.unitary(cirq.I), cirq.unitary(cirq.Y)] return tuple(zip(ps, ops)) def _has_mixture_(self) -> bool: return True def _circuit_diagram_info_(self, args) -> str: return f"BitAndPhaseFlip({self._p})"
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Note: The _has_mixture_ magic method is not strictly required but is recommended. We can now instantiate this channel and get its mixture:
"""Custom channels can be used like any other channels.""" bit_phase_flip = BitAndPhaseFlipChannel(p=0.05) for prob, kraus in cirq.mixture(bit_phase_flip): print(f"With probability {prob}, apply\n", kraus, end="\n\n")
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Note: Since _mixture_ is defined, the cirq.kraus protocol can also be used. The custom channel can be used in a circuit just like other predefined channels.
"""Example of using a custom channel in a circuit.""" circuit = cirq.Circuit( bit_phase_flip.on_each(*cirq.LineQubit.range(3)) ) circuit
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Note: If a custom channel does not have a mixture, it should instead define the _kraus_ magic method to return a sequence of Kraus operators (as numpy.ndarrays). Defining a _has_kraus_ method which returns True is optional but recommended. This method of defining custom channels is the most general, but simple channels such as the custom BitAndPhaseFlipChannel can also be created directly from a Gate with the convenient Gate.with_probability method.
"""Create a channel with Gate.with_probability.""" channel = cirq.Y.with_probability(probability=0.05)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
This produces the same mixture as the custom BitAndPhaseFlip channel above.
for prob, kraus in cirq.mixture(channel): print(f"With probability {prob}, apply\n", kraus, end="\n\n")
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Note that the order of Kraus operators is reversed from above, but this of course does not affect the action of the channel. Simulating noisy circuits Density matrix simulation The cirq.DensityMatrixSimulator can simulate any noisy circuit (i.e., can apply any quantum channel) because it stores the full density matrix $\rho$. This simulation strategy updates the state $\rho$ by directly applying the Kraus operators of each quantum channel.
"""Simulating a circuit with the density matrix simulator.""" # Get a circuit. qbit = cirq.GridQubit(0, 0) circuit = cirq.Circuit( cirq.X(qbit), cirq.amplitude_damp(0.1).on(qbit) ) # Display it. print("Simulating circuit:") print(circuit) # Simulate with the density matrix simulator. dsim = cirq.DensityMatrixSimulator() rho = dsim.simulate(circuit).final_density_matrix # Display the final density matrix. print("\nFinal density matrix:") print(rho)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Note that the density matrix simulator supports the run method which only gives access to measurements as well as the simulate method (used above) which gives access to the full density matrix. Monte Carlo wavefunction simulation Noisy circuits with arbitrary channels can also be simulated with the cirq.Simulator. When simulating such a channel, a single Kraus operator is randomly sampled (according to the probability distribution) and applied to the wavefunction. This method is known as "Monte Carlo (wavefunction) simulation" or "quantum trajectories." Note: For channels which do not support the cirq.mixture protocol, the probability of applying each Kraus operator depends on the state. In contrast, for channels which do support the cirq.mixture protocol, the probability of applying each Kraus operator is independent of the state.
"""Simulating a noisy circuit via Monte Carlo simulation.""" # Get a circuit. qbit = cirq.NamedQubit("Q") circuit = cirq.Circuit(cirq.bit_flip(p=0.5).on(qbit)) # Display it. print("Simulating circuit:") print(circuit) # Simulate with the cirq.Simulator. sim = cirq.Simulator() psi = sim.simulate(circuit).dirac_notation() # Display the final wavefunction. print("\nFinal wavefunction:") print(psi)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
To see that the output is stochastic, you can run the cell above multiple times. Since $p = 0.5$ in the bit-flip channel, you should get $|0\rangle$ roughly half the time and $|1\rangle$ roughly half the time. The run method with many repetitions can also be used to see this behavior.
"""Example of Monte Carlo wavefunction simulation with the `run` method.""" circuit = cirq.Circuit( cirq.bit_flip(p=0.5).on(qbit), cirq.measure(qbit), ) res = sim.run(circuit, repetitions=100) print(res.histogram(key=qbit))
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Adding noise to circuits Often circuits are defined with just unitary operations, but we want to simulate them with noise. There are several methods for inserting noise in Cirq. For any circuit, the with_noise method can be called to insert a channel after every moment.
"""One method to insert noise in a circuit.""" # Define some noiseless circuit. circuit = cirq.testing.random_circuit( qubits=3, n_moments=3, op_density=1, random_state=11 ) # Display the noiseless circuit. print("Circuit without noise:") print(circuit) # Add noise to the circuit. noisy = circuit.with_noise(cirq.depolarize(p=0.01)) # Display it. print("\nCircuit with noise:") print(noisy)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
This circuit can then be simulated using the methods described above. The with_noise method creates a cirq.NoiseModel from its input and adds noise to each moment. A cirq.NoiseModel can be explicitly created and used to add noise to a single operation, single moment, or series of moments as follows.
"""Add noise to an operation, moment, or sequence of moments.""" # Create a noise model. noise_model = cirq.NoiseModel.from_noise_model_like(cirq.depolarize(p=0.01)) # Get a qubit register. qreg = cirq.LineQubit.range(2) # Add noise to an operation. op = cirq.CNOT(*qreg) noisy_op = noise_model.noisy_operation(op) # Add noise to a moment. moment = cirq.Moment(cirq.H.on_each(qreg)) noisy_moment = noise_model.noisy_moment(moment, system_qubits=qreg) # Add noise to a sequence of moments. circuit = cirq.Circuit(cirq.H(qreg[0]), cirq.CNOT(*qreg)) noisy_circuit = noise_model.noisy_moments(circuit, system_qubits=qreg)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Note: In the last two examples, the argument system_qubits can be a subset of the qubits in the moment(s). The output of each "noisy method" is a cirq.OP_TREE which can be converted to a circuit by passing it into the cirq.Circuit constructor. For example, we create a circuit from the noisy_moment below.
"""Creating a circuit from a noisy cirq.OP_TREE.""" cirq.Circuit(noisy_moment)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Another technique is to directly pass a cirq.NoiseModel, or a value that can be trivially converted into one, to the density matrix simulator as shown below.
"""Define a density matrix simulator with a `cirq.NOISE_MODEL_LIKE` object.""" noisy_dsim = cirq.DensityMatrixSimulator( noise=cirq.generalized_amplitude_damp(p=0.1, gamma=0.5) )
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
This will not explicitly add channels to the circuit being simulated, but the circuit will be simulated as though these channels were present. Other than these general methods, channels can be added to circuits at any moment just as gates are. The channels can be different, be correlated, act on a subset of qubits, be custom defined, etc.
"""Defining a circuit with multiple noisy channels.""" qreg = cirq.LineQubit.range(4) circ = cirq.Circuit( cirq.H.on_each(qreg), cirq.depolarize(p=0.01).on_each(qreg), cirq.qft(*qreg), bit_phase_flip.on_each(qreg[1::2]), cirq.qft(*qreg, inverse=True), cirq.reset(qreg[1]), cirq.measure(*qreg), cirq.bit_flip(p=0.07).controlled(1).on(*qreg[2:]), ) print("Circuit with multiple channels:\n") print(circ)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
Circuits can also be modified with standard methods like insert to add channels at any point in the circuit. For example, to model simple state preparation errors, one can add bit-flip channels to the start of the circuit as follows.
"""Example of inserting channels in circuits.""" circ.insert(0, cirq.bit_flip(p=0.1).on_each(qreg)) print(circ)
docs/noisy_simulation.ipynb
quantumlib/Cirq
apache-2.0
These data indicate that there are 73 cases on the second list that are not on the first, 86 cases on the first list that are not on the second, and 49 cases on both lists. To keep things simple, we'll assume that each case has the same probability of appearing on each list. So we'll use a two-parameter model where N is the total number of cases and p is the probability that any case appears on any list. Here are priors you can start with (but feel free to modify them).
qs = np.arange(200, 500, step=5) prior_N = make_uniform(qs, name='N') prior_N.head(3) qs = np.linspace(0, 0.98, num=50) prior_p = make_uniform(qs, name='p') prior_p.head(3) # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here
notebooks/chap15.ipynb
AllenDowney/ThinkBayes2
mit
Now you finish it off from there.
# Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here
notebooks/chap15.ipynb
AllenDowney/ThinkBayes2
mit
We are dealing with many NaN values, but its not clear how to treat them all. I will take the NaNs into account afterwards. <a id='deaths_per_area'></a> Deaths per reporting area (all ages)
# Get a subsample of the dataset with deaths for all ages # Do the report only for 2016 for simplicity df_2016 = df[df['MMWR YEAR']==2016] death_per_area = df_2016[['Reporting Area','All causes, by age (years), All Ages**']] death_per_area.head() death_per_area.columns=['Reporting Area','Deaths'] # 2. Drop NaNs: print(len(death_per_area)) death_per_area = death_per_area.dropna() print(len(death_per_area)) df.mean() means=df.mean().values[3:8] categories=['>=65','45-64','25-44','1-24','LT-1'] categories_ids=[1,2,3,4,5] means # Initialize the matplotlib figure #f, ax = plt.pyplot.subplots(figsize=(15, 6)) #Set context, increase font size sns.set_context("poster", font_scale=1.5) #Create a figure plt.pyplot.figure(figsize=(15, 4)) #Define the axis object ax = sns.barplot(x=categories, y=means, palette="Blues_d") #set parameters ax.set(xlabel='Age category', ylabel='Deaths mean', title= "Deaths per age category") #show the plot sns.plt.show()
tmp/Freedom exploration.ipynb
trangel/Data-Science
gpl-3.0
Download data
# Download the reduced data set (2 GB) !wget -r -np -R "index.html*" -e robots=off https://sparkdltrigger.web.cern.ch/sparkdltrigger/Run2012B_SingleMu_sample.orc/ # This downloads the full dataset (16 GB) #!wget -r -np -R "index.html*" -e robots=off https://sparkdltrigger.web.cern.ch/sparkdltrigger/Run2012B_SingleMu.orc/ # Start the Spark Session from pyspark.sql import SparkSession spark = (SparkSession.builder .appName("HEP benchmark") .master("local[*]") .config("spark.driver.memory", "4g") .config("spark.sql.orc.enableNestedColumnVectorizedReader", "true") .getOrCreate() ) # Read data for the benchmark tasks # download data as detailed at https://github.com/LucaCanali/Miscellaneous/tree/master/Spark_Physics path = "sparkdltrigger.web.cern.ch/sparkdltrigger/" input_data = "Run2012B_SingleMu_sample.orc" # use this if you downloaded the full dataset # input_data = "Run2012B_SingleMu.orc" df_events = spark.read.orc(path + input_data) df_events.printSchema() print(f"Number of events: {df_events.count()}")
Spark_Physics/HEP_benchmark/ADL_HEP_Query_Benchmark_Q1_Q5_Colab_Version.ipynb
LucaCanali/Miscellaneous
apache-2.0
Why does it work so well for me? The Donald Knuth had a dream of "literate programming" which captivated me years ago, but I could never really do it until I had the notebook technology. The notebook works really well for including plots and other graphics as well.
# live code some graphics here import matplotlib.pyplot as plt %matplotlib inline plt.plot([3,1,4,1,5]) plt.style.use("fivethirtyeight") plt.plot([3,1,4,1,5]) # your turn: plot some additional digits of pi import sympy # to digits and then plot pi_str = str(sympy.N(sympy.pi, n=100)) pi_digits = [int(x) for x in pi_str if x != '.'] plt.plot(pi_digits)
2-tutorial-notebook-solutions/1-siamam16-intro.ipynb
aflaxman/siaman16-va-minitutorial
gpl-3.0
We will use two "packages" for the hands-on portion of this tutorial Pandas Scikit-Learn Pandas This is a panel data package with a cute name.
# live code an example of loading the va data csv with pandas here import pandas as pd df = pd.read_csv('../3-data/IHME_PHMRC_VA_DATA_ADULT_Y2013M09D11_0.csv', low_memory=False) # DataFrame.iloc method selects row and columns by "integer location" df.iloc[5:10, 5:10] # If you are new to this sort of thing, what do you think this does? df.iloc[5:10, :10] # I don't have time to show you the details now, but I find that # pandas DataFrames have really done things well. For example: df.gs_text34 df.gs_text34.value_counts()
2-tutorial-notebook-solutions/1-siamam16-intro.ipynb
aflaxman/siaman16-va-minitutorial
gpl-3.0
Scikit-Learn This is a python-based machine learning library that has a lot of great methods in a common framework.
# you can guess what the next line does, # even if you have never used python before: import sklearn.neighbors # here is how sklearn creates a "classifier": clf = sklearn.neighbors.KNeighborsClassifier() # I didn't mention `numpy` before, but this is "the fundamental # package for scientific computing with Python" import numpy as np # sklearn gets mixed up with Pandas DataFrames and Series, # so you need to turn things into np.arrays: X = np.array(df.loc[:, ['va46']]) y = np.array(df.gs_text34) # one nice thing about sklearn is that it has all different # fancy machine learning methods, but they all follow a # common pattern: clf.fit(X, y) clf.predict([[19]])
2-tutorial-notebook-solutions/1-siamam16-intro.ipynb
aflaxman/siaman16-va-minitutorial
gpl-3.0
Tabbed Output Containers
table = pd.DataFrame({'a' : [1, 2, 1, 5], 'b' : ["a", "ab", "b", "ababa"]}) l = TabbedOutputContainerLayoutManager() l.setBorderDisplayed(False) o = OutputContainer() o.setLayoutManager(l) o.addItem(plot1, "Scatter with History") o.addItem(plot2, "Short Term") o.addItem(plot3, "Long Term") o.addItem(table, "Pandas Table") o
doc/python/OutputContainers.ipynb
jpallas/beakerx
apache-2.0
Grid Output Containers
bars = CategoryPlot(initWidth= 300, initHeight= 400) bars.add(CategoryBars(value= [[1.1, 2.4, 3.8], [1, 3, 4]])) lg = GridOutputContainerLayoutManager(3) og = OutputContainer() og.setLayoutManager(lg) og.addItem(plot1, "Scatter with History") og.addItem(plot2, "Short Term") og.addItem(plot3, "Long Term1") og.addItem(bars, "Bar Chart") og.addItem(HTML("<center>some<b>thing</b></center>")) og.addItem(table, "Pandas Table") og
doc/python/OutputContainers.ipynb
jpallas/beakerx
apache-2.0