markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Remember that variables assigned in one cell are available in all cells. This includes cells that you've previously run and cells that are above where the variable was assigned. Try doing the code completion on the cell third up from here.Code completion also comes in handy if you're using a module but don't quite reme... | # Run this
import random | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
> **Exercise:** In the cell below, place the cursor after `random.` then press **tab** to bring up the code completion menu for the module. Choose `random.randint` from the list, you can move through the menu with the up and down arrow keys. | random.randint | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
Above you should have seen all the functions available from the random module. Maybe you're looking to draw random numbers from a [Gaussian distribution](https://en.wikipedia.org/wiki/Normal_distribution), also known as the normal distribution or the "bell curve". TooltipsYou see there is the function `random.gauss` b... | random.gauss | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
You should have seen some simple documentation like this: Signature: random.gauss(mu, sigma) Docstring: Gaussian distribution. The function takes two arguments, `mu` and `sigma`. These are the standard symbols for the mean and the standard deviation, respectively, of the Gaussian distribution. Maybe you're ... | random.gauss | _____no_output_____ | MIT | exercises/Jupyter/working-with-code-cells.ipynb | rogalskim/udacity-ai-with-python |
基于Tensorflow的softmax回归 Tensorflow是近年来非常非常流行的一个分布式的机器学习框架,之前一直想学习但是一直被各种各样的事情耽搁着。这学期恰好选了“人工神经网络”这门课,不得不接触这个框架了。最开始依照书上的教程通过Anaconda来配置环境,安装tensorflow。结果tensorflow是安装好了但是用起来是真麻烦。最后卸载了Anaconda在裸机上用`pip install tensorflow`来安装,可是裸机上的python是3.6.3版本的,似乎不支持tensorflow,于是在电脑上安装了另一个版本的python才算解决了这个问题,哎!说多了都是泪。言归正传,现在通过一个softmax实... | from tensorflow.examples.tutorials.mnist import input_data
import os
import matplotlib.pyplot as plt
import numpy as np
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'#禁止输出警告信息
#加载mnist数据集,one_hot设定为True是使用向量的形式编码数据类别,这主要是考虑到使用softmax
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print("训练集数据的大小为:{0}".format(m... | Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
训练集数据的大小为:(55000, 784)
| Apache-2.0 | notebooks/Softmax Regression.ipynb | yhswjtuILMARE/Machine-Learning-Study-Notes |
从上面代码的输出可以看到:该数据集的训练集的规模是55000x784。数据集中每一个行向量代表着一个28x28图片的一维展开,虽然说在图片识别中像素点的位置页蕴含着非常大的信息,但是在这里就不在意那么多了,仅仅将其一维展开就可以。笔者用mat将数据集中的前三个图像画了出来展示在上面,接下来就要用到softmax回归的方法实现一个基本的首写字母识别。 softmax回归在这里简要介绍一下softmax回归的相关知识。softmax回归也是线性回归的一种,只不过是在输出层使用了softmax函数进行处理。具体的训练方法上也是使用了经典的随机梯度下降法训练。其判别函数有如下形式:$$f(x)=wx+b$$**注意:softmax回归可以用... | import tensorflow as tf
session = tf.InteractiveSession()#定义一个交互式会话
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))#权重w初始化为0
b = tf.Variable(tf.zeros([1, 10]))#bias初始化为0
y = tf.nn.softmax(tf.matmul(x, w) + b)
y_ = tf.placeholder(tf.float32, [None, 10]) | _____no_output_____ | Apache-2.0 | notebooks/Softmax Regression.ipynb | yhswjtuILMARE/Machine-Learning-Study-Notes |
设定其损失函数`cross_entry`,规定优化目标,初始化全局参数: | cross_entry = -tf.reduce_mean(tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_set = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entry)
tf.global_variables_initializer().run() | _____no_output_____ | Apache-2.0 | notebooks/Softmax Regression.ipynb | yhswjtuILMARE/Machine-Learning-Study-Notes |
准备工作都差不多做完了,接下来应该进行模型的训练。在本例中迭代一千次,每次从训练集中随机选取100组数据训练模型。 | for i in range(1000):
trainSet, trainLabel = mnist.train.next_batch(100)
train_set.run(feed_dict={x: trainSet, y_: trainLabel}) | _____no_output_____ | Apache-2.0 | notebooks/Softmax Regression.ipynb | yhswjtuILMARE/Machine-Learning-Study-Notes |
以上,我们已经完成了模型的训练,现在应该检测一下模型的效果。我们使用mnist的测试数据来测试模型的分类效果: | accuracy = tf.cast(tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)), dtype=tf.float32)
accuracy = tf.reduce_mean(accuracy)
print("模型的分类正确率为{0:.3f}".format(session.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))) | 模型的分类正确率为0.917
| Apache-2.0 | notebooks/Softmax Regression.ipynb | yhswjtuILMARE/Machine-Learning-Study-Notes |
Functional Python BProf Python course June 25-29, 2018 Judit Ács Python has 3 built-in functions that originate from functional programming. Map- `map` applies a function on each element of a sequence | def double(e):
return e * 2
l = [2, 3, "abc"]
list(map(double, l))
map(double, l)
%%python2
def double(e):
return e * 2
l = [2, 3, "abc"]
print(map(double, l))
list(map(lambda x: x * 2, [2, 3, "abc"]))
class Doubler:
def __call__(self, arg):
return arg * 2
list(map(Doubler(), l))
[x * 2 fo... | _____no_output_____ | MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
Filter- filter creates a list of elements for which a function returns true | def is_even(n):
return n % 2 == 0
l = [2, 3, -1, 0, 2]
list(filter(is_even, l))
list(filter(lambda x: x % 2 == 0, range(8)))
[e for e in l if e % 2 == 0] | _____no_output_____ | MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
Most comprehensions can be rewritten using map and filter | l = [2, 3, 0, -1, 2, 0, 1]
signum = [x / abs(x) if x != 0 else x for x in l]
print(signum)
list(map(lambda x: x / abs(x) if x != 0 else 0, l))
even = [x for x in l if x % 2 == 0]
print(even)
print(list(filter(lambda x: x % 2 == 0, l))) | [2, 0, 2, 0]
| MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
Reduce- reduce applies a rolling computation on a sequence- the first argument of `reduce` is two-argument function- the second argument is the sequence- the result is accumulated in an accumulator | from functools import reduce
l = [1, 2, -1, 4]
reduce(lambda x, y: x*y, l) | _____no_output_____ | MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
an initial value for the accumulator may be supplied | reduce(lambda x, y: x*y, l, 10)
reduce(lambda x, y: max(x, y), l)
reduce(max, l)
reduce(max, map(lambda n: n*n, l))
reduce(lambda x, y: x + int(y % 2 == 0), l, 0) | _____no_output_____ | MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
`any` and `all`Checks if any or every element of an iterable evaluates to `False` in a boolean context. | def is_even(num):
if num % 2 == 0:
print("{} is even".format(num))
return True
print("{} is odd".format(num))
return False
l = [2, 4, 0, -1, 6, 8, 1]
# all(map(is_even, l))
all(is_even(i) for i in l)
l = [3, 1, 5, 0, 7, 0, 0]
# any(map(is_even, l))
any(is_even(i) for i in l) | 3 is odd
1 is odd
5 is odd
0 is even
| MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
`zip` | x = [1, 2, 0]
y = [-2, 6, 0, 2]
for pair in zip(x, y):
print(type(pair), pair)
for pair in zip(x, y, x, y):
print(type(pair), pair) | <class 'tuple'> (1, -2, 1, -2)
<class 'tuple'> (2, 6, 2, 6)
<class 'tuple'> (0, 0, 0, 0)
| MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
for and while loops do not create a new scope but functions do | y = "outside foo"
def foo():
i = 2
for _ in range(4):
y = 3
print(y)
print("Calling foo")
foo()
print("Global y unchanged: {}".format(y)) | Calling foo
3
Global y unchanged: outside foo
| MIT | lectures/09_Functional_python.ipynb | juditacs/bprof-python |
Matching Registry and PA State Business License Data | import pandas as pd
import mwdsbe
import mwdsbe.datasets.licenses as licenses
import schuylkill as skool
import time
def drop_duplicates_by_date(df, date_column):
df.sort_values(by=date_column, ascending=False, inplace=True)
df = df.loc[~df.index.duplicated(keep="first")]
df.sort_index(inplace=True)
ret... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Data | registry = mwdsbe.load_registry() # geopandas df
license = licenses.CommercialActivityLicenses().get()
registry.head()
state_license = pd.read_csv('./data/PAStateBusinessLicense/Sales_Tax_Licenses_and_Certificates_Current_Monthly_County_Revenue.csv')
print('Size of state_license data:', len(state_license))
# convert st... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Merge registry and state_license by company_name and legal_name / trade name | # t1 = time.time()
# merged = (
# skool.tf_idf_merge(pa_registry, cleaned_state_license, left_on="company_name", right_on="legal_name", score_cutoff=85)
# .pipe(skool.tf_idf_merge, pa_registry, cleaned_state_license, left_on="company_name", right_on="trade_name", score_cutoff=85)
# .pipe(skool.tf_idf_merge,... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Eliminate companies with different zip code | matched_state['postal_code_clean'] = matched_state.postal_code.astype(str).apply(lambda x : x.split("-")[0]).astype(float)
matched_state = matched_state.set_index('left_index')
matched_state_zip = matched_state[matched_state.zip_code == matched_state.postal_code_clean]
len(matched_state_zip)
matched_state_zip['expirati... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Comparing between match between "registry-opendata license" and "registry-state license"How many more new companies do we get from registry-opendata license matching? | # t1 = time.time()
# merged = (
# skool.tf_idf_merge(cleaned_registry, cleaned_license, on="company_name", score_cutoff=85)
# .pipe(skool.tf_idf_merge, cleaned_registry, cleaned_license, left_on="dba_name", right_on="company_name", score_cutoff=85)
# )
# t = time.time() - t1
# print('Execution time:', t/60, 'mi... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Loading matched of registry and opendataphilly_license data | matched_opendataphilly_license = pd.read_excel(r'C:\Users\dabinlee\Desktop\mwdsbe\data\license-opendataphilly\tf-idf\tf-idf-85.xlsx')
matched_opendataphilly_license = matched_opendataphilly_license.set_index('left_index')
len(matched_opendataphilly_license)
matched_opendataphilly_license = drop_duplicates_by_date(match... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Investigate missing companies in opendataphilly license dataWe found 94 newly matched companies from matching between registry and state_license, why these are not appeared in matching between registry and opendataphilly license data? | t1 = time.time()
merged = (
skool.tf_idf_merge(cleaned_registry, cleaned_license, on="company_name", score_cutoff=0)
.pipe(skool.tf_idf_merge, cleaned_registry, cleaned_license, left_on="dba_name", right_on="company_name", score_cutoff=0)
)
t = time.time() - t1
print('Execution time:', t/60, 'min')
matched = me... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Compare intersection between matched_opendataphilly_license and matched_state_zip* matched_opendataphilly_license: matched data between pa_registry and license data from opendataphilly* matched_state_zip: matched data between pa_registry and license data from state_registry and filter matches which do not match zipcod... | intersection = matched_state_zip.index.intersection(matched_opendataphilly_license.index).tolist()
len(intersection) # 246 - 94
intersection1 = matched_opendataphilly_license.loc[intersection]
len(intersection1)
intersection2 = matched_state_zip.loc[intersection]
len(intersection2)
intersection1 = intersection1[['compa... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Merge by address - Not matching well | cleaned_state_license.head()
# split street address from address_with_lat/long
cleaned_state_license['street_address'] = cleaned_state_license['address_with_lat/long'].astype(str).apply(lambda x : x.split("\n")[0])
cleaned_state_license.head()
pa_registry.head()
# clean street information
cleaned_pa_registry = skool.cl... | _____no_output_____ | MIT | mwdsbe/.ipynb_checkpoints/PA_state_business_license-checkpoint.ipynb | BinnyDaBin/MWDSBE |
Secara Visual | import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('seaborn')
iris = pd.read_csv('data/iris.csv')
iris.shape
iris.head()
iris.plot(x='sepal_length', y='sepal_width')
iris.plot(x='sepal_length', y='sepal_width', kind='scatter')
plt.xlabel('sepal length (cm)')
plt.ylabel('sepal width (cm... | _____no_output_____ | MIT | Bagian 4 - Fundamental Pandas/2. Exploratory Data Analysis.ipynb | selmakaramy/Data-warehouse |
Secara Statistik | iris.describe()
iris.count()
iris['sepal_length'].count()
iris.mean()
iris.std()
iris.median()
q = 0.5
iris.quantile(q)
q = [0.25, 0.75]
iris.quantile(q)
iris.min()
iris.max()
iris.plot(kind= 'box')
plt.ylabel('[cm]') | _____no_output_____ | MIT | Bagian 4 - Fundamental Pandas/2. Exploratory Data Analysis.ipynb | selmakaramy/Data-warehouse |
Filtering | iris.head()
iris['species'].describe()
iris['species'].value_counts()
iris['species'].unique()
index_setosa = iris['species'] == 'setosa'
index_versicolor = iris['species'] == 'versicolor'
index_virginica = iris['species'] == 'virginica'
setosa = iris[index_setosa]
versicolor = iris[index_versicolor]
virginica = iris[i... | _____no_output_____ | MIT | Bagian 4 - Fundamental Pandas/2. Exploratory Data Analysis.ipynb | selmakaramy/Data-warehouse |
Geometric Objects {ref_geometric_example}=================The \"Hello, world!\" of VTK | import pyvista as pv | _____no_output_____ | MIT | examples/00-load/create-geometric-objects.ipynb | vtkiorg/vtki-examples |
This runs through several of the available geometric objects availablein VTK which PyVista provides simple convenience methods for generating.Let\'s run through creating a few geometric objects! | cyl = pv.Cylinder()
arrow = pv.Arrow()
sphere = pv.Sphere()
plane = pv.Plane()
line = pv.Line()
box = pv.Box()
cone = pv.Cone()
poly = pv.Polygon()
disc = pv.Disc() | _____no_output_____ | MIT | examples/00-load/create-geometric-objects.ipynb | vtkiorg/vtki-examples |
Now let\'s plot them all in one window | p = pv.Plotter(shape=(3, 3))
# Top row
p.subplot(0, 0)
p.add_mesh(cyl, color="tan", show_edges=True)
p.subplot(0, 1)
p.add_mesh(arrow, color="tan", show_edges=True)
p.subplot(0, 2)
p.add_mesh(sphere, color="tan", show_edges=True)
# Middle row
p.subplot(1, 0)
p.add_mesh(plane, color="tan", show_edges=True)
p.subplot(1, ... | _____no_output_____ | MIT | examples/00-load/create-geometric-objects.ipynb | vtkiorg/vtki-examples |
Settings | # Slumps
INFERENCE_DIR = Path(r'Q:\p_aicore_pf\initze\processed\inference\RTS_6Regions_V01_UnetPlusPlus_resnet34_FocalLoss_sh6_50_bs100_2021-12-04_22-27-53')
# Pingo
#INFERENCE_DIR = Path(r'Q:\p_aicore_pf\initze\processed\inference\pingo_UnetPP_v1_2021-12-12_09-56-50')
OUTPUT_DIR = Path(r'C:\Users\initze\OneDrive\100_... | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
create filelist | flist = list(INFERENCE_DIR.glob('*')) | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
Load files and add to list | %time ds_list = Parallel(n_jobs=10)(delayed(load_dataset)(f) for f in tqdm.tqdm_notebook(flist[:]))
ds_list = []
for f in flist[:]:
try:
ds_list.append(get_vector(f))
except:
print(f'Error on {f.stem}') | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
Merge all GDF to one | rdf = gpd.GeoDataFrame( pd.concat( ds_list, ignore_index=True) ) | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
Set projection (got lost during merge with pandas) | rdf = rdf.set_crs(epsg=4326) | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
Calculate time variables for later analysis | rdf['year'] = pd.to_datetime(rdf.iloc[:]['date'], infer_datetime_format=True).dt.year
rdf['month'] = pd.to_datetime(rdf.iloc[:]['date'], infer_datetime_format=True).dt.month
rdf['doy'] = pd.to_datetime(rdf.iloc[:]['date'], infer_datetime_format=True).dt.day_of_year | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
Write to file | rdf.to_file(out_file) | _____no_output_____ | MIT | ANALYSIS_06_merge_results.ipynb | initze/thaw_slump_preprocessing |
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.  ... | import azureml.core
from azureml.core import Workspace, Datastore, Experiment, Dataset
from azureml.core.compute import AmlCompute
from azureml.core.compute import ComputeTarget
# Check core SDK version number
print("SDK version:", azureml.core.VERSION)
from azureml.data.data_reference import DataReference
from azure... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Compute Targets Retrieve an already attached Azure Machine Learning Compute | from azureml.core.compute_target import ComputeTargetException
aml_compute_target = "cpu-cluster"
try:
aml_compute = AmlCompute(ws, aml_compute_target)
print("found existing compute target.")
except ComputeTargetException:
print("creating new compute target")
provisioning_config = AmlCompute.provi... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Building Pipeline Steps with Inputs and OutputsA step in the pipeline can take [dataset](https://docs.microsoft.com/python/api/azureml-core/azureml.data.filedataset?view=azure-ml-py) as input. This dataset can be a data source that lives in one of the accessible data locations, or intermediate data produced by a previ... | # Uploading data to the datastore
data_path = def_blob_store.upload_files(["./20news.pkl"], target_path="20newsgroups", overwrite=True)
# Reference the data uploaded to blob storage using file dataset
# Assign the datasource to blob_input_data variable
blob_input_data = Dataset.File.from_files(data_path).as_named_input... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Define a Step that consumes a dataset and produces intermediate data.In this step, we define a step that consumes a dataset and produces intermediate data.**Open `train.py` in the local machine and examine the arguments, inputs, and outputs for the script. That will give you a good sense of why the script argument nam... | # trainStep consumes the datasource (Datareference) in the previous step
# and produces processed_data1
source_directory = "publish_run_train"
trainStep = PythonScriptStep(
script_name="train.py",
arguments=["--input_data", blob_input_data, "--output_train", processed_data1],
inputs=[blob_input_data]... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Define a Step that consumes intermediate data and produces intermediate dataIn this step, we define a step that consumes an intermediate data and produces intermediate data.**Open `extract.py` in the local machine and examine the arguments, inputs, and outputs for the script. That will give you a good sense of why the... | # extractStep to use the intermediate data produced by step4
# This step also produces an output processed_data2
processed_data2 = PipelineData("processed_data2", datastore=def_blob_store)
source_directory = "publish_run_extract"
extractStep = PythonScriptStep(
script_name="extract.py",
arguments=["--input_ext... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Define a Step that consumes multiple intermediate data and produces intermediate dataIn this step, we define a step that consumes multiple intermediate data and produces intermediate data. PipelineParameter This step also has a [PipelineParameter](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azur... | # We will use this later in publishing pipeline
pipeline_param = PipelineParameter(name="pipeline_arg", default_value=10)
print("pipeline parameter created") | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
**Open `compare.py` in the local machine and examine the arguments, inputs, and outputs for the script. That will give you a good sense of why the script argument names used below are important.** | # Now define step6 that takes two inputs (both intermediate data), and produce an output
processed_data3 = PipelineData("processed_data3", datastore=def_blob_store)
source_directory = "publish_run_compare"
compareStep = PythonScriptStep(
script_name="compare.py",
arguments=["--compare_data1", processed_data1, ... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Build the pipeline | pipeline1 = Pipeline(workspace=ws, steps=[compareStep])
print ("Pipeline is built") | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Run published pipeline Publish the pipeline | published_pipeline1 = pipeline1.publish(name="My_New_Pipeline", description="My Published Pipeline Description", continue_on_step_failure=True)
published_pipeline1 | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Note: the continue_on_step_failure parameter specifies whether the execution of steps in the Pipeline will continue if one step fails. The default value is False, meaning when one step fails, the Pipeline execution will stop, canceling any running steps. Publish the pipeline from a submitted PipelineRunIt is also poss... | # submit a pipeline run
pipeline_run1 = Experiment(ws, 'Pipeline_experiment').submit(pipeline1)
# publish a pipeline from the submitted pipeline run
published_pipeline2 = pipeline_run1.publish_pipeline(name="My_New_Pipeline2", description="My Published Pipeline Description", version="0.1", continue_on_step_failure=True... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Get published pipelineYou can get the published pipeline using **pipeline id**.To get all the published pipelines for a given workspace(ws): ```cssall_pub_pipelines = PublishedPipeline.get_all(ws)``` | from azureml.pipeline.core import PublishedPipeline
pipeline_id = published_pipeline1.id # use your published pipeline id
published_pipeline = PublishedPipeline.get(ws, pipeline_id)
published_pipeline | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
Run published pipeline using its REST endpoint[This notebook](https://aka.ms/pl-restep-auth) shows how to authenticate to AML workspace. | from azureml.core.authentication import InteractiveLoginAuthentication
import requests
auth = InteractiveLoginAuthentication()
aad_token = auth.get_authentication_header()
rest_endpoint1 = published_pipeline.endpoint
print("You can perform HTTP POST on URL {} to trigger this pipeline".format(rest_endpoint1))
# spec... | _____no_output_____ | MIT | how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.ipynb | oliverw1/MachineLearningNotebooks |
LIDAR to 2D grid map exampleThis simple tutorial shows how to read LIDAR (range) measurements from a file and convert it to occupancy grid.Occupancy grid maps (_Hans Moravec, A.E. Elfes: High resolution maps from wide angle sonar, Proc. IEEE Int. Conf. Robotics Autom. (1985)_) are a popular, probabilistic approach to ... | import math
import numpy as np
import matplotlib.pyplot as plt
from math import cos, sin, radians, pi | _____no_output_____ | MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
The measurement file contains the distances and the corresponding angles in a `csv` (comma separated values) format. Let's write the `file_read` method: | def file_read(f):
"""
Reading LIDAR laser beams (angles and corresponding distance data)
"""
measures = [line.split(",") for line in open(f)]
angles = []
distances = []
for measure in measures:
angles.append(float(measure[0]))
distances.append(float(measure[1]))
angles = ... | _____no_output_____ | MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
From the distances and the angles it is easy to determine the `x` and `y` coordinates with `sin` and `cos`. In order to display it `matplotlib.pyplot` (`plt`) is used. | ang, dist = file_read("lidar01.csv")
ox = np.sin(ang) * dist
oy = np.cos(ang) * dist
plt.figure(figsize=(6,10))
plt.plot([oy, np.zeros(np.size(oy))], [ox, np.zeros(np.size(oy))], "ro-") # lines from 0,0 to the
plt.axis("equal")
bottom, top = plt.ylim() # return the current ylim
plt.ylim((top, bottom)) # rescale y axi... | _____no_output_____ | MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
The `lidar_to_grid_map.py` contains handy functions which can used to convert a 2D range measurement to a grid map. For example the `bresenham` gives the a straight line between two points in a grid map. Let's see how this works. | import lidar_to_grid_map as lg
map1 = np.ones((50, 50)) * 0.5
line = lg.bresenham((2, 2), (40, 30))
for l in line:
map1[l[0]][l[1]] = 1
plt.imshow(map1)
plt.colorbar()
plt.show()
line = lg.bresenham((2, 30), (40, 30))
for l in line:
map1[l[0]][l[1]] = 1
line = lg.bresenham((2, 30), (2, 2))
for l in line:
ma... | _____no_output_____ | MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
To fill empty areas, a queue-based algorithm can be used that can be used on an initialized occupancy map. The center point is given: the algorithm checks for neighbour elements in each iteration, and stops expansion on obstacles and free boundaries. | from collections import deque
def flood_fill(cpoint, pmap):
"""
cpoint: starting point (x,y) of fill
pmap: occupancy map generated from Bresenham ray-tracing
"""
# Fill empty areas with queue method
sx, sy = pmap.shape
fringe = deque()
fringe.appendleft(cpoint)
while fringe:
... | _____no_output_____ | MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
This algotihm will fill the area bounded by the yellow lines starting from a center point (e.g. (10, 20)) with zeros: | flood_fill((10, 20), map1)
map_float = np.array(map1)/10.0
plt.imshow(map1)
plt.colorbar()
plt.show() | _____no_output_____ | MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
Let's use this flood fill on real data: | xyreso = 0.02 # x-y grid resolution
yawreso = math.radians(3.1) # yaw angle resolution [rad]
ang, dist = file_read("lidar01.csv")
ox = np.sin(ang) * dist
oy = np.cos(ang) * dist
pmap, minx, maxx, miny, maxy, xyreso = lg.generate_ray_casting_grid_map(ox, oy, xyreso, False)
xyres = np.array(pmap).shape
plt.figure(figsi... | The grid map is 150 x 100 .
| MIT | Mapping/lidar_to_grid_map/lidar_to_grid_map_tutorial.ipynb | Shelfcol/PythonRobotics |
Recursion- A way of solving a problem by having a function call itself. Performing the same operation with different inputs. Usually smaller inputs for convergence, with a base condition to prevent infinite loop. IRL example- Russian Doll. Pseudocode | def openRussianDoll(doll):
if doll==1: #Smallest Doll
print('All Dolls opened')
else:
openRussianDoll(doll-1)
| _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Recursion logic.Stack Memory is used and last in, first out is followed. Recursion is less time and space efficient as against iteration. But it is easier to code. How to write Recursion Factorial | def factorial(n):
assert n>=0 and int (n)==n, 'The number must be positive integer only'
if n in [0,1]:
return 1
else:
return n*factorial(n-1)
factorial(5) | _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Fibonnaci n-th term of a Fibonnaci series | fib_list=[]
def fibonacci(n):
assert n>=0 and int (n) ==n, 'The number must be integer and positive'
if n in [0,1]:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
fibonacci(5) | _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Fibonacci series containing of n terms | a=0
b=1
fib_list=[0,1]
n= int(input('No of terms you want'))
assert int (n)==n and n>0
i=0
if n==1:
print(0)
else:
while i<n-2:
temp=a+b
fib_list.append(temp)
a=b
b=temp
i+=1
print(fib_list) | No of terms you want15
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
| Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Sum of digits of an integer number | def sumOfDigits(n):
sum=0
assert int (n) == n and n>=0, 'Must be a positive integer'
while n>0:
return n%10 +sumOfDigits(int (n/10))
else:
return 0
sumOfDigits(546)
#sumOfDigits(-87) | _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Power of a number | def powerOfNumber(x,n):
assert int (n) ==n and n >=0
if n==0:
return 1
if n==1:
return x
else:
return x*powerOfNumber(x, n-1)
powerOfNumber( -2, 5)
def gcd(a, b):
assert int (a) == a and int (b) ==b, 'Integer numbers only'
if a%b==0:
return b
else:
return gcd(b, a%b)
print(gcd(48,18... | 6
| Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Decimal to Binary | def decToBinary(n):
assert int (n) ==n
if n is 0:
return 0
if n is 1:
return 1
else:
return (int (n%2))+10*decToBinary(int (n/2))
decToBinary(13) | _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Reverse of a number using Recursion | def reverseNumber(n, r):
#assert int (n) == n and n >0
if n ==0:
return r
else:
return reverseNumber( int ( n/10), r*10+n%10)
reverseNumber(647, 0) | _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Largest number in an Array. | def findMaxNumRec( sampleArray, n): #n is the length of array
if n==1:
return sampleArray[0]
else:
return max(sampleArray[n-1], findMaxNumRec(sampleArray, n-1))
findMaxNumRec([11, 14, 7, 9, 3, 12], 6)
| _____no_output_____ | Apache-2.0 | Recursion_Udemy.ipynb | DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python |
Settings/scenario managementCapacity expansion modeling is often an exercise in exploring the difference between different technical, cost, or policy scenarios across a range of planning years, so PowerGenome has a built-in method for creating modified versions of a single baseline scenario. Within the settings file t... | %load_ext autoreload
%autoreload 2
from pathlib import Path
import pandas as pd
from powergenome.util import (
build_scenario_settings,
init_pudl_connection,
load_settings,
check_settings
) | _____no_output_____ | MIT | notebooks/Scenario management.ipynb | TemoaProject/PowerGenome |
Import settingsSettings are imported by reading the YAML file and converting it to a Python dictionary. In the code below I'm loading the settings and creating a nested dictionary `scenario_settings` that has all of the modified parameters for each case.Settings can also be checked for some common errors using the `ch... | cwd = Path.cwd()
settings_path = (
cwd.parent / "example_systems" / "CA_AZ" / "test_settings.yml"
)
settings = load_settings(settings_path)
settings["input_folder"] = settings_path.parent / settings["input_folder"]
scenario_definitions = pd.read_csv(
settings["input_folder"] / settings["scenario_definitions_fn... | _____no_output_____ | MIT | notebooks/Scenario management.ipynb | TemoaProject/PowerGenome |
We can check to see if the natural gas price has changed from case `p1` to `s1`, and confirm that they are different. | scenario_settings[2030]["p1"]["aeo_fuel_scenarios"]
scenario_settings[2030]["s1"]["aeo_fuel_scenarios"] | _____no_output_____ | MIT | notebooks/Scenario management.ipynb | TemoaProject/PowerGenome |
The values of `model_year` and `model_first_planning_year` have also changed from lists to integers. | settings["model_year"], settings["model_first_planning_year"]
scenario_settings[2030]["p1"]["model_year"], scenario_settings[2030]["p1"]["model_first_planning_year"]
scenario_settings[2045]["p1"]["model_year"], scenario_settings[2045]["p1"]["model_first_planning_year"] | _____no_output_____ | MIT | notebooks/Scenario management.ipynb | TemoaProject/PowerGenome |
This notebook tries to build a world tree by drawing and edge between every character in the save file with their father and mother. Running this code will generate a network with over 270,000 nodes out of a total of almost 400,000. This was taking far too long for Gephi to graph so I did not continue.The next 3 notebo... | pipeline = [
{
"$unwind" : "$parents"
},
{
"$lookup" :
{
"from" : "dynasties",
"localField" : "dnt",
"foreignField" : "_id",
"as" : "dynasty"
}
},
{
"$unwind" : "$dynasty"
},
{
"$match" : ... | _____no_output_____ | MIT | notebooks/9. World Tree (Delete).ipynb | maniacalbrain/ck2-social-networks |
Get all Characters | pipeline = [
{
"$lookup" :
{
"from" : "dynasties",
"localField" : "dnt",
"foreignField" : "_id",
"as" : "dynasty"
}
},
{
"$unwind" : "$dynasty"
},
{
"$project" : {"_id" : 1, "name" : {"$concat" : ["$bn", " ", "$d... | _____no_output_____ | MIT | notebooks/9. World Tree (Delete).ipynb | maniacalbrain/ck2-social-networks |
Build Network | import networkx as nx
import matplotlib.pyplot as plt
chars = list(characters.aggregate(pipeline))
for char in chars:
for key in list(char.keys()):
val = char[key]
if isinstance(val, type(None)):
del char[key]
G = nx.Graph()
for char in chars: #characters.aggregate(pipeline)... | _____no_output_____ | MIT | notebooks/9. World Tree (Delete).ipynb | maniacalbrain/ck2-social-networks |
* [.*](https://zhidao.baidu.com/question/318809970.html) 数组加法:A+B,数组加法和矩阵加法相同。 数组减法:A-B ,数组减法和矩阵减法相同。 数组乘法:A.*B,A 和 B 的元素逐个对应相乘,两数组之间必须有相同的形,或其中一个是标量。 矩阵乘法:A*B,A 和 B 的矩阵乘法,A 的列数必须和 B 的行数相同。 数组右除法:A./B,A 和 B 的元素逐个对应相除:A(i,j)/B(i,j)两数组之间必须有相同的形,或其中一个是标量。 数组左除法:A.\B,A 和 B 的元素逐个对应相除:B(i,j)/A(i,j)两数组之间必须有... | % 目标
z = sum(sum(d.*x)); | _____no_output_____ | MIT | TSP_problem.ipynb | C-Joey/YALMIP_LEARNING |
\begin{aligned} \min Z=& \sum_{i=1}^{n} \sum_{j=1}^{n} d_{i j} x_{i j} \\ &\left(\begin{array}{cc}{\sum_{i=1, i \neq j}^{n} x_{i j}=1,} & {j=1, \cdots, n} \\ {\sum_{j=1, j \neq i}^{n} x_{i j}=1,} & {i=1, \cdots, n} \\ {u_{i}-u_{j}+n x_{i j} \leq n-1,} & { \quad 1<i \neq j \leq n}\\{x_{i j}=\{0 , 1\},} & {i, j=1, \cdots... | % 约束添加
C = [];
for j = 1:n
s = sum(x(:,j))-x(j,j);
C = [C, s == 1];
end
for i = 1:n
s = sum(x(i,:)) - x(i,i);
C = [C, s == 1];
end
for i = 2:n
for j = 2:n
if i~=j
C = [C,u(i)-u(j) + n*x(i,j)<=n-1];
end
end
end
% 求解 假如不把z加进去,则能得到一个可行解
result= optimize(C,z);
% 求解
if... |
ans =
NaN 0 0 1 0 0 0 0 0 0
0 NaN 0 0 0 0 1 0 0 0
0 1 NaN 0 0 0 0 0 0 0
0 0 1 NaN 0 0 0 0 0 0
0 0 0 0 NaN 1 0 0 0 0
0 ... | MIT | TSP_problem.ipynb | C-Joey/YALMIP_LEARNING |
Pythonの基礎 データ型 | # [変数名] = [値] と書くと,その変数名を持った変数に値を代入できる.代入された値は後で利用したりすることができる.
x = 1 # 整数
y = 2.1 # 実数
z = 2 * x + y # 四則演算 (×→*, ÷→/)
print(z) # print(x)でxを表示.print(x, y, ...)ともかけて,xとyにスペースが入って出力される
str1 = "これは文字列"
str2 = 'これも文字列'
str3 = """
このように書くと
複数行に渡る文字列
を表現できる
"""
str4 = '''
こちらでも
良い
'''
str5 = str1 + str2 # 文字列の+は文字列の結合
prin... | False
True
True
The condition was True
| MIT | notebooks/11_python_basics.ipynb | mpkato/iam |
制御構文 | """
if condition:
# conditionがTrueのときにここが実行される
else:
# conditionがFalseのときにここが実行される(else:以降は省略可能)
"""
# 長いコメントは"""や'''で書ける
x = 3
if x > 2:
print("x > 2")
else:
print("x <= 2")
if x == 3:
print("x == 3")
# Pythonでインデントは構文の一部!!
# インデントが増えた箇所から元のインデント数に戻るまで,インデント数が同じ箇所は同じコードブロックと見なされる.
# コードブロック:... | 例外が発生しました
Can't convert 'int' object to str implicitly
| MIT | notebooks/11_python_basics.ipynb | mpkato/iam |
関数 | """
def function_name(var1, var2, ...):
# 関数の中身. e.g. x = var1 + var2
return x
# 引数var1, var2, ...を与えて,xを返す関数function_nameを定義できる
"""
def square(x):
result = x * x
return result
y = square(2)
print(y) | 4
| MIT | notebooks/11_python_basics.ipynb | mpkato/iam |
TRAIN SET | trainDataFull = pd.read_csv("trainData.csv")
trainDataFull.head(3)
trainDataFull.info()
trainDataFull.describe()
trainData = trainDataFull.loc[:,'v1':'v99']
trainData.head(3)
trainLabels = trainDataFull.loc[:,'target']
trainLabels.unique()
# encode string class values as integers
label_encoder = LabelEncoder()
label_en... | _____no_output_____ | MIT | 1D-series/Model-2 (Random Forest).ipynb | umitkacar/1D-Ensemble |
MODEL-2 (Random Forest Classifier) | RFC_model = RandomForestClassifier(n_estimators=800,
verbose=2,
random_state=0,
criterion='gini')
RFC_model
RFC_model.fit(X_train, y_train)
# make predictions for test data
y_pred = RFC_model.predict(X_test)
y_pred
... | [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 0.0s remaining: 0.0s
[Parallel(n_jobs=1)]: Done 800 out of 800 | elapsed: 3.1s finished
| MIT | 1D-series/Model-2 (Random Forest).ipynb | umitkacar/1D-Ensemble |
Save Valid Score | y_score = RFC_model.predict_proba(X_test)
y_score[0]
valid_score = pd.DataFrame(y_score, columns=['c1','c2','c3','c4','c5','c6','c7','c8','c9'])
valid_score
valid_score.to_csv('./results/valid-submission-RFC.csv', index = False) | _____no_output_____ | MIT | 1D-series/Model-2 (Random Forest).ipynb | umitkacar/1D-Ensemble |
Save & Load Model joblib | # Save the model as a pickle in a file
joblib.dump(RFC_model, './model/model_RFC.pkl')
# Load the model from the file
RFC_model_from_joblib = joblib.load('./model/model_RFC.pkl')
# Use the loaded model to make predictions
RFC_model_predictions = RFC_model_from_joblib.predict(X_test)
# evaluate predictions... | [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 0.0s remaining: 0.0s
| MIT | 1D-series/Model-2 (Random Forest).ipynb | umitkacar/1D-Ensemble |
GridSearchCV | clf = GridSearchCV(RFC_model_model,
{'max_depth': [4, 6],
'n_estimators': [100, 200]},
verbose=1,
cv=2)
clf.fit(X_train,
y_train,
early_stopping_rounds=10,
eval_metric='mlogloss',
eval_set=[(X_train, y_train... | _____no_output_____ | MIT | 1D-series/Model-2 (Random Forest).ipynb | umitkacar/1D-Ensemble |
TEST | testData = pd.read_csv("testData.csv")
testData
# Use the loaded model to make predictions
test_predictions = RFC_model.predict(testData.values)
test_predictions
# Use the loaded model to make predictions probability
test_predictions = RFC_model.predict_proba(testData.values)
test_predictions
result = pd.DataFrame(tes... | _____no_output_____ | MIT | 1D-series/Model-2 (Random Forest).ipynb | umitkacar/1D-Ensemble |
LayersUma vez criada uma sequencia de códigos, foi possível definir uma funão que integra todos eles, apresentada abaixo: | from get_data_datageo import * | _____no_output_____ | MIT | get_layers.ipynb | open-geodata/sp_datageo |
Sedes Municipais | # Input dos caminhos para os metadados
url = 'http://datageo.ambiente.sp.gov.br/geoportal/catalog/search/resource/details.page?uuid='
id_metadados = '{64BF344A-3AD0-410A-A3AA-DFE01C4E9BBB}'
# URL
url_meta = '{}{}'.format(url, id_metadados)
# Download
gdf = download_datageo_shp(url_meta)
# Renomeia Colunas
gdf = gdf.... | Página com metadados: http://datageo.ambiente.sp.gov.br/geoportal/catalog/search/resource/details.page?uuid={64BF344A-3AD0-410A-A3AA-DFE01C4E9BBB}
Resposta da página foi <Response [200]>
> Encontrei o shapefile
Link: http://datageo.ambiente.sp.gov.br/geoserver/datageo/SedesMunicipais/wfs?version=1.0.0&request=GetFeatur... | MIT | get_layers.ipynb | open-geodata/sp_datageo |
Limite Municipal | # Input dos caminhos para os metadados
url = 'http://datageo.ambiente.sp.gov.br/geoportal/catalog/search/resource/details.page?uuid='
id_metadados = '{74040682-561A-40B8-BB2F-E188B58088C1}'
# URL
url_meta = '{}{}'.format(url, id_metadados)
# Download
gdf = download_datageo_shp(url_meta)
# Renomeia Colunas
gdf = gdf.... | Página com metadados: http://datageo.ambiente.sp.gov.br/geoportal/catalog/search/resource/details.page?uuid={74040682-561A-40B8-BB2F-E188B58088C1}
Resposta da página foi <Response [200]>
> Encontrei o shapefile
Link: http://datageo.ambiente.sp.gov.br/geoserver/datageo/LimiteMunicipal/wfs?version=1.0.0&request=GetFeatur... | MIT | get_layers.ipynb | open-geodata/sp_datageo |
Trusted Notebook" align="middle"> Accreditation protocol Accreditation Protocol (AP) is a protocol devised to characterize the reliability of noisy quantum devices.Given a noisy quantum device implementing a "target" quantum circuit, AP certifies an upper-bound on the variation distance between the probability distri... | #Import general libraries (needed for functions)
import numpy as np
from numpy import random
import qiskit
#Import Qiskit classes
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors ... | _____no_output_____ | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
Input to the protocol AP can accredit the outputs of a __target circuit__ that1) Takes as input $n$ qubits in the state $|{0}>$2) Ends with single-qubit measurements in the Pauli-$Z$ basis3) Is made of $m$ "bands", each band containing a round of single-qubit gates and a round of controlled-$Z$ gates.The accreditation... | # Create a Quantum Register with n_qb qubits.
q_reg = QuantumRegister(4, 'q')
# Create a Classical Register with n_qb bits.
c_reg = ClassicalRegister(4, 's')
# Create a Quantum Circuit acting on the q register
target_circuit = QuantumCircuit(q_reg, c_reg)
target_circuit.h(0)
target_circuit.h(1)
target_circuit.h(2)
tar... | _____no_output_____ | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
Generating accreditation circuits The function $accreditation\_circuits$ generates all the circuits required by AP, target and traps. It automatically appends random Pauli gates to the circuits (if the implementation is noisy, these random Pauli gates reduce the noise to Pauli errors ! ) It also returns the list $post... | v = 10
circ_list, postp_list, v_zero = accreditation_circuits(target_circuit, v)
circ_list[(v_zero)%(v+1)][0].draw(output = 'mpl') | _____no_output_____ | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
This is how a trap looks like: | circ_list[(v_zero+1)%(v+1)][0].draw(output = 'mpl') | _____no_output_____ | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
Simulate the ideal circuits Let's implement AP.We use $accreditation\_circuits$ to generate target and trap circuits.Then, we use the function $single\_protocol\_run$ to implement all these circuits, keeping the output of the target only if all of the traps return the correct output. | simulator = qiskit.Aer.get_backend('qasm_simulator')
test_1 = accreditationFitter()
# Create target and trap circuits with random Pauli gates
circuit_list, postp_list, v_zero = accreditation_circuits(target_circuit, v)
outputs_list = []
for circuit_k in range(v+1):
job = execute(circuit_list[circuit_k], simulato... | Outputs of the target: [0, 0, 0, 0] , AP accepted these outputs!
| Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
In the absence of noise, all traps return the expected output, therefore we always accept the output of the target.To obtain an upper-bound on the variation distance on the outputs of the target circuit, we need to implement AP $d$ times, each time with ___v___ different trap circuits. | # Number of runs
d = 20
test_2 = accreditationFitter()
for run in range(d):
# Create target and trap circuits with random Pauli gates
circuit_list, postp_list, v_zero = accreditation_circuits(target_circuit, v)
outputs_list = []
# Implement all these circuits
for circuit_k in range(v+1):... | Protocol run number 1 , outputs of the target accepted
Protocol run number 2 , outputs of the target accepted
Protocol run number 3 , outputs of the target accepted
Protocol run number 4 , outputs of the target accepted
Protocol run number 5 , outputs of the target accepted
Protocol run number 6 , outputs of the target... | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
The function $bound\_variation\_distance$ calculates the upper-bound on the variation distance (VD) using$$VD\leq \frac{\varepsilon}{N_{\textrm{acc}}/d-\theta}\textrm{ ,}$$where $\theta\in[0,1]$ is a positive number and$$\varepsilon= \frac{1.7}{v+1}$$is the maximum probability of accepting an incorrect state for the ta... | theta = 5/100
test_2.bound_variation_distance(theta)
print("AP accepted",test_2.N_acc,"out of",test_2.num_runs,"times.")
print("With confidence",test_2.confidence,"AP certifies that VD is upper-bounded by",test_2.bound) | AP accepted 20 out of 20 times.
With confidence 1.0 AP certifies that VD is upper-bounded by 0.16267942583732053
| Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
Defining the noise model We define a noise model for the simulator. We add depolarizing error probabilities to the cotrolled-$Z$ and single-qubit gates. | noise_model = NoiseModel()
p1q = 0.002
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1q, 1), 'u1')
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1q, 1), 'u2')
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1q, 1), 'u3')
p2q = 0.02
noise_model.add_all_qubit_quantum_error(depolar... | _____no_output_____ | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
We then implement noisy circuits and pass their outputs to $single\_protocol\_run$. | test_3 = accreditationFitter()
for run in range(d):
# Create target and trap circuits with random Pauli gates
circuit_list, postp_list, v_zero = accreditation_circuits(target_circuit, v)
outputs_list = []
# Implement all these circuits with noise
for circuit_k in range(v+1):
job =... | Protocol run number 1 , outputs of the target rejected
Protocol run number 2 , outputs of the target rejected
Protocol run number 3 , outputs of the target rejected
Protocol run number 4 , outputs of the target accepted
Protocol run number 5 , outputs of the target accepted
Protocol run number 6 , outputs of the target... | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
Changing the number of trap circuits per protocol run changes the upper-bound on the VD, but not the confidence.What number of trap circuits will ensure the minimal upper-bound for your target circuit? | min_traps = 4
max_traps = 10
for num_trap_circs in range(0,max_traps-min_traps):
test_4 = accreditationFitter()
for run in range(d):
# Create target and trap circuits with random Pauli gates
circuit_list, postp_list, v_zero = accreditation_circuits(target_circuit, num_trap_circs+min_tra... |
With 4 traps, AP accepted 15 out of 20 times.
With confidence 1.0 AP with 4 traps certifies that VD is upper-bounded by 0.48571428571428577
With 5 traps, AP accepted 14 out of 20 times.
With confidence 1.0 AP with 5 traps certifies that VD is upper-bounded by 0.4358974358974359
With 6 traps, AP accepted 9 out of 20 ... | Apache-2.0 | examples/accreditation_tutorial.ipynb | hodgestar/qiskit-ignis |
Lab 2 Ashwin Rajgopal Start off by importing numpy for matrix math, random for random ordering of samples and pyplot for plotting results. | import matplotlib.pyplot as plt
import numpy as np
import random | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
Creating the samplesX variables can be generated by using `np.random.rand` to generate a array of random numbers between 0 and 1, which is what is required. The same can be done to generate the noise, but then it needs to be divided by 5 and subtracted by .1 to fit the interval [-0.1, 0.1]. The expected values can the... | X = np.random.rand(1, 75).flatten()
noise = np.random.rand(1, 75).flatten() / 5 - 0.1
D = 0.5 + 0.4 * np.sin(2 * np.pi * X) + noise
func_X = np.linspace(0, 1, 100)
func_Y = 0.5 + 0.4 * np.sin(2 * np.pi * func_X) | _____no_output_____ | Apache-2.0 | Lab2.ipynb | ashraj98/rbf-sin-approx |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.