code
stringlengths
2.5k
150k
kind
stringclasses
1 value
## Portfolio Exercise: Starbucks <br> <img src="https://opj.ca/wp-content/uploads/2018/02/New-Starbucks-Logo-1200x969.jpg" width="200" height="200"> <br> <br> #### Background Information The dataset you will be provided in this portfolio exercise was originally used as a take-home assignment provided by Starbucks f...
github_jupyter
[Index](Index.ipynb) - [Next](Widget List.ipynb) # Simple Widget Introduction ## What are widgets? Widgets are eventful python objects that have a representation in the browser, often as a control like a slider, textbox, etc. ## What can they be used for? You can use widgets to build **interactive GUIs** for your ...
github_jupyter
``` import numpy as np from pandas import Series, DataFrame import pandas as pd from sklearn import preprocessing, tree from sklearn.metrics import accuracy_score # from sklearn.model_selection import train_test_split, KFold from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import KFold d...
github_jupyter
``` import warnings import collections import os import pandas as pd # manage data import pickle as pk # load and save python objects import numpy as np # matrix operations import matplotlib.pyplot as plt import unidecode # Deal with codifications import regex # use regular expresions from email.header import Header, d...
github_jupyter
``` from sklearn import * from sklearn import datasets from sklearn import linear_model from sklearn import metrics from sklearn import cross_validation from sklearn import tree from sklearn import neighbors from sklearn import svm from sklearn import ensemble from sklearn import cluster from sklearn import model_selec...
github_jupyter
# Matplotlib Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell, web application servers, and six graphical user interface toolkits. ...
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
# `Практикум по программированию на языке Python` <br> ## `Занятие 2: Пользовательские и встроенные функции, итераторы и генераторы` <br><br> ### `Мурат Апишев (mel-lain@yandex.ru)` #### `Москва, 2021` ### `Функции range и enumerate` ``` r = range(2, 10, 3) print(type(r)) for e in r: print(e, end=' ') for ind...
github_jupyter
# Visualizing and Analyzing Jigsaw ``` import pandas as pd import re import numpy as np ``` In the previous section, we explored how to generate topics from a textual dataset using LDA. But how can this be used as an application? Therefore, in this section, we will look into the possible ways to read the topics as ...
github_jupyter
``` %pylab inline import re from pathlib import Path import pandas as pd import seaborn as sns datdir = Path('data') figdir = Path('plots') figdir.mkdir(exist_ok=True) mpl.rcParams.update({'figure.figsize': (2.5,1.75), 'figure.dpi': 300, 'axes.spines.right': False, 'axes.spines.top': False, ...
github_jupyter
``` #uncomment this to install the library # !pip3 install pygeohash ``` ## Libraries and auxiliary functions ``` #load the libraries from time import sleep from kafka import KafkaConsumer import datetime as dt import pygeohash as pgh #fuctions to check the location based on the geo hash (precision =5) #function to c...
github_jupyter
<a href="https://www.kaggle.com/aaroha33/text-summarization-attention-mechanism?scriptVersionId=85928705" target="_blank"><img align="left" alt="Kaggle" title="Open in Kaggle" src="https://kaggle.com/static/images/open-in-kaggle.svg"></a> <font size="+5" color=Green > <b> <center><u> <br>Text Summarization <b...
github_jupyter
``` %matplotlib inline ``` # Brainstorm CTF phantom tutorial dataset Here we compute the evoked from raw for the Brainstorm CTF phantom tutorial dataset. For comparison, see [1]_ and: http://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtf References ---------- .. [1] Tadel F, Baillet S, Mosher JC, Pantazis...
github_jupyter
# Ensemble Learning ## Initial Imports ``` import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd from pathlib import Path from collections import Counter from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import confusion_matrix from imblearn.metrics import cla...
github_jupyter
<a href="https://colab.research.google.com/github/olgOk/XanaduTraining/blob/master/Xanadu3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` pip install pennylane pip install torch pip install tensorflow pip install sklearn pip install pennylane-q...
github_jupyter
# Regular Expressions Regular expressions are text-matching patterns described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. Regular expressions can include a variety of rules, from finding repetition, to text-matching, and much more. As you advance in ...
github_jupyter
# PTN Template This notebook serves as a template for single dataset PTN experiments It can be run on its own by setting STANDALONE to True (do a find for "STANDALONE" to see where) But it is intended to be executed as part of a *papermill.py script. See any of the experimentes with a papermill script to get sta...
github_jupyter
# Recommender Systems 2018/19 ### Practice 4 - Similarity with Cython ### Cython is a superset of Python, allowing you to use C-like operations and import C code. Cython files (.pyx) are compiled and support static typing. ``` import time import numpy as np ``` ### Let's implement something simple ``` def isPrime...
github_jupyter
# 15 PDEs: Solution with Time Stepping ## Heat Equation The **heat equation** can be derived from Fourier's law and energy conservation (see the [lecture notes on the heat equation (PDF)](https://github.com/ASU-CompMethodsPhysics-PHY494/PHY494-resources/blob/master/15_PDEs/15_PDEs_LectureNotes_HeatEquation.pdf)) $$ \...
github_jupyter
# Build a sklearn Pipeline for a to ML contest submission In the ML_coruse_train notebook we at first analyzed the housing dataset to gain statistical insights and then e.g. features added new, replaced missing values and scaled the colums using pandas dataset methods. In the following we will use sklearn [Pipelines](...
github_jupyter
# Running the Direct Fidelity Estimation (DFE) algorithm This example walks through the steps of running the direct fidelity estimation (DFE) algorithm as described in these two papers: * Direct Fidelity Estimation from Few Pauli Measurements (https://arxiv.org/abs/1104.4695) * Practical characterization of quantum ...
github_jupyter
# Gujarati with CLTK See how you can analyse your Gujarati texts with <b>CLTK</b> ! <br> Let's begin by adding the `USER_PATH`.. ``` import os USER_PATH = os.path.expanduser('~') ``` In order to be able to download Gujarati texts from CLTK's Github repo, we will require an importer. ``` from cltk.corpus.utils.impor...
github_jupyter
# Project 3: Implement SLAM --- ## Project Overview In this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world! SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research...
github_jupyter
### In this notebook we investigate a designed simple Inception network on PDU data ``` %reload_ext autoreload %autoreload 2 %matplotlib inline ``` ### Importing the libraries ``` import torch import torch.nn as nn import torch.utils.data as Data from torch.autograd import Function, Variable from torch.optim impor...
github_jupyter
### Import all needed package ``` import os import ast import numpy as np import pandas as pd from keras import optimizers from keras.models import Sequential from keras.layers import Dense, Activation, LSTM, Dropout from keras.utils import to_categorical from keras.datasets import mnist from sklearn.preprocessing imp...
github_jupyter
<a href="https://colab.research.google.com/github/tjido/woodgreen/blob/master/Woodgreen_Data_Science_%26_Python_Nov_2021_Week_3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <h1>Welcome to the Woodgreen Data Science & Python Program by Fireside An...
github_jupyter
<h1>CREAZIONE MODELLO SARIMA REGIONE SARDEGNA ``` import pandas as pd df = pd.read_csv('../../csv/regioni/sardegna.csv') df.head() df['DATA'] = pd.to_datetime(df['DATA']) df.info() df=df.set_index('DATA') df.head() ``` <h3>Creazione serie storica dei decessi totali della regione Sardegna ``` ts = df.TOTALE ts.head()...
github_jupyter
``` ##%overwritefile ##%file:src/compile_out_file.py ##%noruncode def getCompout_filename(self,cflags,outfileflag,defoutfile): outfile='' binary_filename=defoutfile index=0 for s in cflags: if s.startswith(outfileflag): if(len(s)>len(outfileflag)): ...
github_jupyter
# Sentiment analysis with support vector machines In this notebook, we will revisit a learning task that we encountered earlier in the course: predicting the *sentiment* (positive or negative) of a single sentence taken from a review of a movie, restaurant, or product. The data set consists of 3000 labeled sentences, ...
github_jupyter
# Transfer Learning Template ``` %load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network ...
github_jupyter
# Logistic Regression on 'HEART DISEASE' Dataset Elif Cansu YILDIZ ``` from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import col, countDistinct from pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssembler, MinMaxScaler, IndexToString from pysp...
github_jupyter
# 一个完整的机器学习项目 ``` import os import tarfile import urllib import pandas as pd import numpy as np from CategoricalEncoder import CategoricalEncoder ``` # 下载数据集 ``` DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/" HOUSING_PATH = "../datasets/housing" HOUSING_URL = DOWNLOAD_ROOT + HOUSING_...
github_jupyter
# Recommending Movies: Retrieval Real-world recommender systems are often composed of two stages: 1. The retrieval stage is responsible for selecting an initial set of hundreds of candidates from all possible candidates. The main objective of this model is to efficiently weed out all candidates that the user is not i...
github_jupyter
## Instructions Please make a copy and rename it with your name (ex: Proj6_Ilmi_Yoon). All grading points should be explored in the notebook but some can be done in a separate pdf file. *Graded questions will be listed with "Q:" followed by the corresponding points.* You will be submitting **a pdf** file containin...
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
## Querying Nexus knowledge graph using SPARQL The goal of this notebook is to learn the basics of SPARQL. Only the READ part of SPARQL will be exposed. ## Prerequisites This notebook assumes you've created a project within the AWS deployment of Nexus. If not follow the Blue Brain Nexus [Quick Start tutorial](https:...
github_jupyter
``` import pandas as pd import numpy as np from tqdm import tqdm tqdm.pandas() import os, time, datetime from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, f1_score, roc_curve, auc import lightgbm as lgb import xgboost as xgb def format_time(elapsed): ''' Takes a ti...
github_jupyter
# Example usage of the O-C tools ## This example shows how to construct and fit with MCMC the O-C diagram of the RR Lyrae star OGLE-BLG-RRLYR-02950 ### We start with importing some libraries ``` import numpy as np import oc_tools as octs ``` ### We read in the data, set the period used to construct the O-C diagram ...
github_jupyter
``` # load libraries import xarray as xr import numpy as np from argopy import DataFetcher as ArgoDataFetcher from datetime import datetime, timedelta import pandas as pd # User defined functions: def get_argo_region_data(llon,rlon,llat,ulat,depthmin,depthmax,time_in,time_f): """Function to get argo data fo...
github_jupyter
# Consensus Optimization This notebook contains the code for the toy experiment in the paper [The Numerics of GANs](https://arxiv.org/abs/1705.10461). ``` %load_ext autoreload %autoreload 2 import tensorflow as tf from tensorflow.contrib import slim import numpy as np import scipy as sp from scipy import stats from m...
github_jupyter
# Getting Started with Tensorflow ``` import tensorflow as tf # Create TensorFlow object called tensor hello_constant = tf.constant('Hello World!') with tf.Session() as sess: # Run the tf.constant operation in the session output = sess.run(hello_constant) print(output); A = tf.constant(1234) B = tf.const...
github_jupyter
<a href="https://colab.research.google.com/github/bhuwanupadhyay/codes/blob/main/ipynbs/reshape_demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` pip install pydicom # Import tensorflow import logging import tensorflow as tf import keras.bac...
github_jupyter
## 20 Sept 2019 <strong>RULES</strong><br> <strong>Date:</strong> Level 2 heading ## <br> <strong>Example Heading:</strong> Level 3 heading ###<br> <strong>Method Heading:</strong> Level 4 heading #### ### References 1. [Forester_W._Isen;_J._Moura]_DSP_for_MATLAB_and_La Volume II(z-lib.org) 2. H. K. Dass, Advanced E...
github_jupyter
# langages de script – Python ## Modules et packages ### M1 Ingénierie Multilingue – INaLCO clement.plancq@ens.fr Les modules et les packages permettent d'ajouter des fonctionnalités à Python Un module est un fichier (```.py```) qui contient des fonctions et/ou des classes. <small>Et de la documentation bien sû...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd EXPERIMENT = 'bivariate_power' TAG = '' df = pd.read_csv(f'./results/{EXPERIMENT}_results{TAG}.csv', sep=', ', engine='python') plot_df = df x_var_rename_dict = { 'sample_size': '# Samples', 'Number of environments...
github_jupyter
``` ### Python's Dir Function ### def attributes_and_methods(inp): print("The Attributes and Methods of a {} are:".format(type(inp))) print(dir(inp)) # Change x to be any different type # to get different results for that data type x = 'abc' attributes_and_methods(x) ### Contextmanager Example ### # one way...
github_jupyter
<img src="https://github.com/pmservice/ai-openscale-tutorials/raw/master/notebooks/images/banner.png" align="left" alt="banner"> # Working with Watson Machine Learning This notebook should be run in a Watson Studio project, using **Default Python 3.7.x** runtime environment. **If you are viewing this in Watson Studio...
github_jupyter
# This Notebook uses a Session Event Dataset from E-Commerce Website (https://www.kaggle.com/mkechinov/ecommerce-behavior-data-from-multi-category-store and https://rees46.com/) to build an Outlier Detection based on an Autoencoder. ``` import mlflow import numpy as np import os import shutil import pandas as pd impor...
github_jupyter
<a href="https://colab.research.google.com/github/rwarnung/datacrunch-notebooks/blob/master/dcrunch_R_example.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **Data crunch example R script** --- author: sweet-richard date: Jan 30, 2022 require...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Datasets/Terrain/srtm_mtpi.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" h...
github_jupyter
#Introduction to Data Science See [Lesson 1](https://www.udacity.com/course/intro-to-data-analysis--ud170) You should run it in local Jupyter env as this notebook refers to local dataset ``` import unicodecsv from datetime import datetime as dt enrollments_filename = 'dataset/enrollments.csv' engagement_filename = ...
github_jupyter
``` import pandas as pd import numpy as np import keras from keras.models import Sequential,Model from keras.layers import Dense, Dropout,BatchNormalization,Input from keras.optimizers import RMSprop from keras.regularizers import l2,l1 from keras.optimizers import Adam from sklearn.model_selection import LeaveOneOut ...
github_jupyter
This notebook contains code for model comparison. Optimal hyperparameters for models are supposed to be already found. # Imports ``` #imports !pip install scipydirect import math import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_...
github_jupyter
# Apple and Tesla Split on 8/31 ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import math import warnings warnings.filterwarnings("ignore") # for fetching data import yfinance as yf # input # Coronavirus 2nd Wave title = "Apple and Tesla" symbols = ['AAPL', 'TSLA'] ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pandas as pd from matplotlib.pylab import rcParams rcParams['figure.figsize'] = 15, 6 import seaborn as sns import warnings warnings.filterwarnings('ignore') ori=pd.read_csv('website_data_20190225.csv') ori.drop(['STATE','DISTRICT','WLCODE...
github_jupyter
# 2 Dead reckoning *Dead reckoning* is a means of navigation that does not rely on external observations. Instead, a robot’s position is estimated by summing its incremental movements relative to a known starting point. Estimates of the distance traversed are usually obtained from measuring how many times the wheels ...
github_jupyter
## What this code does In short, it is a reverse meme search, that identifies the source of the meme. It takes an image copypasta, extracts the individual *subimages* and compares it with a database of pictures (the database should be made up of copypastas, which is in TODO) ### TODO ### Clean up the code There are m...
github_jupyter
# Computer Vision Nanodegree ## Project: Image Captioning --- In this notebook, you will use your trained model to generate captions for images in the test dataset. This notebook **will be graded**. Feel free to use the links below to navigate the notebook: - [Step 1](#step1): Get Data Loader for Test Dataset -...
github_jupyter
# Purpose: To run the full segmentation using the best scored method from 2_compare_auto_to_manual_threshold Date Created: January 7, 2022 Dates Edited: January 26, 2022 - changed the ogd severity study to be the otsu data as the yen data did not run on all samples. *Step 1: Import Necessary Packages* ``` # import ...
github_jupyter
``` # TensorFlow pix2pix implementation from __future__ import absolute_import, division, print_function, unicode_literals try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf import os import time from matplotlib import pyplot as plt from IPyt...
github_jupyter
# Basic Workflow ``` # Always have your imports at the top import pandas as pd from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.ensemble import RandomForestClassifier from sklearn.base import TransformerMixin from hashlib import sha1 # just for grading purposes import j...
github_jupyter
# Lab 11: MLP -- exercise # Understanding the training loop ``` import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from random import randint import utils ``` ### Download the data and print the sizes ``` train_data=torch.load('../data/fashion-mnist/train_data.pt') print...
github_jupyter
``` # Copyright 2020 NVIDIA Corporation. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
github_jupyter
## Main points * Solution should be reasonably simple because the contest is only 24 hours long * Metric is based on the prediction of clicked pictures one week ahead, so clicks are the most important information * More recent information is more important * Only pictures that were shown to a user could be clicked, so...
github_jupyter
This challenge implements an instantiation of OTR based on AES block cipher with modified version 1.0. OTR, which stands for Offset Two-Round, is a blockcipher mode of operation to realize an authenticated encryption with associated data (see [[1]](#1)). AES-OTR algorithm is a campaign of CAESAR competition, it has suc...
github_jupyter
``` import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline import torch from sklearn.model_selection import train_test_split from sklearn.ensemble import IsolationForest cubism_path = "/home/hopkinsl/Downloads/wikiart/wikiart/Cubism" listdir = os.listdi...
github_jupyter
### Easy string manipulation ``` x = 'a string' y = "a string" if x == y: print("they are the same") fox = "tHe qUICk bROWn fOx." ``` To convert the entire string into upper-case or lower-case, you can use the ``upper()`` or ``lower()`` methods respectively: ``` fox.upper() fox.lower() ``` A common formatting n...
github_jupyter
``` import re import os import keras.backend as K import numpy as np import pandas as pd from keras import layers, models, utils import json def reset_everything(): import tensorflow as tf %reset -f in out dhist tf.reset_default_graph() K.set_session(tf.InteractiveSession()) # Constants for our networks...
github_jupyter
``` import os, sys # os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' os.environ['CUDA_VISIBLE_DEVICES'] = '1' import tensorflow as tf tf.compat.v1.enable_eager_execution() import numpy as np import imageio import json import random import time import pprint import matplotlib.pyplot as plt import run_nerf from load...
github_jupyter
``` from platform import python_version import tensorflow as tf print(tf.test.is_gpu_available()) print(python_version()) import os import numpy as np from os import listdir from PIL import Image import time import tensorflow as tf from tensorflow.keras import layers,models,optimizers from keras import backend as K im...
github_jupyter
# AWS Marketplace Product Usage Demonstration - Algorithms ## Using Algorithm ARN with Amazon SageMaker APIs This sample notebook demonstrates two new functionalities added to Amazon SageMaker: 1. Using an Algorithm ARN to run training jobs and use that result for inference 2. Using an AWS Marketplace product ARN - w...
github_jupyter
# Detrending, Stylized Facts and the Business Cycle In an influential article, Harvey and Jaeger (1993) described the use of unobserved components models (also known as "structural time series models") to derive stylized facts of the business cycle. Their paper begins: "Establishing the 'stylized facts' associat...
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
``` import pandas as pd import numpy as np import os os.chdir('/Users/gianni/Google Drive/Bas Zahy Gianni - Games/Data') oc = [ 'index', 'subject', 'color', 'gi', 'mi', 'status', 'bp', 'wp', 'response', 'rt', 'time', 'mouse_t', 'mouse_x' ] fc = [ 'subject', 'is_comp', 'color', 'status', 'bp', 'wp...
github_jupyter
# Planar data classification with one hidden layer Welcome to your week 3 programming assignment! It's time to build your first neural network, which will have one hidden layer. Now, you'll notice a big difference between this model and the one you implemented previously using logistic regression. By the end of this ...
github_jupyter
``` import numpy as np import datetime import matplotlib.pyplot as plt from PIL import Image from scipy.sparse import csr_matrix import matplotlib.pyplot as plt from sklearn.cluster import KMeans from numpy.linalg import norm from sklearn.feature_extraction import image import warnings warnings.filterwarnings("ign...
github_jupyter
# Solution Graded Exercise 1: Leaky-integrate-and-fire model first name: Eve last name: Rahbe sciper: 235549 date: 21.03.2018 *Your teammate* first name of your teammate: Antoine last name of your teammate: Alleon sciper of your teammate: 223333 Note: You are allowed to discuss the concepts with your class ma...
github_jupyter
# Azure ML Training Pipeline for COVID-CXR This notebook defines an Azure machine learning pipeline for a single training run and submits the pipeline as an experiment to be run on an Azure virtual machine. ``` # Import statements import azureml.core from azureml.core import Experiment from azureml.core import Workspa...
github_jupyter
# SIT742: Modern Data Science **(Week 01: Programming Python)** --- - Materials in this module include resources collected from various open-source online repositories. - You are free to use, change and distribute this package. - If you found any issue/bug for this document, please submit an issue at [tulip-lab/sit74...
github_jupyter
# General Equilibrium This notebook illustrates **how to solve GE equilibrium models**. The example is a simple one-asset model without nominal rigidities. The notebook shows how to: 1. Solve for the **stationary equilibrium**. 2. Solve for (non-linear) **transition paths** using a relaxtion algorithm. 3. Solve for ...
github_jupyter
# LeNet Lab ![LeNet Architecture](lenet.png) Source: Yan LeCun ## Load Data Load the MNIST data, which comes pre-loaded with TensorFlow. You do not need to modify this section. ``` from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_...
github_jupyter
``` import numpy as np import scipy as sp import scipy.interpolate import matplotlib.pyplot as plt import pandas as pd import scipy.stats import scipy.optimize from scipy.optimize import curve_fit import minkowskitools as mt import importlib importlib.reload(mt) n=4000 rand_points = np.random.uniform(size=(2, n-2)) ...
github_jupyter
# Praca domowa 3 ## Ładowanie podstawowych pakietów ``` import pandas as pd import numpy as np import sklearn import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score from sklearn.model_selection import StratifiedKFold # used in cr...
github_jupyter
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # Challenge Notebook ## Problem: Implement depth-first traversals (in-order, pre-order, post-order) on a binary tree. * [Constraints](#Co...
github_jupyter
# Generative Adversarial Networks Throughout most of this book, we've talked about how to make predictions. In some form or another, we used deep neural networks learned mappings from data points to labels. This kind of learning is called discriminative learning, as in, we'd like to be able to discriminate between ph...
github_jupyter
*This notebook is part of course materials for CS 345: Machine Learning Foundations and Practice at Colorado State University. Original versions were created by Asa Ben-Hur. The content is availabe [on GitHub](https://github.com/asabenhur/CS345).* *The text is released under the [CC BY-SA license](https://creativecom...
github_jupyter
# Lecture 3.3: Anomaly Detection [**Lecture Slides**](https://docs.google.com/presentation/d/1_0Z5Pc5yHA8MyEBE8Fedq44a-DcNPoQM1WhJN93p-TI/edit?usp=sharing) This lecture, we are going to use gaussian distributions to detect anomalies in our emoji faces dataset **Learning goals:** - Introduce an anomaly detection pro...
github_jupyter
# Import Necessary Libraries ``` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn import svm from sklearn.metrics import precision_score, recall_score # display images from IPy...
github_jupyter
## Gaussian Transformation with Scikit-learn Scikit-learn has recently released transformers to do Gaussian mappings as they call the variable transformations. The PowerTransformer allows to do Box-Cox and Yeo-Johnson transformation. With the FunctionTransformer, we can specify any function we want. The transformers ...
github_jupyter
``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:95% !important; }</style>")) from jupyterthemes import jtplot jtplot.style() from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) import os import json import numpy a...
github_jupyter
# In-Class Coding Lab: Iterations The goals of this lab are to help you to understand: - How loops work. - The difference between definite and indefinite loops, and when to use each. - How to build an indefinite loop with complex exit conditions. - How to create a program from a complex idea. # Understanding Iterati...
github_jupyter
# 第8章: ニューラルネット 第6章で取り組んだニュース記事のカテゴリ分類を題材として,ニューラルネットワークでカテゴリ分類モデルを実装する.なお,この章ではPyTorch, TensorFlow, Chainerなどの機械学習プラットフォームを活用せよ. ## 70. 単語ベクトルの和による特徴量 *** 問題50で構築した学習データ,検証データ,評価データを行列・ベクトルに変換したい.例えば,学習データについて,すべての事例$x_i$の特徴ベクトル$\boldsymbol{x}_i$を並べた行列$X$と正解ラベルを並べた行列(ベクトル)$Y$を作成したい. $$ X = \begin{pmatrix} \boldsy...
github_jupyter
# Analyse a series <div class="alert alert-block alert-warning"> <b>Under construction</b> </div> ``` import os import pandas as pd from IPython.display import Image as DImage from IPython.core.display import display, HTML import series_details # Plotly helps us make pretty charts import plotly.offline as py imp...
github_jupyter
# VacationPy ---- #### Note * Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing. * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think throug...
github_jupyter
# SLU07 - Regression with Linear Regression: Example notebook # 1 - Writing linear models In this section you have a few examples on how to implement simple and multiple linear models. Let's start by implementing the following: $$y = 1.25 + 5x$$ ``` def first_linear_model(x): """ Implements y = 1.25 + 5*x ...
github_jupyter
``` #importing libraries import pandas as pd import boto3 import json import configparser from botocore.exceptions import ClientError import psycopg2 def config_parse_file(): """ Parse the dwh.cfg configuration file :return: """ global KEY, SECRET, DWH_CLUSTER_TYPE, DWH_NUM_NODES, \ DWH_NOD...
github_jupyter
``` import os, sys os.environ['CUDA_VISIBLE_DEVICES'] = '2' sys.path.append('../') import argparse, json from tqdm import tqdm_notebook as tqdm import os.path as osp from data.pointcloud_dataset import load_one_class_under_folder from utils.dirs import mkdir_and_rename from utils.tf import reset_tf_graph opt = { 'd...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import os import scipy.ndimage as ndi import skimage.filters as fl import warnings from numpy import uint8, int64, float64, array, arange, zeros, zeros_like, ones, mean from numpy.fft import fft, fft2, ifft, ifft2, fftshift from math import log2 from scipy.ndimage ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import tensorflow as tf import os from imageio import imwrite from tqdm import tqdm !ls imgs # no need to resize yet raw_img = tf.io.read_file('imgs/grundlsee_jesus.jpeg') content_img = tf.image.decode_image(raw_img)[None, ...] c...
github_jupyter
# Task 4: Support Vector Machines _All credit for the code examples of this notebook goes to the book "Hands-On Machine Learning with Scikit-Learn & TensorFlow" by A. Geron. Modifications were made and text was added by K. Zoch in preparation for the hands-on sessions._ # Setup First, import a few common modules, en...
github_jupyter