code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# The Theta Model The Theta model of Assimakopoulos & Nikolopoulos (2000) is a simple method for forecasting the involves fitting two $\theta$-lines, forecasting the lines using a Simple Exponential Smoother, and then combining the forecasts from the two lines to produce the final forecast. The model is implemented i...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np %matplotlib inline data_label = pd.read_csv("data(with_label).csv") ``` ### 30 day death age ``` fig = plt.figure(figsize=(12,6)) sns.set_style('darkgrid') ax = sns.violinplot(x="thirty_days", hue="gender", y="age",data=d...
github_jupyter
# Logic: `logic.py`; Chapters 6-8 This notebook describes the [logic.py](https://github.com/aimacode/aima-python/blob/master/logic.py) module, which covers Chapters 6 (Logical Agents), 7 (First-Order Logic) and 8 (Inference in First-Order Logic) of *[Artificial Intelligence: A Modern Approach](http://aima.cs.berkele...
github_jupyter
``` # Copyright 2021 Google LLC # # 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 writi...
github_jupyter
# Classification algorithms In the context of record linkage, classification refers to the process of dividing record pairs into matches and non-matches (distinct pairs). There are dozens of classification algorithms for record linkage. Roughly speaking, classification algorithms fall into two groups: - **supervised...
github_jupyter
# Deep Matrix Factorisation Matrix factorization with deep layers ``` import sys sys.path.append("../") import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd from IPython.display import SVG, display import matplotlib.pyplot as plt import seaborn as sns from reco.preprocess import ...
github_jupyter
# Convolutional Layer In this notebook, we visualize four filtered outputs (a.k.a. activation maps) of a convolutional layer. In this example, *we* are defining four filters that are applied to an input image by initializing the **weights** of a convolutional layer, but a trained CNN will learn the values of these w...
github_jupyter
# AdaDelta compared to AdaGrad Presented during ML reading group, 2019-11-12. Author: Ivan Bogdan-Daniel, ibogdanidaniel@gmail.com ``` #%matplotlib notebook %matplotlib inline import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D print(f'Numpy version: ...
github_jupyter
``` #!/usr/bin/env python # coding: utf-8 # Imports import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn.metrics import f1_score, accuracy_score from sklearn.metrics import roc_curve, confusion_matrix import torch import torch.nn as nn # All neural network mod...
github_jupyter
<a href="https://colab.research.google.com/github/r5racker/012_RahilBhensdadia/blob/main/Lab_05_1_linear_regression_scratch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` # Import Numpy & PyTorch import numpy as np ``` A tensor is a number, ve...
github_jupyter
# Exploratory Data Analysis of AllenSDK ``` # Only for Colab #!python -m pip install --upgrade pip #!pip install allensdk ``` ## References - [[AllenNB1]](https://allensdk.readthedocs.io/en/latest/_static/examples/nb/visual_behavior_ophys_data_access.html) Download data using the AllenSDK or directly from our Amazon...
github_jupyter
``` # # libraries # import pandas as pd from sklearn.linear_model import LinearRegression as OLS from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import seaborn as sns # # # utility function for plotting histograms in a grid # def plot_h...
github_jupyter
# Consumption Equivalent Variation (CEV) 1. Use the model in the **ConsumptionSaving.pdf** slides and solve it using **egm** 2. This notebooks estimates the *cost of income risk* through the Consumption Equivalent Variation (CEV) We will here focus on the cost of income risk, but the CEV can be used to estimate the ...
github_jupyter
# Facial Expression Recognizer ``` #The OS module in Python provides a way of using operating system dependent functionality. #import os # For array manipulation import numpy as np #For importing data from csv and other manipulation import pandas as pd #For displaying images import matplotlib.pyplot as plt import m...
github_jupyter
2017 Machine Learning Practical University of Edinburgh Georgios Pligoropoulos - s1687568 Coursework 4 (part 7) ### Imports, Inits, and helper functions ``` jupyterNotebookEnabled = True plotting = True coursework, part = 4, 7 saving = True if jupyterNotebookEnabled: #%load_ext autoreload %reload_ext aut...
github_jupyter
# Exercises 06 - Strings and Dictionaries ## 0. Length of Strings Let's start with a string lightning round to warm up. What are the lengths of the strings below? For each of the five strings below, predict what `len()` would return when passed that string. Use the variable `length` to record your answer. ``` a = "...
github_jupyter
<a href="https://colab.research.google.com/github/nationalarchives/TechneTraining/blob/main/Code/Techne_ML_workbook.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Set up variables and install useful library code ``` import sys data_source = "Git...
github_jupyter
``` import re import json import pandas as pd import numpy as np from collections import deque ``` ## Process dataset ``` base_folder = "../movies-dataset/" movies_metadata_fn = "movies_metadata.csv" credits_fn = "credits.csv" links_fn = "links.csv" ``` ## Process movies_metadata data structure/schema ``` metadat...
github_jupyter
``` import json import os import time import requests import psycopg2 import os import json database_dict = { "database": os.environ.get("POSTGRES_DB"), "user": os.environ.get("POSTGRES_USERNAME"), "password": os.environ.get("POSTGRES_PASSWORD"), "host": os.environ.get("POSTGRES_WRITER"...
github_jupyter
``` import sympy as sp import numpy as np x = sp.symbols('x') p = sp.Function('p') l = sp.Function('l') poly = sp.Function('poly') p3 = sp.Function('p3') p4 = sp.Function('p4') ``` # Introduction Last time we have used Lagrange basis to interpolate polynomial. However, it is not efficient to update the interpolating ...
github_jupyter
``` import ml reload(ml) from ml import * import timeit import scipy import operator import collections import numpy as np import pandas as pd from scipy import stats import seaborn as sns from collections import Counter import matplotlib.pyplot as plt from __future__ import division from matplotlib.colors import Liste...
github_jupyter
# Spark DataFrames Project Exercise Let's get some quick practice with your new Spark DataFrame skills, you will be asked some basic questions about some stock market data, in this case Walmart Stock from the years 2012-2017. This exercise will just ask a bunch of questions, unlike the future machine learning exercise...
github_jupyter
<img width="10%" alt="Naas" src="https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160"/> # HubSpot - Get closed deals weekly <a href="https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/HubSpot/HubSpot_Get_closed_deals_weekly.ipynb" t...
github_jupyter
``` import numpy as np, pandas as pd, matplotlib.pyplot as plt import os import seaborn as sns sns.set() root_path = r'C:\Users\54638\Desktop\Cannelle\Excel handling' input_path = os.path.join(root_path, "input") output_path = os.path.join(root_path, "output") %%time # this line magic function should always be put on ...
github_jupyter
# fuzzy_pandas examples These are almost all from [Max Harlow](https://twitter.com/maxharlow)'s [awesome NICAR2019 presentation](https://docs.google.com/presentation/d/1djKgqFbkYDM8fdczFhnEJLwapzmt4RLuEjXkJZpKves/) where he demonstrated [csvmatch](https://github.com/maxharlow/csvmatch), which fuzzy_pandas is based on....
github_jupyter
<h1>Demand forecasting with BigQuery and TensorFlow</h1> In this notebook, we will develop a machine learning model to predict the demand for taxi cabs in New York. To develop the model, we will need to get historical data of taxicab usage. This data exists in BigQuery. Let's start by looking at the schema. ``` impo...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np from numpy.linalg import norm import pandas as pd plt.style.use('ggplot') deaths = pd.read_csv('deaths.txt') pumps = pd.read_csv('pumps.txt') print deaths.head() print pumps.head() plt.plot(deaths['X'], deaths['Y'], 'o', lw=0, mew=1, mec='0.9', m...
github_jupyter
# Concise Implementation of Linear Regression With the development of deep learning frameworks, it has become increasingly easy to develop deep learning applications. In practice, we can usually implement the same model, but much more concisely than how we introduce it in the previous section. In this section, we will...
github_jupyter
``` from airsenal.framework.utils import * from airsenal.framework.bpl_interface import get_fitted_team_model from airsenal.framework.season import get_current_season, CURRENT_TEAMS import matplotlib.pyplot as plt import seaborn as sns import numpy as np %matplotlib inline model_team = get_fitted_team_model(get_cur...
github_jupyter
# TV Script Generation In this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network you'll build will ge...
github_jupyter
# Deterministic point jet ``` import matplotlib.pyplot as plt import pandas as pd import numpy as np import matplotlib.pylab as pl ``` \begin{equation} \partial_t \zeta = \frac{\zeta_{jet}}{\tau} - \mu \zeta + \nu_\alpha \nabla^{2\alpha} - \beta \partial_x \psi - J(\psi, \zeta) \zeta \end{equation} Here $\zeta_...
github_jupyter
# Building Autonomous Trader using mt5se ## How to setup and use mt5se ### 1. Install Metatrader 5 (https://www.metatrader5.com/) ### 2. Install python package Metatrader5 using pip #### Use: pip install MetaTrader5 ... or Use sys package ### 3. Install python package mt5se using pip #### Use: pip install mt5se ...
github_jupyter
# Introduction to Deep Learning with PyTorch In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tenso...
github_jupyter
<a href="https://colab.research.google.com/github/Lambda-School-Labs/bridges-to-prosperity-ds-d/blob/SMOTE_model_building%2Ftrevor/notebooks/Modeling_off_original_data_smote_gridsearchcv.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> This notebook ...
github_jupyter
##### Copyright 2019 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); ``` # Copyright 2019 The TensorFlow Hub 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. ...
github_jupyter
<a href="https://cognitiveclass.ai"><img src = "https://ibm.box.com/shared/static/9gegpsmnsoo25ikkbl4qzlvlyjbgxs5x.png" width = 400> </a> <h1 align=center><font size = 5>Waffle Charts, Word Clouds, and Regression Plots</font></h1> ## Introduction In this lab, we will learn how to create word clouds and waffle charts...
github_jupyter
<h2>Factorization Machines - Movie Recommendation Model</h2> Input Features: [userId, moveId] <br> Target: rating <br> ``` import numpy as np import pandas as pd # Define IAM role import boto3 import re import sagemaker from sagemaker import get_execution_role # SageMaker SDK Documentation: http://sagemaker.readthed...
github_jupyter
# The overview of the basic approaches to solving the Uplift Modeling problem <br> <center> <a href="https://colab.research.google.com/github/maks-sh/scikit-uplift/blob/master/notebooks/RetailHero_EN.ipynb"> <img src="https://colab.research.google.com/assets/colab-badge.svg"> </a> <br> <b><a hr...
github_jupyter
``` s = 'abc' s.upper() # L E G B # local # enclosing # global # builtins globals() globals()['s'] s.upper() dir(s) s.title() x = 'this is a bunch of words to show to people' x.title() for attrname in dir(s): print attrname, s.attrname for attrname in dir(s): print attrname, getattr(s, attrname) s.upper getattr...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. **IMPORTANT NOTE:** This notebook is designed to run as a Colab. Click the button on top that says, `Open in Colab`, to run this notebook as a Colab. Running the notebook on your local machine might result in some of the code blocks throwing errors. ``` #@title Licensed un...
github_jupyter
``` # ############################################### # ########## Default Parameters ################# # ############################################### start = '2016-06-16 22:00:00' end = '2016-06-18 00:00:00' pv_nominal_kw = 5000 # There are 3 PV locations hardcoded at node 7, 8, 9 inverter_sizing = 1.05 inverter_q...
github_jupyter
# Basic Examples with Different Protocols ## Prerequisites * A kubernetes cluster with kubectl configured * curl * grpcurl * pygmentize ## Setup Seldon Core Use the setup notebook to [Setup Cluster](seldon_core_setup.ipynb) to setup Seldon Core with an ingress - either Ambassador or Istio. Then port-forward ...
github_jupyter
# Welcome to Python reference this notebook contains pretty much every thing, if you want to refresh your knowledge or what so ever it will help you ;D <ul> <li>Data types<ul> <li>Numbers</li> <li>Strings</li> <li>Lists</li> <li>Dictionairies</li> <li>Booleans</li> ...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import re import time import warnings import sqlite3 from sqlalchemy import create_engine # database connection import csv import os warnings.filterwarnings("ignore") import datetime as dt import numpy as np from nltk.corpus import stopwords from sklearn.decomposi...
github_jupyter
# 01. Tabular Q Learning Tabular Q Learning을 실습해봅니다. - 모든 state의 value function을 table에 저장하고 테이블의 각 요소를 Q Learning으로 업데이트 하는 것으로 학습합니다. ## Colab 용 package 설치 코드 ``` !pip install gym import tensorflow as tf import numpy as np import random import gym # from gym.wrappers import Monitor np.random.seed(777) tf.set_rand...
github_jupyter
## **Accessing Elements in ndarays:** Elements can be accessed using indices inside square brackets, [ ]. NumPy allows you to use both positive and negative indices to access elements in the ndarray. Positive indices are used to access elements from the beginning of the array, while negative indices are used to access ...
github_jupyter
``` (ql:quickload :delta-vega) ``` # Single-View Plots ## Bar Charts ### Simple Bar Chart A bar chart encodes quantitative values as the extent of rectangular bars. ``` (jupyter:vega-lite (delta-vega:make-top-view :description "A simple bar chart with embedded data." :data (delta-vega:ma...
github_jupyter
# Performing Large Numbers of Calculations with Thermo in Parallel A common request is to obtain a large number of properties from Thermo at once. Thermo is not NumPy - it cannot just automatically do all of the calculations in parallel. If you have a specific property that does not require phase equilibrium calcula...
github_jupyter
``` import os import numpy as np import pandas as pd import random from transformers import (AdamW, get_linear_schedule_with_warmup, logging, ElectraConfig, ElectraTokenizer, ElectraForSequenceClassification, ElectraPreTrainedModel, ElectraModel) import torch im...
github_jupyter
``` ## plot plasma density %pylab inline import numpy as np from matplotlib import pyplot as plt from ReadBinary import * filename = "../data/Wp2-x.data" arrayInfo = GetArrayInfo(filename) print("typeCode: ", arrayInfo["typeCode"]) print("typeSize: ", arrayInfo["typeSize"]) print("shape: ", arrayInfo["shape"]) prin...
github_jupyter
# Creating images using shapes and simple simulation with attenuation This exercise shows how to create images via geometric shapes. It then uses forward projection without and with attenuation. It is recommended you complete the [Introductory](../Introductory) notebooks first (or alternatively the [display_and_projec...
github_jupyter
Dictionary and its default functions. ``` # Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use ...
github_jupyter
<a href="https://colab.research.google.com/github/ymoslem/OpenNMT-Tutorial/blob/main/2-NMT-Training.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` # Install OpenNMT-py 2.x !pip3 install OpenNMT-py ``` # Prepare Your Datasets Please make sure y...
github_jupyter
## Distributed Training with Chainer and ChainerMN Chainer can train in two modes: single-machine, and distributed. Unlike the single-machine notebook example that trains an image classification model on the CIFAR-10 dataset, we will write a Chainer script that uses `chainermn` to distribute training to multiple insta...
github_jupyter
``` try: from openmdao.utils.notebook_utils import notebook_mode except ImportError: !python -m pip install openmdao[notebooks] ``` # NonlinearBlockGS NonlinearBlockGS applies Block Gauss-Seidel (also known as fixed-point iteration) to the components and subsystems in the system. This is mainly used to solve ...
github_jupyter
# AVL Tree ``` from Module.classCollection import Queue class AVLNode: def __init__(self, data): self.data = data self.leftChild = None self.rightChild = None self.height = 1 def preorderTraversal(rootNode): if not rootNode: return print(rootNode.data) ...
github_jupyter
# DA320 Assignment 7: Mongo Charts Jon Kaimmer DA320 Winter2022 ### Introduction Lets import our chirp data and then chart it. ``` #IMPORTS import pymongo import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import json as json import plotly.express as px # import war...
github_jupyter
``` #remove cell visibility from IPython.display import HTML tag = HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide() } else { $('div.input').show() } code_show = !code_show } $( document ).ready(code_toggle); </script> Promijeni vidljivost ...
github_jupyter
# Classification Metrics Spark Example Classification metrics are used to calculate the performance of binary predictors based on a binary target. They are used extensively in other Iguanas modules. This example shows how they can be applied in Spark and how to create your own. ## Requirements To run, you'll need th...
github_jupyter
# Template Matching ### Full Image ``` import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline full = cv2.imread('../images/diver_enhanced.jpg') full = cv2.cvtColor(full, cv2.COLOR_BGR2RGB) plt.imshow(full) ``` ### Template Image ``` face= cv2.imread('../images/dolphin_template.jpg') face =...
github_jupyter
Many features of TensorFlow including their computational graphs lend themselves naturally to being computed in parallel. Computational graphs can be split over different processors as well as in processing different batches. This recipe demonstrates how to access different processors on the same machine. ## Getting r...
github_jupyter
``` import sys sys.path.append("../scripts/") from ideal_robot import * from scipy.stats import expon, norm, uniform class Robot(IdealRobot): def __init__( self, pose, agent=None, sensor=None, color="black", noise_per_meter=5, noise_std=math.pi / 60, ...
github_jupyter
## Search algorithms within Optuna In this notebook, I will demo how to select the search algorithm with Optuna. We will compare the use of: - Grid Search - Randomized search - Tree-structured Parzen Estimators - CMA-ES We can select the search algorithm from the [optuna.study.create_study()](https://optuna.readth...
github_jupyter
## Duplicated features ``` import pandas as pd import numpy as np from sklearn.model_selection import train_test_split ``` ## Read Data ``` data = pd.read_csv('../UNSW_Train.csv') data.shape # check the presence of missing data. # (there are no missing data in this dataset) [col for col in data.columns if data[col]....
github_jupyter
# Run Experiments You can use the Azure Machine Learning SDK to run code experiments that log metrics and generate outputs. This is at the core of most machine learning operations in Azure Machine Learning. ## Connect to your workspace All experiments and associated resources are managed within your Azure Machine Le...
github_jupyter
## Install Lib API ``` ! pip install https://dnaink.jfrog.io/artifactory/dna-ink-pypi/model-fkeywords/0.1.0/model_fkeywords-0.1.0-py3-none-any.whl ! python -m spacy download pt_core_news_sm ``` ## Import libs ``` import pandas as pd import spacy import nltk nltk.download('stopwords') from api_model import nlextract ...
github_jupyter
``` import pandas as pd import os import numpy as np from datetime import timedelta from sklearn.ensemble import RandomForestRegressor import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline in_dir = 'D:\\Toppan\\2017-11-20 全データ\\処理済(機械ごと)\\vectorized' out_dir = in_dir holiday_path = 'D:\\Toppan\\201...
github_jupyter
# Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with functions we'll need. **Instructions:** - You will be using Python 3. - Avoid using for-loops and while-lo...
github_jupyter
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # Solution Notebook ## Problem: Generate a list of primes. * [Constraints](#Constraints) * [Test Cases](#Test-Cases) * [Algorithm](#Algor...
github_jupyter
``` import matplotlib matplotlib.use('nbagg') import matplotlib.animation as anm import matplotlib.pyplot as plt import math import matplotlib.patches as patches import numpy as np %matplotlib widget class World: def __init__(self, time_span, time_interval, debug=False): self.objects = [] self.deb...
github_jupyter
## Overview/To-Do This one tries a different, more realistic detecor layouout. ``` %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from BurstCube.LocSim.GRB import * from BurstCube.LocSim.Detector import * from BurstCube.LocSim.Spacecraft import * from BurstCube.LocSim.Stat...
github_jupyter
``` from __future__ import print_function import matplotlib.pyplot as plt %matplotlib inline import SimpleITK as sitk print(sitk.Version()) from myshow import myshow # Download data to work on %run update_path_to_download_script from downloaddata import fetch_data as fdata OUTPUT_DIR = "Output" ``` This section of t...
github_jupyter
# BUSINESS ANALYTICS You are the business owner of the retail firm and want to see how your company is performing. You are interested in finding out the weak areas where you can work to make more profit. What all business problems you can derive by looking into the data? ``` # Importing certain libraries import pandas...
github_jupyter
### LOAD DATA ``` import csv # for csv file import import numpy as np import os import cv2 import math #from keras import optimizers from sklearn.utils import shuffle # to shuffle data in generator from sklearn.model_selection import train_test_split # to split data into Training + Validation def get_file_data(file_pa...
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 ## Overview Yay! It's week 4. Today's we'll keep things light. I've noticed that many of you are struggling a bit to keep up and still working on exercises from the previous week. Thus, this week we only have two components with no lectures and very little reading. ## Informal intro [![IMAGE ALT TEXT HE...
github_jupyter
<a href="http://cocl.us/pytorch_link_top"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png" width="750" alt="IBM Product " /> </a> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN...
github_jupyter
## Introduction In real world, there exists many huge graphs that can not be loaded in one machine, such as social networks and citation networks. To deal with such graphs, PGL develops a Distributed Graph Engine Framework to support graph sampling on large scale graph networks for distributed GNN training. In thi...
github_jupyter
# "[ML] What's the difference between a metric and a loss?" - toc:true - branch: master - badges: false - comments: true - author: Peiyi Hung - categories: [learning, machine learning] In machine learning, we usually use two values to evaluate our model: a metric and a loss. For instance, if we are doing a binary cla...
github_jupyter
# Convolutional Neural Networks A CNN is made up of basic building blocks defined as tensor, neurons, layers and kernel weights and biases. In this lab, we use PyTorch to build a image classifier using CNN. The objective is to learn CNN using PyTorch framework. Please refer to the link below for know more about CNN htt...
github_jupyter
# Canonical correlation analysis in python In this notebook, we will walk through the solution to the basic algrithm of canonical correlation analysis and compare that to the output of implementations in existing python libraries `statsmodels` and `scikit-learn`. ``` import numpy as np from scipy.linalg import sqrtm ...
github_jupyter
``` from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.model_selection ...
github_jupyter
# Testing Various Machine Learning Models I would like to create model that can identify individuals at the greatest risk of injury three months prior to when it occurs. In order to do this, I will first complete feature selection using a step-forward approach to optimize recall. Then I will complete some basic EDA. H...
github_jupyter
``` #!pip install gretel-synthetics --upgrade #!pip install matplotlib #!pip install smart_open # load source training set import logging import os import sys import pandas as pd from smart_open import open source_file = "https://gretel-public-website.s3-us-west-2.amazonaws.com/datasets/uci-heart-disease/train.csv" an...
github_jupyter
# Methods of Approximating Ambient Light Level Using Camera Output ## 1. Helper Functions These helper functions can largely be ignored, but make sure to run each cell before using the algorithm section (Section 2). ### 1.1 Get Camera Capture Get capture from camera. ``` import matplotlib.pyplot as plt import cv2 ...
github_jupyter
``` %matplotlib inline from matplotlib import style style.use('fivethirtyeight') import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime as dt ``` # Reflect Tables into SQLAlchemy ORM ``` # Python SQL toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap imp...
github_jupyter
## Homework 3 and 4 - Applications Using MRJob ``` # general imports import os import re import sys import time import random import numpy as np import pandas as pd import matplotlib.pyplot as plt # tell matplotlib not to open a new window %matplotlib inline # automatically reload modules %reload_ext autoreload %au...
github_jupyter
# Mega-Meta Functional Connectivity Pipeline _________ ``` CHANGE LOG 08/14 . -MJ changed "dur = rel_events.loc[o,'durTR']" to "dur = rel_events.loc[i,'durTR'] -> 0 to i 05/22/2019 - JMP initial commit 05/28/2019 - JMP added 'rest' TR extration ``` #### Description extracts signal from Power ROI spheres (264) for a g...
github_jupyter
# Debugging Numba problems ## Common problems Numba is a compiler, if there's a problem, it could well be a "compilery" problem, the dynamic interpretation that comes with the Python interpreter is gone! As with any compiler toolchain there's a bit of a learning curve but once the basics are understood it becomes eas...
github_jupyter
# Introduction to Strings --- This notebook covers the topic of strings and their importance in the world of programming. You will learn various methods that will help you manipulate these strings and make useful inferences with them. This notebook assumes that you have already completed the "Introduction to Data Scie...
github_jupyter
# Find UniProt IDs in ChEMBL targets Ultimately, we are interested in getting [activity data from ChEMBl](/chembl-27/query_local_chembl-27.ipynb) we need to account for three components: * The compound being measured * The target the compound binds to * The assay where this measurement took place So, to find all act...
github_jupyter
``` %matplotlib inline from pathlib import Path from pandas import DataFrame,Series from pandas.plotting import scatter_matrix from sklearn.model_selection import train_test_split from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score import pandas as pd from...
github_jupyter
##### Copyright 2020 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
<img src="https://nlp.johnsnowlabs.com/assets/images/logo.png" width="180" height="50" style="float: left;"> ## Deep Learning NER In the following example, we walk-through a LSTM NER model training and prediction. This annotator is implemented on top of TensorFlow. This annotator will take a series of word embedding...
github_jupyter
# Naive Bayes Classifier (Self Made) ### 1. Importing Libraries ``` import numpy as np import matplotlib.pyplot as plt import os import pandas as pd from sklearn.metrics import r2_score from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn import preprocessing from...
github_jupyter
``` import numpy as np import pandas as pd import pickle import time import itertools import matplotlib matplotlib.rcParams.update({'font.size': 17.5}) import matplotlib.pyplot as plt %matplotlib inline import sys import os.path sys.path.append( os.path.abspath(os.path.join( os.path.dirname('..') , os.path.pardir ))...
github_jupyter
``` from keras.applications.vgg19 import VGG19 from keras.models import Model from keras.applications.vgg19 import preprocess_input from keras.preprocessing import image import numpy as np import pickle import os val = [] # Leemos el archivo annotation.txt y guardamos los datos en un vector (por palabras) with open('/h...
github_jupyter
``` import arrow as arw import matplotlib.pyplot as plt import netCDF4 as nc import numpy as np import pandas as pd import xarray as xr from salishsea_tools import places, teos_tools %matplotlib inline hindcast_dataset = xr.open_dataset( 'https://salishsea.eos.ubc.ca/erddap/griddap/ubcSSg3DTracerFields1hV17-0...
github_jupyter
# Dense Sentiment Classifier In this notebook, we build a dense neural net to classify IMDB movie reviews by their sentiment. ``` #load watermark %load_ext watermark %watermark -a 'Gopala KR' -u -d -v -p watermark,numpy,pandas,matplotlib,nltk,sklearn,tensorflow,theano,mxnet,chainer,seaborn,keras,tflearn,bokeh,gensim ...
github_jupyter
``` import time import warnings import logging import tensorflow as tf ``` ### Decorate functions with tf.function Functions can be faster than eager code, especially for graphs with many small ops. But for graphs with a few expensive ops (like convolutions), you may not see much speedup. ``` @tf.function def add(a,...
github_jupyter