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, ... | 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-valid... | 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_f... | 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_cla... | 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 Tru... | # 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... | 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 ... | 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, ## mi... | 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":12... | 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... | # 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_... | 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 ... | 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 wa... | 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... | 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)
va... | 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']... | 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 automati... | 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.hist... | 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... | 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, ... | 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... | 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(... | 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
t... | 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... | 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('... | 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()
inp... | 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... | 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)... | 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 contaminati... | 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 ... | 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}... | # 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)
# ... | 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 minim... | # 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 + ... | 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://clou... | 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 ... | # 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
... | 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 En... | 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_ite... | 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 re... | 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": DEPL... | 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
... | 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 th... | 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, ... | 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 t... | # 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 midd... | 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'))... | 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]
... | 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 a... | 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'}
... | 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
<a download="fellows.csv" href="data:application/octet-stream;charset=utf-16le;base64,{{ b64encode_output | safe }}">Download the data as CSV.</a>
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.goog... | 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 \right... | 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 asymme... | """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_... | """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 o... | """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_.... | 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 measur... | 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... | 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... | """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 ... | """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.DensityMatrix... | 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 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_notatio... | 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.... | 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)
# ... | 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 ... | """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)... | 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 ... | 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 go... | 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... | 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.o... | 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 p... | 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... | 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"... | 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 Tab... | 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(... | doc/python/OutputContainers.ipynb | jpallas/beakerx | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.