text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Recognizing Handwritten Digits using Scikit-Learn MNIST dataset: https://en.wikipedia.org/wiki/MNIST_database ![alt text][img] [img]: https://i.imgur.com/2xVHT7a.png "not the best handwriting" * 28x28 (784 pixels total) images of handwritten digits * each image has a label 0-9 * ~~70,000~~ 42,000 total images & l...
github_jupyter
### Introduction ---------------- This is a modified version of Tensorflow's Tutorial: [MNIST For ML Beginners](https://www.tensorflow.org/get_started/mnist/beginners). ### Data Description ---------------- * Training data is from **THE MNIST DATABASE of handwritten digits** (image + label = 60000 data): http://yann...
github_jupyter
# Reading and writing data Let's first do a bit of book keeping - figuring out how to read and write data. The easiest way to do this is with some built in functions in numpy. We'll start by importing our usual things: ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` Let's start by maki...
github_jupyter
``` import xarray as xr import datetime as dt import pandas as pd import numpy as np adir_adcp = 'F:/data/cruise_data/saildrone/baja-2018/adcp_data/' adir = 'F:/data/cruise_data/saildrone/baja-2018/' filename_loggers_usv=adir + 'saildrone-gen_4-baja_2018-sd1002-20180411T180000-20180611T055959-1_minutes-v1_withloggers....
github_jupyter
# Compare hospitaliations across CA counties. This can be a useful benchmark for calibrating the model rates. We show the raw model output as well as that after hospitalization renormalization. ``` import pandas as pd from pyseir import load_data from datetime import datetime, timedelta import seaborn as sns import ...
github_jupyter
# Data Wrangling # Content <a href='#gathering_data'>1. Gathering Data</a> <a href='#assessing_data'>2. Assessing Data </a> <a href='#cleaning_data'>3. Cleaning Data </a> <a href='#storing_data'>4. Storing, Analyzing and Visualizing Data</a> ``` # Importing libraries import matplotlib.pyplot as plt from datetim...
github_jupyter
# Stochastic GD vs Batch GD vs Mini-Batch GD * In the previous post, we saw how to construct 2 Layer Neural Network using back-prop and parameter updates. In this post, we take a look at how Mini-batch Gradient Descent can be a better option. * In the previous NN, every epoch corresponded to one update of the weight...
github_jupyter
``` # 13-1 import sys sys.setrecursionlimit(500*500) N = 5 edge = [(1,2), (2, 3), (4, 5)] G = [[] for _ in range(N)] for e in edge: a, b = e a -= 1 b -= 1 G[a].append(b) G[b].append(a) visited = [False]*N def dfs(v): if visited[v] == True: return visited[v] = True for u in...
github_jupyter
## Facies classification using Machine Learning ### aaML Submission ### By: [Alexsandro G. Cerqueira](https://github.com/alexleogc), [Alã de C. Damasceno](https://github.com/aladamasceno) There are tow main notebooks: - Data Analysis and edition - Submission ``` from libtools import * ``` ### Loading the dat...
github_jupyter
``` import numpy as np from simtk import openmm, unit from simtk.openmm import app from openmmtools import integrators from openmmtools.testsystems import WaterBox import sys sys.path.append("/Users/rossg/Work/saltswap/saltswap") from integrators import GHMCIntegrator as GHMC ``` # Testing energy outputs from GHMC in...
github_jupyter
<a href="https://colab.research.google.com/github/DakaiZhou/machine-learning-algorithm-implementation/blob/main/Linear_Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Linear Regression Linear Regression is one of the very basic supervi...
github_jupyter
# Simple Camera Models with NumPy and Matplotlib ``` import matplotlib.pyplot as plt import numpy as np from camera_models import * # our package DECIMALS = 2 # how many decimal places to use in print %matplotlib notebook %load_ext autoreload %autoreload 2 ``` > **Disclaimer**: The theory described in this not...
github_jupyter
``` !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/bbc-text.csv \ -O /tmp/bbc-text.csv import csv from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences #Stopwords list from https://github....
github_jupyter
PWC-Net-small model training (with cyclical learning rate schedule) ======================================================= In this notebook we: - Use a small model (no dense or residual connections), 6 level pyramid, uspample level 2 by 4 as the final flow prediction - Train the PWC-Net-small model on a mix of the `F...
github_jupyter
# Sea ice draft from AUV, LiDAR and 3D photogrammetry Adam Steer, adam.d.steer@gmail.com Here I'm using AUV draft as 'truth' to look at some parameters for modelling sea ice thickness. My aims are: - get descriptive stats from a patch of LiDAR-derived draft pretty close (within 1-sigma) of AUV draft - visualise the c...
github_jupyter
# DC Line dispatch with pandapower OPF This is an introduction into the usage of the pandapower optimal power flow with dc lines. ## Example Network We use the following four bus example network for this tutorial: <img src="pics/example_opf_dcline.png" width="100%"> We first create this network in pandapower: ``` ...
github_jupyter
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); </script> # The Effective One-Body Cartesian Hamiltonian ### Authors...
github_jupyter
# Optimization Methods Until now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that can speed up learning and perhaps even get you to a better final value for the cost function. Having a good optimization algorit...
github_jupyter
# Deterministic Terms in Time Series Models ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd plt.rc("figure", figsize=(16, 9)) plt.rc("font", size=16) ``` ## Basic Use Basic configurations can be directly constructed through `DeterministicProcess`. These can include a constant, a time tren...
github_jupyter
# Implementation Notes The internals of ChebPy have been designed to resemble the design structure of MATLAB Chebfun. The Chebfun v5 class diagram thus provides a useful map for understanding how the various pieces of ChebPy fit together (diagram courtesy of the Chebfun team, available [here](https://github.com/chebfu...
github_jupyter
## Notebook to explore and demonstrate capabilities for inverse queries: Note inverse queries are those where model output and certain inputs are known and other inputs are to be estimated ``` from GPyOpt.methods import BayesianOptimization from GPyOpt import Design_space, experiment_design import numpy as np import m...
github_jupyter
#### Arbitrary Value Imputation this technique was derived from kaggle competition It consists of replacing NAN by an arbitrary value ``` import pandas as pd df=pd.read_csv("titanic.csv", usecols=["Age","Fare","Survived"]) df.head() def impute_nan(df,variable): df[variable+'_zero']=df[variable].fillna(0) df[v...
github_jupyter
``` import pandas as pd user_data = pd.read_csv("all_user_data_c_50_95.csv") user_data.drop(user_data.columns[[0]], axis=1, inplace=True) user_data.head() user_data = user_data[user_data['status']>0] user_data.describe().apply(lambda s: s.apply(lambda x: format(x, 'g'))) import os.path import numpy as np from trust_s...
github_jupyter
``` !pip install git+https://github.com/keras-team/keras-tuner # !pip uninstall tensorflow -y # !pip install tensorflow-gpu !pip install gdown import os import numpy as np import tensorflow as tf from tensorflow import keras import pandas as pd import seaborn as sns from pylab import rcParams import matplotlib.pyplot a...
github_jupyter
<a href="https://colab.research.google.com/github/bundickm/Study-Guides/blob/master/Unit_2_Sprint_2_Tree_Ensembles_Study_Guide.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> This study guide should reinforce and provide practice for all of the conc...
github_jupyter
# Table of Contents <p><div class="lev1"><a href="#Introduction"><span class="toc-item-num">1&nbsp;&nbsp;</span>Introduction</a></div><div class="lev1"><a href="#Data-Basics"><span class="toc-item-num">2&nbsp;&nbsp;</span>Data Basics</a></div><div class="lev2"><a href="#Numerical-variables"><span class="toc-item-num">...
github_jupyter
# Central Limit Theorem example [![Latest release](https://badgen.net/github/release/Naereen/Strapdown.js)](https://github.com/eabarnes1010/course_objective_analysis/tree/main/code) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eabarnes1010/course_...
github_jupyter
# Gráfico de Transformação - Auto Featuring - Experimento Este é um componente que utiliza uma técnica para explorar as possíveis soluções orientadas por um gráfico para executar a AutoFeaturing. ## Declaração de parâmetros e hiperparâmetros Declare parâmetros com o botão <img src="data:image/png;base64,iVBORw0KGgoA...
github_jupyter
<img src="../../images/banners/python-basics.png" width="600"/> # <img src="../../images/logos/python.png" width="23"/> When to Use a List Comprehension in Python ## <img src="../../images/logos/toc.png" width="20"/> Table of Contents * [How to Create Lists in Python](#how_to_create_lists_in_python) * [Using for...
github_jupyter
``` #coding:utf-8 import matplotlib.pyplot as plt import numpy as np import os, cv2 %matplotlib inline # 内嵌绘图,省去plt.show() LABELS = ['爽快生菜', '当冬菇遇上鸡', '米饭', '忘情糯米鸡', '玉米约肉包', '痴心鱼蛋粉', \ '真心卤蛋', '蒸凤爪', '蒸蛋', '小鲜肉滚粥', '黄汽水', '绿汽水', '奶茶', '小红莓布丁', \ '情意绵绵粥', '蒸能量花卷', '蒸花蛋', '鸡汤', '油焖茄子', '虫草花牛肉粥', '古惑烧麦'...
github_jupyter
``` #Basic Program print ("Hello World") #Creates a Triangle print(" /|") print(" / |") print(" / |") print("/___|") #Basic usage of variables subject_name= "John" subject_age= "35" print("There was once was a man named "+ subject_name+ ",") print("he was " +subject_age+ " years old, ") print("he really liked the n...
github_jupyter
# Dropout and maxout In this lab we will explore the methods of [dropout](https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf), a regularisation method which stochastically drops out activations from the model during training, and [maxout](http://www.jmlr.org/proceedings/papers/v28/goodfellow13.pdf), another non-l...
github_jupyter
``` import os import pathlib import nibabel as nib import numpy as np from matplotlib import pyplot as plt from nilearn.plotting import plot_anat working_dir = pathlib.Path(os.getcwd()) print(f'Working directory: {working_dir}') out_sr = pathlib.Path(working_dir / 'data' / 'sub-01_rec-SR_id-1_T2w.nii.gz') out_sr_png = ...
github_jupyter
# ResnetTrick_s256bs16_e80 > size 256 bs 16 80 epochs runs. # setup and imports ``` # pip install git+https://github.com/ayasyrev/model_constructor # pip install git+https://github.com/kornia/kornia from kornia.contrib import MaxBlurPool2d from fastai.basic_train import * from fastai.vision import * from fastai.scri...
github_jupyter
**How to save this notebook to your personal Drive** To copy this notebook to your Google Drive, go to File and select "Save a copy in Drive", where it will automatically open the copy in a new tab for you to work in. This notebook will be saved into a folder on your personal Drive called "Colab Notebooks". Still st...
github_jupyter
``` #default_exp tabular.core #export from fastai2.torch_basics import * from fastai2.data.all import * #hide from nbdev.showdoc import * #export pd.set_option('mode.chained_assignment','raise') ``` # Tabular core > Basic function to preprocess tabular data before assembling it in a `DataLoaders`. ## Initial preproc...
github_jupyter
# Processing Column Data As part of this module we will explore the functions available under `org.apache.spark.sql.functions` to derive new values from existing column values with in a Data Frame. ## Introduction to Pre-defined Functions We typically process data in the columns using functions in `org.apache.spark....
github_jupyter
``` #Python Basics #Reading files using "open" #you should use "slash" //////////////instead of backslash\\\\\\\\\\\\\\ in addressing #We will use Python’s open function to get a file object #We can apply a method to that object to read data from the file #The open() function opens a file, and returns it as a file ob...
github_jupyter
<a href="https://colab.research.google.com/github/Tomiinek/Multilingual_Text_to_Speech/blob/master/notebooks/code_switching_demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Multilingual Text-to-Speech Demo This notebook demonstrates multiling...
github_jupyter
# Computer Vision Nanodegree ## Project: Image Captioning --- In this notebook, you will learn how to load and pre-process data from the [COCO dataset](http://cocodataset.org/#home). You will also design a CNN-RNN model for automatically generating image captions. Note that **any amendments that you make to this no...
github_jupyter
``` # default_exp data.preparation ``` # Data preparation > Functions required to prepare X (and y) from a pandas dataframe. ``` # export from tsai.imports import * from tsai.utils import * from tsai.data.validation import * from io import StringIO #export def df2Xy(df, sample_col=None, feat_col=None, data_cols=None...
github_jupyter
# Fake News Detection Model People check out this paper: https://sites.cs.ucsb.edu/~william/papers/acl2017.pdf ### Data properties Column 1: the ID of the statement ([ID].json). Column 2: the label. Column 3: the statement. Column 4: the subject(s). Column 5: the speaker. Column 6: the speak...
github_jupyter
## 9-2. 量子エラー 量子ビットに生じるエラーの根本的な要因自体は実は古典ビットとそれほど違いはない。 一つは、外部との環境の相互作用によって一定のレートで外部に情報が漏れ出てしまうことで生じるエラーである。 特に物質を量子ビットとして光やマイクロ波などの電磁波で情報を読み書きする場合、電磁波を注入する経路を確保せねばならず、そこから一定量の情報が漏れ出てしまう。 また、希釈冷凍機で実験をしていてもマイクロ波はエネルギースケールが環境温度と近いため、熱雑音の影響を大きく受けてしまい、これも定常的なノイズの原因となる。 一方、イオンや中性原子のようなトラップを用いて作成する物質の場合、デコヒーレンスに加えて物質がトラップから...
github_jupyter
# Assignment #3 Deep Learning / Spring 1398, Iran University of Science and Technology --- **Please pay attention to these notes:** <br/> - **Assignment Due: ** 1398/02/20 23:59 - If you need any additional information, please review the assignment page on the course website. - The items you need to answer are h...
github_jupyter
# Configure Learning Environment ``` #!pip install git+https://github.com/nockchun/rspy --force import rspy as rsp rsp.setSystemWarning(off=True) #!pip install OpenDartReader import OpenDartReader from bs4 import BeautifulSoup import pandas as pd api_key = '125e216fefd7c214a1a66784b73f76075dff77b7' dart = OpenDartRead...
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W0D5_Statistics/student/W0D5_Tutorial2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Tutorial 2: Statistical Inference **Week 0, Day 5: Prob...
github_jupyter
![Renode](https://dl.antmicro.com/projects/renode/renode.png) <table align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/antmicro/tensorflow-arduino-examples/blob/master/examples/micro_speech/micro_speech.ipynb"><img src="https://raw.githubusercontent.com/antmicro/tensorflow-ardui...
github_jupyter
# PyPlot Animation with MultibodyPlant Tutorial For instructions on how to run these tutorial notebooks, please see the [README](https://github.com/RobotLocomotion/drake/blob/master/tutorials/README.md). ## Selecting matplotlib Backends Jupyter notebooks provide the `%matplotlib` that we will use to select different...
github_jupyter
## Node Classification on Citation Network As a start, we present a end to end example, demonstrating how GraphScope process node classification task on citation network by combining analytics, interactive and graph neural networks computation. In this example, we use [ogbn-mag](https://ogb.stanford.edu/docs/nodeprop...
github_jupyter
``` from matplotlib import pyplot from matplotlib.patches import Rectangle from mtcnn.mtcnn import MTCNN import pandas as pd import os pip install mtcnn import zipfile from google.colab import drive drive.mount('/content/drive/') !unzip '/content/drive/My Drive/train_HNzkrPW (1).zip' -d file_destination zip_ref = zipf...
github_jupyter
# Particle Swarm Optimization Algorithm (in Python!) [SPOILER] We will be using the [Particle Swarm Optimization algorithm](https://en.wikipedia.org/wiki/Particle_swarm_optimization) to obtain the minumum of a customed objective function ![PSO-1D](img/PSS-Example-1D.gif) First of all, let's import the libraries we'll...
github_jupyter
# The Atoms of Computation Programming a quantum computer is now something that anyone can do in the comfort of their own home. But what to create? What is a quantum program anyway? In fact, what is a quantum computer? These questions can be answered by making comparisons to standard digital computers. Unfortunat...
github_jupyter
# K-fold Validation PorkCNN author: davidycliao(David Yen-Chieh Liao) email: davidycliao@gmail.com date: 9-July-2021 ------------------------- ### Stage 1: Libaries & Dependencies ``` #...
github_jupyter
# Prerequisite: Set-up a S3 bucket This notebook assumes you completed the earlier steps in `README.md`, if you did not, go back and do that, the notebook will wait patiently for you to come back. In this notebook you will leverage a provided e-commerce dataset to demonstrate the functionality of Amazon Lookout For M...
github_jupyter
``` import uuid import lightgbm as lgb from scipy import special import numpy as np import pandas as pd from collections import OrderedDict from functools import lru_cache from datetime import date, datetime, timedelta from zenquant.trader.database import get_database from zenquant.trader.constant import Interval from...
github_jupyter
# Yodapy Cloud Data Example ## Inilization To access the OOI API, credentials need to be set. In order to set this up, switch to the python environment that contains yodapy and then fire up python. ```bash $ python ``` Within the python console, set your credentials. ```python from yodapy.utils.creds import set_cr...
github_jupyter
# Introduction to Deep Learning with PyTorch In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tenso...
github_jupyter
This is a work-in-progress proof-of-concept for 3D. ``` from qiskit_textbook.games.jupyter_widget_engine import JupyterWidgetEngineimport random import numpy as np import copy L = 22 # screen size dist = 32 # draw distance h0 = 2 # player height def get_height(x,z,block=20,road=4,verge=4,height=8): if -x%b...
github_jupyter
# MadMiner particle physics tutorial # Part 4a: Limit setting Johann Brehmer, Felix Kling, Irina Espejo, and Kyle Cranmer 2018-2019 In part 4a of this tutorial we will use the networks trained in step 3a and 3b to calculate the expected limits on our theory parameters. ## 0. Preparations ``` from __future__ import...
github_jupyter
# Create your own models This Notebook illustrates how to create your own models using the framework. At the end of this guide, you'll be able to run simulations with your own models. For a guide on how to create new metrics, please see [advanced-metrics](advanced-metrics.ipynb). In what follows, we assume you are fami...
github_jupyter
# Introduction to Data Structures ## <img src='https://az712634.vo.msecnd.net/notebooks/python_course/v1/park.png' alt="Smiley face" width="80" height="42" align="left"> Learning Objectives * * * * Learn about mutable and immutable data structures * See how to use these data structures for useful purposes * Learn ho...
github_jupyter
``` import numpy as np import pandas as pd from matplotlib import pyplot as plt from tqdm import tqdm %matplotlib inline from torch.utils.data import Dataset, DataLoader import torch import torchvision import torch.nn as nn import torch.optim as optim from torch.nn import functional as F device = torch.device("cuda" i...
github_jupyter
# ART - Adversarial Patch - TensorFlow v1 ``` import warnings warnings.filterwarnings('ignore') import random import numpy as np from matplotlib import pyplot as plt plt.rcParams['figure.figsize'] = [10, 10] import imagenet_stubs from imagenet_stubs.imagenet_2012_labels import name_to_label import tensorflow as tf s...
github_jupyter
# Restricting Parameter Values Typically, we don't want to restrict our parameter values both because we don't need to and because it can affect our accuracy. However, there may be times where we need to due to some limitation or another. Let's try to fit and plot a function exactly the way we did before, but using a...
github_jupyter
<img src="../../img/logo_white_bkg_small.png" align="left" /> # Feature Engineering This worksheet covers concepts covered in the first part of day 2 - Feature Engineering. It should take no more than 30-40 minutes to complete. Please raise your hand if you get stuck. ## Import the Libraries For this exercise, we...
github_jupyter
# Estimating a simpel model by simulated minimum distance (SMD) **Inspiration:** This notebook is based on an example given by Julia/Economics ([link](https://juliaeconomics.com/tag/method-of-simulated-moments/)). **MATLAB:** The file **SMD_MATLAB.mlx** contains a MATLAB version of the same notebook. * For a **guid...
github_jupyter
Lambda School Data Science *Unit 2, Sprint 2, Module 4* --- # Classification Metrics ## Assignment - [ ] If you haven't yet, [review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2), then submit your dataset. - [ ] Plot a confusion matrix for your Tanzania Waterpumps model. - [ ] Co...
github_jupyter
# Configurations Configurations can be set in .yml file. See example [config.yml](https://github.com/dssg/aequitas/tree/master/src/aequitas_cli) on github. ## Define reference groups ```--ref-group-method <type>``` Fairness is always determined in relation to a reference group. By default, aequitas uses the majorit...
github_jupyter
# Axelrod Tournament Model This model is a partial recreation of the tournament first detailed in Axelrod (1981), ["Effective Choice in the Prisoner's Dilemma"](https://www.jstor.org/stable/173932). Agents are paired off and play a repeated prisoner's dilemma against each other for some number of rounds. Breeds are de...
github_jupyter
## Over-sampling Method Comparison We will determine if the different over-sampling algorithms discussed in this section improve the performance of Random Forests on different datasets with imbalanced classes. ``` from collections import Counter import pandas as pd import matplotlib.pyplot as plt from sklearn.ensem...
github_jupyter
# Estimate car price - Load data to SAP HANA This notebook is part of a Machine Learning project that is described and available to download on <BR><a href="https://blogs.sap.com/2019/11/05/hands-on-tutorial-machine-learning-push-down-to-sap-hana-with-python/">https://blogs.sap.com/2019/11/05/hands-on-tutorial-machine...
github_jupyter
# Fréchet distance This will compare the performance of calculating the discrete Fréchet distance with the recursive and dynamic programming algorithms. ``` import similaritymeasures as sm import numpy as np import matplotlib.pyplot as plt import toleranceinterval as ti from scipy.spatial import minkowski_distance fr...
github_jupyter
# Coresests ## Intro The notion of **coresets** originates from computational geometry and refers to data summarization with strong theoretical guarantees. Coresets are gaining attention in the machine learning community: they allow to run expensive algorithms on a small subset of the data with error guarantees - this...
github_jupyter
``` import pandas as pd import numpy as np from fbprophet import Prophet import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize']=(20,10) plt.style.use('ggplot') ``` # Load data Let's load our data to analyze. For this example, I'm going to use some stock market data to be able to show so...
github_jupyter
``` from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_distances from sklearn.metrics.pairwise import cosine_similarity from sklearn.manifold import TSNE from sklearn.decomposition import PCA from sklearn.metrics.pairwise import linear_kernel import pandas as pd im...
github_jupyter
## Setup First we load the necessary python packages and initialize variables ``` %load_ext autoreload %autoreload 2 %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np import core_compute as cc import core_plot as cp import scipy.stats as ss sns.set(color_codes=True) D = {} D...
github_jupyter
# Activation Function Reference: [How to Choose an Activation Function for DL](https://machinelearningmastery.com/choose-an-activation-function-for-deep-learning/) ### Table of Contents * [Activation for Hidden Layers](#hidden) * [ReLU](#ReLU) * [Sigmoid](#Sigmoid_hidden) * [Tanh](#Tanh) * [Activation fo...
github_jupyter
``` # import Requests library: import requests # import BeautifulSoup library: from bs4 import BeautifulSoup as BS # import Numpy library: from numpy import * # import WordCloud_Fa library: from wordcloud_fa import WordCloudFa # import Regex library: import re # import Image library: from PIL import Image # impor...
github_jupyter
# Conditional Probability: Notation and Intuition In the last section, we introduced the *concept* of conditional probability:we want to know the probability of an event **given that another event has occurred**. To make our work on conditional probability easier and to effectively communicate with others, we will nee...
github_jupyter
Contents (TODO) | [How to Read and Represent Data](../ica02/How_to_Read_and_Represent_Data.ipynb) > <a href="https://colab.research.google.com/github/stephenbaek/bigdata/blob/master/in-class-assignments/ica01/hello_world.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open ...
github_jupyter
# Chapter 2: Variables, expressions, and statements *** __Contents__ - [Values and types](#Values-and-types) - [Variables](#Variables) - [Variable names and keywords](#Variable-names-and-keywords) - [Statements](#Statements) - [Operators and operands](#Operators-and-operands) - [Expressions](#Expressions) - [Order of o...
github_jupyter
# Word2Vec: A language model implementation In this notebook we will implement a popular machine learning model (word2vec) to obtain word embeddings. **We will:** * Get and preprocess a dataset * Formulate the Word2Vec task, and create input/label pairs according to the task * Implement the Word2Vec model in Keras ...
github_jupyter
``` import os import glob import numpy as np from cpol_processing import processing as cpol_prc from pyhail import hsda, hdr, mesh, common import pyart from datetime import datetime import warnings warnings.filterwarnings('ignore') #paths vol_path = '/g/data/kl02/jss548/hail-research/radar_data' out_path ...
github_jupyter
``` import pandas as pd import numpy as np from sklearn import ensemble from sklearn.metrics import mean_squared_error from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import LabelEncoder fr...
github_jupyter
# [Machine Learning with CoreML](https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-core-ml) **By:** Joshua Newnham (Author) **Publisher:** [Packt Publishing](https://www.packtpub.com/) ## Chapter 7 - Fast Neural Style Transfer This notebook is concerned with extracting the **style** from ...
github_jupyter
# Introduction The [HHL algorithm](https://en.wikipedia.org/wiki/Quantum_algorithm_for_linear_systems_of_equations) underlies many quantum machine learning protocols, but it is a highly nontrivial algorithm with lots of conditions. In this notebook, we implement the algorithm to gain a better understanding of how it w...
github_jupyter
# Tensorflow for Structured Data This tutorial demonstrates how to classify structured data (e.g. tabular data in a CSV). We will use Keras to define the model, and feature columns as a bridge to map from columns in a CSV to features used to train the model. This tutorial contains complete code to: Load a CSV fil...
github_jupyter
``` #TicTacToe row1=[7,8,9] row2='---------' row3=[4,5,6] row4='---------' row5=[1,2,3] #display def display(): print(row1) print(row2) print(row3) print(row4) print(row5) #userinput u=0 l=['1','2','3','4','5','6','7','8','9'] def userinput(): x='a' global u global l while x.is...
github_jupyter
## State space models - concentrating the scale out of the likelihood function ``` import numpy as np import pandas as pd import statsmodels.api as sm dta = sm.datasets.macrodata.load_pandas().data dta.index = pd.date_range(start='1959Q1', end='2009Q4', freq='Q') ``` ### Introduction (much of this is based on Harve...
github_jupyter
# WorkFlow ## Classes ## Load the data ## Test Modelling ## Modelling **<hr>** ## Classes ``` import os import cv2 import torch import numpy as np def load_data(img_size=112): data = [] index = -1 labels = {} for directory in os.listdir('./data/'): index += 1 labels[f'./data/{dire...
github_jupyter
``` import sys import numpy as np import pandas as pd import cPickle import multiprocessing import matplotlib.pyplot as plt %matplotlib inline from IPython.display import clear_output ``` ### Reading tweets ``` review_train = pd.read_csv('../data/kinopoisk_train.csv', encoding='utf-8') review_train.head() texts, labe...
github_jupyter
``` import os import gc import sys import time import pyreadr as py import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from tqdm.notebook import tqdm from collections import defaultdict import torch import torch.nn.functional as F from torch import nn from torch.optim impor...
github_jupyter
# Example of usage Spark OCR with Update Text Position ## Import Spark OCR transformers and Spark NLP annotators ## Install spark-ocr python packge Need specify path to `spark-ocr-assembly-[version].jar` or `secret` ``` secret = "" license = "" version = secret.split("-")[0] spark_ocr_jar_path = "../../target/scala-...
github_jupyter
``` %pylab inline import pybedtools import pandas as pd from pyfaidx import Fasta import json cds = pybedtools.BedTool('../data/mm10/annotation/gencode.vM11.gffutils.cds.bed').to_dataframe()#.set_index('name') gene = pybedtools.BedTool('../data/mm10/annotation/gencode.vM11.gffutils.genes.bed').to_dataframe()#.set_inde...
github_jupyter
# Reading comprehension question answering on SQuAD Adapted from original [tutorial](https://keras.io/examples/nlp/text_extraction_with_bert/) by Keras team. **Description:** Fine tune pretrained BERT from HuggingFace Transformers on SQuAD. ## Introduction This demonstration uses SQuAD (Stanford Question-Answering ...
github_jupyter
# Аспектный анализ тональности текстов: используем возможности fasttext ``` # Если Вы запускаете ноутбук на colab или kaggle, # выполните следующие строчки, чтобы подгрузить библиотеку dlnlputils: # !git clone https://github.com/Samsung-IT-Academy/stepik-dl-nlp.git && pip install -r stepik-dl-nlp/requirements.txt # i...
github_jupyter
# Answers: Functions Provided here are answers to the practice questions at the end of "Functions". ## Function Execution **Function Execution Q1** ``` square_default = square_all([2,3,4]) power_three = square_all([2,3,4], 3) out_4 = square_all([2,2,2,2]) # this execution could differ ``` **Function Execution Q2**...
github_jupyter
# Klasser og Arv ## Arv Klasser i Python kan *arve* fra andre klasser. En klasse som arver, kalles ofte for en *child class*, mens klassen den arver av, kalles ofte dens *parent class*. En *child class* vil automatisk arve alt fra sin *parent class*, men den kan overskrive metoder for å endre på egenskaper fra *par...
github_jupyter
___ <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> ___ # Seaborn Exercises Time to practice your new seaborn skills! Try to recreate the plots below (don't worry about color schemes, just the plot itself. ## The Data We will be working with a famous titanic data set for these exerc...
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import scipy.stats as stats import random print(plt.style.available) plt.style.use('ggplot') data = [] for i in range(1000): data.append(random.normalvariate(0,1)) plt.hist(data) plt.show() stats.probplot(data, dist=stats.norm, sparams=(0,1), plot=plt) plt.sho...
github_jupyter