text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` import torch import pandas as pd import numpy as np import sklearn from collections import Counter from sklearn.utils import Bunch from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from itertools import combinations import re import os import torch.nn as nn impor...
github_jupyter
# Example: Swiss Referenda We propose in this notebook an example of how to use the `predikon` library to make vote predictions. The data is a subsample (10%) of Swiss referenda results. The full dataset can be found in the [submatrix-factorization](https://github.com/indy-lab/submatrix-factorization/blob/master/data/...
github_jupyter
## Macrorheology As the material model is based on microscopic parameters and not on macroscopic parameters (as e.g. the bulk stiffness), the material parameters cannot directly be measured using a rheometer. Instead the rheological experiments are "simulated" on the material model and the resulting curves can be used...
github_jupyter
<h2>Python NumPy</h2> #To install do pip install numpy <b>What is a Python NumPy?</b> NumPy is a Python package which stands for ‘Numerical Python’. It is the core library for scientific computing, which contains a powerful n-dimensional array object, provide tools for integrating C, C++ etc. It is also useful in li...
github_jupyter
# Soring, searching, and counting ``` import numpy as np np.__version__ author = 'kyubyong. longinglove@nate.com' ``` ## Sorting Q1. Sort x along the second axis. ``` x = np.array([[1,4],[3,1]]) out = np.sort(x, axis=1) x.sort(axis=1) assert np.array_equal(out, x) print out ``` Q2. Sort pairs of surnames and first...
github_jupyter
# Introduction Machine learning competitions are a great way to improve your data science skills and measure your progress. In this exercise, you will create and submit predictions for a Kaggle competition. You can then improve your model (e.g. by adding features) to improve and see how you stack up to others taking ...
github_jupyter
### Your very own neural network In this notebook, we're going to build a neural network using naught but pure numpy and steel nerves. It's going to be fun, I promise! ![img](https://s27.postimg.org/vpui4r5n7/cartoon-2029952_960_720.png) ``` # use the preloaded keras datasets and models ! mkdir -p ~/.keras/datasets ...
github_jupyter
## Hospital Preparation ``` import requests import math import pprint import time import numpy as np import pandas as pd import urllib # List from ATC EMS raw data ems_hospitals = ["South Austin Hospital", "Seton Northwest", "North Austin Hospital", "Baylor Scott & White - Austin", "Baylor Scott & White - Lakeway", "...
github_jupyter
``` import pandas as pd, numpy as np from scipy import stats stations=pd.read_csv('data/stations.csv').set_index('ID') c='ro' df=pd.read_csv('data/'+c+'_ds.csv') #daily data # df=pd.read_csv('data/'+c+'_hs.csv') #high_res data df['time']=pd.to_datetime(df['time']) df['year']=df['time'].dt.year df['month']=df['time'].dt...
github_jupyter
# Convolutional Neural Networks --- In this notebook, we train a **CNN** to classify images from the CIFAR-10 database. The process will be broken down into the following steps: >1. Load and visualize the data 2. Define a neural network 3. Train the model 4. Evaluate the performance of our trained model on a test data...
github_jupyter
# Lecture 10 (https://bit.ly/intro_python_10) Today: * Finishing up sequences: * Iterators vs. lists * Generators and the yield keyword * Modules: * Some useful modules * Hierarchical namespaces * Making your own modules * The main() function * PEP 8 (v. briefly) * A revisit to debugging, now that we're writ...
github_jupyter
``` import numpy as np from tifffile import imread, imsave from glob import glob import random import tqdm from matplotlib import pyplot as plt from sklearn.feature_extraction import image X = sorted(glob("/Users/prakash/Desktop/flywing/images/*.tif")) Y = sorted(glob("/Users/prakash/Desktop/flywing/gt/*.tif")) X = lis...
github_jupyter
# Decision Trees and Random Forests in Python This is the code for the lecture video which goes over tree methods in Python. Reference the video lecture for the full explanation of the code! Jose also wrote a [blog post](https://medium.com/@josemarcialportilla/enchanted-random-forest-b08d418cb411#.hh7n1co54) explaini...
github_jupyter
### OCP Data Preprocessing Tutorial This notebook provides an overview of converting ASE Atoms objects to PyTorch Geometric Data objects. To better understand the raw data contained within OC20, check out the following tutorial first: https://github.com/Open-Catalyst-Project/ocp/blob/master/docs/source/tutorials/data...
github_jupyter
``` import numpy as onp import jax.numpy as np from jax import random, vmap from jax.config import config config.update("jax_enable_x64", True) from scipy.optimize import minimize from pyDOE import lhs import matplotlib.pyplot as plt from matplotlib import rc from scipy.interpolate import griddata from jaxbo.models i...
github_jupyter
# Basic Example ## Vector Addition Add a fixed value to an array with numbers in the range [0..99]. The example uses the vector addition kernel included in the [hello world](https://github.com/Xilinx/Vitis_Accel_Examples/tree/63bae10d581df40cf9402ed71ea825476751305d/hello_world) application of the [Vitis Accel Exampl...
github_jupyter
# Querying JSON Databases This notebook demonstrates how to query hierarchical databases with our toy query language BQL. We start with loading a demo JSON dataset with data on departments and employees of the city of Chicago ([source](https://data.cityofchicago.org/Administration-Finance/Current-Employee-Names-Salar...
github_jupyter
##### Copyright 2020 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
# Lab 03: Estimate proportions using SGD Task: Debug some code to use stochastic gradient descent to estimate two proportions. # Scenario Suppose I have two boxes (A and B), each of which have a bunch of small beads in them. Peeking inside, it looks like there are 3 different colors of beads (red, orange, and yellow...
github_jupyter
## 04. Explain the Otimizer in Detail ### Instancing a Optimizer Object 在Basic Tutorial中,我们知道UltraOpt中有如下优化器: |优化器|描述| |-----|---| |ETPE| Embedding-Tree-Parzen-Estimator, 是UltraOpt作者自创的一种优化算法,在TPE算法[<sup>[4]</sup>](#refer-anchor-4)的基础上对类别变量采用Embedding降维为低维连续变量,<br>并在其他的一些方面也做了改进。ETPE在某些场景下表现比HyperOpt的TPE算法要好。 | |For...
github_jupyter
``` from quchem.Hamiltonian_Generator_Functions import * from quchem.Graph import * ### HAMILTONIAN start Molecule = 'H2' geometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.74))] basis = 'sto-3g' ### Get Hamiltonian Hamilt = Hamiltonian_PySCF(Molecule, run_scf=1, run_mp2=1, run_cisd=1, run_ccsd=1,...
github_jupyter
# Model Training (Elasticsearch LTR) We train a LambdaMart model using [RankLib](https://sourceforge.net/p/lemur/wiki/RankLib%20How%20to%20use/) and upload the trained model to Elasticsearch. ``` import json import os import requests DATA_DIR = "../../data" MODEL_FILE = os.path.join(DATA_DIR, "es_lambdamart_model.txt...
github_jupyter
<a href="https://colab.research.google.com/github/BRIJNANDA1979/CNN-Sentinel/blob/master/Understand_band_data_info_using_histogram_and_classifying_pixel_values.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #https://www.earthdatascience.org/cou...
github_jupyter
# Rank Classification using BERT on Amazon Review dataset ## Introduction In this tutorial, you learn how to train a rank classification model using [Transfer Learning](https://en.wikipedia.org/wiki/Transfer_learning). We will use a pretrained DistilBert model to train on the Amazon review dataset. ## About the data...
github_jupyter
##### Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); ``` # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. ...
github_jupyter
# Graph Neural Network (GCN)-based Synthetic Binding Logic Classification with Graph-SafeML The eisting example of GCN-based Synthetic Binding Logic Classification from google research team is used to test the idea of SafeML for Graph-based classifiers. You can find the source code [here](https://github.com/google-rese...
github_jupyter
[@LorenaABarba](https://twitter.com/LorenaABarba) 12 steps to Navier–Stokes ===== *** For a moment, recall the Navier–Stokes equations for an incompressible fluid, where $\vec{v}$ represents the velocity field: $$ \begin{eqnarray*} \nabla \cdot\vec{v} &=& 0 \\ \frac{\partial \vec{v}}{\partial t}+(\vec{v}\cdot\nabla)...
github_jupyter
# Fibonacci Series Classifier *Author: Brianna Gopaul* The fibonacci series is a sequence of numbers that increases as it sums up it's two subsequent values. For example, 1, 1, 2, 3 are numbers within the fibonacci series because 1 + 1 = 2 + 1 = 3. Below we create a supervised model that classifies fibonacci sequenc...
github_jupyter
# Predicting Concrete Compressive Strength - Comparison with Linear Models In this code notebook, we will analyze the statistics pertaining the various models presented in this project. In the Exploratory Data Analysis notebook, we explored the various relationships that each consituent of concrete has on the cured co...
github_jupyter
``` # default_exp vr_parser #hide_input import pivotpy as pp pp.nav_links(1) ``` # Xml Parser > This parser contains functions to extract data from vasprun.xml. All functions in xml parser can work without arguments if working directory contains `vasprun.xml`. - Almost every object in this module returns a `Dict2Dat...
github_jupyter
# Experiments with kernel machines In this notebook we will use simple two-dimensional data sets to illustrate the behavior of the support vector machine and the Perceptron, when used with quadratic and RBF kernels. ## 1. Basic training procedure ``` %matplotlib inline import numpy as np import matplotlib import mat...
github_jupyter
# `logictools` WaveDrom Tutorial [WaveDrom](http://wavedrom.com) is a tool for rendering digital timing waveforms. The waveforms are defined in a simple textual format. This notebook will show how to render digital waveforms using the pynq library. The __`logictools`__ overlay uses the same format as WaveDrom to sp...
github_jupyter
# Математическая оптимизация Многие математические модели задач сводятся к нахождению максимумов или минимумов. Например, в экономических задачах необходимо минимизировать затраты и максимизировать прибыль. Большинство задач машинного обучения также сводятся к нахождению минимума или максимума. Чаще всего задача формул...
github_jupyter
``` from mxnet import nd from mxnet.gluon import nn def conv_block(channels): out = nn.Sequential() out.add( nn.BatchNorm(), nn.Activation('relu'), nn.Conv2D(channels, kernel_size=3, padding=1) ) return out class DenseBlock(nn.Block): def __init__(self, layers, growth_rate,...
github_jupyter
<a href="https://colab.research.google.com/github/NVIDIA/DeepLearningExamples/tree/master/TensorFlow/Segmentation/UNet_Industrial/notebooks/Colab_UNet_Industrial_TF_TFHub_inference_demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` # Copyright...
github_jupyter
##### Copyright 2021 The TensorFlow Cloud Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
github_jupyter
# Confidence Interval: In this notebook you will find: - Get confidence intervals for predicted survival curves using XGBSE estimators; - How to use XGBSEBootstrapEstimator, a meta estimator for bagging; - A nice function to help us plot survival curves. ``` import matplotlib.pyplot as plt plt.style.use('bmh') from I...
github_jupyter
## Copyright 2021 Antoine Simoulin. <i>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) Unless required by ...
github_jupyter
## Our Mission ## Spam detection is one of the major applications of Machine Learning in the interwebs today. Pretty much all of the major email service providers have spam detection systems built in and automatically classify such mail as 'Junk Mail'. In this mission we will be using the Naive Bayes algorithm to cr...
github_jupyter
## Precision-Recall Curves in Multiclass For multiclass classification, we have 2 options: - determine a PR curve for each class. - determine the overall PR curve as the micro-average of all classes Let's see how to do both. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.da...
github_jupyter
``` from __future__ import division, absolute_import import sys import os import numpy as np import random import pickle import time import h5py import pandas as pd from plotnine import * from imblearn import over_sampling from collections import Counter from tables import * import matplotlib.pyplot as plt from matpl...
github_jupyter
``` import graphlab as gl import pickle import pandas as pd import numpy as np from collections import Counter data_items = pickle.load(open("/Users/marvinbertin/Github/family_style_chat_bot/data/user_by_cuisine_by_dish_ratings.pkl", 'rb')) data_cuisine = pickle.load(open("/Users/marvinbertin/Github/family_style_chat_b...
github_jupyter
``` %matplotlib inline %reload_ext autoreload %autoreload 2 # 多行输出 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" from fastai import * from fastai.text import * doc(Config) ``` - IMDB 精简数据 ``` path = untar_data(URLs.IMDB) path path.ls() BATCH = 32 # data_lm ...
github_jupyter
``` %matplotlib inline %config InlineBackend.figure_format = 'retina' import asyncio import aiohttp import json import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import requests import seaborn as sns from ast import literal_eval from collections import defaultdict...
github_jupyter
##### Copyright 2020 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); ``` #@title ##### Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the Lice...
github_jupyter
# Structured Dataset Profiling with Lens ### Find the code This notebook can be found on [github](https://github.com/credo-ai/credoai_lens/blob/develop/docs/notebooks/lens_demos/dataset_profiling.ipynb). ## Contents 1. [What is Covered](#What-is-Covered) 2. [Introduction](#Introduction) 3. [Dataset](#Dataset) 4. [Ru...
github_jupyter
# Training a Linear Model to Predict Length of Stay The [Population Health Management Solution](https://github.com/Azure/cortana-intelligence-population-health-management/tree/master/Azure%20Data%20Lake) uses U-SQL queries in Data Lake Analytics to apply trained models to input data. The solution copies pre-trained mo...
github_jupyter
<a href="https://colab.research.google.com/github/EmilSkaaning/DeepStruc/blob/main/DeepStruc.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # DeepStruc **Github:** https://github.com/EmilSkaaning/DeepStruc **Paper:** DeepStruc: Towards structure s...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # sns.set_context('paper', font_scale=2) def get_talon_nov_colors(samples=None, how='normal'): c_dict = {'Known': '#009E73', 'ISM': '#0072B2', 'NIC': '#D55E00', 'NNC': '#E69F00', 'An...
github_jupyter
CER001 - Generate a Root CA certificate ======================================= If a Certificate Authority certificate for the test environmnet has never been generated, generate one using this notebook. If a Certificate Authoriy has been generated in another cluster, and you want to reuse the same CA for multiple cl...
github_jupyter
# New start...... ``` %cd /content/PyHelpers !ls -a !git add . !git commit -m 'commit 1 from colabs' # !cat '/content/PyHelpers/Libs/OptimalPrime.ipynb' # !git clone https://github.com/bxck75/PyHelpers.git import os import subprocess from IPython.display import clear_output !python /content/PyHelpers/__main__.py # c...
github_jupyter
TSG075 - FailedCreatePodSandBox due to NetworkPlugin cni failed to set up pod ============================================================================= Description ----------- > Error: Warning FailedCreatePodSandBox 58m kubelet, > rasha-virtual-machine Failed create pod sandbox: rpc error: code = > Unknown desc =...
github_jupyter
# 12. 직접 만들어보는 OCR **Text recognition 모델을 구현, 학습하고 Text detection 모델과 연결하여 OCR을 구현한다.** ## 12-1. 들어가며 ## 12-2. Overall structure of OCR ## 12-3. Dataset for OCR ``` import os path = os.path.join(os.getenv('HOME'),'aiffel/ocr') os.chdir(path) print(path) ``` ## 12-4. Recognition model (1) ``` NUMBERS = "0123456...
github_jupyter
# Continuous training with TFX and Google Cloud AI Platform ## Learning Objectives 1. Use the TFX CLI to build a TFX pipeline. 2. Deploy a TFX pipeline version with tuning enabled to a hosted AI Platform Pipelines instance. 3. Create and monitor a TFX pipeline run using the TFX CLI and KFP UI. In this lab, you us...
github_jupyter
# Table of Contents <div class="toc" style="margin-top: 1em;"><ul class="toc-item" id="toc-level0"><li><span><a href="http://localhost:8888/notebooks/ia898/master/tutorial_numpy_1_3.ipynb#Fatiamento-no-ndarray-bidimensional" data-toc-modified-id="Fatiamento-no-ndarray-bidimensional-1"><span class="toc-item-num">1&nbsp...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np # plot style sns.set_style('whitegrid') sns.set_style({'font.family': 'Times New Roman'}) %matplotlib inline df = pd.read_csv("data-policy-results.csv", sep='\t') df.head() len(df) # Pie chart a = df['Policy type'].value_c...
github_jupyter
# Recommender System: - The last thing to do is to use our saved models to recommend items to users: ### For the requested user: - Calculate the score for every item. - Sort the items based on the score and output the top results. ### Check which users exist on the test set ``` !pip install ipython-autotime #### T...
github_jupyter
# About Welcome to the functionality examples notebook. This notebook is only intended for local use: it's a place to try out and explore the `henchman` api without worrying about what will render in html on github or in the docs. ``` import pandas as pd import featuretools as ft es = ft.demo.load_retail() cutoff_ti...
github_jupyter
``` import numpy as np import torch from torch import nn from torch.nn import functional as F DEVICE = "cpu" # if torch.cuda.is_available(): # DEVICE = "cuda" DEVICE class Memory(nn.Module): def __init__(self, N, M): super().__init__() self.N = N self.M = M self.s...
github_jupyter
``` import numpy as np from os.path import isfile from scipy.io import loadmat from collections import OrderedDict from config import DATASET from train_classifiers import train_classifier from utils import compute_kernel, compute_precrec from utils import get_labels, _n_classes, _set_sizes # EXP_NAME = 'FK' EXP_NAME ...
github_jupyter
# DC Resistivity: 1D parametric inversion _Inverting for Resistivities and Layers_ Here we use the module *SimPEG.electromangetics.static.resistivity* to invert DC resistivity sounding data and recover the resistivities and layer thicknesses for a 1D layered Earth. In this tutorial, we focus on the following: - How...
github_jupyter
# **DIVE INTO CODE COURSE** ## **Graduation Assignment** **Student Name**: Doan Anh Tien<br> **Student ID**: 1852789<br> **Email**: tien.doan.g0pr0@hcmut.edu.vn ## Introduction The graduation assignment was based on one of the challenges from the Vietnamese competition **Zalo AI Challenge**. The description of the ch...
github_jupyter
# Непараметрические криетрии Критерий | Одновыборочный | Двухвыборочный | Двухвыборочный (связанные выборки) ------------- | -------------| **Знаков** | $\times$ | | $\times$ **Ранговый** | $\times$ | $\times$ | $\times$ **Перестановочный** | $\times$ | $\times$ | $\times$ ## Недвижимость в Сиэттле ...
github_jupyter
``` import exmp import qiime2 import tempfile import os.path import pandas as pd from qiime2.plugins.feature_table.methods import filter_samples from qiime2.plugins.taxa.methods import collapse ``` # EXMP 1 ``` taxonomy = exmp.load_taxonomy() sample_metadata = exmp.load_sample_metadata() data_dir = exmp.cm_path rare...
github_jupyter
``` import numpy import urllib import scipy.optimize import random from math import * def parseData(fname): for l in urllib.urlopen(fname): yield eval(l) print "Reading data..." data = list(parseData("file:beer_50000.json")) print "done" def feature(datum): text = datum['review/text'].lower().replace(',',' ')...
github_jupyter
# Strategies High-performance solvers, such as Z3, contain many tightly integrated, handcrafted heuristic combinations of algorithmic proof methods. While these heuristic combinations tend to be highly tuned for known classes of problems, they may easily perform very badly on new classes of problems. This issue is bec...
github_jupyter
### Specify a text string to examine with NEMO ``` # specify query string payload = 'The World Health Organization on Sunday reported the largest single-day increase in coronavirus cases by its count, at more than 183,000 new cases in the latest 24 hours. The UN health agency said Brazil led the way with 54,771 cases ...
github_jupyter
This notebook will cover the assumed knowledge of pandas. Here's a few questions to check if you already know the material in this notebook. 1. Does a NumPy array have a single dtype or multiple dtypes? 2. Why is broadcasting useful? 3. How do you slice a DataFrame by row label? 4. How do you select a column of a Data...
github_jupyter
# Testing performance of different 2D Feature detectors in OpenCV Imports... ``` import cv2 import matplotlib.pyplot as plt import numpy as np import seaborn as sn import time sn.set() # Utilities r2b = lambda x: cv2.cvtColor(x, cv2.COLOR_BGR2RGB) r2ba = lambda x: cv2.cvtColor(x, cv2.COLOR_BGRA2RGBA) ``` ## Create ...
github_jupyter
# Logistic regression model ## Setup ``` !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null %cd -q /pyprobml/scripts !pip install -q optax !pip install -q blackjax !pip install -q sgmcmcjax %matplotlib inline import matplotlib.pyplot as plt import numpy as np import itertools import warni...
github_jupyter
# Finding locations to establish temporary emergency facilities Run this notebook to create a Decision Optimization model with Decision Optimization for Watson Studio and deploy the model using Watson Machine Learning. The deployed model can later be accessed using the [Watson Machine Learning client library](https:/...
github_jupyter
``` %matplotlib inline import os import time import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import ndimage import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from IPython.display import clear_output from datetime import dat...
github_jupyter
# Data Analysis This is the main notebook performing all feature engineering, model selection, training, evaluation etc. The different steps are: - Step1 - import dependencies - Step2 - load payloads into memory - Step3A - Feature engineering custom features - Step3B - Feature engineering bag-of-words - Step3C -...
github_jupyter
Handling files belongs also to the basic skills in programming, that's why this chapter was added as a completion by me (Kinga Sipos). <!--NAVIGATION--> < [Strings and Regular Expressions](13-Strings-and-Regular-Expressions.ipynb) | [Contents](Index.ipynb) | [Modules and Packages](15-Modules-and-Packages.ipynb) > # F...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Dynamic-Schedule" data-toc-modified-id="Dynamic-Schedule-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Dynamic Schedule</a></span><ul class="toc-item"><li><span><a href="#Homogeneous-Exponential-Case" d...
github_jupyter
# Circuit Simulation This tutorial demonstrates how to compute (simulate) the outcome probabilities of circuits in pyGSTi. There are currently two basic ways to to this - but constructing and simulating a `Circuit` object, or by constructing and propagating a state. ## Method 1: `Circuit` simulation This is the prima...
github_jupyter
``` # fundamentals import os, glob import numpy as np import pandas as pd from calendar import monthrange, month_name import scipy.stats as stats import funcs as funcs import datetime import imp # plotting libraries and setup from matplotlib.colors import BoundaryNorm import matplotlib.pyplot as plt %matplotlib inline...
github_jupyter
# Create a circuit to generate any two-qubit quantum state in Qiskit Build a general 2-qubit circuit that could output all Hilbert space of states by tuning its parameters. ``` from qiskit import * import numpy as np def state_maker(theta, ang0, ang1): circ = QuantumCircuit(2,2) circ.u3(theta, 0, 0, 0) c...
github_jupyter
# First fitting from amalgams In this phase, we are not considering sequences, leave alone syntax trees, in prediction. Instead we are using the frequency of (shallow) occurence of names in types to predict the (shallow) occurence in definitions. Here we consider the first two models. The second has some depth and sh...
github_jupyter
### Deutsch Jozsa Algorithm! We are given an oracle that implements either a constant function or a balanced function. With just one query, we can find out which one it is. --- Done as part of the NPTEL Course - Introduction to Quantum Computing: Quantum Algorithms and Qiskit https://onlinecourses.nptel.ac.in/noc21_c...
github_jupyter
![](https://i.pinimg.com/564x/79/7b/06/797b06f0efa5afa161add7abaac817dd.jpg) # Magnetometer Calibration Kevin Walchko, Phd 30 May 2020 --- To calibrate a magnetometer, you need to get readings from all directions in 3D space. Ideally, when you plot the readings out, you should get a perfect sphere centered at (0,0...
github_jupyter
#### New to Plotly? Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/). <br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-fo...
github_jupyter
[[source]](../api/alibi.explainers.cem.rst) # Contrastive Explanation Method ## Overview The *Contrastive Explanation Method* (CEM) is based on the paper [Explanations based on the Missing: Towards Constrastive Explanations with Pertinent Negatives](https://arxiv.org/abs/1802.07623) and extends the [code](https://gi...
github_jupyter
``` import pandas as pd import numpy as np #?pd.read_csv ``` # Read Daily Shareprices and Quarterlöy Income statements (Source SimFin) ``` # Import the main functionality from the SimFin Python API. import simfin as sf # Import names used for easy access to SimFin's data-columns. from simfin.names import * sf.set_da...
github_jupyter
# Compound Video Player Widget Most everything in this notebook is a work in progress. ``` import os import IPython import ipywidgets # import nutmeg from jpy_video import Video, TimeCode, compound # Display cells full width txt = """ <style> div#notebook-container { width: 95%; } div#menubar-container ...
github_jupyter
# Exploring Seattle Weather **Learning Objective:** Apply data visualization practices to study the weather in Seattle. In this notebook, we will create visualizations to explore weather data for Seattle, taken from NOAA. The dataset is a CSV file with columns for the temperature (in Celsius), precipitation (in centi...
github_jupyter
# Mentoria Evolution - Python para Data Science https://minerandodados.com.br * Para executar uma célula digite **Control + enter** ou clique em **Run**. * As celulas para rodar script Python devem ser do tipo code. * As celular aceitam comandos python e já executam um "print" automáticamente. ## Mentoria Evolution ...
github_jupyter
## Exercise 3 - Quantum error correction ### Importing Packages ``` from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile from qc_grader import grade_ex3 import qiskit.tools.jupyter from qiskit.test.mock import FakeTokyo ``` #### -------------------------------------------------------...
github_jupyter
# Simulating Clifford randomized benchmarking using a generic noise model This tutorial demonstrates shows how to simulate Clifford RB sequences using arbitrary $n$-qubit process matrices. In this example $n=2$. ``` import pygsti import numpy as np ``` ## Get some CRB circuits First, we follow the [Clifford RB](.....
github_jupyter
# Introduction to programming 1 João Pedro Malhado and Clyde Fare, Imperial College London (contact: [chemistry-git@imperial.ac.uk](mailto:chemistry-git@imperial.ac.uk)) This notebook is licensed under a [Creative Commons Attribution 4.0 (CC-by) license](http://creativecommons.org/licenses/by/4.0/) This is an intera...
github_jupyter
``` %pylab inline from __future__ import division from __future__ import print_function import pandas as pd import seaborn as sb from collections import Counter ``` ## Malware Classification Through Dynamically Mined Traces ### 1. The Dataset The dataset used in this notebook can be freely downloaded from the [c...
github_jupyter
# Aqua Circuit Interoperability Update _Donny Greenberg, Julien Gacon, Ali Javadi, Steve Wood, 24-Mar-19_ ## Basic Vision & End Goal * Make Aqua use circuits as a first-class currency, and feel more like an algorithms library _next to_ Terra, as users expect, rather than an independent library on top of it * No ...
github_jupyter
# TensorFlow Visual Recognition Sample Application Part 1 ## Define the model metadata ``` import tensorflow as tf import requests models = { "mobilenet": { "base_url":"https://github.com/DTAIEB/Thoughtful-Data-Science/raw/master/chapter%206/Visual%20Recognition/mobilenet_v1_0.50_224", "model_file_...
github_jupyter
# k-NN movie reccomendation | User\Film | Movie A | Movie B | Movie C | ... | Movie # | |---------------------------------------------------------| | **User A**| 3 | 4 | 0 | ... | 5 | | **User B**| 0 | 3 | 2 | ... | 0 | | **User C**| 4 | 1 | 3 | ... | ...
github_jupyter
## Quantum Fourier Transform ``` import numpy as np from numpy import pi from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector # doing it for a ...
github_jupyter
# Expression trees in PyBaMM The basic data structure that PyBaMM uses to express models is an expression tree. This data structure encodes a tree representation of a given equation. The expression tree is used to encode the equations of both the original symbolic model, and the discretised equations of that model. On...
github_jupyter
# 응용통계학 (11주차) 5월 12일 > GLM, 일반화선형모형 - toc:true - branch: master - badges: true - comments: false - author: 최서연 - categories: [Applied Statistics, GLM, 일반화 선형 모형] ``` #hide options(jupyter.plot_scale=4) options(repr.plot.width=8,repr.plot.height=6,repr.plot.res=300) #options(jupyter.rich_display=FALSE) #options(max.p...
github_jupyter
# Introduction Do higher film budgets lead to more box office revenue? Let's find out if there's a relationship using the movie budgets and financial performance data that I've scraped from [the-numbers.com](https://www.the-numbers.com/movie/budgets) on **May 1st, 2018**. <img src=https://i.imgur.com/kq7hrEh.png> #...
github_jupyter
``` import os import matplotlib.pyplot as plt import glob from PIL import Image import numpy as np from sklearn.utils import shuffle from tensorflow.python import keras from tensorflow.python.keras import Sequential from tensorflow.python.keras.layers import Dense, InputLayer, Conv2D, MaxPool2D, Flatten, BatchNormaliza...
github_jupyter