text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` from utils import ( get_mnist_data_loaders, NN_FC_CrossEntropy, compute_validation_accuracy_multi, train_one_epoch, ) from fastprogress.fastprogress import master_bar import torch import matplotlib.pyplot as plt from jupyterthemes import jtplot jtplot.style(context="talk") # Configuration parame...
github_jupyter
``` import pandas as pd import warnings warnings.filterwarnings('ignore') df = pd.read_csv('student-por.csv') df.head() df = pd.read_csv('student-por.csv', sep=';') df.head() df.isnull().sum() pd.options.display.max_columns = None df[df.isna().any(axis=1)] df['age'] = df['age'].fillna(-999.0) df['sex'] = df['sex'].fill...
github_jupyter
# This one was created to test the importance of the data taken from the text field - the price extracted from the text field This data is removed in this notebook, so we can check how big is the importance of this feature on test data in Kaggle. ## Additional data sources https://stat.gov.pl/statystyka-regionalna/r...
github_jupyter
# Using Production Coverage Measures to delete Parts of a Software System ## Exercise _Level: Easy_ ### Background Developers of the Java application "Spring PetClinic" said, that there would be much code that isn't used at all. ### Your Task Before migrating the application to the new platform, an analysis shou...
github_jupyter
# Learning under Label Shift - GMM, 0-1 responses ``` import numpy as np import mxnet as mx from mxnet import nd, autograd, gluon ``` First let's set the centroids of our two classes and the marginal distributions during training and testing. ``` means = np.array([[1, 1], [-1, -1]]) variance = 1 py_train = [.5, .5] ...
github_jupyter
<a href="https://colab.research.google.com/github/agemagician/CodeTrans/blob/main/prediction/single%20task/function%20documentation%20generation/java/base_model.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **<h3>Predict the documentation for java...
github_jupyter
# Employee Performance Data Modelling and Prediction ## About We try to predict employee performance scores based 300+ employee demographic characteristics. The dataset in question was acquired as part of a homework assignment and comprises of 20,000 employees and 379 employee characteristics, 1 target variable (emplo...
github_jupyter
# RBIG Demo ``` %matplotlib inline import sys sys.path.insert(0, '/home/emmanuel/code/py_packages/rbig/src') sys.path.insert(0, '/home/emmanuel/code/rbig/') # sys.path.insert(0, '/home/emmanuel/Drives/megatron/temp/2017_RBIG/') # sys.path.insert(0, '/Users/eman/Documents/code_projects/rbig/') import numpy as np # imp...
github_jupyter
``` import numpy as np from collections import Counter, OrderedDict with open('coursera_sessions_train.txt') as f: file_train = f.readlines() with open('coursera_sessions_test.txt') as f: file_test = f.readlines() len(file_train), len(file_test) class OrderedCounter(Counter, OrderedDict): def __repr__(self...
github_jupyter
# VPoser Decoder The original body pose space of [SMPL](http://smpl.is.tue.mpg.de/) are not bounded to natural human pose space. That means you can put a vector value as the pose of a SMPL body model and get broken body, that might not even look like a human. To address this you can replace the original pose space of S...
github_jupyter
# Node classification with Node2Vec using Stellargraph components <table><tr><td>Run the latest release of this notebook:</td><td><a href="https://mybinder.org/v2/gh/stellargraph/stellargraph/master?urlpath=lab/tree/demos/node-classification/keras-node2vec-node-classification.ipynb" alt="Open In Binder" target="_paren...
github_jupyter
# Introduction This notebook demonstrates the use of a trained caffe classification model in python and manual editing of model parameters (net surgery). It is based on the caffe net surgery and filter visualization examples: http://nbviewer.ipython.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb ...
github_jupyter
``` # Copyright 2019 The Kubeflow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
github_jupyter
# Visualizing Conv filters using ActivationMaximization [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/keisen/tf-keras-vis/blob/master/examples/visualize_conv_filters.ipynb) [![Right click and save](https://img.shields.io/badge/Notebook-Open_In_Git...
github_jupyter
# Classifying Images with CNNs In this exercise you will design a Convolutional Neural Network (CNN) for Fashion Mnist. CNNs are the workhorses of modern computer vision. ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np from tensorflow.keras.datasets import fashion_mnist (X_train, y_train),...
github_jupyter
``` import pandas as pd import pickle import numpy as np from scipy.stats import rankdata from sklearn import metrics import seaborn as sns %pylab inline %matplotlib inline PepBindEnerDF = pickle.load( open("../computed_data/PepBindEnerDF.pickle","rb")) #New name NameTest = ["B2CL1_SORTCERY","MCL1_SORTCERY","B2LA1_SORT...
github_jupyter
# Exploring the Lorenz System of Differential Equations (This was downloaded Jan 20, 2016 from the [ipywidgets examples](https://github.com/ipython/ipywidgets/blob/master/examples/notebooks/Index.ipynb)) In this Notebook we explore the Lorenz system of differential equations: $$ \begin{aligned} \dot{x} & = \sigma(y-...
github_jupyter
# Regression with Amazon SageMaker XGBoost (Parquet input) This notebook exhibits the use of a Parquet dataset for use with the SageMaker XGBoost algorithm. The example here is almost the same as [Regression with Amazon SageMaker XGBoost algorithm](xgboost_abalone.ipynb). This notebook tackles the exact same problem ...
github_jupyter
``` import os import Cell_BLAST as cb import utils os.environ["CUDA_VISIBLE_DEVICES"] = utils.pick_gpu_lowest_memory() cb.config.RANDOM_SEED = 0 cb.config.N_JOBS = 4 fixed_model_kwargs = dict( latent_dim=10, cat_dim=20, epoch=500, patience=20 ) cb.__version__ ``` --- # Human ## Madissoon_Oesophagus ``` madiss...
github_jupyter
# SVD-based Agent with LogReg on Bandit Feedback Up until now, we have primarily focused on: - The differences between organic and bandit feedback, and how to properly exploit these signals for model evaluation - Building a model either entirely off of either organic, or bandit feedback - Feature engineering methods i...
github_jupyter
``` from collections import Counter from functools import partial import gc from multiprocessing import Pool import numpy as np import pandas as pd from scipy.stats import f_oneway from scipy.spatial.distance import squareform from statsmodels.stats.multicomp import pairwise_tukeyhsd from tqdm import trange from make...
github_jupyter
# Lecture 11: Numerical optimization [Download on GitHub](https://github.com/NumEconCopenhagen/lectures-2022) [<img src="https://mybinder.org/badge_logo.svg">](https://mybinder.org/v2/gh/NumEconCopenhagen/lectures-2022/master?urlpath=lab/tree/11/Numerical_optimization.ipynb) 1. [Introduction](#Introduction) 2. [Exam...
github_jupyter
# 有限状态机 有限状态机(*finite state machine*,简称 *FSM*),有时也被称为 *finite state automation*,有时就简单地叫 *state machine*,不属于一看就知道大概是什么的概念(这一点和前面我们讲过的都不一样)。有限状态机有相当深刻的理论背景,算是比较高级的东西了,很多程序员别说学校里,工作十年可能都没碰过这东西,但其实真的不难理解,而且学会了就爱不释手,因为它解决某些问题真是太好用了。 ## 什么是有限状态机 其实我们身边到处都是“有限状态机”的例子,最简单的一个是灯:灯有两种状态:“亮”和“熄”,灯可以从一种状态变成另一种,“亮”的状态下接收到“关”的指令就会...
github_jupyter
# EDA - Reprezentativnost dat a centrální limitní věta Z minulých lekcí už známe základní metody datové analýzy a umíme aplikovat obecné postupy a komplexní nástroje tak, abychom z dat dostali zajímavé informace. Situaci nám v tomto snažení mohou komplikovat chybějící data a různé další chyby vedoucí k odlehlým měřen...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import seaborn as sns # plot total_evals #policies = {'lo_50_123': ['random','fixed_one','optimal','optimal_discrete','dqn', 'dqn_gamma0.99'], # 'lo_50_124': ['random','fixed_one','optimal','optimal_discrete','dqn'], # ...
github_jupyter
``` from glob import glob import nibabel as nb import numpy as np from scipy import stats targets = glob("..\coordinates_hcp_train27_no_discriminator_test\images\*targets.nii.gz") def evaluate(model): targets = glob("../" + model + "/images/*targets.nii.gz") r_values = [] percentile_values = [] for targ...
github_jupyter
``` from pytorch_pretrained_bert.tokenization import BertTokenizer tokenizer = BertTokenizer.from_pretrained("bert-base-chinese", do_lower_case=True) text="[MASK] [MASK] more happy 搂哼哧吭导读:联发科在7月31日的法说会上给出了比欧系外资机构预估的业绩更差,预估第三季毛利率约介于42.5%~45.5%之间,较第二季的45.9%进一步下滑,全年营收从成长10%转为衰退5~10%..." #text='\t'.join(text) tokenizer.tok...
github_jupyter
<h1 dir="rtl">ניתוח תחבירי על <a href="https://koichiyasuoka.github.io/deplacy/">deplacy</a></h1> <h2 dir="rtl">עם <a href="https://github.com/nlp-uoregon/trankit">Trankit</a></h2> ``` !pip install deplacy trankit transformers import trankit nlp=trankit.Pipeline("hebrew") doc=nlp("על טעם וריח אין להתווכח.") import de...
github_jupyter
``` import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.metrics import roc_auc_score from sklearn.model_selection import cross_val_score import lightgbm as lgb from sklearn.model_selection import StratifiedKFold # LOAD ...
github_jupyter
``` #Import libraries import cdt from cdt import SETTINGS SETTINGS.verbose=False SETTINGS.NJOBS=16 import networkx as nx import time # A warning on R libraries might occur. It is for the use of the r libraries that could be imported into the framework import numpy as np import pandas as pd from matplotlib import pyplot...
github_jupyter
``` import numpy as np import tensorflow as tf import random from collections import deque import dqn from gym.envs.registration import register import gym from gym import wrappers env = gym.make('CartPole-v0') env._max_episode_steps = 5000 input_size = env.observation_space.shape[0] output_size = env.action_space.n d...
github_jupyter
``` #Dependencies import pandas as pd import matplotlib.pyplot as plt import sqlalchemy from sklearn.datasets import make_regression from sklearn.linear_model import LinearRegression from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.ext.declarative import...
github_jupyter
``` import torch import torch.nn as nn import torch.onnx as onnx import matplotlib.pyplot as plt from torch.utils.data import DataLoader from torchvision import datasets, transforms ``` ## DataSet ``` # image classes classes = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag"...
github_jupyter
``` # default_exp learner #export from fastai2.data.all import * from fastai2.optimizer import * from fastai2.callback.core import * #hide from nbdev.showdoc import * #export _all_ = ['CancelFitException', 'CancelEpochException', 'CancelTrainException', 'CancelValidException', 'CancelBatchException'] #export _loop = ['...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np %matplotlib inline from scipy import stats, integrate #Load data into dataframes #load train data train_answer = pd.read_csv("data/train.answer", sep="\r", header=None ) train_context = pd.read_csv("data/train.context", sep...
github_jupyter
# Searching and sorting You will learn how to write **pseudo code** and a bit about **computational complexity** (big-O notion). You will learn about **functional recursion** and some illustrative **search** (sequential, binary) and **sort** (bubble, insertion, quick) algorithms. **Note:** I will be live-coding a lot...
github_jupyter
# Python Built-Ins --- [Watch a walk-through of this lesson on YouTube](https://youtu.be/kSWWpCga0EE) ## Questions: - How can I use built-in functions? - How can I find out what they do? - What kind of errors can occur in programs? ## Learning Objectives: - Explain the purpose of functions - Correctly call built-i...
github_jupyter
# Specifying boundary velocities in addition to a custom density file This notebook will go through multiple detailed examples of how to properly run TARDIS with a custom ejecta profile specified by a custom density file and a custom abundance file. ``` import tardis import matplotlib.pyplot as plt import numpy as np...
github_jupyter
# TF-Slim Walkthrough This notebook will walk you through the basics of using TF-Slim to define, train and evaluate neural networks on various tasks. It assumes a basic knowledge of neural networks. ## Table of contents <a href="#Install">Installation and setup</a><br> <a href='#MLP'>Creating your first neural netwo...
github_jupyter
## Sentiment140 Dataset (as taken from Kaggle): The current dataset comprises of 1.6 million tweets with a sentiment value of 0 (negative), 2 (neutral) or 4 (positive). We will try to find tweets with mentions interconnecting users to build a directed graph. The zip file can be downloaded from https://www.kaggle.com/k...
github_jupyter
# Exercise 5 - Variational quantum eigensolver ### References + [Rattew *et al.*,2019](https://arxiv.org/abs/1910.09694) + [Qiskit Global Summer School Lab-8](https://www.youtube.com/watch?v=3B04KB0pDwE) + [Coding with Qiskit VQE](https://www.youtube.com/watch?v=Z-A6G0WVI9w) ***Name:*** Lakshmi Siri Appalaneni<br/> *...
github_jupyter
# Transfer Learning Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this not...
github_jupyter
# Verification and Validation Now we have a working solver (the fast version of SOR) we need to know if * we are solving the the right equations? * we are solving the equations right? These two questions are related to the process of Validation and Verification (often called V&V). The fist question asks if the PD...
github_jupyter
# Predicting Survival of Heart Failure Patients with Machine Learning Models ``` #General Purpose Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #Machine Learning Libraries from sklearn.preprocessing import StandardScaler from sklearn import m...
github_jupyter
``` # noexport import os os.system('export_notebook reconstruct_spans_persecond.ipynb') from tmilib import * from reconstruct_focus_times_common import * from sorted_collection import SortedCollection from rescuetime_utils import * import sklearn import sklearn.svm import sklearn.linear_model import sklearn.ensemble...
github_jupyter
# Plan 1. Read through code (~5 minutes) 2. Get into groups and discuss code (~2 minutes) 3. Ask questions on the sheet (~5 minutes) 4. Work on "Questions to answer" (~10 minutes) 5. Work on "Things to explore" (~10 minutes) 6. Work on the "Challenge" (~20 minutes) 7. Work on "What's next?" Getting started: - I reco...
github_jupyter
# Table of Contents * [1) Evaluating a Learning Algorithm](#1%29-Evaluating-a-Learning-Algorithm) * [1) Deciding What to Try Next](#1%29-Deciding-What-to-Try-Next) * [2) Evaluating a Hypothesis](#2%29-Evaluating-a-Hypothesis) * [3) Model Selection and Train/Validation/Test Sets](#3%29-Model-Selection-and-Train...
github_jupyter
# Gallery of examples ![logo_text.png](docs/source/examples/logo_text.png) Here you can browse a gallery of examples using poliastro in the form of Jupyter notebooks. ## [Comparing Hohmann and bielliptic transfers](docs/source/examples/Comparing%20Hohmann%20and%20bielliptic%20transfers.mystnb) [![hohmann_bielliptic...
github_jupyter
Copyright 2021 DeepMind Technologies Limited 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 agreed to in writ...
github_jupyter
# Validación cruzada y métodos de evaluación de rendimiento En los cuadernos anteriores, dividimos los datos en dos partes, un conjunto de entrenamiento y otro de test. Utilizamos el de entrenamiento para ajustar el modelo y el de test para evaluar su capacidad de generalización (como se comportaba con datos nuevos, p...
github_jupyter
# Inertial Measurement Unit (IMU) Kevin J. Walchko, 12 July 2017 --- IMUs are key sensors in Inertial Navigation Systems (INS). INS is key for aircraft, ships, cruise missiles, ICBMs, etc to travel long distances and arrive at a location where we want them. Although the mathematical equations behind an INS is a litt...
github_jupyter
``` import os import numpy as np import pandas as pd import pyreadr import seaborn as sns import matplotlib.pyplot as plt from scipy import stats from gglasso.helper.utils import sparsity, zero_replacement, normalize, log_transform from gglasso.problem import glasso_problem from gglasso.helper.basic_linalg import sc...
github_jupyter
# K-means ``` import numpy as np import sklearn as sk import pandas as pd df = pd.read_csv('creditcard.csv', low_memory=False) df.head() from sklearn.cluster import KMeans from time import time import matplotlib.pyplot as plt from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import ...
github_jupyter
# 6 - Sensitivity Analysis ``` import os from pathlib import Path testfolder = str(Path().resolve().parent.parent / 'PV_ICE' / 'TEMP') # Another option using relative address; for some operative systems you might need '/' instead of '\' # testfolder = os.path.abspath(r'..\..\PV_DEMICE\TEMP') print ("Your simulati...
github_jupyter
``` import pandas as pd import numpy as np import nltk import multiprocessing import difflib import time import gc import xgboost as xgb import warnings warnings.filterwarnings('ignore') from collections import Counter from sklearn.metrics import log_loss from scipy.optimize import minimize from sklearn.cross_validati...
github_jupyter
# Examples Here is a short guide to using carspy in a project: ## Setup ### Import necessary modules ``` from carspy import CarsSpectrum, CarsFit from carspy.utils import downsample from carspy.convol_fcn import asym_Gaussian ``` ### Additional modules `numpy` and `matplotlib` are also used in this demo. ``` imp...
github_jupyter
# Markdown ### ¿Qué es? Lenguaje de marcado que nos permite aplicar formato a nuestros textos mediante unos caracteres especiales. Muy útil cuando tenemos que documentar algo, escribir un artículo, o entregar un reporte. Este lenguaje está pensado para web, pero es muy común utilizarlo en cualquier tipo de texto, inde...
github_jupyter
**Chapter 6 – Decision Trees** _This notebook contains all the sample code and solutions to the exercises in chapter 6._ <table align="left"> <td> <a href="https://colab.research.google.com/github/ageron/handson-ml2/blob/master/06_decision_trees.ipynb" target="_parent"><img src="https://colab.research.google.co...
github_jupyter
# SageMaker Serverless Inference ## NLP Example Amazon SageMaker Serverless Inference is a purpose-built inference option that makes it easy for customers to deploy and scale ML models. Serverless Inference is ideal for workloads which have idle periods between traffic spurts and can tolerate cold starts. Serverless e...
github_jupyter
(Note that all units unless otherwise mentioned are SI units.) ``` import numpy as np import numexpr as ne import matplotlib.pyplot as plt import pickle,os from multislice import prop,prop_utils ``` Importing all the required libraries. ``` def make_zp_from_rings(n,grid_size): zp = np.zeros((grid_size,grid_size)...
github_jupyter
## First: Install Midiapipe ``` # !pip install mediapipe # !pip install pynput import cv2 import time import os import mediapipe as mp import pyvjoy from directkeys import PressKey, A, D, W, S, ReleaseKey ``` # Class for detection of hands ``` def rescale_frame(frame, percent=75): width = int(frame.shape[1] * pe...
github_jupyter
# Wir trainieren nur bergab? ## Das Problem der Regression Bei der Regressionsanalyse muss eine Modellfunktion gefunden werden, die zu einem gegebenen Satz von Datenpunkten N möglichst **genau** passt. Ein häufig verwendetes Maß für die Genauigkeit der Approximation ist die **Methode der kleinsten Quadrate** (engl. le...
github_jupyter
This is a notebook which is a supplement to my blogpost about VQE. It's not a VQE tutorial, rather an illustration and invitation for the Reader to explore the concept described in the blogpost on their own. ``` from pyquil.api import WavefunctionSimulator from pyquil import Program, get_qc from pyquil.gates import *...
github_jupyter
# Praxis - Optimizer mit Imagenette In diesem Notebook werden verschiedene Optimizer (Stochastic Gradient Descent mit Momentum, Stochastic Gradient Descent, Adam und RMSProp) anhand des Imagenette Datensatzes verglichen. ## Imports ``` %tensorflow_version 2.x # Befehl für Google Colab für Tensorflow 2 # TensorFlow ≥...
github_jupyter
``` %matplotlib inline from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt import corner plt.style.use('jpg.mplstyle') import pymfit img_fn = '../data/test-galaxy-2.fits' mask_fn = '../local_data/mask.fits' config_fn = '../local_data/config.txt' boot_fn = '../local_data...
github_jupyter
<a href="https://colab.research.google.com/github/gtbook/robotics/blob/main/S34_vacuum_perception.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` %pip install -U -q gtbook import plotly.express as px import numpy as np import gtsam import pandas...
github_jupyter
# How-To Guide into Feature Engineering ## Introduction If you haven't yet see the [overview posting] for this series, please take a minute to read that first... Are you back? Great. Let's dive in. This post is going to delve into the mechanics of _feature engineering_ for the sorts of time series data that y...
github_jupyter
``` import numpy as np import scipy.io as sio import cv2 import matplotlib.pyplot as plt img = cv2.imread("input_image_64.jpeg") for i in range(img.shape[0]): for j in range(img.shape[1]): img[i, j, 0], img[i, j, 2] = img[i, j, 2], img[i, j, 0] plt.imshow(img) in_img = np.reshape(img[:, :, 0], ...
github_jupyter
``` import sys import torch import torch.nn as nn from torch import optim import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt import pandas as pd import math """ Dimensions need to be checked between n_users. n_items and X before calling this """ class Bias_UV(nn.Module): def __in...
github_jupyter
# Photoionization of hydrogen In this notebook we use a simple python program (`FCF_helper`) specifically designed to calculate the Franck-Condon factors for the photoionization of hydrogen molecules $H_2 \rightarrow H_2^+$. This program operates on the harmonic oscillator approximation level. Let us first import all...
github_jupyter
<a href="https://colab.research.google.com/github/AmirRazaMBA/Tensorflow-in-Practice-Specialization/blob/main/3.%20Natural%20Language%20Processing%20in%20TensorFlow/Codes/Exam%20Prep/RNN/01_nlp_lstms_with_reviews_subwords_dataset.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg...
github_jupyter
# Introduction to the Molecular Attention Transformer. In this tutorial we will learn more about the Molecular Attention Transformer, or MAT. MAT is a model based on transformers, aimed towards performing molecular prediction tasks. MAT is easy to tune and performs quite well relative to other molecular prediction ta...
github_jupyter
``` # imports %matplotlib inline import pickle import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import tensorflow as tf import numpy as np from tqdm import tqdm from sklearn.metrics import confusion_matrix import time from datetime import timedelta import math import random # Load pickled data # ...
github_jupyter
``` #from collections import defaultdict import seaborn as sns import numpy as np import matplotlib.pyplot as plt from Bio.PopGen.GenePop import Controller as gpc %matplotlib inline my_pops = [l.rstrip() for l in open('hapmap10_auto_noofs_2.pops')] num_pops = len(my_pops) ctrl = gpc.GenePopController() (multi_fis, mu...
github_jupyter
# Tutorial 2: Single cell simulation with external feedfoward input (with BioNet) In the previous tutorial we built a single cell and stimulated it with a current injection. In this example we will keep our single-cell network, but instead of stimulation by a step current, we'll set-up an external network that synapse...
github_jupyter
``` %pip install datasets transformers onnx onnxruntime ``` We use the small distilled BERT model from Microsoft as our pre-trained model which we fine-tune on the emotion classification task. See https://huggingface.co/microsoft/xtremedistil-l6-h256-uncased for details. ``` model_name = 'microsoft/xtremedistil-l6-h...
github_jupyter
``` # Imports # Algorithms: from koebe.algorithms.incrementalConvexHull import incrConvexHull, orientationPointE3, randomConvexHullE3 from koebe.algorithms.hypPacker import * from koebe.algorithms.sampling import surfaceSampling, boundarySampling from koebe.algorithms.poissonDiskSampling import slowAmbientSurfaceSampl...
github_jupyter
``` import requests import json import time from bs4 import BeautifulSoup from urllib import parse def get_restaurants_url_list(soup): back_url_list = [] list_restaurants = soup.find_all('div', class_='list-restaurant-item') for restaurant in list_restaurants: restaurant_href = restaurant.find('div'...
github_jupyter
``` import numpy as np import pandas as pd import linearsolve as ls import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline ``` # Class 13: Introduction to Real Business Cycle Modeling Real business cycle (RBC) models are extensions of the stochastic Solow model. RBC models replace the ad hoc assu...
github_jupyter
``` from fastai import * from fastai.vision import * ``` pytorch loss functions: - torch.nn.L1Loss - torch.nn.MSELoss - torch.nn.CrossEntropyLoss **need to be softmax-ed** - torch.nn.CTCLoss - torch.nn.NLLLoss **need to be exp-ed** - torch.nn.PoissonNLLLoss **need to be exp-ed if log_input is True (d...
github_jupyter
# Pandas Tutorial ![trump](./images/trump.jpg) ``` !pip install nltk !pip install -U spacy !python -m spacy download en import nltk nltk.download('stopwords') nltk.download('vader_lexicon') import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import re import spacy from nltk.corp...
github_jupyter
``` # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. ``` # Render DensePose DensePose refers to dense human pose representation: https://github.com/facebookresearch/DensePose. In this tutorial, we provide an example of using DensePose data in PyTorch3D. This tutorial shows how to: - load a m...
github_jupyter
# Classifying Fashion-MNIST Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 9...
github_jupyter
``` import numpy as np import pandas as pd import tracktor as tr import cv2 import sys import time from scipy.optimize import linear_sum_assignment from scipy.spatial.distance import cdist ``` ## Global parameters This cell (below) enlists user-defined parameters ``` # colours is a vector of BGR values which are used...
github_jupyter
<h1> Ship Type Prediction </h1> <p align='justify'> This Jupyter notebook contains a classification example which is done with the help of Scikit-Learn library. In this notebook, the following steps are performed: </p> <ol align='justify'> <li> The preprocessing i.e. feature generation, filtering and in...
github_jupyter
# How to work with the PDTB _based on the course "Computational Pragmatics" by Chris Potts_ Shared under a cc-by-nc-sa license. https://creativecommons.org/licenses/by-nc-sa/3.0/ ## Loading & accessing the corpus We can access the corpus using the compiled csv-version (a tabular format with one relation per line):...
github_jupyter
# Gradient-boosting decision tree (GBDT) In this notebook, we will present the gradient boosting decision tree algorithm and contrast it with AdaBoost. Gradient-boosting differs from AdaBoost due to the following reason: instead of assigning weights to specific samples, GBDT will fit a decision tree on the residuals ...
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
# Solving the advection equation [AMath 586, Spring Quarter 2019](http://staff.washington.edu/rjl/classes/am586s2019/) at the University of Washington. For other notebooks, see [Index.ipynb](Index.ipynb) or the [Index of all notebooks on Github](https://github.com/rjleveque/amath586s2019/blob/master/notebooks/Index.i...
github_jupyter
## Part I ## Raw Data Process, Word2Vec and Sentiment Analysis ``` import pandas as pd import numpy as np ``` ### Step 1) Read Twitter csv file and compress the data to one-line-each-day format (concatenate all tweets within one day to a single string) ``` # Read twitter csv file tw = pd.read_csv('corona.csv', enco...
github_jupyter
# Space Situational Awareness Demo ## Installing the Orbit Prediction Pipeline Tools First we need to install the [orbit prediction package](https://github.com/IBM/spacetech-ssa/tree/master/orbit_prediction) from the [SSA project](https://github.com/ibm/spacetech-ssa) that will allow us to work with satellite orbit ...
github_jupyter
Given a graph: a--------b | | | | | | | | c--------d---------e The task we need to do is: 1. display vertices 2. display edges 3. add a vertex 4. add an edge 5. create a graph A graph can be easily presented using the python **dictionary...
github_jupyter
# Trade Demo **Summary:** In this demo, a data scientist wants to be able to determine that the amount of goods exported from a handful of nations (usa, canada, netherlands, united kingdom, and italy) matches the amount of goods those nations claim to have imported from each other. We want to return a list of commodit...
github_jupyter
This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # Challenge Notebook ## Problem: Implement an algorithm to determine if a string has all unique characters. * [Constraints](#Constraints) * [Test...
github_jupyter
# Modeling spawning salmon The plot below shows the relationship between the number of spawning salmon in a particular stream and the number of fry that are recruited into the population in the spring. We would like to model this relationship, which appears to be non-linear (we have biological knowledge that suggests...
github_jupyter
``` import sys sys.path.append("../..") from common import * import torch.utils.model_zoo as model_zoo # ############################################################## # https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py # https://pytorch.org/docs/stable/torchvision/models.html # # normalize ...
github_jupyter
# TensorFlow Tutorial #12 # Adversarial Noise for MNIST by [Magnus Erik Hvass Pedersen](http://www.hvass-labs.org/) / [GitHub](https://github.com/Hvass-Labs/TensorFlow-Tutorials) / [Videos on YouTube](https://www.youtube.com/playlist?list=PL9Hr9sNUjfsmEu1ZniY0XpHSzl5uihcXZ) ## WARNING! **This tutorial does not work ...
github_jupyter
# Creating Machine Learning Pipeline ``` from IPython.display import Image Image(filename='C:\\Users\\User\\Desktop\\capture.png') #Filtering Warnings import warnings warnings.filterwarnings('ignore') #importing packages import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessin...
github_jupyter
``` import pandas as pd import numpy as np import os import pathlib import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten from tensorflow.keras.optimizers import RMSprop import tensorflow.comp...
github_jupyter
``` import numpy as np # Avoid inaccurate floating values (for inverse matrices in dot product for instance) # See https://stackoverflow.com/questions/24537791/numpy-matrix-inversion-rounding-errors np.set_printoptions(suppress=True) ``` $$ \newcommand\bs[1]{\boldsymbol{#1}} $$ # Introduction We will see some very i...
github_jupyter