text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` import pandas as pd import numpy as np import pickle as pk file_name = '1_min' df = pd.read_csv(file_name + '.csv') df['behavior'] = np.zeros(len(df)).astype(np.int) intention_2_action_delay = 3000 acc_threshold = 1 # 0 for changing to left # 1 for changing to right # 2 for following next_lane_change_time = dict...
github_jupyter
### Testing accuracy of RF classifier for lightly loaded, testing and training with all the rotational speeds ``` from jupyterthemes import get_themes import jupyterthemes as jt from jupyterthemes.stylefx import set_nb_theme set_nb_theme('chesterish') import pandas as pd data_10=pd.read_csv(r'D:\Acads\BTP\Lightly Loa...
github_jupyter
``` %matplotlib inline ``` # Demo Axes Grid Grid of 2x2 images with single or own colorbar. ``` import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid plt.rcParams["mpl_toolkits.legacy_colorbar"] = False def get_demo_image(): import numpy as np from matplotlib.cbook import get_sa...
github_jupyter
### Generator States Let's look at a simple generator function: ``` def gen(s): for c in s: yield c ``` We create an generator object by calling the generator function: ``` g = gen('abc') ``` At this point the generator object is **created**, but we have not actually started running it. To do so, we ca...
github_jupyter
``` %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('.') import utils def f(x): return x * np.cos(np.pi*x) utils.set_fig_size(mpl, (4.5, 2.5)) x = np.arange(-1.0, 2.0, 0.1) fig = plt.figure() sub...
github_jupyter
``` !pip install d2l==0.17.2 # implement several utility functions to facilitate data downloading import hashlib import os import tarfile import zipfile import requests DATA_HUB = dict() DATA_URL = 'http://d2l-data.s3-accelerate.amazonaws.com/' # download function to download a dataset def download(name, cache_dir=os....
github_jupyter
# Filling in Missing Values in Tabular Records You can select Run->Run All Cells from the menu to run all cells in Studio (or Cell->Run All in a SageMaker Notebook Instance). ## Introduction Missing data values are common due to omissions during manual entry or optional input. Simple data imputation such as using th...
github_jupyter
<a href="https://colab.research.google.com/github/mrklees/pgmpy/blob/feature%2Fcausalmodel/examples/Causal_Games.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Causal Games Causal Inference is a new feature for pgmpy, so I wanted to develop a fe...
github_jupyter
# Bounding Box Visualizer ``` try: import cv2 except ImportError: cv2 = None COLORS = [ "#6793be", "#990000", "#00ff00", "#ffbcc9", "#ffb9c7", "#fdc6d1", "#fdc9d3", "#6793be", "#73a4d4", "#9abde0", "#9abde0", "#8fff8f", "#ffcfd8", "#808080", "#808080", "#ffba00", "#6699ff", "#009933", "#1c1c1c", "...
github_jupyter
# Analyze Data Quality with SageMaker Processing Jobs and Spark Typically a machine learning (ML) process consists of few steps. First, gathering data with various ETL jobs, then pre-processing the data, featurizing the dataset by incorporating standard techniques or prior knowledge, and finally training an ML model ...
github_jupyter
<p><font size="6"><b> CASE - Observation data - analysis</b></font></p> > *© 2021, Joris Van den Bossche and Stijn Van Hoey (<mailto:jorisvandenbossche@gmail.com>, <mailto:stijnvanhoey@gmail.com>). Licensed under [CC BY 4.0 Creative Commons](http://creativecommons.org/licenses/by/4.0/)* --- ``` import numpy as np i...
github_jupyter
# Classify Images using Residual Network with 50 layers (ResNet-50) ## Import Turi Create Please follow the repository README instructions to install the Turi Create package. **Note**: Turi Create is currently only compatible with Python 2.7 ``` import turicreate as turi ``` ## Reference the dataset path ``` url =...
github_jupyter
# More To Come. Stay Tuned. !! If there are any suggestions/changes you would like to see in the Kernel please let me know :). Appreciate every ounce of help! **This notebook will always be a work in progress**. Please leave any comments about further improvements to the notebook! Any feedback or constructive criticis...
github_jupyter
### DemIntro02: # Rational Expectations Agricultural Market Model #### Preliminary task: Load required modules ``` from compecon.quad import qnwlogn from compecon.tools import discmoments import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('dark') %matplotlib notebook ``` Generate ...
github_jupyter
# Baseline model classification The purpose of this notebook is to make predictions for all six categories on the given dataset using some set of rules. <br>Let's assume that human labellers have labelled these comments based on the certain kind of words present in the comments. So it is worth exploring the comments t...
github_jupyter
<a href="https://colab.research.google.com/github/hansong0219/Advanced-DeepLearning-Study/blob/master/UNET/UNET_Build.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import numpy as np import os import sys from tensorflow.keras.layers import Inp...
github_jupyter
# Bayesian GAN Bayesian GAN (Saatchi and Wilson, 2017) is a Bayesian formulation of Generative Adversarial Networks (Goodfellow, 2014) where we learn the **distributions** of the generator parameters $\theta_g$ and the discriminator parameters $\theta_d$ instead of optimizing for point estimates. The benefits of the B...
github_jupyter
``` import os os.environ['CUDA_VISIBLE_DEVICES']='0' from fasterai.visualize import * plt.style.use('dark_background') #Adjust render_factor (int) if image doesn't look quite right (max 64 on 11GB GPU). The default here works for most photos. #It literally just is a number multiplied by 16 to get the square render r...
github_jupyter
# AutoRec: Rating Prediction with Autoencoders Although the matrix factorization model achieves decent performance on the rating prediction task, it is essentially a linear model. Thus, such models are not capable of capturing complex nonlinear and intricate relationships that may be predictive of users' preferences. ...
github_jupyter
# Automatic generation of Notebook using PyCropML This notebook implements a crop model. ### Model Cumulttfrom ``` model_cumulttfrom <- function (calendarMoments_t1 = c('Sowing'), calendarCumuls_t1 = c(0.0), cumulTT = 8.0){ #'- Name: CumulTTFrom -Version: 1.0, -Time step: 1 #'- Descripti...
github_jupyter
``` import requests import requests_cache requests_cache.install_cache('calrecycle') import pandas as pd import time URL = 'https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Destination/CountywideSummary' params = {'CountyID': 58, 'ReportFormat': 'XLS'} resp = requests.post(URL, data=params) resp import io def...
github_jupyter
# A tutorial for the whitebox Python package This notebook demonstrates the usage of the **whitebox** Python package for geospatial analysis, which is built on a stand-alone executable command-line program called [WhiteboxTools](https://github.com/jblindsay/whitebox-tools). * Authors: Dr. John Lindsay (https://jblind...
github_jupyter
``` import lifelines import pymc as pm import pyBMA import matplotlib.pyplot as plt import numpy as np from math import log from datetime import datetime import pandas as pd %matplotlib inline ``` The first step in any data analysis is acquiring and munging the data An example data set can be found at: https://jak...
github_jupyter
``` import os import random import shutil from shutil import copyfile import csv root_dir = "ISAFE MAIN DATABASE FOR PUBLIC/" data = "Database/" global_emotion_dir = "emotions_5/" # global_emotion_dir = "emotions/" subject_list = os.path.join(root_dir, data) x = os.listdir(subject_list) csv_file = "ISAFE MAIN DATABASE ...
github_jupyter
``` import numpy as np import pandas as pd import datetime from pandas.tseries.frequencies import to_offset import niftyutils from niftyutils import load_nifty_data import matplotlib.pyplot as plt start_date = datetime.datetime(2005,8,1) end_date = datetime.datetime(2020,9,25) nifty_data = load_nifty_data(start_date...
github_jupyter
# Modeling and Simulation in Python Chapter 3 Copyright 2017 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an as...
github_jupyter
# Tutorial: PyTorch ``` __author__ = "Ignacio Cases" __version__ = "CS224u, Stanford, Spring 2021" ``` ## Contents 1. [Motivation](#Motivation) 1. [Importing PyTorch](#Importing-PyTorch) 1. [Tensors](#Tensors) 1. [Tensor creation](#Tensor-creation) 1. [Operations on tensors](#Operations-on-tensors) 1. [GPU compu...
github_jupyter
# How to create Popups ## Simple popups You can define your popup at the feature creation, but you can also overwrite them afterwards: ``` import folium m = folium.Map([45, 0], zoom_start=4) folium.Marker([45, -30], popup="inline implicit popup").add_to(m) folium.CircleMarker( location=[45, -10], radius=...
github_jupyter
##### Copyright 2018 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of th...
github_jupyter
# CHAPTER 14 - Probabilistic Reasoning over Time ### George Tzanetakis, University of Victoria ## WORKPLAN The section number is based on the 4th edition of the AIMA textbook and is the suggested reading for this week. Each list entry provides just the additional sections. For example the Expected reading include ...
github_jupyter
# <span style="color:green"> Numerical Simulation Laboratory (NSL) </span> ## <span style="color:blue"> Numerical exercises 10</span> ### Exercise 10.1 By adapting your Genetic Algorithm code, developed during the Numerical Exercise 9, write a C++ code to solve the TSP with a **Simulated Annealing** (SA) algorithm. ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Plot style sns.set() %pylab inline pylab.rcParams['figure.figsize'] = (4, 4) # Avoid inaccurate floating values (for inverse matrices in dot product for instance) # See https://stackoverflow.com/questions/24537791/numpy-matrix-inversion-roun...
github_jupyter
<a href="https://colab.research.google.com/github/constantinpape/dl-teaching-resources/blob/main/exercises/classification/5_data_augmentation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Data Augmentation on CIFAR10 In this exercise we will us...
github_jupyter
# KFServing Sample In this notebook, we provide two samples for demonstrating KFServing SDK and YAML versions. ### Setup 1. Your ~/.kube/config should point to a cluster with [KFServing installed](https://github.com/kubeflow/kfserving/blob/master/docs/DEVELOPER_GUIDE.md#deploy-kfserving). 2. Your cluster's Istio Ing...
github_jupyter
``` %autosave 0 ``` # 4. Evaluation Metrics for Classification In the previous session we trained a model for predicting churn. How do we know if it's good? ## 4.1 Evaluation metrics: session overview * Dataset: https://www.kaggle.com/blastchar/telco-customer-churn * https://raw.githubusercontent.com/alexeygrigor...
github_jupyter
# 神经网络的训练 作者:杨岱川 时间:2019年12月 github:https://github.com/DrDavidS/basic_Machine_Learning 开源协议:[MIT](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/LICENSE) 参考文献: - 《深度学习入门》,作者:斋藤康毅; - 《深度学习》,作者:Ian Goodfellow 、Yoshua Bengio、Aaron Courville。 - [Keras overview](https://tensorflow.google.cn/guide/keras...
github_jupyter
# AEJxLPS (Auroral electrojets SECS) > Abstract: Access to the AEBS products, SECS type. This notebook uses code from the previous notebook to build a routine that is flexible to plot either the LC or SECS products - this demonstrates a prototype quicklook routine. ``` %load_ext watermark %watermark -i -v -p virescli...
github_jupyter
``` import torch from torch import nn, optim from torch.utils.data import DataLoader, Dataset from torchvision import datasets, transforms from torchvision.utils import make_grid import matplotlib from matplotlib import pyplot as plt import seaborn as sns from IPython import display import torchsummary as ts import num...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import torch from torch import nn as nn from math import factorial import random import torch.nn.functional as F import numpy as np import seaborn as sn import pandas as pd import os from os.path import join import glob from math import factorial ttype = torch.cud...
github_jupyter
``` import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os import gc import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline pal = sns.color_palette() df_train = pd.read_csv('train.csv') df_train.head() print('Total number of question pairs...
github_jupyter
``` # default_exp models.OmniScaleCNN ``` # OmniScaleCNN > This is an unofficial PyTorch implementation by Ignacio Oguiza - oguiza@gmail.com based on: * Rußwurm, M., & Körner, M. (2019). Self-attention for raw optical satellite time series classification. arXiv preprint arXiv:1910.10536. * Official implementation: h...
github_jupyter
# Natural Language Processing - Unsupervised Topic Modeling with Reddit Posts ###### This project dives into multiple techniques used for NLP and subtopics such as dimensionality reduction, topic modeling, and clustering. 1. [Google BigQuery](#Google-BigQuery) 1. [Exploratory Data Analysis (EDA) & Preprocessing](#Exp...
github_jupyter
``` from keras.layers import Input, Dense, merge from keras.models import Model from keras.layers import Convolution2D, MaxPooling2D, Reshape, BatchNormalization from keras.layers import Activation, Dropout, Flatten, Dense def default_categorical(): img_in = Input(shape=(120, 160, 3), name='img_in') ...
github_jupyter
# Notebook to visualize location data ``` import csv # count the number of Starbucks in DC with open('starbucks.csv') as file: csvinput = csv.reader(file) acc = 0 for record in csvinput: if 'DC' in record[3]: acc += 1 print( acc ) def parse_locations(csv_iterator,state=''): ...
github_jupyter
# 基于Tensorflow的softmax回归 Tensorflow是近年来非常非常流行的一个分布式的机器学习框架,之前一直想学习但是一直被各种各样的事情耽搁着。这学期恰好选了“人工神经网络”这门课,不得不接触这个框架了。最开始依照书上的教程通过Anaconda来配置环境,安装tensorflow。结果tensorflow是安装好了但是用起来是真麻烦。最后卸载了Anaconda在裸机上用`pip install tensorflow`来安装,可是裸机上的python是3.6.3版本的,似乎不支持tensorflow,于是在电脑上安装了另一个版本的python才算解决了这个问题,哎!说多了都是泪。言归正传,现在通过一个softma...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.png)...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import numpy as np import statistics import math from sklearn.linear_model import LinearRegression from scipy.optimize import curve_fit er_cas_100_data = pd.read_csv('proc_er_cas_100.csv') del er_cas_100_data['Unnamed: 0'] er_500_50_0012 = pd.read_csv('proc_er_5...
github_jupyter
``` from pymongo import MongoClient import pandas as pd import datetime client = MongoClient() characters = client.ck2.characters ``` This notebook tries to build a world tree by drawing and edge between every character in the save file with their father and mother. Running this code will generate a network with over ...
github_jupyter
``` # General from os import path from random import randrange from sklearn.model_selection import train_test_split, GridSearchCV #cross validation from sklearn.metrics import confusion_matrix, plot_confusion_matrix, make_scorer from sklearn.metrics import accuracy_score, roc_auc_score, balanced_accuracy_score from s...
github_jupyter
<a href="https://colab.research.google.com/github/ashraj98/rbf-sin-approx/blob/main/Lab2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Lab 2 ### Ashwin Rajgopal Start off by importing numpy for matrix math, random for random ordering of sample...
github_jupyter
To finish, check out: http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1992AJ....104.2213L&amp;data_type=PDF_HIGH&amp;whole_paper=YES&amp;type=PRINTER&amp;filetype=.pdf ``` # Third-party from astropy.io import ascii, fits import astropy.coordinates as coord import astropy.units as u from astropy.constants...
github_jupyter
# TensorFlow Tutorial Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Ke...
github_jupyter
# Project Description Another CV2 tutorial this one from https://pythonprogramming.net/loading-images-python-opencv-tutorial/ ``` #http://tsaith.github.io/record-video-with-python-3-opencv-3-on-osx.html import numpy as np import cv2 cap = cv2.VideoCapture(0) # Capture video from camera # Get the width and height...
github_jupyter
``` import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # import data from the github page of the book data = pd.read_csv('https://raw.githubusercontent.com/Develop-Packt/Exploring-Absenteeism-at-Work/master/data/Absenteeism_at_work.csv', sep=";") # print dimensionality of the...
github_jupyter
## 8.2 创建超链接 超链接指按内容链接,可以从一个文本内容指向文本其他内容或其他文件、网址等。超链接可以分为文本内链接、网页链接以及本地文件链接。LaTeX提供了`hyperref`宏包,可用于生成超链接。在使用时,只需在前导代码中申明宏包即可,即`\usepackage{hyperref}`。 ### 8.2.1 超链接类型 #### 文本内链接 在篇幅较大的文档中,查阅内容会比较繁琐,因此,往往会在目录中使用超链接来进行文本内容的快速高效浏览。可以使用`hyperref`宏包创建文本内超链接。 【**例8-4**】使用`\usepackage{hyperref}`创建一个简单的目录链接文本内容的例子。 ```t...
github_jupyter
``` import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt from sklearn.preprocessing import normalize import seaborn as sns # list of models # Commented few models because they produced very big results which interfere visualization models = [ # 'RandomForestRegressor', # ...
github_jupyter
``` suppressMessages(library("mc2d")) library("scales") library("ggplot2") library("gridExtra") ``` # Risk Study for REPLACE ME See the [ISO 27005 Risk Cookbook](http://www.businessofsecurity.com/docs/FAIR%20-%20ISO_IEC_27005%20Cookbook.pdf) for a more detailed explanation of this template. # Asset Define the asset...
github_jupyter
``` from planaritychecker import PlanarityChecker from numpy.random import random, randint import networkx as nx from planarity.planarity_networkx import planarity %matplotlib inline ``` # Check $K_5$ and $K_{3,3}$ without one edge ``` almost_K5 = PlanarityChecker(5) graph_almost_K5 = nx.Graph() graph_almost_K5.add_n...
github_jupyter
``` from __future__ import print_function import os from netCDF4 import Dataset import requests from lxml import etree import matplotlib.pyplot as plt from owslib.wps import WebProcessingService, ComplexDataInput verify_ssl = True if 'DISABLE_VERIFY_SSL' not in os.environ else False def parseStatus(execute): o =...
github_jupyter
# Research ## Imports ``` import pandas as pd import pandas_datareader as dr from pandas_datareader import data as web import matplotlib.pyplot as plt from matplotlib import style import numpy as np import datetime import mplfinance as mpl import plotly.graph_objects as go import plotly import yfinance as yf ``` ## ...
github_jupyter
[this doc on github](https://github.com/dotnet/interactive/tree/master/samples/notebooks/fsharp/Docs) # Object formatters ## Default formatting behaviors When you return a value or a display a value in a .NET notebook, the default formatting behavior is to try to provide some useful information about the object. If ...
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
# <center>Introduction on Using Python to access GeoNet's GNSS data In this notebook we will learn how to get data from one GNSS(Global Navigation Satellite System) station. By the end of this tutorial you will have make a graph like the one below. <img src="plot.png"> ## &nbsp;Table of contents ### 1. Introduction #...
github_jupyter
``` import keras import tensorflow as tf print(keras.__version__) print(tf.__version__) import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report,confusion_matrix NGRAMS = 2 S...
github_jupyter
# Deploy and perform inference on Model Package from AWS Marketplace This notebook provides you instructions on how to deploy and perform inference on model packages from AWS Marketplace object detection model. This notebook is compatible only with those object detection model packages which this notebook is linked ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt ``` # Parte 1: Iteração de Rayleigh Vimos que podemos iterar um vetor $v$ pela matriz $A$, obtendo a sequência de vetores $A^nv$, por multiplicações sucessivas, e que isso permite encontrar um autovetor. ## Questão 1 Implemente uma função `itera(A,v,tol,debug)`...
github_jupyter
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title"><b>The Knapsack Problem</b></span> by <a xmlns:cc="http://cre...
github_jupyter
# Content: 1. [Definitions](#1.-Definitions) 2. [The root finding problem](#2.-The-root-finding-problem) 3. [Fixed point iteration](#3.-Fixed-point-iteration) >3.1 [The cobweb diagram](#3.1-The-cobweb-diagram) >3.2 [Fixed point iteration theorem](#3.2-Fixed-point-iteration-theorem) >3.3 [The code](#3.3-The-code) ...
github_jupyter
# 第二十三讲 微分方程和$e^{At}$ ## 微分方程$\frac{du}{dt} = Au$ 现有一阶(First-order)微分方程组:$\left\{\begin{matrix} \frac{du_1}{dt} & = & -u_1 & + 2u_2\\ \frac{du_2}{dt} & = & u_1 & -2u_2 \end{matrix}\right.$,其中初始状态 $u(0) = \begin{bmatrix}u_1 \\ u_2 \end{bmatrix} = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$,现在我们需要求解方程的一般形式 $u(t)$。 首先,通过微分方...
github_jupyter
``` !git clone https://github.com/huggingface/transformers.git %cd transformers !pwd !git reset --hard 52f44dd !cp ./examples/token-classification/run_ner.py ../ %cd .. #!wget https://raw.githubusercontent.com/huggingface/transformers/master/examples/token-classification/run_ner.py !wget https://raw.githubusercontent.c...
github_jupyter
# Introducing Scikit-Learn There are several Python libraries which provide solid implementations of a range of machine learning algorithms. One of the best known is [Scikit-Learn](http://scikit-learn.org), a package that provides efficient versions of a large number of common algorithms. Scikit-Learn is characterized...
github_jupyter
``` given = """ Grey BOTTOM BOTTOM 4 Grey BOTTOM BOTTOM 2 Grey RIGHT RIGHT 2 Grey LEFT LEFT 2 BLACK RIGHT RIGHT 2 Grey LEFT LEFT 2 BLACK RIGHT RIGHT 2 Grey EMPTY EMPTY 4 Grey LEFT LEFT 3 BLACK TOP TOP 1 BLACK EMPTY EMPTY 5 Grey TOP TOP 3 Grey RIGHT RIGHT 5 Grey BOTTOM BOTTOM 5 Grey BOTTOM BOTTOM 2 BLACK EMPTY EMPTY 3 B...
github_jupyter
# Demonstration of integrating POI Points to OSM road network 1. Use anyway you like to get the sample [POI data](https://assets.onemap.sg/shp/supermarkets.zip) consisting of supermarkets from [OneMap SG](https://www.onemap.sg/). 2. Use [OSMnx](https://osmnx.readthedocs.io/en/stable/index.html) to download the pedestri...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') # from google.colab import drive # drive.mount('/content/drive') !pwd path = '/content/drive/MyDrive/Research/AAAI/cifar_new/k_001/sixth_run1_' import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib...
github_jupyter
``` # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range # The folder when dumped big 3D array has been stored from...
github_jupyter
## Fitting a diagonal covariance Gaussian mixture model to text data In a previous assignment, we explored k-means clustering for a high-dimensional Wikipedia dataset. We can also model this data with a mixture of Gaussians, though with increasing dimension we run into two important issues associated with using a full...
github_jupyter
# Text Data Explanation Benchmarking: Emotion Multiclass Classification This notebook demonstrates how to use the benchmark utility to benchmark the performance of an explainer for text data. In this demo, we showcase explanation performance for partition explainer on an Emotion Multiclass Classification model. The me...
github_jupyter
# Unsupervised outliers detection (event detection) ``` import drama as drm import numpy as np import matplotlib.pylab as plt from matplotlib import gridspec from drama.outlier_finder import grid_run_drama from keras.datasets import mnist %matplotlib inline n_try = 5 # MNIST dataset (x_train, y_train), (x_test, y_...
github_jupyter
``` # Import conventions we'll be using here. See Part 1 import matplotlib # matplotlib.use('nbagg') import matplotlib.pyplot as plt import numpy as np ``` # Limits, Legends, and Layouts In this section, we'll focus on what happens around the edges of the axes: Ticks, ticklabels, limits, layouts, and legends. # Lim...
github_jupyter
## QE methods and QE_utils In this tutorial, we will explore various methods needed to handle Quantum Espresso (QE) calculations - to run them, prepare input, and extract output. All that will be done with the help of the **QE_methods** and **QE_utils** modules, which contains the following functions: **QE_methods** ...
github_jupyter
# Naive-Bayes Classifier ``` #Baseline SVM with PCA classifier import sklearn import numpy as np import sklearn.datasets as skd import ast from sklearn.feature_extraction import DictVectorizer from sklearn import linear_model from sklearn import naive_bayes from sklearn.metrics import precision_recall_fscore_support f...
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
# Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning....
github_jupyter
# ACA-Py & ACC-Py Basic Template ## Copy this template into the root folder of your notebook workspace to get started ### Imports ``` from aries_cloudcontroller import AriesAgentController import os from termcolor import colored ``` ### Initialise the Agent Controller ``` api_key = os.getenv("ACAPY_ADMIN_API_KEY")...
github_jupyter
# 作业3:设计并训练KNN算法对图片进行分类。 ## example1: ``` import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data k=7 test_num=int(input('请输入需要测试的数据数量:')) #加载TFRecord训练集的数据 reader = tf.TFRecordReader() filename_queue = tf.train.string_input_producer(["/home/srhyme/ML project/DS/train.t...
github_jupyter
# Continuous Delivery Explained > "An introduction to the devops practice of CI/CD." - toc: false - branch: master - badges: true - comments: true - categories: [devops, continuous-delivery] - image: images/copied_from_nb/img/devops/feedback-cycle.png ![DevOps Feedback Cycle](img/devops/feedback-cycle.png) > *I wrote...
github_jupyter
# Content-based recommender using Deep Structured Semantic Model An example of how to build a Deep Structured Semantic Model (DSSM) for incorporating complex content-based features into a recommender system. See [Learning Deep Structured Semantic Models for Web Search using Clickthrough Data](https://www.microsoft.co...
github_jupyter
# Plots for logistic regression, consistent vs inconsistent noiseless AT, increasing epsilon ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.patches import dotenv import pandas as pd import mlflow import plotly import plotly.graph_objects as go import plotly.express as px import plotly.subplot...
github_jupyter
# RNN - LSTM - Toxic Comments A corpus of manually labeled comments - classifying each comment by its type of toxicity is available on Kaggle. We will aim to do a binary classification of whether a comment is toxic or not. Approach: - Learning Embedding with the Task - LSTM - BiLSTM ``` import numpy as np import pan...
github_jupyter
## Mask Adaptivity Detection Using YOLO Mask became an essential accessory post COVID-19. Most of the countries are making face masks mandatory to avail services like transport, fuel and any sort of outside activity. It is become utmost necessary to keep track of the adaptivity of the crowd. This notebook contains imp...
github_jupyter
## Precision-Recall Curves in Multiclass For multiclass classification, we have 2 options: - determine a PR curve for each class. - determine the overall PR curve as the micro-average of all classes Let's see how to do both. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.da...
github_jupyter
## A motivating example: harmonic oscillator ### created by Yuying Liu, 11/02/2019 ``` # imports import os import sys import torch import numpy as np import scipy as sp from scipy import integrate from tqdm.notebook import tqdm import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.m...
github_jupyter
Decoding with ANOVA + SVM: face vs house in the Haxby dataset =============================================================== This example does a simple but efficient decoding on the Haxby dataset: using a feature selection, followed by an SVM. ``` import warnings warnings.filterwarnings('ignore') import matplotlib...
github_jupyter
# Assignment 3: Question Answering Welcome to this week's assignment of course 4. In this you will explore question answering. You will implement the "Text to Text Transfer from Transformers" (better known as T5). Since you implemented transformers from scratch last week you will now be able to use them. <img src = ...
github_jupyter
``` #default_exp dataset_torch ``` # dataset_torch > Module to load the slates dataset into a Pytorch Dataset and Dataloaders with default train/valid test splits. ``` #export import torch import recsys_slates_dataset.data_helper as data_helper from torch.utils.data import Dataset, DataLoader import torch import jso...
github_jupyter
# Collaborative filtering on the MovieLense Dataset ###### This notebook is based on part of Chapter 9 of [BigQuery: The Definitive Guide](https://www.oreilly.com/library/view/google-bigquery-the/9781492044451/ "http://shop.oreilly.com/product/0636920207399.do") by Lakshmanan and Tigani. ### MovieLens dataset To illus...
github_jupyter
``` import neuroglancer # Use this in IPython to allow external viewing # neuroglancer.set_server_bind_address(bind_address='192.168.158.128', # bind_port=80) from nuggt.utils import ngutils viewer = neuroglancer.Viewer() viewer import numpy as np import zarr import os # working_d...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import warnings warnings.filterwarnings('ignore') df1 = pd.read_csv('monday.csv', sep = ";") df2 = pd.read_csv('tuesday.csv', sep = ";") df3 = pd.read_csv('wednesday.csv', sep = ";") df4 = pd.read_csv('thursday.csv', sep = ...
github_jupyter
# Example 1: How to Generate Synthetic Data (MarginalSynthesizer) In this notebook we show you how to create a simple synthetic dataset. # Environment ## Library Imports ``` import numpy as np import pandas as pd from pathlib import Path import os import sys ``` ## Jupyter-specific Imports and Settings ``` # set p...
github_jupyter
# Simplifying Codebases Param's just a Python library, and so anything you can do with Param you can do "manually". So, why use Param? The most immediate benefit to using Param is that it allows you to greatly simplify your codebases, making them much more clear, readable, and maintainable, while simultaneously provi...
github_jupyter