code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Get all tracts within certain cities Given a CSV file containing city names, get all the tracts within those cities' boundaries. ``` import geopandas as gpd import json import os import pandas as pd all_tracts_path = 'data/us_census_tracts_2014' places_path = 'data/us_census_places_2014' states_by_fips_path = 'dat...
github_jupyter
By the end of this activity, you will be able to perform the following in Spark: Determine the accuracy of a classifier model Display the confusion matrix for a classifier model In this activity, you will be programming in a Jupyter Python Notebook. If you have not already started the Jupyter Notebook server, see the ...
github_jupyter
## Computing native contacts with MDTraj Using the definition from Best, Hummer, and Eaton, "Native contacts determine protein folding mechanisms in atomistic simulations" PNAS (2013) [10.1073/pnas.1311599110](http://dx.doi.org/10.1073/pnas.1311599110) Eq. (1) of the SI defines the expression for the fraction of nati...
github_jupyter
First, load the data, from the supplied data file ``` import tarfile import json import gzip import pandas as pd import botometer from pandas.io.json import json_normalize ## VARIABLE INITIATION tar = tarfile.open("../input/2017-09-22.tar.gz", "r:gz") mashape_key = "QRraJnMT9KmshkpJ7iu74xKFN1jtp1IyBBijsnS5NGbEuwIX54"...
github_jupyter
Wayne H Nixalo - 09 Aug 2017 FADL2 L9: Generative Models neural-style-GPU.ipynb ``` %matplotlib inline import importlib import os, sys sys.path.insert(1, os.path.join('../utils')) from utils2 import * from scipy.optimize import fmin_l_bfgs_b from scipy.misc import imsave from keras import metrics from vgg16_avg im...
github_jupyter
``` import pandas as pd from matplotlib import pyplot as plt import matplotlib.ticker as mtick from dateutil.parser import parse as date_parse import requests %matplotlib inline pd.options.mode.chained_assignment = None jhu_data = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/' \ ...
github_jupyter
# The Central Limit Theorem Elements of Data Science by [Allen Downey](https://allendowney.com) [MIT License](https://opensource.org/licenses/MIT) ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ ...
github_jupyter
``` %tensorflow_version 2.x %load_ext tensorboard import tensorflow as tf from tensorflow.keras import layers, models import matplotlib.pyplot as plt from os import path, walk import numpy as np import datetime from skimage import feature, util, io, color import cv2 device_name = tf.test.gpu_device_name() if device_...
github_jupyter
### **PINN eikonal solver using transfer learning for a smooth v(x,z) model** ``` from google.colab import drive drive.mount('/content/gdrive') cd "/content/gdrive/My Drive/Colab Notebooks/Codes/PINN_isotropic_eikonal" !pip install sciann==0.4.6.2 !pip install tensorflow==2.2.0 !pip install keras==2.3.1 import numpy a...
github_jupyter
# Qcodes example with Alazar ATS 9360 ``` # import all necessary things %matplotlib nbagg import qcodes as qc import qcodes.instrument.parameter as parameter import qcodes.instrument_drivers.AlazarTech.ATS9360 as ATSdriver import qcodes.instrument_drivers.AlazarTech.ATS_acquisition_controllers as ats_contr # Command ...
github_jupyter
``` source("base/it-402-dc-common_vars.r") # library(tidyverse) - called in common_vars library(assertr) ``` ## Notes #### Legal (ISO) gender types: * https://data.gov.uk/education-standards/sites/default/files/CL-Legal-Sex-Type-v2-0.pdf #### For data from 2010 and all stored as % * need to relax sum to 100% * ...
github_jupyter
# Machine Translation and the Dataset :label:`sec_machine_translation` We have used RNNs to design language models, which are key to natural language processing. Another flagship benchmark is *machine translation*, a central problem domain for *sequence transduction* models that transform input sequences into output s...
github_jupyter
# Using BagIt to tag oceanographic data [`BagIt`](https://en.wikipedia.org/wiki/BagIt) is a packaging format that supports storage of arbitrary digital content. The "bag" consists of arbitrary content and "tags," the metadata files. `BagIt` packages can be used to facilitate data sharing with federal archive centers ...
github_jupyter
Exercise 1 (5 points): Discrete Naive Bayes Classifier [Pen and Paper] In this exercise, we want to get a basic idea of the naive Bayes classifier by analysing a small example. Suppose we want to classify fruits based on the criteria length, sweetness and the colour of the fruit and we already spent days by categorizin...
github_jupyter
# Assignment 2: Parts-of-Speech Tagging (POS) Welcome to the second assignment of Course 2 in the Natural Language Processing specialization. This assignment will develop skills in part-of-speech (POS) tagging, the process of assigning a part-of-speech tag (Noun, Verb, Adjective...) to each word in an input text. Tag...
github_jupyter
# <center>RumbleDB sandbox</center> This is a RumbleDB sandbox that allows you to play with simple JSONiq queries. It is a jupyter notebook that you can also download and execute on your own machine, but if you arrived here from the RumbleDB website, it is likely to be shown within Google's Colab environment. To get...
github_jupyter
# Aggregating statistics ``` import pandas as pd air_quality = pd.read_pickle('air_quality.pkl') air_quality.info() ``` ### Series/one column of a DataFrame ``` air_quality['TEMP'].count() air_quality['TEMP'].mean() air_quality['TEMP'].std() air_quality['TEMP'].min() air_quality['TEMP'].max() air_quality['TEMP'].qua...
github_jupyter
# Getting Started with CREST CREST is a hybrid modelling DSL (domain-specific language) that focuses on the flow of resources within cyber-physical systems (CPS). CREST is implemented in the Python programming language as the `crestdsl` internal DSL and shipped as Python package. `crestdsl`'s source code is hosted o...
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 in import numpy as np # linear algebra import pandas as pd # data processing, CSV file...
github_jupyter
# Tests on PDA ``` import sys sys.path[0:0] = ['../..', '../../3rdparty'] # Append to the beginning of the search path from jove.SystemImports import * from jove.DotBashers import * from jove.Def_md2mc import * from jove.Def_PDA import * ``` __IMPORTANT: Must time-bound explore-pda, run-pda, explore-tm,...
github_jupyter
# esBERTus: evaluation of the models results In this notebook, an evaluation of the results obtained by the two models will be performed. The idea here is not as much to measure a benchmarking metric on the models but to understand the qualitative difference of the models. In order to do so ## Keyword extraction In o...
github_jupyter
# 对象和类 - 一个学生,一张桌子,一个圆都是对象 - 对象是类的一个实例,你可以创建多个对象,创建类的一个实例过程被称为实例化, - 在Python中对象就是实例,而实例就是对象 ## 定义类 class ClassName: do something - class 类的表示与def 一样 - 类名最好使用驼峰式 - 在Python2中类是需要继承基类object的,在Python中默认继承,可写可不写 - 可以将普通代码理解为皮肤,而函数可以理解为内衣,那么类可以理解为外套 ``` # 类必须初始化,是用self,初始化自身. # 类里面所有的函数中的第一个变量不再是参数,而是一个印记. # 在类中,...
github_jupyter
# Transfer Learning Template ``` %load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network ...
github_jupyter
## Week 4 ## T - testing and Inferential Statistics Most people turn to IMB SPSS for T-testings, but this programme is very expensive, very old and not really necessary if you have access to Python tools. Very focused on click and point and is probably more useful to people without a programming background. ### Lib...
github_jupyter
``` # Загрузка зависимостей import numpy import pandas import matplotlib.pyplot from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler # Загрузка и анализ набора данных raw_dataset = pandas.read_csv('machine.data.csv', header=None) # Убедиться в правильности пути к файлу! raw_da...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. # Explore Duplicate Question Matches Use this dashboard to explore the relationship between duplicate and original questions. ## Setup This section loads needed packages, and defines useful functions. ``` from __future__ impo...
github_jupyter
<h1 align="center"> Registration Initialization: We Have to Start Somewhere</h1> Initialization is a critical aspect of most registration algorithms, given that most algorithms are formulated as an iterative optimization problem. In many cases we perform initialization in an automatic manner by making assumptions wit...
github_jupyter
<a href="https://colab.research.google.com/github/PytorchLightning/pytorch-lightning/blob/master/notebooks/04-transformers-text-classification.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Finetune 🤗 Transformers Models with PyTorch Lightning ⚡...
github_jupyter
# Spreadsheets Functions ## Logical #### `=IF(logical_test, value_if_true, value_if_false)` #### `Comparison operators: =, >, <, >=, <=, <>` ### `Comparison Functions : ` #### `=ISNA()` #### `=ISNUMBER()` #### `=ISTEXT()` #### `=ISBLANK()` #### `=ISNONTEXT()` #### `=ISLOGICAL()` ## Text #### `FIND("!", mytext):` Fi...
github_jupyter
# Convolutional Neural Networks: Application Welcome to Course 4's second assignment! In this notebook, you will: - Implement helper functions that you will use when implementing a TensorFlow model - Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:** - Build and t...
github_jupyter
# Rebound model Aim: Quantify the environmental impact due to the savings of households in consumption expenses, across different - industrial sectors and scenarios: - housing (rent): baseline for 2011, - energy: efficient_devices, renewable_energy - food-waste: avoidable_waste_saving - clothing: su...
github_jupyter
![CMCC](http://cmcc.ufabc.edu.br/images/logo_site.jpg) # **Regressão Linear** #### Este notebook mostra uma implementação básica de Regressão Linear e o uso da biblioteca [MLlib](http://spark.apache.org/docs/1.4.0/api/python/pyspark.ml.html) do PySpark para a tarefa de regressão na base de dados [Million Song Dataset]...
github_jupyter
# Anomaly detection Anomaly detection is a machine learning task that consists in spotting so-called outliers. “An outlier is an observation in a data set which appears to be inconsistent with the remainder of that set of data.” Johnson 1992 “An outlier is an observation which deviates so much from the other observa...
github_jupyter
# Intro to machine learning - k-means --- Scikit-learn has a nice set of unsupervised learning routines which can be used to explore clustering in the parameter space. In this notebook we will use k-means, included in Scikit-learn, to demonstrate how the different rocks occupy different regions in the available param...
github_jupyter
# Beating the betting firms with linear models * **Data Source:** [https://www.kaggle.com/hugomathien/soccer](https://www.kaggle.com/hugomathien/soccer) * **Author:** Anders Munk-Nielsen **Result:** It is possible to do better than the professional betting firms in terms of predicting each outcome (although they may ...
github_jupyter
# Assignment 2: Naive Bayes Welcome to week two of this specialization. You will learn about Naive Bayes. Concretely, you will be using Naive Bayes for sentiment analysis on tweets. Given a tweet, you will decide if it has a positive sentiment or a negative one. Specifically you will: * Train a naive bayes model on a...
github_jupyter
``` from graph2text.finetune import SummarizationModule, Graph2TextModule import argparse import pytorch_lightning as pl import os import sys from pathlib import Path import pdb SEED = 42 import torch torch.cuda.is_available(), torch.cuda.device_count() MODEL='t5-base' DATA_DIR = './graph2text/data/webnlg' OUTPUT_DIR ...
github_jupyter
``` %matplotlib inline import numpy as np import seaborn import nltk from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.metrics import classification_report # prepare corpus corpus = [] for d in range(1400...
github_jupyter
``` import keras keras.__version__ ``` # Using a pre-trained convnet This notebook contains the code sample found in Chapter 5, Section 3 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more content, in partic...
github_jupyter
# Filled Julia set ___ Let $C\in \mathbb{C}$ is fixed. A *Filled Julia set* $K_C$ is the set of $z\in \mathbb{C}$ which satisfy $\ f^n_C(z)$ $(n \ge 1)$is bounded : $$K_C = \bigl\{ z\in \mathbb{C}\bigm|\{f^n_C(z)\}_{n\ge 1} : bounded\bigr\},$$ where $\ \ f^1_C(z) = f_C(z) = z^2 + C $, $\ \ f^n_C = f^{n-1}_C \circ f_C$...
github_jupyter
![152-1525861_ethereum-classic-logo-ethereum-classic-logo-png.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABGgAAAErCAYAAACCfrVVAACAAElEQVR42uydB5gbxdnH70JICCEQ2geE0FvoJfQSjmbnfNp5Z0aIbnA5m7ONAdP7JaaEECD0UBNI6BBaSEJvpmNM7zUQeu8YjPO9rzR73pO1RbrTnbT7/z3PPJJWW2ZmZ1c7f72lpQUAAAAAAAAAAAAAgLRRKBTmMMZsYy3dbIx+Qud1npfNg54...
github_jupyter
``` !conda install --yes scikit-learn !conda install --yes matplotlib !conda install --yes seaborn from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn impo...
github_jupyter
# Setting Node Capacities Capacities of a FABRIC node are basic characteristics of the virtual machine including number of compute core, amount of memory, and amount of local disk. This notebook will demonstrate the options for setting these node capciites. ## Configure the Environment ``` import os from fabrictest...
github_jupyter
# 2. Beyond simple plotting --- In this lecture we'll go a bit further with plotting. We will: - Create figures of different sizes; - Use Numpy to generate data for plotting; - Further change the appearance of our plots; - Add multiple axes to the same figure. ``` from matplotlib import pyplot as plt %matplotlib i...
github_jupyter
# Gromos Tutorial Pipeline ``` import os, sys from pygromos.utils import bash root_dir = os.getcwd() #if package is not installed and path not set correct - this helps you out :) sys.path.append(root_dir+"/..") import pygromos from pygromos.gromos.gromosPP import GromosPP from pygromos.gromos.gromosXX import Gromos...
github_jupyter
# Self-Driving Car Engineer Nanodegree ## Project: **Finding Lane Lines on the Road** *** In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really j...
github_jupyter
``` import os from glob import glob import random import torch from torchvision import datasets as dset from torchvision import transforms from matplotlib import pyplot as plt from torch.utils.data import DataLoader, Dataset from tqdm.notebook import tqdm from siamesenet import SiameseNet from arguments import get_co...
github_jupyter
``` import numpy as np import heron import heron.models.georgebased generator = heron.models.georgebased.Heron2dHodlrIMR() generator.parameters = ["mass ratio"] times = np.linspace(-0.05, 0.05, 1000) hp, hx = generator.mean({"mass ratio": 1}, times) import matplotlib.pyplot as plt %matplotlib inline plt.plot(hp.data) s...
github_jupyter
<img src="https://upload.wikimedia.org/wikipedia/commons/4/47/Logo_UTFSM.png" width="200" alt="utfsm-logo" align="left"/> # MAT281 ### Aplicaciones de la Matemática en la Ingeniería ## Módulo 03 ## Clase 01: Teoría y Landscape de Visualizaciones ## Objetivos * Comprender la importancia de las visualizaciones. * Con...
github_jupyter
<a href="https://colab.research.google.com/github/Rivaldop/metodologidatascience/blob/main/Regresi_Linear.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <img src = "https://evangsmailoa.files.wordpress.com/2019/09/ml.png" align = "center"> #<cent...
github_jupyter
# Tutorial Part 10: Exploring Quantum Chemistry with GDB1k Most of the tutorials we've walked you through so far have focused on applications to the drug discovery realm, but DeepChem's tool suite works for molecular design problems generally. In this tutorial, we're going to walk through an example of how to train a ...
github_jupyter
<a href="https://colab.research.google.com/github/Chiebukar/Deep-Learning/blob/main/regression/temperature_forcasting_with_RNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Temperature Forcasting with Jena climate dataset ``` from google.colab...
github_jupyter
### PPO, Actor-Critic Style _______________________ &nbsp;&nbsp;**for** iteration=1,2,... do<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**for** actor=1,2,...,N do<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Run policy $\pi_{\theta_{old}}$ in environment for T timesteps<br> &nbsp...
github_jupyter
<h1> Create TensorFlow model </h1> This notebook illustrates: <ol> <li> Creating a model using the high-level Estimator API </ol> ``` # change these to try this notebook out BUCKET = 'qwiklabs-gcp-37b9fafbd24bf385' PROJECT = 'qwiklabs-gcp-37b9fafbd24bf385' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCK...
github_jupyter
<img style="float: right; margin: 0px 0px 15px 15px;" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQt6eQo8JPYzYO4p6WmxLtccdtJ4X8WR6GzVVKbsMjyGvUDEn1mg" width="300px" height="100px" /> # Trabajando con opciones Una opción puede negociarse en el mercado secundario por lo que es importante determinar su v...
github_jupyter
# List and Dictionary Comprehensions Comprehension is a different way to construct lists and dictionaries. Up to now, every time that we have built up a list or dictionary, we began by initializing it. We then took advantage of their mutability inherent to build them up one element or key-value pair at a time. However...
github_jupyter
``` import numpy as np import pandas as pd from pathlib import Path from matplotlib import pyplot as plt from sklearn.preprocessing import LabelEncoder train_df = pd.read_csv(Path('Resources/2019loans.csv')) test_df = pd.read_csv(Path('Resources/2020Q1loans.csv')) train_df test_df # Convert categorical data to numeric ...
github_jupyter
## Denoising Autoencoder on MNIST dataset * This notebook will give you a very good understanding abou denoising autoencoders * For more information: visit [here](https://lilianweng.github.io/lil-log/2018/08/12/from-autoencoder-to-beta-vae.html) * The entire notebook is in PyTorch ``` # Importing packages that will be...
github_jupyter
# Cleaning the data to build the prototype for crwa ### This data cleans the original sql output and performs cleaning tasks. Also checking validity of the results against original report found at ### https://www.crwa.org/uploads/1/2/6/7/126781580/crwa_ecoli_web_2017_updated.xlsx ``` import pandas as pd pd.options.di...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.formula.api as sm %matplotlib inline diab = pd.read_csv("../data/diabetes.csv") print(""" # Variables are # subject: subject ID number # age: age diagnosed with diabetes # acidity: a measure of acidity called base deficit # ...
github_jupyter
# MATH 4100: Temporal data analysis and applications to stock analysis *Curtis Miller* ## Introduction This is a lecture for [MATH 4100/CS 5160: Introduction to Data Science](http://datasciencecourse.net/), offered at the University of Utah, introducing time series data analysis applied to finance. Advanced mathemat...
github_jupyter
# Вебинар 6. Консультация по курсовому проекту. ### Задание для курсового проекта Метрика: R2 - коэффициент детерминации (sklearn.metrics.r2_score) Сдача проекта: 1. Прислать в раздел Задания Урока 10 ("Вебинар. Консультация по итоговому проекту") ссылку на программу в github (программа должна содержаться в файле Ju...
github_jupyter
``` #''' #Demonstrates GRAPPA reconstruction of undersampled data. #See function grappa_detail.py for an example showing more of the #workings and functionality of the SIRF code. # #Pre-requisites: # 1) If the reconstruction engine is set to Gadgetron (default), then # this Python script needs to be able to access ...
github_jupyter
# Radial Velocity Orbit-fitting with RadVel ## Week 6, Intro-to-Astro 2021 ### Written by Ruben Santana & Sarah Blunt, 2018 #### Updated by Joey Murphy, June 2020 #### Updated by Corey Beard, July 2021 ## Background information Radial velocity measurements tell us how the velocity of a star changes along the directi...
github_jupyter
``` import math import string import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.special import logit from IPython.display import display import tensorflow as tf from tensorflow.keras.layers import (Input, Dense, Lambda, Flatten, Reshape, BatchNormalization, Layer, ...
github_jupyter
# Calculating a custom statistic This example shows how to define and use a custom `iris.analysis.Aggregator`, that provides a new statistical operator for use with cube aggregation functions such as `~iris.cube.Cube.collapsed`, `~iris.cube.Cube.aggregated_by` or `~iris.cube.Cube.rolling_window`. In this case, we hav...
github_jupyter
``` import pandas as pd import geopandas import glob import matplotlib.pyplot as plt import numpy as np import seaborn import shapefile as shp from paths import * from refuelplot import * setup() wpNZ = pd.read_csv(data_path + "/NZ/windparks_NZ.csv", delimiter=';') wpBRA = pd.read_csv(data_path + '/BRA/turbine_data.csv...
github_jupyter
# Test Coffea This will test Coffea to see if we can figure out how to use it with our code. First are the includes from coffea. This is based on the [example written by Ben](https://github.com/CoffeaTeam/coffea/blob/master/binder/servicex/ATLAS/LocalExample.ipynb). ``` from servicex import ServiceXDataset from cof...
github_jupyter
# dwtls: Discrete Wavelet Transform LayerS This library provides downsampling (DS) layers using discrete wavelet transforms (DWTs), which we call DWT layers. Conventional DS layers lack either antialiasing filters and the perfect reconstruction property, so downsampled features are aliased and entire information of inp...
github_jupyter
``` # Imports import matplotlib.pyplot as plt import json # Load data from result files results_file = './results/results_5.json' summary_file = './results/summary.json' results = json.load(open(results_file))['results'] summary = json.load(open(summary_file)) def autolabel(rects, label_pos=0): """ Generate ...
github_jupyter
<a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/sprinkler_pgm.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Directed graphical models We illustrate some basic properties of DGMs. ``` !pip install causal...
github_jupyter
``` import json from datetime import datetime, timedelta import matplotlib.pylab as plot import matplotlib.pyplot as plt from matplotlib import dates import pandas as pd import numpy as np import matplotlib matplotlib.style.use('ggplot') %matplotlib inline # Read data from http bro logs with open("http.log",'r') as in...
github_jupyter
# Method4 DCT based DOST + Huffman encoding ## Import Libraries ``` import mne import numpy as np from scipy.fft import fft,fftshift import matplotlib.pyplot as plt from scipy.signal import butter, lfilter from scipy.signal import freqz from scipy import signal from scipy.fftpack import fft, dct, idct from itertools ...
github_jupyter
# ElasticNet with RobustScaler **This Code template is for the regression analysis using a ElasticNet Regression and the feature rescaling technique RobustScaler in a pipeline** ### Required Packages ``` import warnings as wr import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot...
github_jupyter
# Let's Import Our Libraries ``` # Keras from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Dense, Flatten, LSTM, Conv1D, MaxPooling1D, Dropout, Activation from keras.layers.embeddings import Embedding # Pl...
github_jupyter
<a href="https://colab.research.google.com/github/sroy8091/deep-learning-v2-pytorch/blob/master/convolutional-neural-networks/cifar-cnn/cifar10_cnn_exercise.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Convolutional Neural Networks --- In this ...
github_jupyter
# Quickstart In this tutorial, we explain how to quickly use ``LEGWORK`` to calculate the detectability of a collection of sources. ``` %matplotlib inline ``` Let's start by importing the source and visualisation modules of `LEGWORK` and some other common packages. ``` import legwork.source as source import legwork....
github_jupyter
- **Let us see how well our model would perform if we would deploy our model at the end of 2018** - **ie: Let us test our model on 2019 data** ``` import numpy as np import pandas as pd import category_encoders as ce from sklearn.preprocessing import LabelBinarizer from sklearn.preprocessing import OneHotEncoder dat...
github_jupyter
``` import transportation_tutorials as tt ``` # Creating Dynamic Maps In this gallery, we will demonstrate the creation of a variety of interactive maps. Interactive, dynamic maps are a good choice for analytical work that will be reviewed online, either in a Jupyter notebook by an analyst, or published on a website....
github_jupyter
### Data Scientist Nano Degree - Capstone Project ### Car Booking Analysis and Prediction ### Tarek Abd ElRahman Ahmed ElAyat #### Let's import the needed libraries ``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import warnings from sklearn import model_selection fr...
github_jupyter
``` from __future__ import division, print_function import os import torch import pandas import numpy as np from torch.utils.data import DataLoader,Dataset from torchvision import utils, transforms from skimage import io, transform import matplotlib.pyplot as plt import warnings #ignore warnings warnings.filterwarning...
github_jupyter
## K Means Clustering ### Our Objective - Perform K-Means Clustering to detect Network Intrusion Attempts (Cybersecurity) ``` #matrix math import numpy as np #graphing import matplotlib.pyplot as plt #graphing animation import matplotlib.animation as animation #load textfile dataset (2D data points) # for each user, h...
github_jupyter
### B.1.1.7 #### The selection of suitable loci (done on Tue 22. Dec. 2020) To identify suitable targets for primer/probe design, we downloaded 1,136 sequences from the GISAID repository filtered during a collection time spanning 1 - 21 December 2020. We focused on the spike gene because lineage B.1.1.7 contains a num...
github_jupyter
``` %matplotlib inline import gym import matplotlib import numpy as np import sys from collections import defaultdict if "../" not in sys.path: sys.path.append("../") from lib.envs.blackjack import BlackjackEnv from lib import plotting matplotlib.style.use('ggplot') env = BlackjackEnv() def mc_prediction(policy,...
github_jupyter
# Generate correction profiles for denoised by Pu Zheng 2019.06.18 ``` %run "E:\Users\puzheng\Documents\Startup_py3.py" sys.path.append(r"E:\Users\puzheng\Documents") import ImageAnalysis3 as ia %matplotlib notebook from ImageAnalysis3 import * print(os.getpid()) reload(ia.get_img_info) reload(ia.corrections) rel...
github_jupyter
<a href="https://colab.research.google.com/github/haribharadwaj/notebooks/blob/main/BME511/ProbabilisticClassificationClustering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Classification and clustering: probabilistic modeling approach Here, ...
github_jupyter
``` #Fill the paths below PATH_FRC = "" # git repo directory path PATH_ZENODO = "" # Data and models are available here: https://zenodo.org/record/5831014#.YdnW_VjMLeo DATA_FLAT = PATH_ZENODO+'/data/goi_1000/flat_1000/*.png' DATA_NORMAL = PATH_ZENODO+'/data/goi_1000/standard_1000/*.jpg' GAUSS_L2_MODEL = PATH_ZENODO+'...
github_jupyter
``` import pandas df = pandas.read_csv( 'https://archive.ics.uci.edu/ml/' 'machine-learning-databases/iris/iris.data', header=None, ) df.tail() import numpy targets = df.iloc[0:100, 4].values targets = numpy.where(targets == 'Iris-setosa', -1, 1) targets[:10] samples = df.iloc[0:100, [0, 2]].values samples....
github_jupyter
# Autonomous driving - Car detection Welcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: Redmon et al., 2016 (https://arxiv.org/abs/1506.02640) and Redmon and Farhadi, 2016 (htt...
github_jupyter
``` import datetime import os, sys import numpy as np import matplotlib.pyplot as plt import casadi as cas import pickle import copy as cp # from ..</src> import car_plotting # from .import src.car_plotting PROJECT_PATH = '/home/nbuckman/Dropbox (MIT)/DRL/2020_01_cooperative_mpc/mpc-multiple-vehicles/' sys.path.appe...
github_jupyter
``` # %load CommonFunctions.py # # COMMON ATOMIC AND ASTRING FUNCTIONS # In[14]: ############### One String Pulse with width, shift and scale ############# def StringPulse(String1, t: float, a = 1., b = 0., c = 1., d = 0.) -> float: x = (t - b)/a if (x < -1): res = -0.5 elif (x > 1): res...
github_jupyter
``` import numpy as np from exploration.config import sql_inst, mongo_inst val_random_db = mongo_inst['val_random_db'] val_dump = (val_random_db['osu_scores_high'], val_random_db['osu_user_stats']) pdf_func = np.load("exploration/skill_biased_sampling_function/pdf_sample_func.npy") greedy_func = np.load("exploration/...
github_jupyter
``` import ast from glob import glob import sys import os from copy import deepcopy import networkx as nx from stdlib_list import stdlib_list STDLIB = set(stdlib_list()) CONVERSIONS = { 'attr': 'attrs', 'PIL': 'Pillow', 'Image': 'Pillow', 'mpl_toolkits': 'matplotlib', 'dateutil': 'python-dateutil...
github_jupyter
# Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and...
github_jupyter
# HRNet for MARS Tutorial This notebook will walk through using the [HRNet pose estimator](https://github.com/leoxiaobin/deep-high-resolution-net.pytorch) with the [data](https://data.caltech.edu/records/2011) used in the [Mouse Action Recognition System](https://www.biorxiv.org/content/10.1101/2020.07.26.222299v1). ...
github_jupyter
``` import pandas as pd import numpy as np %matplotlib inline import joblib import json import tqdm import glob import numba import dask import xgboost from dask.diagnostics import ProgressBar import re ProgressBar().register() fold1, fold2 = joblib.load("./valid/fold1.pkl.z"), joblib.load("./valid/fold2.pkl.z") tra...
github_jupyter
``` import os import time import numpy as np import tensorflow as tf from tensorflow.random import set_seed from math import factorial from scipy.stats import norm from scipy.integrate import odeint import numpy.polynomial.hermite_e as H from sklearn.preprocessing import StandardScaler import dolfin as fn from numpy.p...
github_jupyter
# EDA of All Sides Media ratings for 'debiaser' data product #### Sagar Setru, September 21th, 2020 ## Brief description using CoNVO framework ### Context Some people are eager to get news from outside of their echo chamber. However, they do not know where to go outside of their echo chambers, and may also have some...
github_jupyter
# Task 1: Word Embeddings (10 points) This notebook will guide you through all steps necessary to train a word2vec model (Detailed description in the PDF). ## Imports This code block is reserved for your imports. You are free to use the following packages: (List of packages) ``` # Imports from pandas import Dat...
github_jupyter
``` # The purpose of this notebook is to compare the # efficacy of various Machine Learning models on # the dataset. import os import numpy as np import pandas as pd from sklearn.model_selection import train_test_split np.random.seed(0) script_dir = os.path.abspath('') file = os.path.realpath(script_dir + '/../data...
github_jupyter