text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
<h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from *Introduction to TensorFlow* to label images of English letters! The data you are using, <a href="http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html">notMNIST</a>, consi...
github_jupyter
``` #export from fastai2.data.all import * from fastai2.text.core import * from nbdev.showdoc import * #default_exp text.models.awdlstm #default_cls_lvl 3 ``` # AWD-LSTM > AWD LSTM from [Smerity et al.](https://arxiv.org/pdf/1708.02182.pdf) ## Basic NLP modules On top of the pytorch or the fastai [`layers`](/layers...
github_jupyter
``` import sys, os sys.path.append('..') from Data.TimeSeries import * from ETF.AAA import * from Data import factors import Quandl import pandas as pd import matplotlib import cvxopt as opt from cvxopt import blas, solvers %matplotlib inline sector_tickers = [ 'GOOG/NYSEARCA_XLB', 'GOOG/NYS...
github_jupyter
``` import numpy as np, pandas as pd, matplotlib.pyplot as plt from scipy.stats.stats import pearsonr from scipy.stats.stats import spearmanr from scipy.optimize import minimize from BTC_Alpha_func import * from tqdm import tqdm import os %matplotlib inline class signal_search(object): def __init__(self, data,...
github_jupyter
# SBTi-Finance Tool for Temperature Scoring & Portfolio Coverage ***Do you want to understand what drives the temperature score of your portfolio to make better engagement and investment decisions?*** ![ExampleGraphs](https://github.com/OFBDABV/SBTi/raw/master/examples/images/JN_HeroImage.jpg) This notebook provides ...
github_jupyter
``` import json import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import os from pprint import pprint from scipy.stats import ttest_ind num_evals = 5 evals = {} task_dir = '/Users/ethanperez/research/ParlAI/parlai/mturk/core/run_data/live/context_evaluator_' task_setup = [ # ## Persuading Humans (D...
github_jupyter
<!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> *This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/Pyth...
github_jupyter
``` """Optimal prioritizing of your tasks, in the sense of minimizing redundant memory footprint. Idea is to take the longest graph path with most dependancies so that you don't mentally backtrack so often. From the optimal paradigm of cpu worker allotment. Simply make a dictionary where each key is a task name and the...
github_jupyter
# Cart-pole Balancing Model with Amazon SageMaker on SageMaker Managed Spot Training The example here is almost the same as [Cart-pole Balancing Model with Amazon SageMaker](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/reinforcement_learning/rl_cartpole_coach/rl_cartpole_coach_gymEnv.ipynb). This ...
github_jupyter
# Window Splitters in Sktime In this notebook we describe the window splitters included in the [`sktime.forecasting.model_selection`](https://github.com/alan-turing-institute/sktime/blob/main/sktime/forecasting/model_selection/_split.py) module. These splitters can be combined with `ForecastingGridSearchCV` for model ...
github_jupyter
# Classify structured data using Keras Preprocessing Layers ## Learning Objectives * Load a CSV file using [Pandas](https://pandas.pydata.org/). * Build an input pipeline to batch and shuffle the rows using [tf.data](https://www.tensorflow.org/guide/datasets). * Map from columns in the CSV to features used to train ...
github_jupyter
### Imports ``` import keras import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data import math ``` ### Data Examination ``` mnist_data = input_data.read_data_sets('MNIST_data/', one_hot = True) input_batch, gt_batch = mnist_data.train.next_batch(10) x, y = inpu...
github_jupyter
# Missing value imputation: MeanMedianImputer The MeanMedianImputer() replaces missing data by the mean or median value of the variable. It works only with numerical variables. We can pass a list of variables to be imputed. Alternatively, the MeanMedianImputer() will automatically select all variables of type numeric...
github_jupyter
``` import sys sys.path.append("../libs/basic_units/") import numpy as np import librosa import python_speech_features from basic_units import cm, inch import matplotlib.pyplot as plt from scipy.signal.windows import hann, hamming import tensorflow as tf import matplotlib.pyplot as plt k = 2 max_iterations = 100 n_mfcc...
github_jupyter
<img src='https://certificate.tpq.io/quantsdev_banner_color.png' width="250px" align="right"> # Reinforcement Learning **Adding Noise to the Time Series Data** &copy; Dr Yves J Hilpisch | The Python Quants GmbH [quants@dev Discord Server](https://discord.gg/uJPtp9Awaj) | [@quants_dev](https://twitter.com/quants_dev...
github_jupyter
<a href="https://colab.research.google.com/github/jan-1995/Trajectory_Ctrl_LQR/blob/main/TRAJECTORY_CONTROL_QC.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **IMPORTING ALL THE IMPORTANT LIBRARIES** ``` from math import cos, sin import numpy as n...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import cv2 import sys from collections import defaultdict from time import time from os import makedirs from os.path import join, isdir from glob import glob from keras.callbacks import TensorBoard sys.path.append('scripts') from model_helpers import * from data_...
github_jupyter
# Ray RLlib - Extra Application Example - FrozenLake-v0 © 2019-2020, Anyscale. All Rights Reserved ![Anyscale Academy](../../../images/AnyscaleAcademy_Logo_clearbanner_141x100.png) This example uses [RLlib](https://ray.readthedocs.io/en/latest/rllib.html) to train a policy with the `FrozenLake-v0` environment ([gym....
github_jupyter
## Importing Libraries ``` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from scipy import stats from plotly import express as px import matplotlib.pyplot as plt import seaborn as sns import datetime as dt today = dt.datetime.today() ``` ## Importing the Tables ``` df...
github_jupyter
<a href="https://colab.research.google.com/github/FranciscoLuna/curso_ICE_STM32CUBEIDE/blob/master/IMDB_y_RNR_entrenamiento%2C_evaluacion_y_descarga.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Análisis de sentimientos con Redes Neuronales Recu...
github_jupyter
# Explaining Tree Models with Interventional Feature Perturbation Tree SHAP <div class="alert alert-info"> To enable SHAP support, you may need to run ```bash pip install alibi[shap] ``` </div> ## Introduction This example shows how to apply interventional Tree SHAP to compute shap values exactly for an `xgboo...
github_jupyter
``` import numpy as np import tensorflow as tf %matplotlib inline import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) plt.gray() plt.imshow(mnist.train.images[0].reshape(28, 28)) plt.show() print(mnist.train.labels[0])...
github_jupyter
# Exploratory data analysis for hourly time series ``` import pandas as pd import numpy as np from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.seasonal import STL from matplotlib import pyplot as plt, rc_context, rc plt.style.use('seaborn-deep') ``` We start by reading in the data. ...
github_jupyter
# Phase 3. Statistical Information ## Contents - [Configuration](#Configuration) - [Imports](#Imports) - [Variables](#Variables) - [Support functions](#Support-functions) - [Botscore distribution](#Botscore-distribution) - [Daily total traffic](#Daily-total-traffic) - [Tweet type distributions per botscore autho...
github_jupyter
# Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [i...
github_jupyter
<a href="https://colab.research.google.com/github/wtsyang/UserIntentPrediction/blob/BERT/BERT/LSTM-multiPrediction_addPenality_32_lrschedule.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from google.colab import drive # import drive from googl...
github_jupyter
# Introduction to ImageJ Ops [ImageJ Ops](https://imagej.net/ImageJ_Ops) is a library for N-dimensional image processing. The primary design goals of Ops are: 1. __Ease of use.__ Ops provides a wealth of easy-to-use image processing operations ("ops"). 2. __Reusability.__ Ops extends Java's mantra of "[write once, r...
github_jupyter
# Identifying safe loans with decision trees ``` import pandas as pd import numpy as np from sklearn import tree from IPython.display import Image import pydotplus %matplotlib inline loans = pd.read_csv('lending-club-data.csv') loans.head() loans.columns ``` ## Features for the classification algorithm ``` # safe_lo...
github_jupyter
Before you begin, execute this cell to import numpy and packages from the D-Wave Ocean suite, and all necessary functions for the gate-model framework you are going to use, whether that is the Forest SDK or Qiskit. In the case of Forest SDK, it also starts the qvm and quilc servers. ``` %run -i "assignment_helper.py" ...
github_jupyter
Based on: https://arxiv.org/abs/1508.06576 ``` !ln -s "/content/drive/MyDrive/meu/imgs" ./data # from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim from PIL import Image import torchvision.transforms as transforms import torchvision.models as models from torchvision.u...
github_jupyter
``` from azureml.train.estimator import Estimator from azureml.core import Workspace, Experiment from azureml.core.compute import ComputeTarget, AmlCompute from azureml.widgets import RunDetails from azureml.train.hyperdrive import * from azureml.train.automl import AutoMLConfig from azureml.train.automl.constants impo...
github_jupyter
<a href="https://colab.research.google.com/github/napsternxg/ipython-notebooks/blob/master/Keras_Elmo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` ! pip install nltk import tensorflow as tf import tensorflow_hub as hub import tensorflow.keras...
github_jupyter
# SUSA CX Kaggle Capstone Project ## Part 3: Hyperparameter Tuning, Decision Trees, Ensemble Learning ### Table Of Contents * [Introduction](#section1) * [Hyperparameters](#section2) * [GridSearch](#section2i) * [Decision Trees](#section3) * [Random Forest](#section4) * [Ensemble Learning](#section5) * [Conclusion]...
github_jupyter
# Single cell data analysis using Scanpy * __Notebook version__: `v0.0.5.2` * __Created by:__ `Imperial BRC Genomics Facility` * __Maintained by:__ `Imperial BRC Genomics Facility` * __Docker image:__ `imperialgenomicsfacility/scanpy-notebook-image:release-v0.0.4` * __Github repository:__ [imperial-genomics-facility/s...
github_jupyter
# Description Generates the figure for top cell types for a specified LV (in Settings section below). # Modules loading ``` %load_ext autoreload %autoreload 2 import re from pathlib import Path import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from data.recount2 import LVAnalysis from utils...
github_jupyter
``` %matplotlib inline ``` 3D interpolation ============= Interpolation of a three-dimensional regular grid. Trivariate ----------- The [trivariate](https://pangeo-pyinterp.readthedocs.io/en/latest/generated/pyinterp.trivariate.html#pyinterp.trivariate) interpolation allows obtaining values at arbitrary points in a...
github_jupyter
# Meshed AC-DC example This example has a 3-node AC network coupled via AC-DC converters to a 3-node DC network. There is also a single point-to-point DC using the Link component. The data files for this example are in the examples folder of the github repository: <https://github.com/PyPSA/PyPSA>. ``` import pypsa i...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
#### Based on https://github.com/bkj/basenet/tree/master/examples ``` import sys import json import argparse import numpy as np from time import time from PIL import Image import torch from torch import nn from torch.nn import functional as F from torch.autograd import Variable from torchvision import transforms, da...
github_jupyter
<a href="https://colab.research.google.com/github/JiaminJIAN/20MA573/blob/master/src/Stochastic_approximation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## **Stochastic Approximation** Let $D = \{X_{i}: i \in \mathbb{N}\}$ be a data set of iid...
github_jupyter
# Generating statistics for subset of Wikidata Example Dataset wikidata subset: https://drive.google.com/drive/u/1/folders/1KjNwV5M2G3JzCrPgqk_TSx8wTE49O2Sx \ Example Dataset statistics: https://drive.google.com/drive/u/0/folders/1_4Mxd0MAo0l9aR3aInv0YMTJrtneh7HW ## Example Invocation command papermill Knowledg...
github_jupyter
Before you begin, execute this cell to import numpy and packages from the D-Wave Ocean suite, and all necessary functions the gate-model framework you are going to use, whether that is the Forest SDK or Qiskit. In the case of Forest SDK, it also starts the qvm and quilc servers. ``` %run -i "assignment_helper.py" ``` ...
github_jupyter
``` import os from pathlib import Path import numpy as np import scipy.io import matplotlib.pyplot as plt # set Human SAO directory here SAO_BASE_DIR_NAME = 'F:/Ionosonde/SAO_pick' SAO_BASE_DIR = Path(SAO_BASE_DIR_NAME) # set SBF directory here SBF_BASE_DIR_NAME = 'F:/Ionosonde/SBF_mat' SBF_BASE_DIR = Path(SBF_BASE_DI...
github_jupyter
``` import cv2 import numpy as np import os,sys from time import time as t from __future__ import absolute_import from __future__ import division from __future__ import print_function from firebase import firebase import firebase_admin from firebase_admin import credentials from firebase_admin import db import argpars...
github_jupyter
# Singly LInked List ``` class Node: def __init__(self,data): self.val = data self.next = None class LinkedList: def __init__(self): self.head = None def insertStart(self,data): newNode = Node(data) newNode.next = self.head self.head = newNode ...
github_jupyter
# Introduction This notebook was used in order to create the **"Early-fusion + Odom correction" row in TABLE II**. Note that a lot of code is copy-pasted across notebooks, so you may find some functionality implemented here that is not used, for instance the network is implemented in a way to support late-fusion, whi...
github_jupyter
# 8章 二値分類 ``` # 必要ライブラリの宣言 %matplotlib inline import numpy as np import matplotlib.pyplot as plt # PDF出力用 from IPython.display import set_matplotlib_formats set_matplotlib_formats('png', 'pdf') ``` ### シグモイド関数のグラフ 図8-4 ``` xx = np.linspace(-6, 6, 500) yy = 1 / (np.exp(-xx) + 1) plt.figure(figsize=(6,6)) plt.ylim(-...
github_jupyter
# Word Embeddings **Learning Objectives** You will learn: 1. How to use Embedding layer 1. How to create a classification model 1. Compile and train the model 1. How to retrieve the trained word embeddings, save them to disk and visualize it. ## Introduction This notebook contains an introduction to word embeddin...
github_jupyter
# <center> Word Tokenization Techniques in NLP ## What is word tokenization? Tokenization is breaking the raw text into small chunks. Tokenization breaks the raw text into words, sentences called **tokens**. These tokens help in understanding the context or developing the model for the NLP. The tokenization helps in ...
github_jupyter
``` import os,sys sys.path.append('/home/tanmay/JHU/project/deep-mediation/manuscript/code/deep-mediation/src') import tensorflow as tf import importlib import auxiliaryfunctions import statsmodels.api as sm import statsmodels.formula.api as smf import seaborn as sns import numpy as np from scipy.stats import zscore,no...
github_jupyter
# TensorFlow Scan Examples #### By [Rob DiPietro](http://rdipietro.github.io) – Version 0.32 – April 28, 2016. ## Post or Jupyter Notebook? This work is available both as a [post](http://rdipietro.github.io/tensorflow-scan-examples/) and as a [Jupyter notebook](https://github.com/rdipietro/jupyter-notebooks/tree/mast...
github_jupyter
<font color=gray>Oracle Cloud Infrastructure Data Science Sample Notebook Copyright (c) 2021 Oracle, Inc. All rights reserved. <br> Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. </font> # Deploying a Simple Sklearn Linear Regression Model In this tutorial we ...
github_jupyter
# Project: Investigate a Dataset (TMDb Movies Dataset) ## Table of Contents <ul> <li><a href="#intro">Introduction</a></li> <li><a href="#wrangling">Data Wrangling</a></li> <li><a href="#eda">Exploratory Data Analysis</a></li> <li><a href="#conclusions">Conclusions</a></li> <a id='intro'></a> ## Introduction This d...
github_jupyter
# SetUp ``` import os import numpy as np import matplotlib import matplotlib.pyplot as plt import tensorflow as tf %matplotlib inline def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) np.random.seed(seed) plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 plt...
github_jupyter
# Tabular data handling This module defines the main class to handle tabular data in the fastai library: [`TabularDataset`](/tabular.data.html#TabularDataset). As always, there is also a helper function to quickly get your data. To allow you to easily create a [`Learner`](/basic_train.html#Learner) for your data, it ...
github_jupyter
``` import torch from torch import nn from txtfeeder import TXTFeeder import math RANDOM_SEED = 42 # Num of bits for the SDR input for character # The ASCII input has 7 bits. To have sparse representation (< 2%) # We set 512 as the number of bits and 10 as number of ON bits NUM_SDR_BIT = 512 NUM_SDR_ON_BIT = 10 INPUT_N...
github_jupyter
## **Step 1: Please select a GPU runtime** ![](https://i.imgur.com/RUIixAQ.png) ![image.png](https://i.imgur.com/zKc74pP.png) ## **Step 2: Install TVM by running the following block.** We have pre-compiled a tvm build for your convenience. ![](https://i.imgur.com/k9U5WCB.png) ``` # Let's first install TVM! # This ...
github_jupyter
## Summary - *hidden_size = 162*. - *num_heads = 9*. - *dropout = 0*. - N=16. - Add node and edge features (node features as 81-dim. embedding in `hidden_size`-dim space). - Edgeconv: embed x and edge to half their size and keep row x only. - Embed attention with `model_size == 63` and add `output_dim` attribute to at...
github_jupyter
# Useful Methods * [apply() method](#apply_method) * [apply() with a function](#apply_function) * [apply() with a lambda expression](#apply_lambda) * [apply() on multiple columns](#apply_multiple) * [numpy Vectorize()](#vectorize) * [describe()](#describe) * [sort_values()](#sort) * [corr()](#corr) * [idxmin and idxma...
github_jupyter
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/8.Generic_Classifier.ipynb) # Generic Clas...
github_jupyter
# Распознавание речи Мы все больше ждем, что компьютеры смогут использовать ИИ для понимания произнесенных и напечатанных команд на естественном языке человека. Например, можно внедрить систему автоматизации дома, которая позволит контролировать устройства в вашем доме с помощью голосовых команд, например «включи св...
github_jupyter
# Balances <div class="alert alert-danger"> <strong>Warning!</strong> This notebook contains a fake portfolio <i>(automatically generated)</i> and <b>does not</b> represent my own, it merely serves as an example. </div> ``` import pytz import socket from datetime import datetime, timezone now = datetime.now().asti...
github_jupyter
## Module loading ``` import h5py import matplotlib.pyplot as plt import numpy as np import tensorflow.keras as keras import tensorflow as tf import os import nibabel as nib import random import re from sklearn.model_selection import train_test_split from natsort import natsorted from collections import Counter from t...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import string import gzip import json import re import numpy as np import pandas as pd import scipy from scipy import interpolate import glob import sklearn.cluster import sklearn.feature_extraction import sklearn.feature_extraction.text import sklearn.metrics im...
github_jupyter
``` import json import tensorflow as tf import csv import random import numpy as np from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.utils import to_categorical from tensorflow.keras import regularizers embedding_dim = 1...
github_jupyter
``` import numpy as np from mlxtend.plotting import plot_decision_regions import matplotlib.pyplot as plt from sklearn import datasets from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.base import ClassifierMixin xx, yy = np.meshgrid(np.linspace(-3, 3, 50), np.lin...
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
# LSTM - Test Model Si eseguono i test a partire da un modello LSTM. ## Caricamento del dataframe ``` import torch from torch import nn from torch.utils.tensorboard import SummaryWriter from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler import torch.nn as nn import numpy as np import pandas as ...
github_jupyter
``` import pydeck as pdk import pandas as pd # 2014 locations of car accidents in the UK UK_ACCIDENTS_DATA = ('https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv') pd.read_csv(UK_ACCIDENTS_DATA).head() # Define a layer to display on a map layer = pdk.Layer( 'Hexa...
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
<img src="../img/saturn_logo.png" width="300" /> # Parallel Inference We are ready to scale up our inference task! <img src="https://media.giphy.com/media/4H5nOUqX7FywOGpCF7/giphy.gif" alt="scaleup" style="width: 200px;"/> **Dataset:** [Stanford Dogs](http://vision.stanford.edu/aditya86/ImageNetDogs/main.html) *...
github_jupyter
# Figure 8. Compare vaccine strains to estimated and observed closest strains to the future Observed distance to natural H3N2 populations one year into the future for each vaccine strain (green) and the observed (blue) and estimated (orange) closest strains to the future at the corresponding timepoints. Vaccine strain...
github_jupyter
# 初始化环境 ``` from IPython.display import display, Math from sympy import * init_printing() from helper import comparator_factory, comparator_eval_factory, comparator_method_factory x,y,z = symbols('x y z') comparator = comparator_factory('使用{}前:','使用后:') method_comparator = comparator_method_factory('调用{}前:','调用后:')...
github_jupyter
*** # 数据清洗: > # 对占中新闻进行数据清洗 *** *** 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communication.com ``` # 使用with open读取每一行数据 with open("/Users/chengjun/github/cjc2016/data/occupycentral/zz-hk-2014-10.rtf") as f: news = f.readlines() # 查看总共有多少行 len(news) # 注意:标题和版面之间存在一个空行!所以title是block的第4个元素。 for i in r...
github_jupyter
<img src="../figures/HeaDS_logo_large_withTitle.png" width="300"> <img src="../figures/tsunami_logo.PNG" width="600"> [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Center-for-Health-Data-Science/PythonTsunami/blob/intro/Data_structures/Arrays_num...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import pandas as pd training_set = pd.read_csv('train.csv') test_set = pd.read_csv('test.csv') training_set.head() test_set.head() x_train = training_set.iloc[:, 1:].values y_train = training_set.iloc[:, 0:1].values x_test = test_set.iloc[:, :].values x_train = x_t...
github_jupyter
# MNIST classification example with TensorFlow ## Install packages on Google Cloud Datalab (locally use conda env) ### Select in the Python3 Kernel: In the menu bar the of 'Kernel', select **python3** ### Install needed packages copy the command below in a Google Cloud Datalab cell **!pip install tensorflow==2....
github_jupyter
``` # import the project1-prepareData notebook: !pip install ipynb from ipynb.fs.full.data_analysis import * import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) berlinDf_final_linear = berlinDf_select.copy() # berlinDf_final_linear.drop(['newlyConst', 'balcony','...
github_jupyter
``` from six.moves import cPickle as pickle import numpy as np import tensorflow as tf from IPython.display import display, Image import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy import stats from utils import show_graph %matplotlib inline ``` ## Load Data ``` with open('SVHN_data.pickle', 'rb') ...
github_jupyter
``` import numpy as np import cntk_unet import simulation %matplotlib inline import helper import cntk as C from cntk.learners import learning_rate_schedule, UnitType # Generate some random images input_images, target_masks = simulation.generate_random_data(192, 192, count=3) print(input_images.shape, target_masks.sh...
github_jupyter
# Sequence prediction analysis The Sequence prediction analysis tests are done to analyze several different elements of different algorithms. ### Networks to Evaluate - Fully Connected Networks - LSTM Networks - Other RNNs (bidirectionals, GRUs, ...) - TCN (Temporal Convolutional Networks) - MANNs (different on...
github_jupyter
##### Copyright 2018 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
# 🔄 Online learning for time series prediction 🔄 In [1], the authors develop an online learning method to predict time-series generated by and ARMA (autoregressive moving average) model. They develop an effective online learning algorithm based on an **improper learning** approach which consists to use an AR model...
github_jupyter
# LSTM implementation for the centralized model ``` # Dataset - 2019 # Imputation tech - KNN for both air pollutants and meteorological data # Evaluation metric - MAE while training and SMAPE metric for validating test data # Negative values where not replaced import os import datetime import matplotlib.pyplot as plt...
github_jupyter
# 第2章 感知机 二分类模型 $f(x) = sign(w*x + b)$ 损失函数 $L(w, b) = -\Sigma{y_{i}(w*x_{i} + b)}$ --- #### 算法 随即梯度下降法 Stochastic Gradient Descent 随机抽取一个误分类点使其梯度下降。 $w = w + \eta y_{i}x_{i}$ $b = b + \eta y_{i}$ 当实例点被误分类,即位于分离超平面的错误侧,则调整w, b的值,使分离超平面向该无分类点的一侧移动,直至误分类点被正确分类 拿出iris数据集中两个分类的数据和[sepal length,sepal width]作为特征 `...
github_jupyter
# Single Qubit Gates In the previous section we looked at all the possible states a qubit could be in. We saw that qubits could be represented by 2D vectors, and that their states are limited to the form: $$ |q\rangle = \cos{(\tfrac{\theta}{2})}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle $$ Where $\theta$ ...
github_jupyter
# Machine Learning Workflow Automation using the Step Functions Data Science SDK >__NOTE:__ This Notebook uses the _Python 3 (Data Science)_ Kernel. --- ## 1. Pre-Requisites ### Load the Step Functions Data Science Python Library ``` %%capture !pip install stepfunctions==2.2.0 sagemaker==2.49.1 ``` ### Simulate B...
github_jupyter
## Coronary Heart Disease Prediction ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns # Sklearn from sklearn.preprocessing import normalize from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection imp...
github_jupyter
# Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. **Notation**: - Superscript $[l]$ denotes an object of the $l...
github_jupyter
# Getting Started This section gives an overview over parsing, simulating and filtering models using **pydsge**. It also explains how to load and process data from an estimation. ``` # only necessary if you run this in a jupyter notebook %matplotlib inline import matplotlib.pyplot as plt import numpy as np ``` ## P...
github_jupyter
``` import keras from keras.models import Sequential, Model, load_model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Lambda from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Conv1D, MaxPooling1D, LSTM, ConvLSTM2D, GRU, CuDNNLSTM, CuDNNGRU, BatchNormalization, LocallyConnected2D, ...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np mse_d = pd.read_csv('C:/Users/peter/Desktop/volatility-forecasting/results/test_res/mse_values_daily.csv') mse_d.set_index(mse_d.iloc[:, 0], inplace = True) mse_d = mse_d.iloc[:, 1:] mse_td = pd.read_csv('C:/Users/peter/De...
github_jupyter
``` %matplotlib inline ``` `파이토치(PyTorch) 기본 익히기 <intro.html>`_ || `빠른 시작 <quickstart_tutorial.html>`_ || `텐서(Tensor) <tensorqs_tutorial.html>`_ || `Dataset과 Dataloader <data_tutorial.html>`_ || `변형(Transform) <transforms_tutorial.html>`_ || `신경망 모델 구성하기 <buildmodel_tutorial.html>`_ || **Autograd** || `최적화(Optimizati...
github_jupyter
``` ## Import numpy and visualization packages import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import datasets # import data boston = datasets.load_boston() X_boston = boston['data'] X_boston = (X_boston - X_boston.mean(0))/(X_boston.std(0)) y_boston = boston['target'] y_boston =...
github_jupyter
# Archiving Discourse This Jupyter notebook contains the Python code I use to auto-archive my Discourse instances using the API. You can read more about this in [my question](https://meta.discourse.org/t/a-basic-discourse-archival-tool/62614) on [DiscourseMeta](https://meta.discourse.org/). If you're reading the HTML...
github_jupyter
# CUSTOMER CHURN ANALYSIS ## Business Project Analysis - Final _By **Grégory PINCHINAT**_ --- The leading telecom company has a massive market share but one big problem: several rivals that are constantly trying to steal customers. Because this company has been the market leader for so many years, there are not si...
github_jupyter
``` import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import sys SOURCE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__name__))) sys.path.insert(0, SOURCE_DIR) import malaya_speech import malaya_speech.config from malaya_speech.train.model import fastspeech2 import tensorflow as tf import numpy as np config...
github_jupyter
# Borderline-SMOTE - Creates new samples by interpolation between samples of the minority class and their closest neighbours. - It does not use all observations from the minority class as templates, unllike SMOTE. - It selects those observations (from the minority) for which, most of their neighbours belong to a diff...
github_jupyter
# Temporal-Difference Methods In this notebook, you will write your own implementations of many Temporal-Difference (TD) methods. While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. --- ### Part 0: Explore CliffWalkingEnv We begin by importing the necess...
github_jupyter
``` ! pip install -Uq pandas fastparquet import pandas as pd DATA_PATH = '../data' ! ls {DATA_PATH} df = pd.read_parquet(f'{DATA_PATH}/data.parquet', engine='fastparquet') df ``` --- Now we want to cleanup timestamp columns to `datetime`: ``` df[df['timestamp'].isna()].count() df[df['first_order_ts'].isna()].count() ...
github_jupyter