text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Distributed Quantum Phase Estimation Algorithm Quantum phase estimation is a quantum algorithm which is used to estimate the phase (or eigenvalue) of an eigenvector of a unitary operator. If we consider a unitary matrix $U$ and a quantum state $|\psi \rangle$ such that $U|\psi \rangle =e^{2\pi i\theta }$, the algo...
github_jupyter
### Response Figure 1 Since this manuscript's main advance regarding variation in paternal age effect over the Rahbari, et al. result is greater statistical power, more robust statistical analyses of this pattern would strengthen the paper. Figure 3 presents a commendable amount of raw data in a fairly clear way, yet ...
github_jupyter
# Train a QA model The [Hugging Face Model Hub](https://huggingface.co/models) has a wide range of models that can handle many tasks. While these models perform well, the best performance is often found when fine-tuning a model with task-specific data. Hugging Face provides a [number of full-featured examples](https...
github_jupyter
``` # code edited by Tanvi Deora on 28th Sept # decomposes the x y coordinate tracks of each visits into PCA components # output 1) Do we see a separation acorss light or visits # output 2) what are PCA or SVD components that get pulled up as the first few vectors import cv2 import matplotlib.pyplot as plt import glob ...
github_jupyter
``` import random import torch,torchvision import cv2 import os from tqdm import tqdm import matplotlib.pyplot as plt import wandb import numpy as np from torch.nn import * from torch.optim import * from torchvision.transforms import * torch.manual_seed(42) np.random.seed(42) random.seed(42) IMG_SIZE = 224 PROJECT_NAME...
github_jupyter
<h1 align='center' style="margin-bottom: 0px"> An end to end implementation of a Machine Learning pipeline </h1> <h4 align='center' style="margin-top: 0px"> SPANDAN MADAN</h4> <h4 align='center' style="margin-top: 0px"> Visual Computing Group, Harvard University</h4> <h4 align='center' style="margin-top: 0px"> Computer...
github_jupyter
``` import os import sys import subprocess import shlex import operator ``` ## Transmission-Distribution Power Flow Co-simulation This script runs a transmission-distribution power flow. The network is assumed to consist of a single transmission network connected to distribution feeders at each load bus. The number of...
github_jupyter
# Developing an AI application Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall appli...
github_jupyter
# 加载模型用于推理或迁移学习 ## 概述 在模型训练过程中保存在本地的CheckPoint文件,或从MindSpore Hub下载的CheckPoint文件,都可以帮助用户进行推理或迁移学习使用,提高效率。 以下通过示例来介绍如何通过本地加载加载模型,用于推理验证和迁移学习。 > 本文档适用于CPU、GPU和Ascend环境。 ## 整体流程 1. 准备环节。下载数据集,配置运行信息。 2. 数据处理。创建可用于网络训练的数据集,可视化数据集图像。 3. 预训练模型。生成CheckPoint文件。 4. 本地加载模型用于推理验证。 5. 本地加载模型用于迁移学习。 ## 准备环节 ### 下载数据集 运行以下...
github_jupyter
``` %load_ext autoreload %autoreload 2 ``` This notebook will closely follow the [Simulating Molecules using VQE Qiskit Tutorial](https://qiskit.org/textbook/ch-applications/vqe-molecules.html). Our goal is to estimate the ground state energy $\lambda_{\text{min}}$ of some Hamiltonian $H$. By the variational princi...
github_jupyter
# Machine Learning Test You have 3 days to solve the test from the moment you receive it. Show us your skills ! ## Problem description You are hired as a Data Scientist at a top real state company in California, and you first job is to develop an ML model to predict house prices. This model will then be used as an...
github_jupyter
<h1><font size=12> Weather Derivates </h1> <h1> Precipitation Bogota Exploration - El Dorado Airport<br></h1> Developed by [Jesus Solano](mailto:ja.solano588@uniandes.edu.co) <br> 31 Julio 2018 ``` # Configure path to read txts. path = '../datasets/ideamBogota/' # Download the update dataset. import os if not os....
github_jupyter
This demo provides examples of `ImageReader` class from `niftynet.io.image_reader` module. What is `ImageReader`? The main functionality of `ImageReader` is to search a set of folders, return a list of image files, and load the images into memory in an iterative manner. A `tf.data.Dataset` instance can be initialise...
github_jupyter
#### Metode i primjena vjestacke inteligencije #### Laboratorijska vjezba 2 #### Student: Masovic Haris #### Index: 1689/17993 ## 0. Dependencies ``` import sys !{sys.executable} -m pip install tabletext ``` ## 2. KNN algoritam ### 2.1 Implementacija KNN algoritma ``` from collections import Counter from tabletex...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Plot style sns.set() %pylab inline pylab.rcParams['figure.figsize'] = (4, 4) %%html <style> .pquote { text-align: left; margin: 40px 0 40px auto; width: 70%; font-size: 1.5em; font-style: italic; display: block; line-height: 1....
github_jupyter
# Regression Week 4: Ridge Regression (interpretation) In this notebook, we will run ridge regression multiple times with different L2 penalties to see which one produces the best fit. We will revisit the example of polynomial regression as a means to see the effect of L2 regularization. In particular, we will: * Use ...
github_jupyter
# Appendix A - A Crash Course in Python ## IPython and Jupyter Basic notebook operations. ``` a = 'hello' b = 'world' a + ' ' + b ``` Referencing output from previous cells. ``` Out[3] ``` Referencing input from previous cells. ``` In[3] a ``` # Data Types and Collections ## Numeric Data Types ``` type(100) t...
github_jupyter
# <div style="text-align: center">Tutorial on Ensemble Learning </div> <img src='https://data-science-blog.com/wp-content/uploads/2017/12/ensemble-learning-stacking.png' width=400 height=400 > ### <div style="text-align: center"> Quite Practical and Far from any Theoretical Concepts </div> <div style="text-align:cent...
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/W2D1-postcourse-bugfix/tutorials/W2D2_LinearSystems/W2D2_Tutorial2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Neuromatch Academy 2020, Week 2, Day 2, Tuto...
github_jupyter
# Land Cover Change Detection and Description The purpose of this notebook is to provide an easy to use method for comparing and visualising differences between 2 tiles which were classified using the L3 FAO land cover classification system. ``` %matplotlib inline import xarray as xr import numpy as np import lccs_ch...
github_jupyter
<a href="https://colab.research.google.com/github/Rishit-dagli/AI-Workshop-for-beginners/blob/master/Week%202/Week_2_Lab_1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##### Copyright 2020 Rishit Dagli ``` #@title Licensed under the Apache Licen...
github_jupyter
## Movielens ``` %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.learner import * from fastai.column_data import * ``` Data available from http://files.grouplens.org/datasets/movielens/ml-latest-small.zip ``` path='data/ml-latest-small/' ``` We're working with the movielens data, which contains...
github_jupyter
``` import torch import torch.nn.init from torch.autograd import Variable import torchvision.utils as utils import torchvision.datasets as dsets import torchvision.transforms as transforms torch.manual_seed(8) import matplotlib.pyplot as plt import numpy as np import random %matplotlib inline ``` ## Loading MNIST data...
github_jupyter
This notebook checks the correctness of the LDS net implementation ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import nengo from kalman import LDS, LDSNet ``` # 1D tests ``` def test_ldsnet_1d(): """Test LDSNet correctness with tau xdot = -x + u """ SIM_TIME = 1. ...
github_jupyter
## Version 03 -> Pred RUL ``` !pip install texttable from platform import python_version print(python_version()) # importing required libraries from scipy.io import loadmat import matplotlib.pyplot as plt import numpy as np from pprint import pprint as pp from sklearn.pipeline import make_pipeline from sklearn.preproc...
github_jupyter
``` import hail as hl import pandas as pd import numpy as np import matplotlib.pyplot as plt hl.init() ``` ### MAF and Call Rates ``` mt = hl.balding_nichols_model(3, 6, 10) mt = mt.annotate_entries(GT=hl.case().when(hl.rand_bool(.5, seed=1), mt.GT).or_missing()) mt = hl.variant_qc(mt) mt.count() mt.aggregate_entries...
github_jupyter
# Use Core ML to predict Boston house prices with `ibm-watson-machine-learning` This notebook demonstrates how to perform regression analysis using scikit-learn and the watson-machine-learning-client package. Some familiarity with Python is helpful. This notebook is compatible with Python 3.8. You will use the sampl...
github_jupyter
# Using Python to Access NEXRAD Level 2 Data from Unidata THREDDS Server This is a modified version of Ryan May's notebook here: http://nbviewer.jupyter.org/gist/dopplershift/356f2e14832e9b676207 The TDS provides a mechanism to query for available data files, as well as provides access to the data as native volume fi...
github_jupyter
# Project CodeNet Language Classification ## Introduction This notebook takes you through the steps of a simple experiment that shows how to create and exercise a Keras model to detect the language of a piece of source code. We will be using TensorFlow as its backend. For convenience, all the necessary steps will be ...
github_jupyter
``` from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) import os os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2,3" cd /media/datastorage/Phong/svhn_v2 ls mkdir svhn_v2 !wget http://ufldl.stanford.edu/housenumbers/train_32x32.mat !wget http://ufldl.stanford.edu/housenumbers/extra_32x32.mat...
github_jupyter
# Tutorial Part 2: Learning MNIST Digit Classifiers In the previous tutorial, we learned some basics of how to load data into DeepChem and how to use the basic DeepChem objects to load and manipulate this data. In this tutorial, you'll put the parts together and learn how to train a basic image classification model in...
github_jupyter
``` import pandas as pd df = pd.read_csv("../input/train/train.csv") df_test = pd.read_csv("../input/test/test.csv") print(len(df), len(df_test)) for a in range(5): dfs = df[df["AdoptionSpeed"] == a] for i, text in enumerate(dfs["Description"].values): if i == 5: break print(text) ...
github_jupyter
# XAI Tutorial 1: Label Tracking ## Overview In this tutorial, we will discuss the following topics: * [Label Tracking](#tx01labels) We'll start by getting the imports out of the way: ``` import tempfile import fastestimator as fe from fastestimator.architecture.tensorflow import LeNet from fastestimator.backend im...
github_jupyter
## Text generation using tensor2tensor on Cloud ML Engine This notebook illustrates using the <a href="https://github.com/tensorflow/tensor2tensor">tensor2tensor</a> library to do from-scratch, distributed training of a poetry model. Then, the trained model is used to complete new poems. <p/> ### Install tensor2tensor...
github_jupyter
``` %pylab inline from mpl_toolkits import mplot3d import matplotlib import matplotlib.pyplot as plt import seaborn as sns import os import pandas as pd import numpy as np from importlib import reload import sys sys.path.append('../../code/scripts') from dataset_params import dataset_params import utils import plotti...
github_jupyter
``` """ This module consisted of two steps: 1) make planet ARD images and 2) call AFMapTSComposite for making composites """ import boto3 import pandas as pd import gdal import geopandas as gpd import osr from shapely.geometry import mapping from math import ceil from datetime import datetime import os import click fr...
github_jupyter
# Multilayer Perceptron - Old Refactor ## Import dependencies ``` import pickle, gzip, numpy as np import matplotlib.pyplot as plt import matplotlib.style as style style.use('fivethirtyeight') from IPython.core.display import display, HTML invert_l = lambda x: 100 - x discretize_l = lambda x: x / 100 f = gzip.open(...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import fitsio as ft import sys sys.path.append('/home/mehdi/github/LSSutils') import lssutils.utils as lu import numpy as np import healpy as hp old = ft.read('/home/mehdi/data/dr9v0.57.0/sv3nn_v1/tables/sv3tab_LRG_NBMZLS_256.fits') new = ft.read('/home/mehdi/data/...
github_jupyter
# CatBoost and CoreML tutorial — Iris dataset Get iris dataset: ``` from sklearn import datasets iris = datasets.load_iris() ``` Train the model: ``` import catboost cls = catboost.CatBoostClassifier(loss_function='MultiClass') cls.fit(iris.data, iris.target) ``` Predict probabilities: ``` cls.predict(iris.data[0...
github_jupyter
# GFL ENVIRONMENTAL 2020 STOCK TREND ANALYSIS ``` import warnings warnings.filterwarnings('ignore') # Hide warnings import datetime as dt import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like import pandas_datareader.data as web import numpy as np import matplotlib.pyplot as plt import seaborn a...
github_jupyter
# What can go wrong? Consider a simple python computational model of chemical reaction networks: ``` class Element: def __init__(self, symbol, number): self.symbol = symbol self.number = number def __str__(self): return str(self.symbol) class Molecule: def __init__(self, mass): ...
github_jupyter
# 3D Geometries ## Introduction In this tutorial we will describe how to create 3 dimensional structures that are based on one or more 2d profiles. We assume that you already know how to create 2d profiles using the `weldx` package. If this is not the case, please read the corresponding tutorial first. You will lear...
github_jupyter
# NumPy In this lesson we will learn the basics of numerical analysis using the NumPy package. <div align="left"> <a href="https://github.com/madewithml/basics/blob/master/notebooks/03_NumPy.ipynb" role="button"><img class="notebook-badge-image" src="https://img.shields.io/static/v1?label=&amp;message=View%20On%20Git...
github_jupyter
# Introduction to Neural Networks with TensorFlow In this notebook, you'll get introduced to [TensorFlow](https://www.tensorflow.org/), an open source library to help you develop and train machine learning models. TensorFlow in a lot of ways behaves like the arrays you love from NumPy. NumPy arrays, after all, are ju...
github_jupyter
``` import pandas as pd import fredpy as fp import numpy as np ``` # US Seigniorage Data Seigniorage is the real value of the change in the monetary base: \begin{align} \frac{M_{t}-M_{t-1}}{P_t} & = \Delta m_t + \frac{\pi_t}{1+\pi_t}m_{t-1} \end{align} where $\Delta m_t = m_t - m_{t-1}$ and $\pi_t = P_t/ P_{t-1} - ...
github_jupyter
# Using packages ## Math ``` import java.lang.Math; for (int i = 0; i < 5; i++) { var num = Math.random(); var s = String.format("%.5f", num); System.out.println(s); } ``` ## Strings ``` import java.lang.StringBuilder; var entity = "One-Off Coder"; var address = "7526 Old Linton Hall Road"; var city =...
github_jupyter
### TUTORIAL: Train LDA with OCTIS Welcome! This is a tutorial that allows you to train a topic model using OCTIS (Optimizing and Comparing Topic Models Is Simple). ![](https://github.com/MIND-Lab/OCTIS/blob/master/logo.png?raw=true) A topic model allows you to discover the latent topics in your documents in a comp...
github_jupyter
<a href="https://colab.research.google.com/github/dlmacedo/starter-academic/blob/master/The_ultimate_guide_to_Encoder_Decoder_Models_1_4.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` %%capture !pip install -qq git+https://github.com/huggingfac...
github_jupyter
# Solving the heat equation in PyBaMM In this notebook we create and solve a model for unsteady heat diffusion in 1D, with a spatially dependent heat source term. The notebook is adapted from example 4.1.2 on pg.16 of the online notes found [here](https://faculty.uca.edu/darrigo/Students/M4315/Fall%202005/sep-var.pdf)...
github_jupyter
# Self Pix2Pix <table class="tfo-notebook-buttons" align="left" > <td> <a target="_blank" href="https://colab.research.google.com/github/HighCWu/SelfGAN/blob/master/implementations/pix2pix/self_pix2pix.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td>...
github_jupyter
``` from data_loader import load_data from naive_bayes import BernoulliNaiveBayes from nlp_processing import LemmaCountVectorizer from sklearn.pipeline import Pipeline from sklearn.model_selection import RandomizedSearchCV, GridSearchCV from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from...
github_jupyter
# Attention - Qutorch ``` import numpy as np import math, copy, time import torch.nn as nn import torch import torch.nn.functional as F from torch.autograd import Variable import matplotlib.pyplot as plt import seaborn seaborn.set_context(context="talk") %matplotlib inline """ def smiles2int(drug): return [VOCAB...
github_jupyter
Test shotnoise in the contaminated mocks --- small scale clustering changed due to Poisson ``` import fitsio as ft import numpy as np import healpy as hp import os import sys %matplotlib inline import matplotlib.pyplot as plt class mock(object): def __init__(self, featsfile, paramsfile, func='lin', sf=1207432.790...
github_jupyter
``` import numpy as np import pandas as pd from scipy.stats import f import matplotlib.pyplot as plt df = pd.read_csv('insurance.csv') df.head() ``` ## Test of proportions * 'sex' and 'smoker' are two categorical variables * We want to see if the proportion of smokers in the female population is significantly less th...
github_jupyter
# **New Variable Processing** `BIOMASS, SFC_CHL, SFC_FED, SFC_IRR` `BIOMASS` consists of `sfc_ndi`, `sfc_nlg_diatoms`, `sfc_nlg_nondiatoms`, and `sfc_nsm` ``` import os import warnings warnings.filterwarnings("ignore", message="invalid value encountered in true_divide") warnings.filterwarnings("ignore", message="Unab...
github_jupyter
``` # Copyright 2020 Erik Härkönen. All rights reserved. # This file is licensed to you 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 http://www.apache.org/licenses/LICENSE-2.0 # Unless required by app...
github_jupyter
``` import tensorflow as tf import tsp_env import numpy as np import itertools import Q_function_graph_model import matplotlib.pyplot as plt %matplotlib inline n_cities = 5 T = 4 n_mlp_layers = 0 p = 64 n_dagger_steps = 10; max_steps_per_rollout = 10; n_rollouts = 50; n_gradient_steps = 20 learning_rate = 1e-2 obs_ph ...
github_jupyter
``` %load_ext autoreload %autoreload 2 import sys import os import argparse import logging import shutil import re import pickle from PIL import Image from skimage import io import matplotlib.pyplot as plt import numpy as np import pandas as pd from auto_tqdm import tqdm import torch import torch.nn.functional as F imp...
github_jupyter
# Path sum: two ways <div class="problem_content" role="problem"> <p>In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by <b>only moving to the right and down</b>, is indicated in bold red and is equal to 2427.</p> <div style="text-align:center;"> $$ \begin{pmatrix} \color{red}{13...
github_jupyter
# First model: a single hidden layer ``` %matplotlib inline import os import time import numpy as np import matplotlib from matplotlib import pyplot from pandas import DataFrame from pandas.io.parsers import read_csv from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from nolearn.l...
github_jupyter
``` """ The MIT License (MIT) Copyright (c) 2021 NVIDIA Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, pub...
github_jupyter
# Técnicas de Validación Las técnicas de validación consisten en la búsqueda de los metaparametros que mejor resultados nos retornan, las técnicas de validación comúnmente utilizadas son el **K-fold** y el **Grid search**. ## K-fold ![](https://upload.wikimedia.org/wikipedia/commons/b/b5/K-fold_cross_validation_EN.s...
github_jupyter
First install the repo and requirements. ``` %pip --quiet install git+https://github.com/mfinzi/equivariant-MLP.git ``` # Multilinear Maps Our codebase extends trivially to multilinear maps, since these maps are in fact just linear maps in disguise. If we have a sequence of representations $R_1$, $R_2$, $R_3$ for e...
github_jupyter
``` #remove cell visibility from IPython.display import HTML tag = HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide() } else { $('div.input').show() } code_show = !code_show } $( document ).ready(code_toggle); </script> Promijeni vidljivost ...
github_jupyter
# Implementing a Recommender System with SageMaker, MXNet, and Gluon _**Making Video Recommendations Using Neural Networks and Embeddings**_ --- --- *This work is based on content from the [Cyrus Vahid's 2017 re:Invent Talk](https://github.com/cyrusmvahid/gluontutorials/blob/master/recommendations/MLPMF.ipynb)* #...
github_jupyter
``` test_index = 0 ``` #### testing ``` from load_data import * # load_data() ``` ## Loading the data ``` from load_data import * X_train,X_test,y_train,y_test = load_data() len(X_train),len(y_train) len(X_test),len(y_test) ``` ## Test Modelling ``` import torch import torch.nn as nn import torch.optim as optim i...
github_jupyter
``` # pytorch import torch from torchvision.utils import make_grid import torch.optim as optim from torch.utils.data import Dataset, DataLoader # fastmri import fastmri from fastmri.data import subsample from fastmri.data import transforms, mri_data from fastmri.evaluate import ssim, psnr, nmse from fastmri.losses imp...
github_jupyter
``` import sys sys.path.append("..") from nerpharma import PharmaEntitiesTagger, DrugEntitiesTagger pharma_keywords = ["Pharma", "Pharmaceuticals", "Pharmaceutical", "Drugs", "Biotech", "Medical", "World", "Institute", "Health", "Medicare", "Oncology", "Medicine", "Medicines", "Labs", "Healthcare", "Laboratories", "Pha...
github_jupyter
``` import librosa import tensorflow as tf from tensorflow.keras.utils import Sequence import numpy as np import os import glob from tqdm.auto import tqdm import IPython.display as ipd class Signal_Synthesis_Datagen_tf(Sequence): def __init__(self, noise_dir, signal_dir, signal_nums_save=None, num_noise_samples=...
github_jupyter
``` import pandas as pd df = pd.read_csv('car data.csv') df.head() df.shape ``` 301 rows 9 columns ``` print(df['Seller_Type'].unique()) # all unique values in seller print(df['Transmission'].unique()) print(df['Owner'].unique()) print(df['Fuel_Type'].unique()) ## check missing or null values df.isnull().sum() df.de...
github_jupyter
``` %matplotlib inline %load_ext autoreload %autoreload 2 import os import sys import copy import pickle import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy import interpolate from astropy.table import Table, Column, vstack, join color_bins = ["#377eb8", "#e41a1c", "#1b9e77", "#...
github_jupyter
Takes the results from both methods (IRG and U-NEt), introduce on a pandas dataset, saves it on csv and creates a boxplot with the comparison ``` import os import nibabel as nib import matplotlib.pyplot as plt import numpy as np from nilearn import image import matplotlib.pyplot as plt import sys sys.path.insert(0,'C:...
github_jupyter
<a href="https://colab.research.google.com/github/bipinKrishnan/fastai_course/blob/master/text_preprocessing.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from torchvision.datasets.utils import download_and_extract_archive from torch.utils.dat...
github_jupyter
``` from IPython.display import Image ``` # Continuous Factors 1. Base Class for Continuous Factors 2. Joint Gaussian Distributions 3. Canonical Factors 4. Linear Gaussian CPD In many situations, some variables are best modeled as taking values in some continuous space. Examples include variables such as position, v...
github_jupyter
``` from NADINEmainloop import NADINEmain, NADINEmainId from NADINEbasic import NADINE from utilsNADINE import dataLoader, plotPerformance import random import torch import numpy as np # random seed control np.random.seed(0) torch.manual_seed(0) random.seed(0) # load data dataStreams = dataLoader('../dataset/rfid2.mat'...
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 torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import torch.optim as optim from matplotlib import pyp...
github_jupyter
# Bayesian Statistics for Physicists: 05 Sampling ## Contents of the BSFP series <ul> <li><a href="BSFP_01_Overview_and_setup.ipynb">01 Overview and Setup</a> <li><a href="BSFP_02_Basics.ipynb">02 Bayesian basics</a> <li><a href="BSFP_03_Choosing_priors.ipynb">03 Choosing priors</a> <li><a href="BSFP_...
github_jupyter
# Fraud_Detection_Using_SMOTE_OVERSAMPLING I am able to achieve the following accuracies in the validation data. These results can be further improved by reducing the parameter, number of frauds used to create features from category items. I have used a threshold of 100. * Logistic Regression : Validation A...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from matplotlib import cm plt.rcParams['axes.facecolor'] = 'white' params = {"text.usetex" : True, "text.latex.preamble": r"\usepackage{bm}", "font.size" : 25, "axes.labelsize": 30, 'axes.labelpad': 0 } plt.rcParam...
github_jupyter
``` # Make the following code support python2 and python3 from __future__ import division, print_function, unicode_literals # Check if the version of python is 3.5 and above import sys assert sys.version_info >= (3, 5) # Check to see if sklearn is version 0.20 and above import sklearn assert sklearn.__version__ >= "0...
github_jupyter
# Tree cover classification using deep learning on AWS SageMaker This notebook show how to run the [tree cover example](tree-cover-keras.ipynb) on AWS SageMaker. Please read [these](sagemaker.md) instructions on how to setup AWS SageMaker. ``` import os import datetime from os import path as op import itertools fro...
github_jupyter
# ECE 3 : Homework 3 ## Instructions To get started, you should go through the following steps. - Rename this jupyter notebook by adding your name: e.g. `ECE3_HW3_<your-name>.ipynb`. - Complete all the exercises by directly editing your notebook. - Make sure that the coding portions run without errors. ## Problem 1 ...
github_jupyter
## Exercises ### Forward rates #### Discrete with specific numbers ###### Question If the $\,\mathrm{3Y}\,$ bond pays $\,4\%\,$, and the $\,\mathrm{5Y}\,$ bond pays $\,4.5\%\,$, then is the $\,\mathrm{3Y}\to\mathrm{5Y}\,$ forward rate $\,0.5\%\,$?<br/> `Help:` use the definitions to calculate the forward rate. ####...
github_jupyter
# Estimating Joint Tour Frequency This notebook illustrates how to re-estimate a single model component for ActivitySim. This process includes running ActivitySim in estimation mode to read household travel survey files and write out the estimation data bundles used in this notebook. To review how to do so, please ...
github_jupyter
# Task-3 To design a OpenQASM3 interpreter which does the following: 1. Convert the OpenQASM3 code to a Quantum Circuit 2. Calculates the inverse of the circuit For this task, I first start with writing out a basic tokenizer and line-by-line interpreter. The code for the tokenizer and interpreter is in the `qasm_to_q...
github_jupyter
## TensorFlow 1.X ### Installing TensorFlow 1.X ``` %tensorflow_version 1.x import tensorflow as tf tf.__version__ ``` ### Constants #### Defining a constant ``` # Defining a TensorFlow constant tensor = tf.constant([[23, 4], [32, 51]]) tensor # If a session is not initialized, we cannot access the values of th...
github_jupyter
# Estimation Walkthrough ``` from shapely.geometry import Polygon import numpy as np %matplotlib inline import geopandas as gpd from tobler import area_weighted from tobler.area_weighted import _area_tables_binning as area_tables from tobler.area_weighted import area_interpolate ``` ## Example: Two GeoDataFrames ```...
github_jupyter
# Summary <p class='lead'> Compute the optical crosstalk in two 48-pixel SPAD arrays from the 48-spot smFRET-PAX setup. </p> # Find the data ``` fname = 'data/2017-10-16_00_DCR.hdf5' fname from pathlib import Path assert Path(fname).is_file(), 'File not found.' mlabel = Path(fname).stem mlabel ``` # Load software ...
github_jupyter
# Marginal Likelihood Implementation The `gp.Marginal` class implements the more common case of GP regression: the observed data are the sum of a GP and Gaussian noise. `gp.Marginal` has a `marginal_likelihood` method, a `conditional` method, and a `predict` method. Given a mean and covariance function, the functio...
github_jupyter
# Some Variations of Banach's Matchbox Problem Banach's matchbox problem is a good entry point into stochastic stopping problems. A man buys two matchbooks and puts one in each of his two pockets. He then selects a matchbox at random from either pocket, uses a single match, and then returns the matchbox to the same po...
github_jupyter
# Агрегирование в pandas Pandas поддерживает все возможности по агрегированию, которые есть в NumPy. Кроме простых агрегирующих функций в pandas также есть возможность группировки и трансформации данных, которая поволяет выполнять очень сложные вычисления над данными. Создадим небольшой набор данных для простых пример...
github_jupyter
## Importing Dependencies ``` import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline import sklearn from datetime import datetime import pickle df = pd.read_csv('ipl.csv') df.head() ``` ## Data Cleaning ``` columns_remove=['mid','venue','batsman','bowler','str...
github_jupyter
# Reporting Conditions and Predicted Capacities ``` import pandas as pd import matplotlib as plt from captest import capdata as pvc ``` First we load the NREL data used for testing and set the translation dictionary. ``` meas = pvc.CapData('meas') meas.load_data(path='../../tests/data/', fname='nrel_data.csv', sourc...
github_jupyter
# Implementing the Gradient Descent Algorithm In this lab, we'll implement the basic functions of the Gradient Descent algorithm to find the boundary in a small dataset. First, we'll start with some functions that will help us plot and visualize the data. ``` import matplotlib.pyplot as plt import numpy as np import ...
github_jupyter
# Creation of Line Plot Results Figure Here we will be creating the figure displaying the skill of the trained models by visualizing true positive, false positive, false negative, and true negative events as a function of number of kernels used to train the model or as a function of lead time. The figure will contain ...
github_jupyter
# Introduction to Programming with Python # Unit 3: Conditional Operator In the last unit, you were asked to solve a quadratic equation of the form `$$ax^2+bx+c=0$$`. To solve this equation, we can write the following function (based on the well-known [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formu...
github_jupyter
# GluonTS SageMaker SDK Tutorial ***This notebook is meant to be uploaded to a SageMaker notebook instance and executed there. As a kernel choose `conda_mxnet_p36`*** ***In this how-to tutorial we will train a SimpleFeedForwardEstimator on the m4_hourly dataset on AWS SageMaker using the GluonTSFramework, and later r...
github_jupyter
``` import numpy as np arr = np.random.rand(5,5) ``` ### element-wise addition, subtraction, multiplication and division ``` print(arr + 10) print(arr - 10) print(arr * 10) print(arr / 10) # the above operations can be performed using numpy built-in functions # which can save memory as the output can be stored in the...
github_jupyter
# Human numbers ``` from fastai import * from fastai.text import * bs=64 ``` ## Data ``` path = untar_data(URLs.HUMAN_NUMBERS) path.ls() def readnums(d): return [', '.join(o.strip() for o in open(path/d).readlines())] train_txt = readnums('train.txt'); train_txt[0][:80] valid_txt = readnums('valid.txt'); valid_txt[0...
github_jupyter