text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
04 .Differential expression using DESeq2 ======================================== The analysis process includes three main steps, namely normalization, dispersion estimation and test for differential expression. ``` library(phyloseq) library(ggplot2) library(scales) library(gridExtra) suppressPackageStartupMessages(l...
github_jupyter
``` import json with open("../out/202006222159_spanishfn.json") as fp: data = json.load(fp) from scipy.stats import rankdata def rank_transform(orig): data = np.copy(orig) indices = [i for i, s in enumerate(data) if s > 0] norm = rankdata([data[i] for i in indices], "max") / len(indices) for i, s...
github_jupyter
# Quantum Teleportation This notebook demonstrates quantum teleportation. We first use Qiskit's built-in simulators to test our quantum circuit, and then try it out on a real quantum computer. ## Contents 1. [Overview](#overview) 2. [The Quantum Teleportation Protocol](#how) 3. [Simulating the Teleportati...
github_jupyter
# Model viewer Quickly view results of previously run models in Jupyter Notebook. Results and parameters can also be viewed in the directory itself, but this notebook provides a quick way to either (1) view all data from a single run in one place and (2) compare the same file across multiple runs. It does require some...
github_jupyter
# Bayesian Survival Analysis Copyright 2017 Allen Downey MIT License: https://opensource.org/licenses/MIT ``` from __future__ import print_function, division %matplotlib inline import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd import thinkbayes2 import thinkplot ``` ## Sur...
github_jupyter
# Imports ``` import numpy as np import sklearn.metrics from sklearn import linear_model from sklearn.datasets import load_breast_cancer ``` # Load Data "Breast Cancer" is a tiny dataset for binary classification ``` features, targets = load_breast_cancer(return_X_y=True) print('Features') print('shape:', features....
github_jupyter
# Sample Survey Bihar Election 2021 EDA ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns ``` ### Load the dataset into a pandas dataframe. Name the variable as “survey”. ``` survey=pd.read_excel('Sample Survey.xlsx',sheet_name='Data') survey.head() ``` ### How many sa...
github_jupyter
``` # !wget http://s3-ap-southeast-1.amazonaws.com/huseinhouse-storage/bert-bahasa/bert-bahasa-base.tar.gz # !tar -zxf bert-bahasa-base.tar.gz from tqdm import tqdm import json import bert from bert import run_classifier from bert import optimization from bert import tokenization from bert import modeling import numpy ...
github_jupyter
``` %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns heart_df = pd.read_csv("data/heart-disease.csv") heart_df.head() # classification dataset - supervised learning ``` ## 1. Tuning hyperparameters by hand so far we've worked with training and test datase...
github_jupyter
# 6장. 알고리즘 체인과 파이프라인 *아래 링크를 통해 이 노트북을 주피터 노트북 뷰어(nbviewer.org)로 보거나 구글 코랩(colab.research.google.com)에서 실행할 수 있습니다.* <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://nbviewer.org/github/rickiepark/intro_ml_with_python_2nd_revised/blob/main/06-algorithm-chains-and-pipelines...
github_jupyter
# Mixture Density Network for Regression ``` import nbloader,os,warnings warnings.filterwarnings("ignore") import numpy as np import matplotlib.pyplot as plt import scipy.io as sio import tensorflow as tf import tensorflow.contrib.slim as slim from sklearn.utils import shuffle from util import gpusession,create_gradi...
github_jupyter
# Ensembles notebook <a href="https://mybinder.org/v2/gh/tinkoff-ai/etna/master?filepath=examples/ensembles.ipynb"> <img src="https://mybinder.org/badge_logo.svg" align='left'> </a> This notebook contains the simple examples of using the ensemble models with ETNA library. **Table of Contents** * [Load Dataset]...
github_jupyter
# Calculation of the entropy for sources with and without memory ## Introduction This tutorial will get you familiar with the calculation of the entropy associated with a given source. We start by recalling some definitions and fundamental results from the [Shannon's information theory](http://people.math.harvard.edu/~...
github_jupyter
<a href="https://colab.research.google.com/github/clemencia/ML4PPGF_UERJ/blob/master/correlations.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **Valores esperados, médias e variância** **Valor esperado** ou média de x: $\mu = E[x] = \int_{-\in...
github_jupyter
# Tutorial NlOpt ## Зачем это нужно? В современных компетенциях инженерных или научных специальностей всё чаще приходится сталкиваться с теми или иными задачами требующими оптимизации функции. В общем смысле под оптимизацией понимают поиск экстремума исследуемой функции. $$f(x,y) \rightarrow max(min)$$ Заметим, что ...
github_jupyter
# Vessels making voyages The `voyages` table contains top level information about a voyage from one port to another, including when and where the voyage started and ended, and which vessel was involved in the voyage. You can use this information to identify which vessels made a voyage from one port to another in some t...
github_jupyter
# The Lasso Modified from the github repo: https://github.com/JWarmenhoven/ISLR-python which is based on the book by James et al. Intro to Statistical Learning. ``` # %load ../standard_import.txt import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import scale from sklea...
github_jupyter
``` import pandas as pd from googleapiclient.discovery import build from googleapiclient.errors import HttpError from oauth2client.tools import argparser target = "아디다스 슈퍼스타" DEVELOPER_KEY = "AIzaSyAnEEAKE50qxf5lHbsucDiMNayh9aFUj5g" YOUTUBE_API_SERVICE_NAME="youtube" YOUTUBE_API_VERSION="v3" youtube = build(YOUTUBE_API...
github_jupyter
# Stacking LSTM Layers ----------------- Here we implement an LSTM model on all a data set of Shakespeare works. We will stack multiple LSTM models for a more accurate representation of Shakespearean language. We will also use characters instead of words. ``` import os import re import string import requests import n...
github_jupyter
#### Verification Alignment A forecast is verified by comparing a set of initializations at a given lead to observations over some window of time. However, there are a few ways to decide *which* initializations or verification window to use in this alignment. One must pass the keyword ``alignment=...`` to the hindcas...
github_jupyter
In this notebook, we explore the learning curve for the toxic spans detector ``` from transformers import RobertaTokenizer, RobertaForTokenClassification from transformers import BertTokenizer, BertForTokenClassification from transformers import AutoTokenizer, AutoModelForTokenClassification import torch import numpy ...
github_jupyter
# DecisionTreeRegressor with Normalize This Code template is for regression analysis using simple DecisionTreeRegressor based on the Classification and Regression Trees algorithm along with Normalize Feature Scaling technique. ### Required Packages ``` import warnings import numpy as np import pandas as pd import se...
github_jupyter
``` from IPython.core.display import HTML, display display(HTML("<style>.container { width:80% !important; }</style>")) display(HTML("<style>div.output_scroll { height: 44em; }</style>")) %%capture # install popmon (if not installed yet) import sys !"{sys.executable}" -m pip install popmon import pandas as pd import...
github_jupyter
## packages ``` import tensorflow as tf from tensorflow import keras import tensorflow_probability as tfp from tensorflow.keras import layers from tensorflow.keras.models import load_model from sklearn.metrics import mean_squared_error from sklearn.preprocessing import RobustScaler from tensorflow.keras.preprocessing....
github_jupyter
## Flexible models This toolbox can handle models with fitted model parts. In this demo we will see how this is done. First we need some imports: ``` import numpy as np import matplotlib.pyplot as plt import rsatoolbox ``` As a first step lets generate a few random RDMs, which will serve as our data. We generate 10 ...
github_jupyter
# 1-异常检测 ## note: * [covariance matrix](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html) * [multivariate_normal](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html) * [seaborn bivariate kernel density estimate](https://stanford.edu/~mwaskom/software/seaborn/ge...
github_jupyter
## Filtering and Annotation Tutorial ### Filter You can filter the rows of a table with [Table.filter](https://hail.is/docs/0.2/hail.Table.html#hail.Table.filter). This returns a table of those rows for which the expression evaluates to `True`. ``` import hail as hl hl.utils.get_movie_lens('data/') users = hl.rea...
github_jupyter
# Logistic Regression --- Lets first import required libraries: ``` import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix, jac...
github_jupyter
# Linear regression as a statistical estimation problem ### Dr. Tirthajyoti Sarkar, Fremont, CA 94536 --- This notebook demonstrates linear regression as a statistical estimation problem. We will see how to do the following as part of a linear regression modeling, - Compute statistical properties like standard error...
github_jupyter
## Tercera parte pandas - Operaciones con fechas - Combinar dataframes - Reacomodar datos ``` %pylab inline import pandas as pd # Cargar nuestra base de datos de elencos elenco = pd.read_csv('data/cast.csv', encoding='utf-8') elenco.head() # Ahora tambien cargaremos datos de otra base de datos # fecha_lanz = pd.read...
github_jupyter
# Initialization Welcome to the first assignment of "Improving Deep Neural Networks". Training your neural network requires specifying an initial value of the weights. A well chosen initialization method will help learning. If you completed the previous course of this specialization, you probably followed our ins...
github_jupyter
``` import os, sys import paddle sys.path.append('/workspace/fnet_paddle/PaddleNLP') from paddlenlp.datasets import load_dataset test_ds = load_dataset("glue", name="cola", splits=("test")) len(test_ds) def convert_example(example, tokenizer, max_seq_length=512, ...
github_jupyter
``` # get current timestamp for proper documentation of testing and validation results from datetime import datetime currentTime = str(datetime.now()) model_save_name = 'causal_classifier_' + currentTime + '.bin' #path = F"/content/gdrive/My Drive/Causality Classification/" ``` ## Setup Load the transformers library...
github_jupyter
# Interactions from the literature ``` %pylab inline %config InlineBackend.figure_format = 'retina' import json import numpy as np studies = [ { 'name' : 'Gopher, Lice', 'type' : 'parasitism', 'host' : 'data/gopher-louse/gopher.tree', 'guest': 'data/gopher-louse/lice.tree', ...
github_jupyter
# Rigid-body transformations in three-dimensions > Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil The kinematics of a rigid body is completely described by its pose, i.e., its position and orientation in space (and the co...
github_jupyter
There are two main functions * decision_function * predict_proba Most of classifiers have at least one of them, and many have both ``` from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import make_circles import numpy as np import matpl...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') import torch import torch.nn as nn class DepthwiseConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding=1): super(DepthwiseConv2d, self).__init__() self.depthwiseconv = nn.Sequential( ...
github_jupyter
``` import os import csv import sys import scipy.optimize as opt import scipy.stats as stat from operator import itemgetter import random import numpy as np import numpy.ma as ma import numpy.linalg as la pi = np.pi sin = np.sin cos = np.cos def fillin2(data): """ Fills in blanks of arrays without shifting fra...
github_jupyter
``` import pandas as pd import numpy as np data=pd.read_csv("/home/jay/Desktop/Cricket/Final/FinalTrainingDataset.csv") data X=data.iloc[:,1:14].values y=data.iloc[:,14].values y X.shape from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.20,random_state...
github_jupyter
# 作業 : (Kaggle)鐵達尼生存預測 *** - 分數以網站評分結果為準, 請同學實際將提交檔(*.csv)上傳試試看 https://www.kaggle.com/c/titanic/submit # [作業目標] - 試著模仿範例寫法, 在鐵達尼生存預測中, 觀查堆疊泛化 (Stacking) 的寫法與效果 # [作業重點] - 完成堆疊泛化的寫作, 看看提交結果, 想想看 : 分類與回歸的堆疊泛化, 是不是也與混合泛化一樣有所不同呢?(In[14]) 如果可能不同, 應該怎麼改寫會有較好的結果? - Hint : 請參考 mlxtrend 官方網站 StackingClassifier 的頁面說明 : ...
github_jupyter
# SLU09 - Linear Algebra & NumPy, Part 1 ### Learning Notebook 1/2 In this notebook we will be covering the following: - **Vectors**: definition, transpose, norm, multiplication by a scalar and addition, linear combinations, linear independence and dot product; - **Introduction to NumPy arrays:** vectors and nump...
github_jupyter
``` # from google.colab import drive # drive.mount('/content/drive') # path = "/content/drive/MyDrive/Research/cods_comad_plots/sdc_task/mnist/" import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvisi...
github_jupyter
## Notebook 1: ``` ### Notebook 1 ### Data set 1 (Viburnum) ### Language: Bash ### Data Location: NCBI SRA PRJNA299402 & PRJNA299407 %%bash ## make a new directory for this analysis mkdir -p empirical_1/ mkdir -p empirical_1/halfrun mkdir -p empirical_1/fullrun ## import Python libraries import pandas as pd import num...
github_jupyter
# Class Session 10 - Date Hubs and Party Hubs ## Comparing the histograms of local clustering coefficients of date hubs and party hubs In this class, we will analyze the protein-protein interaction network for two classes of yeast proteins, "date hubs" and "party hubs" as defined by Han et al. in their 2004 study of ...
github_jupyter
``` import autoreg import GPy import numpy as np from matplotlib import pyplot as plt from __future__ import print_function %matplotlib inline from autoreg.benchmark import tasks # Function to compute root mean square error: def comp_RMSE(a,b): return np.sqrt(np.square(a.flatten()-b.flatten()).mean()) # Define cl...
github_jupyter
[![AnalyticsDojo](https://github.com/rpi-techfundamentals/spring2019-materials/blob/master/fig/final-logo.png?raw=1)](http://rpi.analyticsdojo.com) <center><h1>Train Test Splits with Python</h1></center> <center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center> ``` #Let's get rid of ...
github_jupyter
# MNIST SVD Classification Follows Chapter 11 of Matrix Methods in Data Mining and Pattern Recognition by Lars Elden, with added dimensionality reduction visualization #### Author: Daniel Yan #### Email: daniel.yan@vanderbilt.edu ``` from keras.datasets import mnist from matplotlib import pyplot as plt import numpy as...
github_jupyter
The goal of this notebook is to verify that you can load the checkpointed model from it's github repo and run it on a few test image samples and verify that the whole inference pipeline works. ``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) ``` ...
github_jupyter
# Neural Network for Regression In the previous homework you implemented a linear regression network. In this exercise, we will solve the same problem with a neural network instead, to leverage the power of Deep Learning. We will implement our neural networks using a modular approach. For each layer we will implement ...
github_jupyter
``` # import packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import featuretools as ft import lightgbm as lgb %matplotlib inline import seaborn as sns import math import pickle import os, sys, gc, warnings, random, datetime RSEED = 50 ``` ## Load Data ``` # Load training data df_train...
github_jupyter
# Transfer Learning A Convolutional Neural Network (CNN) for image classification is made up of multiple layers that extract features, such as edges, corners, etc; and then use a final fully-connected layer to classify objects based on these features. You can visualize this like this: <table> <tr><td rowspan=2 st...
github_jupyter
``` var = 3 print(var) var = 7 var arr1 = [] type(arr1) arr2 = [1,2,3,4,5] type(arr2) len(arr2) dir(arr1) print(arr1) arr1.append(3) arr1 arr1.append(4) arr1 arr1.append(5) arr1.insert(3,2) arr1 dir(arr1.insert) arr3 = [1,3,4,'Winner','Emeto',4,6,4] arr3 arr3.count(4) arr3.index(3) def hi(): print('Hello Fellows!')...
github_jupyter
# [Sensor name] :::{eval-rst} :opticon:`tag` :badge:`[Environment],badge-primary` :badge:`Sensors,badge-secondary` ::: ## Context ### Purpose *Describe the purpose of the use case.* ### Sensor description *Describe the main features of the sensor e.g. variables.* ### Highlights *Provide 3-5 bullet points that conve...
github_jupyter
``` %pylab inline from simqso.sqgrids import * from simqso import sqbase from simqso.sqmodels import QLF_McGreer_2013 # set up a luminosity-redshift grid M = AbsMagVar(UniformSampler(-30,-25),restWave=1450) z = RedshiftVar(UniformSampler(1,5)) MzGrid = QsoSimGrid([M,z],(4,3),2,seed=12345) scatter(MzGrid.z,MzGrid.absMag...
github_jupyter
# <div align="center">Credit Fraud Detector</div> --------------------------------------------------------------------- you can find the kernel link below: > ###### [ Kaggle](https://www.kaggle.com/janiobachmann/credit-fraud-dealing-with-imbalanced-datasets) ## Introduction In this kernel we will use various predicti...
github_jupyter
This short example show how to get data from FMI Open Data multipointcoverage format. The format is used in INSPIRE specifications and is somewhat complex. Anyway, it's the most efficient way to get large amounts of data. Here we fetch all observations from Finland during two days. This example is for "old" format WF...
github_jupyter
# HPDM097: Foundations of combinatorial optimisation for routing and scheduling problems in health Many healthcare systems manage assets or workforce that they need to deploy geographically. One example, is a community nursing team. These are teams of highly skilled nurses that must visit patients in their own home. A...
github_jupyter
# Cox model ``` import warnings import arviz as az import numpy as np import pymc3 as pm import scipy as sp import theano.tensor as tt from pymc3 import ( NUTS, Gamma, Metropolis, Model, Normal, Poisson, find_MAP, sample, starting, ) from theano import function as fn from theano i...
github_jupyter
## ------- >--------- >----------PLAYSTORE ANALYSIS USING PYTHON-------- >----------- >--------- ## # BY : # ARAVINTH.S # BE - COMP SCIENCE ENGINEERING ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns ps = pd.read_csv("plst.csv") ps.head() ps.shape ps.size ps....
github_jupyter
# Example Seldon Core Deployments using Helm with Istio Prequisites * [Install istio](https://istio.io/latest/docs/setup/getting-started/#download) ## Setup Cluster and Ingress Use the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html#Setup-Clus...
github_jupyter
<a href="https://colab.research.google.com/github/agemagician/CodeTrans/blob/main/prediction/transfer%20learning%20fine-tuning/source%20code%20summarization/csharp/small_model.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **<h3>Summarize the cshar...
github_jupyter
# Spam Filter using Naive Bayes Classifier ``` import os print(os.listdir("../input")) ``` **Import libraries** ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline ``` **Read csv file** ``` df = pd.read_csv('../input/spam.csv', encoding='latin-1')[['v...
github_jupyter
# Setup ``` library(ggplot2) library(cowplot) library(ranger) library(Metrics) library(latex2exp) library(reshape2) library(akima) library(pander) ``` # Generate Model Following is an example of how to generate the prediction model using the Random Forest Model with AIWC metrics and experimental runtimes of the Exte...
github_jupyter
Note! For a most up to date version of this notebook, make sure you copy from: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1wTMIrJhYsQdq_u7ROOkf0Lu_fsX5Mu8a) ## Configs and Hyperparameters Support a variety of models, you can find more pretrain...
github_jupyter
# Attentional Networks in Computer Vision Prepared by Comp411 Teaching Unit (TA Can Küçüksözen) in the context of Computer Vision with Deep Learning Course. Do not hesitate to ask in case you have any questions, contact me at: ckucuksozen19@ku.edu.tr Up until this point, we have worked with deep fully-connected networ...
github_jupyter
# German Company Registry IDs ## Introduction The function `clean_de_handelsregisternummer()` cleans a column containing German company registry id (handelsregisternummer) strings, and standardizes them in a given format. The function `validate_de_handelsregisternummer()` validates either a single handelsregisternumm...
github_jupyter
``` import sys sys.path.append("/home/sean/pench") sys.path.append("/network/lustre/iss01/home/adrien.martel") import os # os.environ["CUDA_VISIBLE_DEVICES"]="1" # !git clone https://github.com/vlawhern/arl-eegmodels.git from eegmodels.EEGModels import EEGNet, ShallowConvNet, DeepConvNet from myModels import dualLSTM,...
github_jupyter
# Home 4: Build a seq2seq model for machine translation. ### Name: [Your-Name?] ### Task: Translate English to [what-language?] ## 0. You will do the following: 1. Read and run my code. 2. Complete the code in Section 1.1 and Section 4.2. * Translation English to **German** is not acceptable!!! Try another lan...
github_jupyter
###### Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 L.A. Barba, G.F. Forsyth. # Relax and hold steady Ready for more relaxing? This is the third lesson of **Module 5** of the course, exploring solutions to elliptic PDEs. In [Lesson 1](http://nbviewer.ipython.org/github/...
github_jupyter
# Day 0 Practical: Churn for Bank Customers Welcome to the first practical session of the SPAI Advanced Machine Learning Workshop. In this practical, you will experience the full workflow of building a simple classifier to predict whether does a customer decides to leave the bank*(also known as churning)* given the fe...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/NAIP/loop_FeatureCollection.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" ...
github_jupyter
# Aplicação: cores PANTONE ## Leitura de arquivos _json_ ``` import os, json # diretório base base = '../database/pantone-colors/' for fi in os.listdir(base): n,e = os.path.splitext(fi) if e == '.json': with open(os.path.join(base,fi), 'r') as f: # define variáveis dinamicamente ...
github_jupyter
<div class="contentcontainer med left" style="margin-left: -50px;"> <dl class="dl-horizontal"> <dt>Title</dt> <dd> RGB Element</dd> <dt>Dependencies</dt> <dd>Matplotlib</dd> <dt>Backends</dt> <dd><a href='./RGB.ipynb'>Matplotlib</a></dd> <dd><a href='../bokeh/RGB.ipynb'>Bokeh</a></dd> <dd><a href='../...
github_jupyter
## pyHail MESH Animation This code utilizes the pyHAIL package to plot MESH, or the "maximum expected size of hail", grid the plots, and then create an animation with the plots. ``` from __future__ import print_function import warnings import warnings warnings.filterwarnings('ignore') """ MESH sub-module of pyhail C...
github_jupyter
# MinPy (MXNet NumPy) *"Everybody loves NumPy."* In this tutorial, we present MinPy -- a NumPy-like package based on MXNet. NumPy is a well-known python package widely used in scientific computing, statistics and machine learning. It supports a wide range of tensor operators and is very friendly to machine learning b...
github_jupyter
``` __depends__=[] __dest__="../results/f8.eps" ``` # Plot Terms in the Two-fluid EBTEL Equations As part of our derivation of the two-fluid EBTEL equations, we'll plot the different terms of the two-fluid electron energy equation, $$ \frac{L}{\gamma - 1}\frac{dp_e}{dt} = \psi_{TR} - (\mathcal{R}_C + \mathcal{R}_{TR})...
github_jupyter
``` from bayestuner.tuner import BayesTuner import numpy as np import seaborn as sns from bayestuner.optimizer import DifferentialEvolution from bayestuner.acquisitionfunc import UCB import matplotlib.pyplot as plt import math import matplotlib.animation as animation from sklearn.gaussian_process.kernels import Constan...
github_jupyter
``` ## This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/...
github_jupyter
``` # Allow us to load `open_cp` without installing import sys, os.path sys.path.insert(0, os.path.abspath("..")) ``` # Crime prediction from Hawkes processes Here we continue to explore the EM algorithm for Hawkes processes, but now concentrating upon: 1. Mohler et al. "Randomized Controlled Field Trials of Predict...
github_jupyter
# Emotion Classification **Module 1: Introduction** * Author: [Andrés Mitre](https://github.com/andresmitre), [Center for Research in Mathematics (CIMAT)](http://www.cimat.mx/en) in Zacatecas, México. For installation, I highly recommend to follow the instructions from [Jeff Heaton](https://sites.wustl.edu/jeffheaton...
github_jupyter
# Qiskit Aer: Applying noise to custom unitary gates The latest version of this notebook is available on https://github.com/Qiskit/qiskit-tutorial. ## Introduction This notebook shows how to add custom unitary gates to a quantum circuit, and use them for noise simulations in Qiskit Aer. ``` from qiskit import execu...
github_jupyter
# 🔪 JAX - The Sharp Bits 🔪 *levskaya@ mattjj@* When walking about the countryside of [Italy](https://iaml.it/blog/jax-intro), the people will not hesitate to tell you that __JAX__ has _"una anima di pura programmazione funzionale"_. __JAX__ is a language for __expressing__ and __composing__ __transformations__ of ...
github_jupyter
``` import os import pyvtk import numpy as np import xarray as xr import matplotlib.pyplot as plt # The data structure in element-wise output is too complicated for xarray.open_mfdataset. # Here we open the files as individual datasets and concatenate them on the variable level. # This code is compatible with parallel ...
github_jupyter
# Image Deduplication with FiftyOne This recipe demonstrates a simple use case of using FiftyOne to detect and remove duplicate images from your dataset. ## Requirements This notebook requires the `tensorflow` package: ``` !pip install tensorflow ``` ## Download the data First we download the dataset to disk. The...
github_jupyter
# Comprehensive Guide to Grouping and Aggregating with Pandas Chris Mofitt. "Comprehensive Guide to Grouping and Aggregating with Pandas". _Practical Business Python_, 9 Nov. 2020, https://pbpython.com/groupby-agg.html. ``` import pandas as pd import seaborn as sns df = sns.load_dataset('titanic') ``` ## Pandas aggre...
github_jupyter
# Tabular Datasets As we have already discovered, Elements are simple wrappers around your data that provide a semantically meaningful representation. HoloViews can work with a wide variety of data types, but many of them can be categorized as either: * **Tabular:** Tables of flat columns, or * **Gridded:** Arr...
github_jupyter
``` %load_ext autoreload %autoreload 2 import os, sys sys.path.insert(0, os.path.expandvars('/data/users/$USER/fbsource/fbcode/beanmachine')) sys.path.insert(1, os.path.expandvars('/data/users/$USER/fbsource/third-party/pypi/flowtorch/0.0.dev2')) import beanmachine.ppl as bm import beanmachine.ppl as bm import matplot...
github_jupyter
``` import pandas as pd import numpy as np from tqdm import tqdm_notebook from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer, TfidfVectorizer from sklearn.neighbors import NearestNeighbors %matplotlib inline links = pd.read_csv('links.csv') movies = pd.read_csv('movies.csv') ratings = pd.r...
github_jupyter
## Unsupervised Learning ## Project: Creating Customer Segments ## Getting Started In this project analyzed a dataset containing data on various customers' annual spending amounts (reported in *monetary units*) of diverse product categories for internal structure. One goal of this project is to best describe the vari...
github_jupyter
``` # PyTorch import torch from torch import nn, optim from torch.utils.data import Dataset, DataLoader from torchvision import transforms, datasets import torch.nn.functional as F from torch.optim.lr_scheduler import ReduceLROnPlateau # PyTorch Lightning import pytorch_lightning as pl from pytorch_lightning import Tr...
github_jupyter
``` import os import numpy as np import pandas as pd import cv2 import math import matplotlib.pyplot as plt import torch from PIL import Image import torchvision.transforms as T train_data= pd.read_csv("../ELEC576project/sartorius-cell-instance-segmentation/train.csv") def rotate_image(image, angle): # Get th...
github_jupyter
# Rigid-body transformations in three-dimensions > Marcos Duarte > Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) > Federal University of ABC, Brazil The kinematics of a rigid body is completely described by its pose, i.e., its position and orientation in space (and the co...
github_jupyter
# Design of Digital Filters *This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. ## Example: Non-Recursive versus Recursive Filter In the following example, the characteristics and computational complexity of a non-recursive and a recursive fil...
github_jupyter
# Visualizing tweets and the Logistic Regression model **Objectives:** Visualize and interpret the logistic regression model **Steps:** * Plot tweets in a scatter plot using their positive and negative sums. * Plot the output of the logistic regression model in the same plot as a solid line ## Import the required li...
github_jupyter
# Student-t Process PyMC3 also includes T-process priors. They are a generalization of a Gaussian process prior to the multivariate Student's T distribution. The usage is identical to that of `gp.Latent`, except they require a degrees of freedom parameter when they are specified in the model. For more information, ...
github_jupyter
# GMNS Format Validation for networks stored as CSV files This notebook demonstrates validation for whether a GMNS network conforms to the schema. It uses a modified version of [GMNSpy](https://github.com/e-lo/GMNSpy), originally developed by Elizabeth Sall. The first time you run this notebook after cloning this rep...
github_jupyter
# Census- Employment Status Data ``` import pandas as pd import requests #Census Subject Table API for Employment Status data within Unified School Districts in California for 2018 url="https://api.census.gov/data/2016/acs/acs1/subject?get=group(S2301)&for=school%20district%20(unified)&in=state:06" #Request for HTTP D...
github_jupyter
#### New to Plotly? Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/). <br>You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initiali...
github_jupyter
<h1><font color='blue'> 8E and 8F: Finding the Probability P(Y==1|X)</font></h1> <h2><font color='Geen'> 8E: Implementing Decision Function of SVM RBF Kernel</font></h2> <font face=' Comic Sans MS' size=3>After we train a kernel SVM model, we will be getting support vectors and their corresponsing coefficients $\alph...
github_jupyter
# Mnist classification pipeline using Sagemaker The `mnist-classification-pipeline.py` sample runs a pipeline to train a classficiation model using Kmeans with MNIST dataset on Sagemaker. We will have all required steps here and for other details like how to get source data, please check [documentation](https://githu...
github_jupyter