text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Bayesian Temporal Matrix Factorization **Published**: October 8, 2019 **Revised**: October 8, 2020 **Author**: Xinyu Chen [[**GitHub homepage**](https://github.com/xinychen)] **Download**: This Jupyter notebook is at our GitHub repository. If you want to evaluate the code, please download the notebook from the [*...
github_jupyter
# AWS SageMaker ### Resources #### AWS - The Open Guide to Amazon Web Services: EC2 Basics _(just this one short section!)_ https://github.com/open-guides/og-aws#ec2-basics - AWS in Plain English https://www.expeditedssl.com/aws-in-plain-english - Amazon SageMaker » Create an Amazon SageMaker Notebook Instance https:...
github_jupyter
``` import json import pandas import numpy import os from collections import defaultdict root = '../DataExport_2022-01-12' with open(os.path.join(root, 'result.json'), encoding='utf8') as handle: data = json.load(handle) chats_list = data['chats']['list'] saved_messages_chats = [chat for chat in chats_list if chat[...
github_jupyter
This file loads results from a main model run, and produces the figures used in the paper. ``` %load_ext autoreload %autoreload 2 from epimodel import EpidemiologicalParameters, DefaultModel, preprocess_data from epimodel.pymc3_models.base_model import produce_CIs, add_cms_to_plot import numpy as np import pymc3 as p...
github_jupyter
<div class="contentcontainer med left" style="margin-left: -50px;"> <dl class="dl-horizontal"> <dt>Title</dt> <dd> Distribution Element</dd> <dt>Dependencies</dt> <dd>Bokeh, SciPy</dd> <dt>Backends</dt> <dd><a href='./Distribution.ipynb'>Bokeh</a></dd> <dd><a href='../matplotlib/Distribution.ipynb'>Matplo...
github_jupyter
# Realization of Non-Recursive Filters *This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## Introduction Computing the output $y[k...
github_jupyter
# Matching when including the contralateral connections ## Preliminaries ``` from pkg.utils import set_warnings set_warnings() import datetime import time import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.optimize import linear_sum_assignment import seaborn as sns from numba import...
github_jupyter
``` import wave import numpy as np from scipy.ndimage import uniform_filter, maximum_filter from IPython.display import display, Audio import matplotlib.pyplot as plt %matplotlib inline ``` ## preparing implementation of STFT and ISTFT ``` def stft(x): window = np.hamming(1024) return np.array([np.fft.fft(win...
github_jupyter
# GDELT initial findings from articles in January 2020 Author: Mike Pesavento Email: mike@peztek.com Started: 2020-06-29 Last change: 2020-07-08 This report isolates and mines the [GDELT collection of news articles](https://blog.gdeltproject.org/a-new-contextual-dataset-for-exploring-climate-change-narratives-...
github_jupyter
## Graph Mode Static Quantization ``` import functools from tqdm import tqdm import torch from datasets import load_dataset from transformers import AutoTokenizer, AutoModelForQuestionAnswering from nn_pruning.inference_model_patcher import optimize_model from nn_pruning.modules.quantization import prepare_static,...
github_jupyter
<a href="https://colab.research.google.com/github/Pranjalya/fake-news-twitter/blob/master/Fake_News_Countering.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Using Spark Installing dependencies (JAVA, Hadoop and Spark) ``` !apt-get install open...
github_jupyter
# Anyscale Academy - Training on Ray and the Ray Ecosystem © 2019-2020, Anyscale. All Rights Reserved ![Anyscale Academy](images/AnyscaleAcademyLogo.png) [Video introduction 🎥](https://youtu.be/Zy_AuL7xLpk) &nbsp; (Look for these throughout the notebooks.) Welcome to the [Anyscale Academy](https://anyscale.com/ac...
github_jupyter
# 📃 Solution for Exercise M6.04 The aim of this exercise is to: * verify if a GBDT tends to overfit if the number of estimators is not appropriate as previously seen for AdaBoost; * use the early-stopping strategy to avoid adding unnecessary trees, to get the best statistical performances. we will use the Calif...
github_jupyter
# Live Data The [HoloMap](../reference/containers/bokeh/HoloMap.ipynb) is a core HoloViews data structure that allows easy exploration of parameter spaces. The essence of a HoloMap is that it contains a collection of [Elements](http://holoviews.org/reference/index.html) (e.g. ``Image``s and ``Curve``s) that you can ea...
github_jupyter
# Result figures for *Enhanced spatio-temporal electric load forecasts with less data using active deep learning* --- ## Overview 1. Import and test results 2. Numeric results 3. Space and time selection 4. Budget vs. accuracy 5. Training and validation losses against unqueried candidates 6. Validation losses against...
github_jupyter
``` import os import pandas as pd import numpy as np class PreProc: def __init__(self, input_dir, pred_energy): self.input_dir = input_dir self.pred_energy = pred_energy def set_train_test_files(self, train_file, test_file): self.train_file = train_file self.test_file =...
github_jupyter
## NBA Career Prediction Experiment ``` experiment_label = 'xgb02a' ``` ### Aim: * To improve on xgb01, by using imblearn * To improve on 0.71259 on Kaggle. ### Findings: Retain -ve values, apply SMOTE & under sampling pipeline, search on roc_auc. Results train, val auc: * SMOTE, under = 0.50, 0.75 : 0.73, 0.70 * ...
github_jupyter
``` #|hide #|skip ! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab #|default_exp layers #|default_cls_lvl 3 #|export from __future__ import annotations from fastai.imports import * from fastai.torch_imports import * from fastai.torch_core import * from torch.nn.utils import weight_norm, spectral_...
github_jupyter
##### Copyright 2018 The TF-Agents 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 a...
github_jupyter
# Title **Exercise: A.2 - MSE for varying β1 values** # Description The goal here is to produce a plot like the one given below. <img src="../img/image2.png" style="width: 500px;"> # Instructions: We want to find the model that fit best the data. To do so we are going to 1) Fix $\beta_0 = 2.2$, 2) Change $\bet...
github_jupyter
# **Save this file as studentid1_studentid2_lab2.ipynb**, please check this suffix when you upload your lab, especially when you have multiple copy's in the same folder! (Your student-id is the number shown on your student card.) E.g. if you work with 3 people, the notebook should be named: 12301230_3434343_1238938934...
github_jupyter
<a href="https://colab.research.google.com/github/akash-kaul/ecosys/blob/master/SyntheaGraphViz.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Code-Installations ``` !pip install python-igraph !pip install plotly !pip install plotly.express !pip...
github_jupyter
<a href="https://colab.research.google.com/github/7ossam81/EvoloPy/blob/master/EvoloPy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <h1>EvoloPy</h1> An open source nature-inspired optimization toolbox for global optimization in Python The EvoloP...
github_jupyter
# *Relaxation and Decoherence* This notebook gives examples for how to use the ``ignis.characterization.coherence`` module for measuring $T_1$ and $T_2$. ``` import numpy as np import matplotlib.pyplot as plt import qiskit from qiskit.providers.aer.noise.errors.standard_errors import thermal_relaxation_error from ...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Implementing-SQL-Operations:-Aggregates-(Part-1)" data-toc-modified-id="Implementing-SQL-Operations:-Aggregates-(Part-1)-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Implementing SQL Operations: Aggreg...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. # 06. Logging APIs This notebook showcase various ways to use the Azure Machine Learning service run logging APIs, and view the results in the Azure portal. ## Prerequisites Make sure you go through the [00. Installation and Co...
github_jupyter
<img src="portfolio_gothic.png" /> If someone says “gothic” to you, do you think of lush rolling countryside or a sunny day? Chances are you don’t. Most people - myself included - associate that word with things that are dark, mysterious and even frightening. Maybe you picture ornate stone architecture of a castle ...
github_jupyter
``` import pandas as pd # f(x, y) bisa di-override di tiap cell kalo males scroll2 ke atas # dy/dx = f(x, y) def f(x, y): return x+y-1 ``` *Rumus dari [PPT Tutorial](https://docs.google.com/presentation/d/1f7vb8ypHqQl0LHZLHbgmTuwkD_2UBhpH/edit)* # Euler ``` def Euler(f, xi, yi, h, x_target, data=False): xii ...
github_jupyter
``` import numpy as np import pandas as pd import spotipy from spotipy.oauth2 import SpotifyClientCredentials import keyring ``` ## Setup Spotipy credentials and query wrapper ``` client_credentials_manager = SpotifyClientCredentials(client_id=keyring.get_password('spotify', 'cid'), ...
github_jupyter
``` %pylab inline data_dir='/usr/local/share/galsim/COSMOS_25.2_training_sample' stamp_size=64 pixel_scale=0.03 k_scale=2. * np.pi / (pixel_scale * stamp_size) import galsim # First step is to find an HST PSF that will work for all images, # we are taking a random sample of 1000 psfs, take the largest one, # and dilate...
github_jupyter
``` import math import numpy as np import pandas as pd from cvxopt import matrix, solvers import matplotlib.pyplot as plt from sklearn.svm import SVC # Q2 X = np.array([[1, 0], [0, 1], [0, -1], [-1, 0], [0, 2], [0, -2], [-2, 0]]) Y = np.array([-1, -1, -1, 1, 1, 1, 1]) row, col = X.shape z = np.zeros(X.shape) z[:, 0] = ...
github_jupyter
# Run network model ``` %load_ext autoreload %autoreload 2 #from keras.layers import merge from src.models.catdata import * from src.models.catmodel import * from src.data.utils import get_tile_prefix from src.models.metrics_img import auc_roc #import rasterio.plot as rioplot import matplotlib import matplotlib.pyplo...
github_jupyter
## 1. Requirements ``` import numpy as np import json import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as Data import torchvision.utils from torchvision import models import torchvision.datasets as dsets import torchvision.transforms as transforms import matplotlib.pyplot as plt...
github_jupyter
## Use SageMaker Experiments to track and compare multiple trials In this notebook, we aim to show how data-scientists can use SageMaker Experiments to keep track and organize their machine learning experimentation. ### The Machine Learning problem We will be predicting house values for the California districts. The...
github_jupyter
Словари в Python - неупорядоченные коллекции произвольных объектов с доступом по ключу. Их иногда ещё называют ассоциативными массивами или хеш-таблицами. ``` # Создание словарей dict_1 = {'a': 1, 'b': 2, 'c': 3} dict_2 = dict(a=1, b=2, c=3) dict_3 = dict.fromkeys(['a', 'b', 'c'], 100) # С помощью генератора словаря d...
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.cluster import KMeans from sklearn.svm import SVC from sklearn import metrics from mlxtend.plotting import plot_decision_regions from sklearn import preprocessing from skl...
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline import numpy as np import torch import random import sys from copy import deepcopy import matplotlib.pyplot as plt device = 'cuda' if torch.cuda.is_available() else 'cpu' from ex_biology import p sys.path.append('preprocessing') import data import neural_networ...
github_jupyter
``` import pickle import statistics import matplotlib import pandas as pd import seaborn as sns import matplotlib.pyplot as plt matplotlib.rcParams['font.sans-serif'] = "Arial" matplotlib.rcParams['font.family'] = "sans-serif" sns.set(font_scale=1.75) ``` # Variables ``` seed = 13 dataframes_names = ['fs1', 'fs2', '...
github_jupyter
``` import networkx as nx import matplotlib.pyplot as plt import numpy as np import random import time def pps(n,ND) : P=n*100/ND PP= "{:.2f}".format(P) print("\r",end="") print("processes",PP,"% completed: ",end="") i=50*n/ND a=50-int(i) b=(int(i)+1)*"🟩" c=(a-1)*"⬜️" print(b,end=...
github_jupyter
``` from database.strategy import Strategy from database.sec import SEC from database.market import Market from transformer.date_transformer import DateTransformer from transformer.column_transformer import ColumnTransformer from transformer.model_transformer import ModelTransformer from transformer.product_transformer...
github_jupyter
# Explain *Anything* Like I'm Five: ## A Model for Open Domain Long Form Question Answering --- ### Table of Contents 1. [**Introduction**](#intro) a. [Preliminaries](#prelims) b. [Note on Data and Biases](#reddit_biases) 2. [**Task and Data Description**](#task_description) 3. [**Sparse Retrieval:...
github_jupyter
``` #Resource #https://github.com/ardendertat/Applied-Deep-Learning-with-Keras/blob/master/notebooks/Part%202%20-%20Case%20Studies.ipynb from __future__ import print_function %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import pandas as pd import numpy as np import ...
github_jupyter
## Questionário 24 (Q24) Orientações: - Registre suas respostas no questionário de mesmo nome no SIGAA. - O tempo de registro das respostas no questionário será de 10 minutos. Portanto, resolva primeiro as questões e depois registre-as. - Haverá apenas 1 (uma) tentativa de resposta. - Submeta seu arquivo-fonte (util...
github_jupyter
<a href="https://colab.research.google.com/github/tjwei/NCTU_Private_DeepLearning/blob/master/Secret_Sharing.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Additive Secret Sharing Most of the material taken from https://github.com/udacity/privat...
github_jupyter
``` #Importing Libraries import pandas as pd from datetime import datetime import matplotlib.pyplot as plt from yahoofinancials import YahooFinancials ticker_details = pd.read_excel("Ticker List.xlsx") ticker = ticker_details['Ticker'].to_list() names = ticker_details['Description'].to_list() #Preparing Date Range end_...
github_jupyter
``` from keras.models import Sequential from keras.optimizers import SGD from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, AveragePooling2D, ZeroPadding2D, Dropout, Flatten, merge, Reshape, Activation from keras.layers.normalization import BatchNormalization from keras.models import Model from keras ...
github_jupyter
``` %matplotlib inline ``` PyTorch 모듈 프로파일링 하기 --------------------------- **Author:** `Suraj Subramanian <https://github.com/suraj813>`_ **번역:** `이재복 <http://github.com/zzaebok>`_ PyTorch는 코드 내의 다양한 Pytorch 연산에 대한 시간과 메모리 비용을 파악하는 데 유용한 프로파일러(profiler) API를 포함하고 있습니다. 프로파일러는 코드에 쉽게 통합될 수 있으며, 프로파일링 결과는 표로 출력되거나 JS...
github_jupyter
``` %config InlineBackend.figure_formats = ['svg'] import geopandas as gpd from math import sqrt from lxml import etree from shapely.geometry import box from shapely.affinity import scale, translate from shapely.geometry.polygon import LinearRing, Polygon from svg.path import parse_path, Line import matplotlib.pyplot a...
github_jupyter
# Receiver Operating Characteristic (ROC) Curve on Iris In this notebook we find an example of Receiver Operating Characteristic (ROC) Curves. An ROC curve represents the discriminative ability of a binary classification in a graphical plot. In an ROC curve the true positive rate of the binary classification on the Y...
github_jupyter
+ This notebook is part of lecture 23 *Differential equations and exponent A* in the OCW MIT course 18.06 by Prof Gilbert Strang [1] + Created by me, Dr Juan H Klopper + Head of Acute Care Surgery + Groote Schuur Hospital + University Cape Town + <a href="mailto:juan.klopper@uct.ac.za">Email me with you...
github_jupyter
``` #hide #default_exp read ``` # nbprocess.read - Reading a notebook, and initial bootstrapping for notebook exporting ``` #export from datetime import datetime from fastcore.imports import * from fastcore.foundation import * from fastcore.utils import * from fastcore.test import * from fastcore.script import * from...
github_jupyter
# Introduction to multi-channel images > A short introduction to RGB and remote sensing images. - toc: true - badges: true - comments: true - categories: [images] ``` #hide from fastai.vision.all import * path = Path(".") (path / "2020-09-16").mkdir(exist_ok=True) ``` # About In the previous [post](https://kai-tu...
github_jupyter
``` consumer_key = '*******' consumer_secret = '********' access_token = '******' access_token_secret = '*******' """Twitter retweet bot""" """ Before running this make sure your twitter developer account has read and write acess """ import tweepy # This is a Twitter API helper library. import time auth = tweepy.OAu...
github_jupyter
# Exercises 4 From now on we will not specify which packages to import. It's up to you to decide/understand what is needed. It's a safe bet to systematically import numpy and matplotlib.pyplot ## Part1 - Find a picture on the web, import it and plot it (usually the link to the image ends with the format of the image ...
github_jupyter
# Introduction to TensorFlow ## Computation graphs In the first semester we used the NumPy-based `mlp` Python package to illustrate the concepts involved in automatically propagating gradients through multiple-layer neural network models. We also looked at how to use these calculated derivatives to do gradient-descen...
github_jupyter
### Import Modules ``` import pandas as pd import numpy as np eps = np.finfo(float).eps from sklearn import decomposition from sklearn import preprocessing import seaborn as sns import matplotlib.pyplot as plt from typing import NoReturn, Callable ``` ### Read Dataset ``` df = pd.read_csv('datasets/preprocessed.c...
github_jupyter
``` import numpy as np from pathlib import Path import pandas as pd import os import matplotlib.pyplot as plt import seaborn as sns from scipy import signal, fftpack import time import datetime import h5py # import torch # import torch.nn as nn # import torch.nn.functional as F # import torch.optim as optim from skle...
github_jupyter
# Test Stree with AdaBoost and Bagging with different configurations # Setup Uncomment the next cell if STree is not already installed ``` # # Google Colab setup # #!pip install git+https://github.com/doctorado-ml/stree !pip install pandas import time import os import random import warnings import pandas as pd import...
github_jupyter
# 1D domain wall **Author**: Marijan Beg **Date**: 26/02/2016 This notebook can be downloaded from the github repository, found [here](https://github.com/computationalmodelling/fidimag/blob/master/doc/ipynb/1d_domain_wall.ipynb). ### Problem specification The domain wall profile is computed in a one-dimenaional do...
github_jupyter
``` import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import Pipeline from sklearn.metrics import mean_squared_error from sklearn.model_selection import GridSearchCV from sklearn.linear_model import Lasso f...
github_jupyter
``` import functools import numpy as np import tensorflow as tf LABEL_COLUMN = 'Close' BATCH_SIZE = 32 WINDOW_SIZE = 24 EPOCHS = 1 train_file_path = 'data/all_data.csv' #train_file_path = 'data/reduced_data.csv' def get_dataset(file_path, **kwargs): dataset = tf.data.experimental.make_csv_dataset( file_path, ...
github_jupyter
<a href="https://colab.research.google.com/github/PyDataOsaka/handson_pytorch/blob/master/resnet18_tpu.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Pytorch hands-on (Resnet18) Code of Resnet18 was adapted from [here](https://github.com/pytorch...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing, linear_model, datasets from sklearn.metrics import r2_score, mean_squared_error ``` # `scikit-learn`: Machine Learning in Python `scikit-learn` es una librería que tiene muchas funcionalidades y modelos relac...
github_jupyter
# Ordinary Least Squares ## Course (very short) recap This lab consists in implementing the **Ordinary Least Squares** (OLS) algorithm, which is **a linear regression with a least-squares penalty**. Given a training set $ D = \left\{ \left(x^{(i)}, y^{(i)}\right), x^{(i)} \in \mathcal{X}, y^{(i)} \in \mathcal{Y}, i \in...
github_jupyter
<font size="6" color="#0047b2" face="verdana"> <B>Notebook 00: Unplugged Programming</B></font> -------------------------------- _**Computational Thinking and progrmming without a computer?**_ YES! It turns out one does not even need a computer to engange into Computational Thinking and to build actual algorithms. ...
github_jupyter
``` import re def stemRule(word, rule, replacement=""): """ Get word to stem. The rule that is a regular expression. And replacement is what we add to the word after removing the rule matched. """ word = str.strip(str.lower(word)) rule = str.lower(rule) replacement = str.lower(repla...
github_jupyter
# Genetic Algorithms for Trees ## Crossover ### Subtree exchange crossover After two parent individuals have been selected, a subtree is randomly chosen in each of the parents. Next the two subtrees are exchanged resulting in two trees each of which is a different combination of the two parents. In the binary express...
github_jupyter
# Feature Engineering ``` import pandas as pd import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt from datetime import datetime from datetime import timedelta ``` ## Create New Features ### MEMBERS dataset ``` MEMBERS = pd.read_csv("../data/processed/MEMBERS_TRAIN.csv", parse_dates=Tru...
github_jupyter
**Copyright 2021 Antoine SIMOULIN.** Licensed under the Apache License, Version 2.0 (the "License"); 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 Un...
github_jupyter
# Arrays There are several kinds of sequences in Python. A [list](lists) is one. However, the sequence type that we will use most in the class, is the array. The `numpy` package, abbreviated `np` in programs, provides Python programmers with convenient and powerful functions for creating and manipulating arrays. `...
github_jupyter
Deep Learning ============= Assignment 4 ------------ Previously in `2_fullyconnected.ipynb` and `3_regularization.ipynb`, we trained fully connected networks to classify [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) characters. The goal of this assignment is make the neural network convol...
github_jupyter
<a href="https://colab.research.google.com/github/tyoc213/fastai_xla_extensions/blob/explorations1/explore_nbs/collab_example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` VERSION = "20200707" #"nightly" #"20200515" @param ["1.5" , "20200325"...
github_jupyter
(divide_and_conquer)= # Divide and Conquer ``` {index} Divide and Conquer ``` *Divide and Conquer* algorithms are one of the major groups in computer problem-solving. The main idea is to split the more complicated tasks into independent subproblems that can be composed in the solution. The term is closely related to [r...
github_jupyter
# SLU02 Command Line & Text Editor - Exercise Notebook *** ``` # For evaluation purposes, please import this package: import hashlib ``` ### Exercise 1: Where is home? <img src="./assets/tortoise_home.png" width="400"/> Imagine that you have a Linux user called `tortoise`, what is the correct path for this user's *...
github_jupyter
<hr> # PREDICTING THE STOCK MARKET WITH WATSON ## Part 2: Introduction In this Jupyter Notebook you'll learn step-by-step how to use the Watson Machine Learning API that was automatically generated when the previously created WS Modeler flow was deployed. You will also learn how to download files from IBM Cloud Obje...
github_jupyter
# Testing Proportions II: K Proportions Source: https://web.williams.edu/Mathematics/sjmiller/public_html/BrownClasses/162/Handouts/StatsTests04.pdf ``` import numpy as np import pandas as pd from scipy.stats import chi2 #create toy data math = np.random.binomial(1, 0.58, 600) coding = np.random.binomial(1, 0.51, 800...
github_jupyter
Lambda School Data Science *Unit 2, Sprint 3, Module 2* --- # Wrangle ML datasets 🍌 In today's lesson, we’ll work with a dataset of [3 Million Instacart Orders, Open Sourced](https://tech.instacart.com/3-million-instacart-orders-open-sourced-d40d29ead6f2)! ### Setup ``` # Download data import requests def down...
github_jupyter
``` %pip install datasets transformers onnx onnxruntime ``` We use the small distilled BERT model from Microsoft as our pre-trained model which we fine-tune on the emotion classification task. See https://huggingface.co/microsoft/xtremedistil-l6-h256-uncased for details. Inspiration for dataset adjustment from https:...
github_jupyter
``` from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np ``` # Solution: Basic synthesis of single qubit gates ## 1 Show that the Hadamard gate can be written in the following two forms $$H = \frac{X+Z}{\sqrt{2}} \equiv \exp\left(i \frac{\pi}{2} \, \frac{X+Z}{\sqrt{2}}\right...
github_jupyter
``` import json import os from glob import glob import re import numpy as np import spacy # from scispacy.umls_linking import UmlsEntityLinker NER_tagger = spacy.load('en_ner_jnlpba_md') # linker = UmlsEntityLinker(resolve_abbreviations=True) # NER_tagger.add_pipe(linker) from transformers import * # load bert tokenize...
github_jupyter
``` from dateutil.parser import parse import pandas as pd import numpy as np import pingouin as pg import matplotlib.pyplot as plt import plotly.express as px import datetime import seaborn as sns df= pd.read_csv('Monthly_Performance.csv', parse_dates =['mth_reprt_prd'], index_col = 'mth_reprt_prd') df.head(10) df.dtyp...
github_jupyter
# KubeFlow Pipeline Using TFX OSS Components In this notebook, we will demo: * Defining a KubeFlow pipeline with Python DSL * Submiting it to Pipelines System * Customize a step in the pipeline We will use a pipeline that includes some TFX OSS components such as [TFDV](https://github.com/tensorflow/data-validation)...
github_jupyter
# Week 5 - How to ethically scrape the web *© 2020 Colin Conrad* Welcome to Week 5 of INFO 6270! Last week we covered ways of working with files on your local computer using the csv and PyPDF libraries, and was considered our final module on basic Python programming. There will be no new programming concepts from this...
github_jupyter
##### Copyright 2021 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
# Guide to the ParameterNode The `ParameterNode` is a container that can group parameters, and also other `ParameterNodes`. For those familiar with object-oriented programming, the `ParameterNode` can be viewed as the object, and the `Parameters` as the attributes. One distinction with is that ParameterNodes can ...
github_jupyter
**Note**: Click on "*Kernel*" > "*Restart Kernel and Clear All Outputs*" in [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) *before* reading this notebook to reset its output. If you cannot run this file on your machine, you may want to open it [in the cloud <img height="12" style="display: inline-block" src...
github_jupyter
``` # Load image # Get their 3 image stars most brightness # Get the distances: a->b, a->c, b->c # Load the catalog # Get pairs in the distance ab+-0.1 and save them as S1 # Get pairs in the distance ac+-0.1 and save them as S2 # For each star in both S1 and S2 check the other two stars angular distance # it should be ...
github_jupyter
***Javier Sáez Maldonado*** ***José Antonio Álvarez Ocete*** # Métodos Avanzados en Aprendizaje Automático # Algoritmo de eliminación de variables Este algoritmo es utilizado para realizar inferencia en redes. Supongamos que tenemos la factorización de una distribución conjunta $$ P(\mathbf{X}) = P(X_1, X_2, \dot...
github_jupyter
# Clojupyter demo: Jupyter Notebook-only features This notebook demonstrates some features of Clojupyter for Jupyter Notebook. Please note that it uses <font color=red>**Notebook-only functionality**</font> and does not render correctly using *Jupyter Lab* which uses renderers instead of allowing direct access to exte...
github_jupyter
# Refactor: Wine Quality Analysis In this exercise, you'll refactor code that analyzes a wine quality dataset taken from the UCI Machine Learning Repository [here](https://archive.ics.uci.edu/ml/datasets/wine+quality). Each row contains data on a wine sample, including several physicochemical properties gathered from t...
github_jupyter
# 3. Predicting Bike Sharing In this project, we'll be building our project! ``` %matplotlib inline %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` ## Loading and preparing the data A critical step in worki...
github_jupyter
# Main imports ``` import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import os import sys import re import pandas as pd import numpy as np import _pickle as cPickle import matplotlib.pyplot as plt import plotly import plotly.graph_objs as go from matplotlib.patches import C...
github_jupyter
![NetCDF Logo](https://www.unidata.ucar.edu/images/logos/netcdf-400x400.png "NetCDF Logo") # NetCDF and CF: The Basics --- ## Overview This notebook will introduce you to the basics of Climate and Forecasting (CF) metadata for netCDF data files. Along with an introduction to netCDF, we will introduce the CF data mode...
github_jupyter
## 🖼 Working with image data in `Meerkat` *What is `Meerkat`?* `Meerkat` makes it easier for ML practitioners to interact with high-dimensional, multi-modal data. It provides simple abstractions for data inspection, model evaluation and model training supported by efficient and robust IO under the hood. **Colab Run...
github_jupyter
## Generate hierarchical clustering artwork and haplotype groups - using whole genome phasing - based upon Ag1000g phase 1 paper ``` %run setup.ipynb %matplotlib inline import hapclust from scipy.cluster.hierarchy import _convert_to_double from scipy.spatial import distance from scipy.cluster.hierarchy import _hierar...
github_jupyter
# Forecast Scheduling - WellsGroup Classes `WellsGroup` class in the one on top of the others. You can specify a group of `Well` instances that, as seen before, each of them can be groups of scenarios and periods. `WellsGroup` has different functionality when evaluating it. Each `Well` part of this have n scenarios ...
github_jupyter
``` from openpyxl import load_workbook from bs4 import BeautifulSoup from selenium import webdriver from time import sleep import csv from random import randint import json, io from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select ...
github_jupyter
# Approximate q-learning In this notebook you will teach a __tensorflow__ neural network to do Q-learning. __Frameworks__ - we'll accept this homework in any deep learning framework. This particular notebook was designed for tensorflow, but you will find it easy to adapt it to almost any python-based deep learning fr...
github_jupyter
``` from fastai.vision import * ``` ## Data One-time download, uncomment the next cells to get the data. ``` #path = Config().data_path() #! wget https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/summer2winter_yosemite.zip -P {path} #! unzip -q -n {path}/summer2winter_yosemite.zip -d {path} #! rm {pat...
github_jupyter
# Entity Match Categorizer Although entity matching in SDK offers greater flexibility, its utility is constrained by the lack of an easy way to group matches by pattern. As experience tells, strict reliance on the confidence score may be misleading; some matches have low confidence scores but in fact high-quality, whi...
github_jupyter