code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Problem Simulation Tutorial ``` import pyblp import numpy as np import pandas as pd pyblp.options.digits = 2 pyblp.options.verbose = False pyblp.__version__ ``` Before configuring and solving a problem with real data, it may be a good idea to perform Monte Carlo analysis on simulated data to verify that it is poss...
github_jupyter
# Softmax exercise *Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.* This exercise is ...
github_jupyter
<a href="https://colab.research.google.com/github/ai-fast-track/timeseries/blob/master/nbs/index.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # `timeseries` package for fastai v2 > **`timeseries`** is a Timeseries Classification and Regression p...
github_jupyter
<a href="https://colab.research.google.com/github/mouctarbalde/concrete-strength-prediction/blob/main/Cement_prediction_.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns fr...
github_jupyter
# The Extended Kalman Filter 선형 칼만 필터 (Linear Kalman Filter)에 대한 이론을 바탕으로 비선형 문제에 칼만 필터를 적용해 보겠습니다. 확장칼만필터 (EKF)는 예측단계와 추정단계의 데이터를 비선형으로 가정하고 현재의 추정값에 대해 시스템을 선형화 한뒤 선형 칼만 필터를 사용하는 기법입니다. 비선형 문제에 적용되는 성능이 더 좋은 알고리즘들 (UKF, H_infinity)이 있지만 EKF 는 아직도 널리 사용되서 관련성이 높습니다. ``` %matplotlib inline # HTML(""" # <style> # .ou...
github_jupyter
# Method for visualizing warping over training steps ``` import os import imageio import numpy as np import matplotlib.pyplot as plt np.random.seed(0) ``` ### Construct warping matrix ``` g = 1.02 # scaling parameter # Matrix for rotating 45 degrees rotate = np.array([[np.cos(np.pi/4), -np.sin(np.pi/4)], ...
github_jupyter
# Documenting Classes It is almost as easy to document a class as it is to document a function. Simply add docstrings to all of the classes functions, and also below the class name itself. For example, here is a simple documented class ``` class Demo: """This class demonstrates how to document a class. ...
github_jupyter
# Lab 4: EM Algorithm and Single-Cell RNA-seq Data ### Name: Your Name Here (Your netid here) ### Due April 2, 2021 11:59 PM #### Preamble (Don't change this) ## Important Instructions - 1. Please implement all the *graded functions* in main.py file. Do not change function names in main.py. 2. Please read the des...
github_jupyter
# Week 2 Tasks During this week's meeting, we have discussed about if/else statements, Loops and Lists. This notebook file will guide you through reviewing the topics discussed and assisting you to be familiarized with the concepts discussed. ## Let's first create a list ``` # Create a list that stores the multiples...
github_jupyter
# launch scripts through SLURM The script in the cell below submits SLURM jobs running the requested `script`, with all parameters specified in `param_iterators` and the folder where to dump data as last parameter. The generated SBATCH scipts (`.job` files) are saved in the `jobs` folder and then submitted. Output ...
github_jupyter
<a href="https://colab.research.google.com/github/Vanagand/DS-Unit-2-Applied-Modeling/blob/master/module1-define-ml-problems/Unit_2_Sprint_3_Module_1_LESSON.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint...
github_jupyter
<img src="images/strathsdr_banner.png" align="left"> # An RFSoC Spectrum Analyzer Dashboard with Voila ---- <div class="alert alert-box alert-info"> Please use Jupyter Labs http://board_ip_address/lab for this notebook. </div> The RFSoC Spectrum Analyzer is an open source tool developed by the [University of Strathc...
github_jupyter
# Examples I - Inferring $v_{\rm rot}$ By Minimizing the Line Width This Notebook intends to demonstrate the method used in [Teague et al. (2018a)](https://ui.adsabs.harvard.edu/#abs/2018ApJ...860L..12T) to infer the rotation velocity as a function of radius in the disk of HD 163296. The following [Notebook](Examples%...
github_jupyter
## Data Extraction and load from FRED API.. ``` ## Import packages for the process... import requests import pickle import os import mysql.connector import time ``` ### Using pickle to wrap the database credentials and Fred API keys ``` if not os.path.exists('fred_api_secret.pk1'): fred_key = {} fred_key['...
github_jupyter
``` import pathlib import lzma import re import os import datetime import copy import numpy as np import pandas as pd # Makes it so any changes in pymedphys is automatically # propagated into the notebook without needing a kernel reset. from IPython.lib.deepreload import reload %load_ext autoreload %autoreload 2 impor...
github_jupyter
<img src="https://storage.googleapis.com/arize-assets/arize-logo-white.jpg" width="200"/> # Arize Tutorial: Surrogate Model Feature Importance A surrogate model is an interpretable model trained on predicting the predictions of a black box model. The goal is to approximate the predictions of the black box model as cl...
github_jupyter
<a href="https://colab.research.google.com/github/MingSheng92/AE_denoise/blob/master/DL_Example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !pip show tensorflow !git clone https://github.com/MingSheng92/AE_denoise.git from google.colab impor...
github_jupyter
``` !pwd %matplotlib inline ``` PyTorch: nn ----------- A fully-connected ReLU network with one hidden layer, trained to predict y from x by minimizing squared Euclidean distance. This implementation uses the nn package from PyTorch to build the network. PyTorch autograd makes it easy to define computational graphs...
github_jupyter
# Understanding Data Types in Python Effective data-driven science and computation requires understanding how data is stored and manipulated. This section outlines and contrasts how arrays of data are handled in the Python language itself, and how NumPy improves on this. Understanding this difference is fundamental to...
github_jupyter
``` import numpy as np from keras.models import Model from keras.layers import Input from keras.layers.pooling import GlobalMaxPooling1D from keras import backend as K import json from collections import OrderedDict def format_decimal(arr, places=6): return [round(x * 10**places) / 10**places for x in arr] DATA = O...
github_jupyter
# GWAS, PheWAS, and Mendelian Randomization > Understanding Methods of Genetic Analysis - categories: [jupyter] ## GWAS Genome Wide Association Studies (GWAS) look for genetic variants across the genome in a large amount of individuals to see if any variants are associated with a specific trait such as height or dis...
github_jupyter
``` import nltk from nltk import * emma = nltk.Text(nltk.corpus.gutenberg.words('austen-emma.txt')) len(emma) emma.concordance("surprise") from nltk.corpus import gutenberg print(gutenberg.fileids()) emma = gutenberg.words("austen-emma.txt") type(gutenberg) for fileid in gutenberg.fileids(): n_chars = len(gutenberg...
github_jupyter
# Water quality ## Setup software libraries ``` # Import and initialize the Earth Engine library. import ee ee.Initialize() ee.__version__ # Folium setup. import folium print(folium.__version__) # Skydipper library. import Skydipper print(Skydipper.__version__) import matplotlib.pyplot as plt import numpy as np import...
github_jupyter
# Calculating Area and Center Coordinates of a Polygon ``` %load_ext lab_black %load_ext autoreload %autoreload 2 import geopandas as gpd import pandas as pd %aimport src.utils from src.utils import show_df ``` <a id="toc"></a> ## [Table of Contents](#table-of-contents) 0. [About](#about) 1. [User Inputs](#user-inpu...
github_jupyter
# PTN Template This notebook serves as a template for single dataset PTN experiments It can be run on its own by setting STANDALONE to True (do a find for "STANDALONE" to see where) But it is intended to be executed as part of a *papermill.py script. See any of the experimentes with a papermill script to get sta...
github_jupyter
# Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional layers, followed by a fully connected layer. We'll use it to classify handwritten digits in the MNIST dataset, which should be f...
github_jupyter
# Country Economic Conditions for Cargo Carriers This report is written from the point of view of a data scientist preparing a report to the Head of Analytics for a logistics company. The company needs information on economic and financial conditions is different countries, including data on their international trade,...
github_jupyter
``` import warnings warnings.filterwarnings('ignore') import os import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd import seaborn as sns sns.set(rc={'figure.figsize':(12, 6),"font.size":20,"axes.titlesize":20,"axes.labelsize":20},style="darkgrid") ``` Is there any ...
github_jupyter
# Set-up notebook environment ## NOTE: Use a QIIME2 kernel ``` import numpy as np import pandas as pd import seaborn as sns import scipy from scipy import stats import matplotlib.pyplot as plt import re from pandas import * import matplotlib.pyplot as plt %matplotlib inline from qiime2.plugins import feature_table fro...
github_jupyter
## Health, Wealth of Nations from 1800-2008 ``` import os import numpy as np import pandas as pd from pandas import Series, DataFrame from bqplot import Figure, Tooltip, Label from bqplot import Axis, ColorAxis from bqplot import LogScale, LinearScale, OrdinalColorScale from bqplot import Scatter, Lines from bqplot im...
github_jupyter
I want to analyze changes over time in the MOT GTFS feed. Agenda: 1. [Get data](#Get-the-data) 3. [Tidy](#Tidy-it-up) ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import partridge as ptg from ftplib import FTP import datetime import re import zipfile import os %m...
github_jupyter
Write in the input space, click `Shift-Enter` or click on the `Play` button to execute. ``` (3 + 1 + 12) ** 2 + 2 * 18 ``` Give a title to the notebook by clicking on `Untitled` on the very top of the page, better not to use spaces because it will be also used for the filename Save the notebook with the `Diskette` b...
github_jupyter
# Saving and Loading Models In this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data. ``` %matplotlib inline %config InlineBackend.figure_format = 'retina' i...
github_jupyter
``` Function Order in a Single File¶ In the following code example, the functions are out of order, and the code will not compile. Try to fix this by rearranging the functions to be in the correct order. #include <iostream> using std::cout; void OuterFunction(int i) { InnerFunction(i); } void InnerFunction(int i...
github_jupyter
# Deep Learning & Art: Neural Style Transfer Welcome to the second assignment of this week. In this assignment, you will learn about Neural Style Transfer. This algorithm was created by Gatys et al. (2015) (https://arxiv.org/abs/1508.06576). **In this assignment, you will:** - Implement the neural style transfer alg...
github_jupyter
# Predicting Student Admissions with Neural Networks In this notebook, we predict student admissions to graduate school at UCLA based on three pieces of data: - GRE Scores (Test) - GPA Scores (Grades) - Class rank (1-4) The dataset originally came from here: http://www.ats.ucla.edu/ ## Loading the data To load the da...
github_jupyter
<a href="https://colab.research.google.com/github/ahvblackwelltech/DS-Unit-2-Kaggle-Challenge/blob/master/module2-random-forests/Ahvi_Blackwell_LS_DS_222_assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2,...
github_jupyter
``` # List all NVIDIA GPUs as avaialble in this computer (or Colab's session) !nvidia-smi -L import sys print( f"Python {sys.version}\n" ) import numpy as np print( f"NumPy {np.__version__}" ) import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf print( f"TensorFlow {tf.__version__}" ) print( f"...
github_jupyter
# Imports and Paths ``` import torch from torch import nn import torch.nn.functional as F import torch.optim as optim import numpy as np import pandas as pd import os import shutil from skimage import io, transform import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, Da...
github_jupyter
``` %matplotlib inline ``` # Compute LCMV inverse solution on evoked data in volume source space Compute LCMV inverse solution on an auditory evoked dataset in a volume source space. It stores the solution in a nifti file for visualisation e.g. with Freeview. ``` # Author: Alexandre Gramfort <alexandre.gramfort@te...
github_jupyter
``` #default_exp dataset.dataset #export import os import torch import transformers import pandas as pd import numpy as np import Hasoc.config as config #hide df = pd.read_csv(config.DATA_PATH/'fold_df.csv') #hide df.head(2) #hide from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit_transform(df.t...
github_jupyter
# Speeding-up gradient-boosting In this notebook, we present a modified version of gradient boosting which uses a reduced number of splits when building the different trees. This algorithm is called "histogram gradient boosting" in scikit-learn. We previously mentioned that random-forest is an efficient algorithm sinc...
github_jupyter
``` import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import Imputer from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from sklearn import metrics...
github_jupyter
``` # Install libraries !pip -qq install rasterio tifffile # Import libraries import os import glob import shutil import gc from joblib import Parallel, delayed from tqdm import tqdm_notebook import h5py import pandas as pd import numpy as np import datetime as dt from datetime import datetime, timedelta import matplo...
github_jupyter
# Explore endangered languages from UNESCO Atlas of the World's Languages in Danger ### Input Endangered languages - https://www.kaggle.com/the-guardian/extinct-languages/version/1 (updated in 2016) - original data: http://www.unesco.org/languages-atlas/index.php?hl=en&page=atlasmap (published in 2010) Countries of...
github_jupyter
# Polynomials Class ``` from sympy import * import numpy as np x = Symbol('x') class polinomio: def __init__(self, coefficienti: list): self.coefficienti = coefficienti self.grado = 0 if len(self.coefficienti) == 0 else len( self.coefficienti) - 1 i = 0 while i < len(sel...
github_jupyter
# Function to list overlapping Landsat 8 scenes This function is based on the following tutorial: http://geologyandpython.com/get-landsat-8.html This function uses the area of interest (AOI) to retrieve overlapping Landsat 8 scenes. It will also output on the scenes with the largest portion of overlap and with less t...
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
# 증식을 통한 데이터셋 크기 확장 ## 1. Google Drive와 연동 ``` from google.colab import drive drive.mount("/content/gdrive") path = "gdrive/'My Drive'/'Colab Notebooks'/CNN" !ls gdrive/'My Drive'/'Colab Notebooks'/CNN/datasets ``` ## 2. 모델 생성 ``` from tensorflow.keras import layers, models, optimizers ``` 0. Sequential 객체 생성 1. ...
github_jupyter
<a href="https://colab.research.google.com/github/coenarrow/MNistTests/blob/main/MNIST.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ### Start Julia evironment ``` # Install any required python packages here # !pip install <packages> # Here we in...
github_jupyter
# 컴파일러에서 변수, 조건문 다루기 변수를 다루기 위해서는 기계상태에 메모리를 추가하고 메모리 연산을 위한 저급언어 명령을 추가한다. 조건문을 다루기 위해서는 실행코드를 순차적으로만 실행하는 것이 아니라 특정 코드 위치로 이동하여 실행하는 저급언어 명령을 추가한다. ``` data Expr = Var Name -- x | Val Value -- n | Add Expr Expr -- e1 + e2 -- | Sub Expr Expr -- | Mul Expr...
github_jupyter
# <span style="color: #B40486">BASIC PYTHON FOR RESEARCHERS</span> _by_ [**_Megat Harun Al Rashid bin Megat Ahmad_**](https://www.researchgate.net/profile/Megat_Harun_Megat_Ahmad) last updated: April 14, 2016 ------- ## _<span style="color: #29088A">8. Database and Data Analysis</span>_ --- <span style="color: #00...
github_jupyter
# Investigation of No-show Appointments Data ## Table of Contents <ul> <li><a href="#intro">Introduction</a></li> <li><a href="#wrangling">Data Wrangling</a></li> <li><a href="#eda">Exploratory Data Analysis</a></li> <li><a href="#conclusions">Conclusions</a></li> </ul> <a id='intro'></a> ## Introduction The data ...
github_jupyter
# Test for Embedding, to later move it into a layer ``` import numpy as np # Set-up numpy generator for random numbers random_number_generator = np.random.default_rng() # First tokenize the protein sequence (or any sequence) in kmers. def tokenize(protein_seqs, kmer_sz): kmers = set() # Loop over protein seque...
github_jupyter
# Spectral encoding of categorical features About a year ago I was working on a regression model, which had over a million features. Needless to say, the training was super slow, and the model was overfitting a lot. After investigating this issue, I realized that most of the features were created using 1-hot encoding ...
github_jupyter
# Multivariate SuSiE and ENLOC model ## Aim This notebook aims to demonstrate a workflow of generating posterior inclusion probabilities (PIPs) from GWAS summary statistics using SuSiE regression and construsting SNP signal clusters from global eQTL analysis data obtained from multivariate SuSiE models. ## Methods o...
github_jupyter
``` from utils import config, parse_midas_data, sample_utils as su, temporal_changes_utils, stats_utils, midas_db_utils, parse_patric from collections import defaultdict import math, random, numpy as np import pickle, sys, bz2 import matplotlib.pyplot as plt # Cohort list cohorts = ['backhed', 'ferretti', 'yassour', '...
github_jupyter
``` import keras from keras.applications import VGG16 from keras.models import Model from keras.layers import Dense, Dropout, Input from keras.regularizers import l2, activity_l2,l1 from keras.utils import np_utils from keras.preprocessing.image import array_to_img, img_to_array, load_img from keras.applications.vgg16 ...
github_jupyter
# Guided Investigation - Anomaly Lookup __Notebook Version:__ 1.0<br> __Python Version:__ Python 3.6 (including Python 3.6 - AzureML)<br> __Required Packages:__ azure 4.0.0, azure-cli-profile 2.1.4<br> __Platforms Supported:__<br> - Azure Notebooks Free Compute - Azure Notebook on DSVM __Data Source Re...
github_jupyter
# 4 - Train models and make predictions ## Motivation - **`tf.keras`** API offers built-in functions for training, validation and prediction. - Those functions are easy to use and enable you to train any ML model. - They also give you a high level of customizability. ## Objectives - Understand the common training wor...
github_jupyter
<a href="https://colab.research.google.com/github/dribnet/clipit/blob/future/demos/CLIP_GradCAM_Visualization.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # CLIP GradCAM Colab This Colab notebook uses [GradCAM](https://arxiv.org/abs/1610.02391) ...
github_jupyter
# Capstone Project - Flight Delays # Does weather events have impact the delay of flights (Brazil)? ### It is important to see this notebook with the step-by-step of the dataset cleaning process: [https://github.com/davicsilva/dsintensive/blob/master/notebooks/flightDelayPrepData_v2.ipynb](https://github.com/davicsilv...
github_jupyter
``` # Reload when code changed: %load_ext autoreload %reload_ext autoreload %autoreload 2 %pwd import sys import os path = "../" sys.path.append(path) #os.path.abspath("../") print(os.path.abspath(path)) import os import core import logging import importlib importlib.reload(core) try: logging.shutdown() impor...
github_jupyter
Notebook prirejen s strani http://www.pieriandata.com # NumPy Indexing and Selection In this lecture we will discuss how to select elements or groups of elements from an array. ``` import numpy as np #Creating sample array arr = np.arange(0,11) #Show arr ``` ## Bracket Indexing and Selection The simplest way to pic...
github_jupyter
# Chapter 4: Linear models [Link to outline](https://docs.google.com/document/d/1fwep23-95U-w1QMPU31nOvUnUXE2X3s_Dbk5JuLlKAY/edit#heading=h.9etj7aw4al9w) Concept map: ![concepts_LINEARMODELS.png](attachment:c335ebb2-f116-486c-8737-22e517de3146.png) #### Notebook setup ``` import numpy as np import pandas as pd impo...
github_jupyter
``` try: import saspy except ImportError as e: print('Installing saspy') %pip install saspy import pandas as pd # The following imports are only necessary for automated sascfg_personal.py creation from pathlib import Path import os from shutil import copyfile import getpass # Imports without the setup check...
github_jupyter
# VacationPy ---- #### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import gmaps import os ...
github_jupyter
# Support Vector Machine (SVM) Tutorial Follow from: [link](https://towardsdatascience.com/support-vector-machine-introduction-to-machine-learning-algorithms-934a444fca47) - SVM can be used for both regression and classification problems. - The goal of SVM models is to find a hyperplane in an N-dimensional space that...
github_jupyter
<small><i>This notebook was put together by [Jake Vanderplas](http://www.vanderplas.com). Source and license info is on [GitHub](https://github.com/jakevdp/sklearn_tutorial/).</i></small> # Supervised Learning In-Depth: Random Forests Previously we saw a powerful discriminative classifier, **Support Vector Machines**...
github_jupyter
# Talks markdown generator for academicpages Takes a TSV of talks with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html)). The co...
github_jupyter
<a href="https://colab.research.google.com/github/isb-cgc/Community-Notebooks/blob/master/MachineLearning/How_to_build_an_RNAseq_logistic_regression_classifier_with_BigQuery_ML.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # How to build an RNA-se...
github_jupyter
# FireCARES ops management notebook ### Using this notebook In order to use this notebook, a single production/test web node will need to be bootstrapped w/ ipython and django-shell-plus python libraries. After bootstrapping is complete and while forwarding a local port to the port that the ipython notebook server w...
github_jupyter
# Solving vertex cover with a quantum annealer The problem of vertex cover is, given an undirected graph $G = (V, E)$, colour the smallest amount of vertices such that each edge $e \in E$ is connected to a coloured vertex. This notebooks works through the process of creating a random graph, translating to an optimiza...
github_jupyter
``` import sys sys.path.append("/Users/sgkang/Projects/DamGeophysics/codes/") from Readfiles import getFnames from DCdata import readReservoirDC %pylab inline from SimPEG.EM.Static import DC from SimPEG import EM from SimPEG import Mesh ``` Read DC data ``` fname = "../data/ChungCheonDC/20150101000000.apr" survey = r...
github_jupyter
# FloPy ## Using FloPy to simplify the use of the MT3DMS ```SSM``` package A multi-component transport demonstration ``` import os import sys import numpy as np # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(f...
github_jupyter
# Home2 Your home away from home <br> The best location for your needs, anywhere in the world <br> ### Inputs: Addresses (eg. 'Pune, Maharashtra') Category List (eg. 'Food', 'Restaurant', 'Gym', 'Trails', 'School', 'Train Station') Limit of Results to return (eg. 75) Radius of search in metres (eg. 10,...
github_jupyter
# Introduction In a prior notebook, documents were partitioned by assigning them to the domain with the highest Dice similarity of their term and structure occurrences. The occurrences of terms and structures in each domain is what we refer to as the domain "archetype." Here, we'll assess whether the observed similari...
github_jupyter
``` import pandas as pd import praw import re import datetime as dt import seaborn as sns import requests import json import sys import time ## acknowledgements ''' https://stackoverflow.com/questions/48358837/pulling-reddit-comments-using-python-praw-and-creating-a-da...
github_jupyter
``` #pip install sklearn numpy scipy matplotlib from sklearn import datasets iris = datasets.load_iris() digits = datasets.load_digits() print(digits.data) digits.target digits.images[0] ``` create a support vector classifier and manually set the gamma ``` from sklearn import svm, metrics clf = svm.SVC(gamma=0.001, C...
github_jupyter
# Residual Networks Welcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](h...
github_jupyter
# Project 3 Sandbox-Blue-O, NLP using webscraping to create the dataset ## Objective: Determine if posts are in the SpaceX Subreddit or the Blue Origin Subreddit We'll utilize the RESTful API from pushshift.io to scrape subreddit posts from r/blueorigin and r/spacex and see if we cannot use the Bag-of-words algorithm...
github_jupyter
Uses Fine-Tuned BERT network to classify biomechanics papers from PubMed ``` # Check date !rm /etc/localtime !ln -s /usr/share/zoneinfo/America/Los_Angeles /etc/localtime !date # might need to restart runtime if timezone didn't change ## Install & load libraries !pip install tensorflow==2.7.0 try: from official.nl...
github_jupyter
# Wilcoxon and Chi Squared ``` import numpy as np import pandas as pd df = pd.read_csv("prepared_neuror2_data.csv") def stats_for_neuror2_range(lo, hi): admissions = df[df.NR2_Score.between(lo, hi)] total_patients = admissions.shape[0] readmits = admissions[admissions.UnplannedReadmission] total_readm...
github_jupyter
Note: This notebook was executed on google colab pro. ``` !pip3 install pytorch-lightning --quiet from google.colab import drive drive.mount('/content/drive') import os os.chdir('/content/drive/MyDrive/Colab Notebooks/atmacup11/experiments') ``` # Settings ``` EXP_NO = 27 SEED = 1 N_SPLITS = 5 TARGET = 'target' GR...
github_jupyter
``` %reset -f # libraries used # https://stats.stackexchange.com/questions/181/how-to-choose-the-number-of-hidden-layers-and-nodes-in-a-feedforward-neural-netw import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn...
github_jupyter
# Essential Objects This tutorial covers several object types that are foundational to much of what pyGSTi does: [circuits](#circuits), [processor specifications](#pspecs), [models](#models), and [data sets](#datasets). Our objective is to explain what these objects are and how they relate to one another at a high lev...
github_jupyter
<img src="Techzooka.png"> ## Hacker Factory Cyber Hackathon Solution ### by Team Jugaad (Abhiraj Singh Rajput, Deepanshu Gupta, Manuj Mehrotra) We are a team of members, that are NOT moved by the buzzwords like Machine Learning, Data Science, AI etc. However we are a team of people who get adrenaline rush for seekin...
github_jupyter
# Day and Night Image Classifier --- The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images. We'd like to build a classifier that can accurately label these images as day or night, and that relies on f...
github_jupyter
``` from plot import * from gen import * # from load_data import * from func_tools import * from AGM import * from GM import * from BFGS import * from LBFGS import * from sklearn import metrics import warnings warnings.filterwarnings('ignore') def purity_score(y_true, y_pred): contingency_matrix = metrics.cluster...
github_jupyter
##### Copyright 2018 The AdaNet 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 agre...
github_jupyter
# CW Attack Example TJ Kim <br /> 1.28.21 ### Summary: Implement CW attack on toy network example given in the readme of the github. <br /> https://github.com/tj-kim/pytorch-cw2?organization=tj-kim&organization=tj-kim A dummy network is made using CIFAR example. <br /> https://pytorch.org/tutorials/beginner/blitz/c...
github_jupyter
# Simple RNN In this notebook, we're going to train a simple RNN to do **time-series prediction**. Given some set of input data, it should be able to generate a prediction for the next time step! <img src='assets/time_prediction.png' width=40% /> > * First, we'll create our data * Then, define an RNN in PyTorch * Fin...
github_jupyter
``` import numpy as np %matplotlib inline import matplotlib.pyplot as plt from matplotlib import rc,rcParams rc('text', usetex=True) rcParams['figure.figsize'] = (8, 6.5) rcParams['ytick.labelsize'],rcParams['xtick.labelsize'] = 17.,17. rcParams['axes.labelsize']=19. rcParams['legend.fontsize']=17. rcParams['axes.title...
github_jupyter
# Load MNIST Data ``` # MNIST dataset downloaded from Kaggle : #https://www.kaggle.com/c/digit-recognizer/data # Functions to read and show images. import numpy as np import pandas as pd import matplotlib.pyplot as plt d0 = pd.read_csv('./mnist_train.csv') print(d0.head(5)) # print first five rows of d0. # ...
github_jupyter
``` !pip install vcrpy import vcr offline = vcr.VCR( record_mode='new_episodes', ) ``` # APIs and data Catherine Devlin (@catherinedevlin) Innovation Specialist, 18F Oakwood High School, Feb 16 2017 # Who am I? (hint: not Jean Valjean) ![International Falls, MN winter street scene](http://kcc-tv.org/wp-cont...
github_jupyter
# Random Forest Aplicação do random forest em uma mão de poker ***Dataset:*** https://archive.ics.uci.edu/ml/datasets/Poker+Hand ***Apresentação:*** https://docs.google.com/presentation/d/1zFS4cTf9xwvcVPiCOA-sV_RFx_UeoNX2dTthHkY9Am4/edit ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt fro...
github_jupyter
``` import numpy as np import matplotlib.pylab as plt def Weight(phi,A=5, phi_o=0): return 1-(0.5*np.tanh(A*((np.abs(phi)-phi_o)))+0.5) def annot_max(x,y, ax=None): x=np.array(x) y=np.array(y) xmax = x[np.argmax(y)] ymax = y.max() text= "x={:.3f}, y={:.3f}".format(xmax, ymax) if not ax: ...
github_jupyter
# Description This task is to do an exploratory data analysis on the balance-scale dataset ## Data Set Information This data set was generated to model psychological experimental results. Each example is classified as having the balance scale tip to the right, tip to the left, or be balanced. The attributes are the ...
github_jupyter
# Summarizing Emails using Machine Learning: Data Wrangling ## Table of Contents 1. Imports & Initalization <br> 2. Data Input <br> A. Enron Email Dataset <br> B. BC3 Corpus <br> 3. Preprocessing <br> A. Data Cleaning. <br> B. Sentence Cleaning <br> C. Tokenizing <br> 4. Store Data <br> A. Local...
github_jupyter
``` # Load essential libraries import csv import numpy as np import matplotlib.pyplot as plt import statistics import numpy as np from scipy.signal import butter, lfilter, freqz from IPython.display import Image from datetime import datetime # Time and robot egomotion time = [] standardized_time = [] standardized_tim...
github_jupyter