code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Rare Labels ## Labels that occur rarely Categorical variables are those which values are selected from a group of categories, also called labels. Different labels appear in the dataset with different frequencies. Some categories appear a lot in the dataset, whereas some other categories appear only in a few number...
github_jupyter
<a href="https://colab.research.google.com/github/cccadet/Tensorflow/blob/master/Celsius_to_Fahrenheit.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Versi...
github_jupyter
<a href="https://colab.research.google.com/github/julianox5/Desafios-Resolvidos-do-curso-machine-learning-crash-course-google/blob/master/numpy_para_machine_learning.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Importando o numpy ``` import nump...
github_jupyter
<a href="https://colab.research.google.com/github/boangri/uai-thesis-notebooks/blob/main/notebooks/Pong_PyTorch_DQN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Решение задачи Pong методом DQN в PyTorch ``` import os import torch as T import t...
github_jupyter
``` import torch import torch.nn as nn class ResNetBlock(nn.Module): # <1> def __init__(self, dim): super(ResNetBlock, self).__init__() self.conv_block = self.build_conv_block(dim) def build_conv_block(self, dim): conv_block = [] conv_block += [nn.ReflectionPad2d(1)] ...
github_jupyter
# Doom Deadly Corridor with Dqn The purpose of this scenario is to teach the agent to navigate towards his fundamental goal (the vest) and make sure he survives at the same time. ### Enviroment Map is a corridor with shooting monsters on both sides (6 monsters in total). A green vest is placed at the oposite end of t...
github_jupyter
# TRTR Dataset D ``` #import libraries import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import os print('Libraries imported!!') #define directory of functions and actual directory HOME_PATH = '' #home path of the project FUNCTIONS_DIR = 'EVALUATION FUNCTIONS/UTILITY' ACTUAL_DIR ...
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
# Create a cell (function for calculating the DGSLR index from the input datat) ``` import numpy as np from scipy import interp import matplotlib.pyplot as plt from itertools import cycle # the module for the roc_curve value from sklearn.metrics import * # Config the matlotlib backend as plotting inline in IPython ...
github_jupyter
# matplotlib基础 - [API path](https://matplotlib.org/api/path_api.html) - [Path Tutorial](https://matplotlib.org/tutorials/advanced/path_tutorial.html#sphx-glr-tutorials-advanced-path-tutorial-py) 众所周知,matplotlib的图表是由艺术家使用渲染器在画布上完成的。 其API自然分为3层: - 画布是绘制图形的区域:matplotlib.backend_bases.FigureCanvas - 渲染器是知晓如何在画布上绘制的对象:...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training/train-hyperparameter-tune-deploy-with-sklearn/train-hyperparameter-tune-deploy-with-sklearn....
github_jupyter
<h2> ======================================================</h2> <h1>MA477 - Theory and Applications of Data Science</h1> <h1>Lesson 12: Lab </h1> <h4>Dr. Valmir Bucaj</h4> United States Military Academy, West Point AY20-2 <h2>======================================================</h2> <h2>House Voting Datse...
github_jupyter
# Combine DESI Imaging ccds for DR9 The eboss ccd files did not have the same dtype, therefore we could not easily combine them. We have to enfore a dtype to all of them. ``` # import modules import fitsio as ft import numpy as np from glob import glob # read files ccdsn = glob('/home/mehdi/data/templates/ccds/dr9/c...
github_jupyter
# Brazilian Newspaper analysis In this project, we'll use a dataset from a Brazilian Newspaper called "Folha de São Paulo". We're going to use word embeddings, tensorboard and rnn's and search for political opinions and positions. You can find the dataset at [kaggle](https://www.kaggle.com/marlesson/news-of-the-site...
github_jupyter
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/work-with-data/dataprep/how-to-guides/join.png) # Join Copyright (c) Microsoft Corporation. All rights reserved.<br> Licensed under the MIT License.<br> In Data Prep you can easily join two D...
github_jupyter
# Credit Risk Resampling Techniques ``` import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd from pathlib import Path from collections import Counter ``` # Read the CSV and Perform Basic Data Cleaning ``` columns = [ "loan_amnt", "int_rate", "installment", "home_ownership", ...
github_jupyter
``` import numpy as np import random from tqdm import * import os import sklearn.preprocessing from utils import * from graph_utils import * from rank_metrics import * import time params = get_cmdline_params() model_name = "STHgraph_{}_{}_step{}".format(params.walk_type, params.modelinfo, params.walk_steps) ########...
github_jupyter
# <font color='Purple'>Gravitational Wave Generation Array</font> A Phase Array of dumbells can make a detectable signal... #### To do: 1. Calculate the dumbell parameters for given mass and frequency 1. How many dumbells? 1. Far-field radiation pattern from many radiators. 1. Beamed GW won't be a plane wave. So what...
github_jupyter
# Introduction to Linear Regression *Adapted from Chapter 3 of [An Introduction to Statistical Learning](http://www-bcf.usc.edu/~gareth/ISL/)* ||continuous|categorical| |---|---|---| |**supervised**|**regression**|classification| |**unsupervised**|dimension reduction|clustering| ## Motivation Why are we learning li...
github_jupyter
# Testing Configurations The behavior of a program is not only governed by its data. The _configuration_ of a program – that is, the settings that govern the execution of a program on its (regular) input data, as set by options or configuration files – just as well influences behavior, and thus can and should be test...
github_jupyter
# The Discrete Fourier Transform *This Jupyter notebook is part of a [collection of notebooks](../index.ipynb) in the bachelors module Signals and Systems, Comunications Engineering, Universität Rostock. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## ...
github_jupyter
# Concise Implementation of Linear Regression :label:`sec_linear_concise` Broad and intense interest in deep learning for the past several years has inspired companies, academics, and hobbyists to develop a variety of mature open source frameworks for automating the repetitive work of implementing gradient-based learn...
github_jupyter
--- ![Header](img/conditionals-header.png) --- # Estrutura de controles de fluxo Servem para alterar a ordem dos passos de um algoritmo/programa. <img src="img/conditionals/control-flow.png" width="600px"/> ## Tipos de estruturas de controle - Estruturas condicionais - Laços de repetição - Funções ## Estrutu...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import pandas as pd pd.set_option('display.float_format', lambda x: '%.4f' % x) import seaborn as sns sns.set_context("paper", font_scale=1.3) sns.set_style('white') import warnings warnings.filterwarnings('ignore') from time import time import matplotlib.ticker as...
github_jupyter
# libCEED for Python examples This is a tutorial to illustrate the main feautures of the Python interface for [libCEED](https://github.com/CEED/libCEED/), the low-level API library for efficient high-order discretization methods developed by the co-design [Center for Efficient Exascale Discretizations](https://ceed.ex...
github_jupyter
``` from pyalink.alink import * useLocalEnv(1) from utils import * import os import pandas as pd pd.set_option('display.max_colwidth', 5000) pd.set_option('display.html.use_mathjax', False) DATA_DIR = ROOT_DIR + "mnist" + os.sep DENSE_TRAIN_FILE = "dense_train.ak"; DENSE_TEST_FILE = "dense_test.ak"; SPARSE_TRAIN_FI...
github_jupyter
``` import spark %reload_ext spark %%ignite # Happy path: # fill_style accepts strings, rgb and rgba inputs # fill_style caps out-of-bound numbers to respective ranges def setup(): size(200, 200) print("fill_style renders fill color ") def draw(): global color clear() with_string() wit...
github_jupyter
``` import os os.environ['CUDA_VISIBLE_DEVICES'] = '' os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/husein/t5/prepare/mesolitica-tpu.json' import malaya_speech.train.model.conformer as conformer import malaya_speech.train.model.transducer as transducer import malaya_speech import tensorflow as tf import numpy a...
github_jupyter
``` import datafaucet as dfc # start the engine project = dfc.project.load() spark = dfc.context() df = spark.range(100) df.data.grid() (df .cols.get('name').obscure(alias='enc') .cols.get('enc').unravel(alias='dec') ).data.grid() df.data.grid().groupby(['id', 'name'])\ .agg({'fight':[max, 'min'], 'trade': ...
github_jupyter
# Sonar - Decentralized Model Training Simulation (local) DISCLAIMER: This is a proof-of-concept implementation. It does not represent a remotely product ready implementation or follow proper conventions for security, convenience, or scalability. It is part of a broader proof-of-concept demonstrating the vision of the...
github_jupyter
``` from urllib2 import Request, urlopen from urlparse import urlparse, urlunparse import requests, requests_cache import pandas as pd import json import os import numpy as np from matplotlib import pyplot as plt plt.style.use('ggplot') %matplotlib inline from urllib2 import Request, urlopen import requests # In te...
github_jupyter
# Session 3 --- ``` import numpy as np ar = np.arange(3, 32) ar ``` np.any np.all np.where ``` help(np.where) ar np.where(ar < 10, 15, 18) ``` ```python x if condition else y ``` ``` np.where(ar < 10, 'Y', 'N') np.where(ar < 10, 'Y', 18) np.where(ar < 10, 15) np.where(ar < 10) type(np.where(ar < 10)) help(np.any) ...
github_jupyter
# NSCI 801 - Quantitative Neuroscience ## Reproducibility, reliability, validity Gunnar Blohm ### Outline * statistical considerations * multiple comparisons * exploratory analyses vs hypothesis testing * Open Science * general steps toward transparency * pre-registration / registered report * Open sci...
github_jupyter
<a href="https://colab.research.google.com/github/krmiddlebrook/intro_to_deep_learning/blob/master/machine_learning/mini_lessons/image_data.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Processing Image Data Computer vision is a field of machine...
github_jupyter
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i> <i>Licensed under the MIT License.</i> # Evaluation Evaluation with offline metrics is pivotal to assess the quality of a recommender before it goes into production. Usually, evaluation metrics are carefully chosen based on the actual application scena...
github_jupyter
# Overview ## &copy; [Omkar Mehta](omehta2@illinois.edu) ## ### Industrial and Enterprise Systems Engineering, The Grainger College of Engineering, UIUC ### <hr style="border:2px solid blue"> </hr> This notebook will show you how to create and query a table or DataFrame that you uploaded to DBFS. [DBFS](https://do...
github_jupyter
# 📃 Solution for Exercise M3.01 The goal is to write an exhaustive search to find the best parameters combination maximizing the model generalization performance. Here we use a small subset of the Adult Census dataset to make the code faster to execute. Once your code works on the small subset, try to change `train_...
github_jupyter
## Look at supply and demand of available datasets and ML models ``` import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns dataset_regular = '../datasets/Dataset_evolution_regular.csv' dataset_consortia = '../datasets/Dataset_evolution_consortia.csv' freesurfer_papers ...
github_jupyter
# Using the same code as before, please solve the following exercises 4. Examine the code where we plot the data. Study how we managed to get the value of the outputs. In a similar way, find get the value of the weights and the biases and print it. This exercise will help you comprehend the TensorFlow syn...
github_jupyter
## <div style="text-align: center"> 20 ML Algorithms from start to Finish for Iris</div> <div style="text-align: center"> I want to solve<b> iris problem</b> a popular machine learning Dataset as a comprehensive workflow with python packages. After reading, you can use this workflow to solve other real problems and u...
github_jupyter
# Use PyTorch to recognize hand-written digits with Watson Machine Learning REST API This notebook contains steps and code to demonstrate support of PyTorch Deep Learning experiments in Watson Machine Learning Service. It introduces commands for getting data, training experiments, persisting pipelines, publishing mode...
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline #export from exp.nb_07a import * path = untar_data(URLs.IMAGENETTE_160) path #export import os, PIL, mimetypes Path.ls = lambda x: list(x.iterdir()) path.ls() (path/'val').ls() path_tench = path/'val'/'n01440764' img_fn = path_tench.ls()[0] img_fn img = PIL.Im...
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fshorts&branch=master&subPath=Matplotlib.ipynb&depth=1" target="_parent"><img src="...
github_jupyter
# Writing Low-Level TensorFlow Code **Learning Objectives** 1. Practice defining and performing basic operations on constant Tensors 2. Use Tensorflow's automatic differentiation capability 3. Learn how to train a linear regression from scratch with TensorFLow ## Introduction In this notebook, we will start b...
github_jupyter
# Clasification ## MNIST dataset ``` from sklearn.datasets import fetch_openml mnist = fetch_openml('mnist_784', version=1) mnist.keys() X, y = mnist['data'], mnist['target'] print(X.shape) print(y.shape) %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt idx = 2 some_digit = X[idx] some_d...
github_jupyter
# Simple Test between NumPy and Numba $$ x = \exp(-\Gamma_s d) $$ ``` import numba import cython import numexpr import numpy as np %load_ext cython from empymod import filters from scipy.constants import mu_0 # Magn. permeability of free space [H/m] from scipy.constants import epsilon_0 # Elec. permittivity o...
github_jupyter
## Fourier Transforms The frequency components of an image can be displayed after doing a Fourier Transform (FT). An FT looks at the components of an image (edges that are high-frequency, and areas of smooth color as low-frequency), and plots the frequencies that occur as points in spectrum. In fact, an FT treats pat...
github_jupyter
``` %load_ext autoreload %autoreload 2 import os import sys import numpy as np import pandas as pd import csv import cv2 import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import torchvision from skimage import io, transform from skimage import color import scipy.m...
github_jupyter
``` import argparse import copy import os import os.path as osp import pprint import sys import time from pathlib import Path import open3d.ml as _ml3d import open3d.ml.tf as ml3d import yaml from open3d.ml.datasets import S3DIS, SemanticKITTI, SmartLab from open3d.ml.tf.models import RandLANet from open3d.ml.tf.pipel...
github_jupyter
``` import random import numpy as np import matplotlib.pyplot as plt valid_RPS_actions = [0, 1, 2] # Signifying Rock, Paper, or Scissors def playRPS(action_p1, action_p2): if (action_p1 not in valid_RPS_actions) or (action_p2 not in valid_RPS_actions): raise Exception("Invalid Move Detected.") return -100 ...
github_jupyter
# ETL Processes Use this notebook to develop the ETL process for each of your tables before completing the `etl.py` file to load the whole datasets. ``` import os import glob import psycopg2 import pandas as pd from sql_queries import * conn = psycopg2.connect("host=127.0.0.1 dbname=sparkifydb user=student password=st...
github_jupyter
``` import numpy as np import pandas as pd import scipy import pickle import matplotlib.pyplot as plt import seaborn as sns import ipdb ``` # generate data ## 4 types of GalSim images ``` #### 1000 training images with open("data/galsim_simulated_2500gals_lambda0.4_theta3.14159_2021-05-20-17-01.pkl", 'rb') as hand...
github_jupyter
``` import pandas as pd from IPython.core.display import display, HTML display(HTML("<style>.container {width:90% !important;}</style>")) # Don't wrap repr(DataFrame) across additional lines pd.set_option("display.expand_frame_repr", True) # Set max rows displayed in output to 25 pd.set_option("display.max_rows", 25)...
github_jupyter
Probabilistic Programming ===== and Bayesian Methods for Hackers ======== ##### Version 0.1 `Original content created by Cam Davidson-Pilon` `Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)` ___ Welcome to *Bayesian Methods for Hackers*. The ...
github_jupyter
# Tracking Callbacks ``` from fastai.gen_doc.nbdoc import * from fastai.vision import * from fastai.callbacks import * ``` This module regroups the callbacks that track one of the metrics computed at the end of each epoch to take some decision about training. To show examples of use, we'll use our sample of MNIST and...
github_jupyter
## Современные библиотеки градиентного бустинга Ранее мы использовали наивную версию градиентного бустинга из scikit-learn, [придуманную](https://projecteuclid.org/download/pdf_1/euclid.aos/1013203451) в 1999 году Фридманом. С тех пор было предложено много реализаций, которые оказываются лучше на практике. На сегодняш...
github_jupyter
``` %cd ../ from torchsignal.datasets import OPENBMI from torchsignal.datasets.multiplesubjects import MultipleSubjects from torchsignal.trainer.multitask import Multitask_Trainer from torchsignal.model import MultitaskSSVEP import numpy as np import torch import matplotlib.pyplot as plt from matplotlib.pyplot import ...
github_jupyter
**Exploratory Data Analysis for HMDA** Ideas: Outcome Variable, Quantity of Filers, Property Type, Loan Type ``` %matplotlib inline import os import requests import matplotlib import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix ``` ...
github_jupyter
``` # TODO # 1. # of words # 2. # of sensor types # 3. how bag of words clustering works # 4. how data feature classification works on sensor types # 5. how data feature classification works on tag classification # 6. # of unique sentence structure import json from functools import reduce import os.path import os impor...
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
Lambda School Data Science, Unit 2: Predictive Modeling # Applied Modeling, Module 1 You will use your portfolio project dataset for all assignments this sprint. ## Assignment Complete these tasks for your project, and document your decisions. - [ ] Choose your target. Which column in your tabular dataset will you...
github_jupyter
# Example Usage of plotDist This notebook presents the usage of the `plotDist` and `utilities` module. The general starting point is a 3-dimensional array `samples` of size `samples.shape = (nObservables, nXrange, nSamples)`, where * `nObservables` is the number of observables * `nXrange` the independent variable of ...
github_jupyter
# **Custom Training: Walkthrough `tf-1.x`** --- [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/kyle-w-brown/tensorflow-1.x.git/HEAD) This guide uses machine learning to *categorize* Iris flowers by species. It uses TensorFlow's [eager execution](https://www.tensorflow.org/guide/eager) ...
github_jupyter
# Assignment 4: Transfer learning The goal of this assignment is to demonstrate a technique called transfer learning. Transfer learning is a good way to quickly get good performance on the Patch-CAMELYON benchmark. ### Peliminaries Transfer learning is a technique where instead of random initialization of the parame...
github_jupyter
# Python Basics ## Variables Python variables are untyped, i.e. no datatype is required to define a variable ``` x=10 # static allocation print(x) # to print a variable ``` Sometimes variables are allocated dynamically during runtime by user input. Python not only creates a new variable on-demand, also, it assigns ...
github_jupyter
<a href="https://colab.research.google.com/github/furkanonat/DS-Unit-2-Applied-Modeling/blob/master/module3-permutation-boosting/Furkan_Onat_LS_DS_233_assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import pandas as pd import os from ...
github_jupyter
Unsupervised learning means a lack of labels: we are looking for structure in the data, without having an *a priori* intuition what that structure might be. A great example is clustering, where the goal is to identify instances that clump together in some high-dimensional space. Unsupervised learning in general is a ha...
github_jupyter
``` %tensorflow_version 1.x !pip install -q h5py==2.10.0 from scipy.io import loadmat from scipy import stats import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from scipy import stats import tensorflow as tf #import tensorflow.compat.v1 as tf1 #tf1.disable_v2_behavior() import seaborn...
github_jupyter
``` import scipy.io as io import matplotlib.pyplot as plt import matplotlib.pylab as pylab #Set up parameters for figure display params = {'legend.fontsize': 'x-large', 'figure.figsize': (8, 10), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'axes.labelweight': 'bold', ...
github_jupyter
``` from ceres_infer.session import workflow from ceres_infer.models import model_infer_ens_custom import logging logging.basicConfig(level=logging.INFO) params = { # directories 'outdir_run': '../out/20.0909 Lx/L200only_reg_rf_boruta/', # output dir for the run 'outdir_modtmp': '../out/20.0909 Lx/L200only_...
github_jupyter
``` #Source for DBSCAN code: https://www.youtube.com/watch?v=5cOhL4B5waU&t=918s import matplotlib.pyplot as plt from sklearn.datasets import make_moons from sklearn.cluster import DBSCAN from sklearn.neighbors import NearestNeighbors from scipy.spatial.distance import euclidean import numpy as np import numpy.matlib ...
github_jupyter
# sift down ``` # python3 class HeapBuilder: def __init__(self): self._swaps = [] #array of tuples or arrays self._data = [] def ReadData(self): n = int(input()) self._data = [int(s) for s in input().split()] assert n == len(self._data) def WriteResponse(self): ...
github_jupyter
If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets as well as other dependencies. Uncomment the following cell and run it. ``` #! pip install datasets transformers rouge-score nltk ``` If you're opening this notebook locally, make sure your environment has the ...
github_jupyter
# Welcome to Python 101 <a href="http://pyladies.org"><img align="right" src="http://www.pyladies.com/assets/images/pylady_geek.png" alt="Pyladies" style="position:relative;top:-80px;right:30px;height:50px;" /></a> Welcome! This notebook is appropriate for people who have never programmed before. A few tips: - To ex...
github_jupyter
# Part 4: Create an approximate nearest neighbor index for the item embeddings This notebook is the fourth of five notebooks that guide you through running the [Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN](https://github.com/GoogleCloudPlatform/analytics-componentized-patterns...
github_jupyter
# Principal Component Analysis on Breast Cancer Dataset <b>Transformation of data in order to find out what features explain the most variance in our data<b/> <b>Import required libraries<b/> ``` import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline ``` <b>L...
github_jupyter
# Working with Text data ``` %matplotlib inline from preamble import * ``` # http://ai.stanford.edu/~amaas/data/sentiment/ ## Example application: Sentiment analysis of movie reviews ``` !tree -L 2 data/aclImdb from sklearn.datasets import load_files reviews_train = load_files("data/aclImdb/train/") # load_files r...
github_jupyter
# Day 24 - Cellular automaton We are back to [cellar automatons](https://en.wikipedia.org/wiki/Cellular_automaton), in a finite 2D grid, just like [day 18 of 2018](../2018/Day%2018.ipynb). I'll use similar techniques, with [`scipy.signal.convolve2d()`](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy....
github_jupyter
``` import statsmodels.formula.api as smf import matplotlib.pyplot as plt import pandas as pd import numpy as np np.random.seed(123) ``` --- # Lecture 11: Regression discontinuity --- --- ## Lee (2008) --- The author studies the "incumbency advantage", i.e. the overall causal impact of being the current incumbent p...
github_jupyter
``` """ Please run notebook locally (if you have all the dependencies and a GPU). Technically you can run this notebook on Google Colab but you need to set up microphone for Colab. Instructions for setting up Colab are as follows: 1. Open a new Python 3 notebook. 2. Import this notebook from GitHub (File -> Upload N...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np from os import mkdir from os.path import join bov_counter = 0 def writeBOV(g): """g is presumed to be a numpy 2D array of doubles""" global bov_counter bovNm = 'file_%03d.bov' % bov_counter dataNm = 'file_%03d.doubles' % bov_counter bov_counter...
github_jupyter
# Домашнее задание 2 по обработке текстов Рассмотрим задачу бинарной классификации. Пусть дано два списка имен: мужские и женские имена. Требуется разработать классификатор, который по данному имени будет определять мужское оно или женское. Данные: * Женские имена: female.txt * Мужские имена: male.txt ``` # plots f...
github_jupyter
# Quantum Counting To understand this algorithm, it is important that you first understand both Grover’s algorithm and the quantum phase estimation algorithm. Whereas Grover’s algorithm attempts to find a solution to the Oracle, the quantum counting algorithm tells us how many of these solutions there are. This algori...
github_jupyter
# CORD-19 overview In this notebook, we provide an overview of publication medatata for CORD-19. ``` %matplotlib inline import matplotlib.pyplot as plt # magics and warnings %load_ext autoreload %autoreload 2 import warnings; warnings.simplefilter('ignore') import os, random, codecs, json import pandas as pd import...
github_jupyter
``` import pandas as pd import numpy as np import os #import data from biom import load_table from gneiss.util import match #deicode from deicode.optspace import OptSpace from deicode.preprocessing import rclr from deicode.ratios import log_ratios #skbio import warnings; warnings.simplefilter('ignore') #for PCoA warnin...
github_jupyter
``` from ppsim import Simulation, StatePlotter, time_trials import numpy as np import seaborn as sns from matplotlib import pyplot as plt # Either this backend or the qt backend is necessary to use the StatePlotter Snapshot object for dynamic visualization while the simulation runs %matplotlib notebook ``` # 3-state o...
github_jupyter
``` import matplotlib from matplotlib import pyplot as plt import numpy as np import os import pandas as pd from gPhoton import galextools as gt plt.rcParams.update({'font.size': 18}) # Import the function definitions that accompany this notebook tutorial. nb_funcdef_file = "function_defs.py" if os.path.isfile(nb_funcd...
github_jupyter
### 2.2 CNN Models - Test Cases The trained CNN model was performed to a hold-out test set with 10,873 images. The network obtained 0.743 and 0.997 AUC-PRC on the hold-out test set for cored plaque and diffuse plaque respectively. ``` import time, os import torch torch.manual_seed(42) from torch.autograd import Var...
github_jupyter
TSG023 - Get all BDC objects (Kubernetes) ========================================= Description ----------- Get a summary of all Kubernetes resources for the system namespace and the Big Data Cluster namespace Steps ----- ### Common functions Define helper functions used in this notebook. ``` # Define `run` funct...
github_jupyter
# HMDA Data -- Regression Modeling ## Using ML with *scikit-learn* for modeling -- (02) Logistical Regression This notebook explores the Home Mortgage Disclosure Act (HMDA) data for one year -- 2015. We use concepts from as well as tools from our own research and further readings to create a machine learning logis...
github_jupyter
# Chapter 10: Tuples ### Tuples are immutable A tuple is a sequence of values much like a list. The values stored in a tuple can be **any type**, and they are **indexed by integers**. ``` tp1 = 'a', 'b', 'c', 'd', 'e' type(tp1) tp2 = ('a', 'b', 'c', 'd', 'e') type(tpl2) tp1 is tp2 # Without the comma Python treats (...
github_jupyter
<a href="https://colab.research.google.com/github/araffin/rl-tutorial-jnrr19/blob/master/1_getting_started.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Stable Baselines Tutorial - Getting Started Github repo: https://github.com/araffin/rl-tuto...
github_jupyter
<img src="https://github.com/pmservice/ai-openscale-tutorials/raw/master/notebooks/images/banner.png" align="left" alt="banner"> # Working with Watson OpenScale - Custom Machine Learning Provider This notebook should be run using with **Python 3.7.x** runtime environment. **If you are viewing this in Watson Studio an...
github_jupyter
# ETS models The ETS models are a family of time series models with an underlying state space model consisting of a level component, a trend component (T), a seasonal component (S), and an error term (E). This notebook shows how they can be used with `statsmodels`. For a more thorough treatment we refer to [1], chapt...
github_jupyter
## **Bootstrap Your Own Latent A New Approach to Self-Supervised Learning:** https://arxiv.org/pdf/2006.07733.pdf ``` # !pip install torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html # !pip install -qqU fastai fastcore # !pip install nbdev import fastai, fastcore, torch ...
github_jupyter
``` import torch from torch import nn import numpy as np from matplotlib import pyplot as plt import seaborn as sns sns.set() hval = {} def dhook(name): def inner_hook(grad): global hval hval[name] = grad return grad return inner_hook def to_plot(tensor): return tensor.squeeze...
github_jupyter
# Fitbit Data Analysis ## About Fitbit Data Analysis This project provides some high-level data analysis of steps, sleep, heart rate and weight data from Fitbit tracking. Please using fitbit_downloader file to first collect and export your data. ------- ### Dependencies and Libraries ``` import numpy as np import...
github_jupyter
Evaluate experimental design using D-Efficiency. **Definitions**: $\mathbf{X}$ is the model matrix: A row for each run and a column for each term in the model. For instance, a model assuming only main effects: $\mathbf{Y} = \mathbf{X} \beta + \alpha$ $\mathbf{X}$ will contain $p = m + 1$ columns (number of factors...
github_jupyter
# Introduction to Neural Networks Based off of the lab exercises from deeplearning.ai, using public datasets and personal flair. ## Objectives - Build the general architecture of a learning algorithm, including: - initializing parameters - calculating the cost function and its gradient - using an op...
github_jupyter
# R API Serving Examples In this example, we demonstrate how to quickly compare the runtimes of three methods for serving a model from an R hosted REST API. The following SageMaker examples discuss each method in detail: * **Plumber** * Website: [https://www.rplumber.io/](https://www.rplumber.io) * SageMaker Exampl...
github_jupyter