text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Value-at-Risk for Stocks: Delta-Normal Approach, EWMA ### Lecture Notes by Jakov Ivan S. Dumbrique (jdumbrique@ateneo.edu) MATH 100.2: Topics in Financial Mathematics II \ First Semester, S.Y. 2021-2022 \ Ateneo de Manila University ``` import numpy as np # Numerical Computing import pandas as pd # Data wrangling ...
github_jupyter
``` import keras import tensorflow as tf print('TensorFlow version:', tf.__version__) print('Keras version:', keras.__version__) import os from os.path import join import json import random import itertools import re import datetime import cairocffi as cairo import editdistance import numpy as np from scipy import ndim...
github_jupyter
### Imports ``` from datetime import datetime import time from contracts_lib_py.account import Account from common_utils_py.agreements.service_types import ServiceTypesIndices from nevermined_sdk_py import Config, Nevermined from nevermined_sdk_py.nevermined.keeper import NeverminedKeeper as Keeper CONSUMER_ADDRES...
github_jupyter
# ODYM Example no. 5. Estimating the material content of the global vehicle fleet ODYM was designed to handle extensive MFA systems by covering multiple aspects (time, age-cohort, region, material, chemical elements, processes, goods, components, ...) in a systematic manner. Its data format is used to structure and st...
github_jupyter
``` # for use in tutorial and development; do not include this `sys.path` change in production: import sys ; sys.path.insert(0, "../") ``` # Statistical Relational Learning with `pslpython` In this section we'll explore one form of [*statistical relational learning*](../glossary/#statistical-relational-learning) cal...
github_jupyter
``` from utils import * from defense import * from skimage.measure import compare_ssim import argparse import imutils import cv2 config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) sess = tf.Session(config=config) def ssim_score(cleandata,data): # cleandata = (cleandata * 255).astype('uint8') # ...
github_jupyter
# Black Scholes Model The Black Scholes model is considered to be one of the best ways of determining fair prices of options. It requires five variables: the strike price of an option, the current stock price, the time to expiration, the risk-free rate, and the volatility. ## Black and Scholes componets - C = call opt...
github_jupyter
# Tratamento de Dados Radioativos Importação das bibliotecas utilizadas ``` import re import pandas as pd import matplotlib.pyplot as plt import numpy as np ``` Leitura de arquivos contendo os dados ``` enviroment = open('enviroment.txt') radioactive_source = open('radioactive_source.txt') uranite = open('uranite.t...
github_jupyter
# SSD This is to go through each important step of SSD. Firstly, load the model. You only need to do this one time. ``` import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10, 10) plt.rcParams['image.interpolation'] = 'nearest' import numpy as np import os os.chdir('..') caffe_root ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from OpenGoddard.optimize import Problem, Guess, Condition, Dynamics from rocket import Rocket r = Rocket() r def og_dynamics(prob, obj, section): #extract states and controls s = tuple([prob.states(i, section) for i in range(5)]) u = tuple([prob....
github_jupyter
``` %pylab inline import pandas as pd import os # Just use 1 GPU os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" import pandas as pd from pyvirchow.io import WSIReader from pyvirchow.morphology import TissuePatch from matplotlib.patches import Polygon from sh...
github_jupyter
# Spark Learning Note - MLlib Jia Geng | gjia0214@gmail.com <a id='directory'></a> ## Directory - [Data Source](https://github.com/databricks/Spark-The-Definitive-Guide/tree/master/data/) - [1. Some Machine Learning Examples](#sec1) - [2. Classic ML Developmental Stages](#sec2-1) - [3. Spark MLlib Overview](#sec3) ...
github_jupyter
## Aplicando Pipeline na base de dados adult.data disponivel em: https://archive.ics.uci.edu/ml/datasets/Adult #### Resumo : Preveja se a renda excede US $ 50 mil / ano com base nos dados do censo. Também conhecido como conjunto de dados "Renda do Censo". * Informações sobre atributos: * Listagem de atributos: * re...
github_jupyter
# TORCHVISION.TRANSFORMS ``` import torchvision.datasets as datasets import torchvision.transforms as transforms import torch from matplotlib.pyplot import imshow from torchvision.transforms import ToPILImage def get_transform(centercrop, resize, totensor, normalize, normalize2): options = [] if centercrop: ...
github_jupyter
## 01. Object-oriented programming In __procedural programming__ paradigm, the focus is on writing functions or procedures which operate on data. While in __object-oriented programming__ the focus is on the creation of objects which contain both data and functionality together. ## 02. User Defined Classes If the firs...
github_jupyter
# Ensembles and Predictions Clipping The combination of predictions from several methods to one forecast often leads to great performance improvements. ## Simple Ensembles The most common strategy just takes an average of all the forecast, which often leads to surprisingly good results, for more on this topic, see fo...
github_jupyter
# `Практикум по программированию на языке Python` <br> ## `Занятие 4: Основы ООП, особенности ООП в Python` <br><br> ### `Мурат Апишев (mel-lain@yandex.ru)` #### `Москва, 2020` ### `Парадигмы проектирования кода` Императивное программирование (язык ассемблера) `mov ecx, 7` Декларативное программирование (SQL) `...
github_jupyter
``` !curl -s https://course.fast.ai/setup/colab | bash from google.colab import drive drive.mount('/content/gdrive', force_remount=True) root_dir = "/content/gdrive/My Drive/" base_dir = root_dir + 'fastai-v3/' ``` **Important note:** You should <mark>always work on a duplicate of the course notebook</mark>. On the pa...
github_jupyter
# Load Packages ``` import sys sys.path.append('..') from numpy_fracdiff import fracdiff import numpy as np import scipy.special import matplotlib.pyplot as plt %matplotlib inline #!pip install memory_profiler import memory_profiler %load_ext memory_profiler ``` # Load Demo Data ``` with np.load('data/demo1.npz') as...
github_jupyter
``` import pandas as pd from ast import literal_eval import matplotlib.pyplot as plt import matplotlib plt.style.use('fivethirtyeight') %matplotlib inline !ls #Importing the data df = pd.read_csv('readable_cleaned.csv') del df['Date.1'] df.index = pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M:%S') df.info() ``` # ...
github_jupyter
# Churn Prediction This notebook will introduce the use of the churn dataset to create churn prediction model using deep kernel learning. The dataset used to ingest is from SIDKDD 2009 competition. The pipeline is composed using Azure ML pipeline and trained on Azure ML compute with hyper parameters of the gaussian...
github_jupyter
``` from tensorflow.keras.preprocessing.text import Tokenizer sentences = [ 'i love my dog', 'I, love my cat', 'You love my dog!' ] tokenizer = Tokenizer(num_words = 100) tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index print(word_index) import tensorflow as tf from tensorflow import ke...
github_jupyter
``` !pip install autokeras !pip install git+https://github.com/keras-team/keras-tuner.git@1.0.2rc4 ``` In this tutorial we are making use of the [AutoModel](/auto_model/#automodel-class) API to show how to handle multi-modal data and multi-task. ## What is multi-modal? Multi-modal data means each data instance has...
github_jupyter
``` #hide #skip ! [ -e /content ] && pip install -Uqq mrl-pypi # upgrade mrl on colab # default_exp core ``` # Core > Core functions for MRL, mostly low level plumbing and parallel processing ``` #hide from nbdev.showdoc import * %load_ext autoreload %autoreload 2 # export from mrl.imports import * from multiproces...
github_jupyter
## Creating a Convolutional Neural Network-Dogs-v-Cats ### Imports ``` import os import numpy as np import cv2 import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F ``` ### Creating a NN ``` class Net(nn.Module): def __init__(self): super().__init__() ...
github_jupyter
# Proglearn: Scene Segmentation of ISIC using Scikit-Image *Neuro Data Design II: Spring 2022* This tutorial provides a walkthrough to applying a Random Forest model to perform scene segmentation on images taken from the International Skin Imaging Collaboration (ISIC) dataset from 2016 using Scikit-Image. **Contri...
github_jupyter
<a href="https://colab.research.google.com/github/lucianogaldino/ENEM-2019-SP/blob/main/Enem_2019_SP.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # **PROJETO ENEM 2019** ## Este projeto analisa os resultados do ENEM no estado de São Paulo no ano...
github_jupyter
``` %reload_ext autoreload %autoreload 2 import logging import numpy as np # Make analysis reproducible np.random.seed(0) # Enable logging logging.basicConfig(level=logging.INFO) from replay_trajectory_classification import make_track_graph, plot_track_graph import matplotlib.pyplot as plt node_positions = [(40, 80...
github_jupyter
# Plagiarism Detection Model Now that you've created training and test data, you are ready to define and train a model. Your goal in this notebook, will be to train a binary classification model that learns to label an answer file as either plagiarized or not, based on the features you provide the model. This task wi...
github_jupyter
## 1. Introduction We will reimplement the methodology of the paper in Python. ## 2. Preliminary Concepts Initially, we will recreate the basic variables defined in the paper. To make calculations easier, we will use NaNs instead of zeros if a movie is not rated by a user. ``` import numpy as np m = 6040 # users n ...
github_jupyter
# MNIST Image Classification with TensorFlow on Cloud ML Engine This notebook demonstrates how to implement different image models on MNIST using Estimator. Note the MODEL_TYPE; change it to try out different models ``` import os PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID BUCKET = 'cloud-traini...
github_jupyter
# Batch Normalization One way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. One idea along these lines is batch normalization which was proposed...
github_jupyter
There was some problem in building the past .ttl file. I'll redo the steps and debug. Now that the entities are on Wikidata, while there is no has_positive_marker property there, we can make a local RDF file using Wikidata IDs. ``` import pandas as pd gene_reference = pd.read_csv("../results/human_gene_reference_fr...
github_jupyter
## Import our modules. Remember it is always good to do this at the begining of a notebook. If you don't have seaborn, you can install it with `conda install seaborn`. ``` import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ``` ### Use the notebook magic to render matplotlib figures inline wit...
github_jupyter
``` import os import pandas as pd import numpy as np import json import pickle from pprint import pprint from collections import defaultdict from pathlib import Path import matplotlib.pyplot as plt import seaborn as sns import torch import os, sys parentPath = os.path.abspath("..") if parentPath not in sys.path: ...
github_jupyter
# Load packages ``` %matplotlib inline from ifis_tools import database_tools as db from ifis_tools import asynch_manager as am from ifis_tools import auxiliar as aux from wmf import wmf import pandas as pd import numpy as np import os import pylab as pl from string import Template from param_ident import core f...
github_jupyter
## Herramientas En este taller usamos pandas, sklearn y OpenCV, las siguientes celdas muestran algunos metodos que usaremos [Pandas](https://pandas.pydata.org/) Es una librería muy útil para trabajar con datos tabulares. Es muy común encontrarla en el análisis de datos y en procesos de Machine Learning. En este talle...
github_jupyter
<a href="https://colab.research.google.com/github/wileyw/DeepLearningDemos/blob/master/handwriting_generator/IBM_Transformer%2BTimeEmbedding.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Notebook Original code from here: [code](https://github.co...
github_jupyter
<span style="color:red; font-family:Helvetica Neue, Helvetica, Arial, sans-serif; font-size:2em;">An Exception was encountered at '<a href="#papermill-error-cell">In [2]</a>'.</span> ``` # Parameters msgs = "Ran from Airflow at 2022-03-20T18:04:11.892055+00:00!" ``` <span id="papermill-error-cell" style="color:red; f...
github_jupyter
## Thermally driven Convection -pt 2 Analysis of the convection run, and more advanced behaviour **New concepts:** Advection-diffusion solver template, thermal boundary conditions, Rayleigh number, analysis functions, interpolation **NOTE:** I saved all the python setup of the previous notebook in a file so we don...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt file = pd.read_csv("mamographic.csv",sep=',', na_values=["?"]) print(file.tail()) file.isnull().values.any() file.columns[file.isnull().any()] file.describe() file['BI-RADS'].fillna(file['BI-RADS'].mean(),inplace=True) file['Age'].fillna(file['...
github_jupyter
# UBI-FIT (flat income tax) For each level of a UBI, calculate the required flat income tax rate, and associated measures like poverty rate (depth) and inequality. * Disruption: average decrease to after-tax income (also per person) * Gini per person *Data: CPS | Tax year: 2018 | Type: Static | Author: Max Ghe...
github_jupyter
## datasets This module has the necessary functions to be able to download several useful datasets that we might be interested in using in our models. ``` from fastai.gen_doc.nbdoc import * from fastai.datasets import * from fastai.datasets import Config from pathlib import Path show_doc(URLs) ``` This contains all...
github_jupyter
[Deep Learning Summer School 2019](http://2019.dl-lab.eu) in Gdansk, Poland Ordinal Regression Tutorial by [Sebastian Raschka](https://sebastianraschka.com) GitHub Repository: https://github.com/rasbt/DL-Gdasnk2019-tutorial ``` %load_ext watermark %watermark -a 'Sebastian Raschka' -v -p torch ``` # Modifying the ...
github_jupyter
``` import numpy as np from astropy.table import Table from scipy.sparse import lil_matrix from sklearn.cluster import DBSCAN from sklearn.neighbors import NearestNeighbors import time def jaccard(a,b): """ Calculate Jaccard distance between two arrays. :param a: array array of neighbors :param ...
github_jupyter
``` %load_ext watermark %watermark -d -u -a 'Andreas Mueller, Kyle Kastner, Sebastian Raschka' -v -p numpy,scipy,matplotlib,scikit-learn ``` # SciPy 2016 Scikit-learn Tutorial # Model Evaluation, Scoring Metrics, and Dealing with Class Imbalances In the previous notebook, we already went into some detail on how to ...
github_jupyter
# Creating a Bathymetric Surface from ICESAT-2 data The spaceborne ICESAT-2 LiDAR instrument is a photo counting LiDAR which has a wavelength of 532 nm. At this wavelength the signal penetrates into waterbodies and therefore point samples of water depths can be retrived (e.g., Thomas et al., 2021) down to 40 m in dept...
github_jupyter
``` # MATH FUNCTIONS IN PYTHON # SOURCE - https://docs.python.org/3/library/math.html #-------------------------------------------------------------------------------------------------- # first we need to import the math module # This module provides access to the mathematical functions defined by the C standard. # # ...
github_jupyter
``` from sklearn.preprocessing import LabelBinarizer from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, model_from_json from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau from keras.constraints import maxnorm from ...
github_jupyter
# Cats and Dogs Problem Solution The inspiration for this script comes from a beautiful [keras blog](https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html). ``` #Imports import os from random import shuffle #Keras imports from keras.preprocessing.image import ImageDataGenera...
github_jupyter
# PageRank In this notebook, we will use both NetworkX and cuGraph to compute the PageRank of each vertex in our test dataset. The NetworkX and cuGraph processes will be interleaved so that each step can be compared. Notebook Credits * Original Authors: Bradley Rees and James Wyles * Created: 08/13/2019 * Updated:...
github_jupyter
# Итерационные методы для собственных значений ## PINVIT - Идея - минимизировать отношение Релея - Используем градиентный спуск предобусловленный матрицей $(A - \sigma I)$ ``` import numpy as np import scipy.sparse.linalg as spsplin import scipy.sparse as spsp def pinvit(A, x0, sigma, tau, num_iter, tol, inexact=Tr...
github_jupyter
# Accessing and Processing the Optical Absorption and Attenuation (OPTAA) Data from OOI OOI uses the [Sea-Bird Electronics, AC-S In-Situ Spectrophotometer](https://www.seabird.com/ac-s-spectral-absorption-and-attenuation-sensor/product?id=60762467715) to measure the in situ absorption and beam attenuation coefficients...
github_jupyter
# Pricing assets with the risk-free metric ## Vanilla assets 1. Based on mainly observations select a microscopic process that generates the price path of the asset or its underlier.<br/> For example, in the simplest case this microscopic process is a normalized random walk with a constant drift. 2. Generate paths wit...
github_jupyter
``` import matplotlib %matplotlib inline import matplotlib.pyplot as plt import numpy as np import deepthought, mne, os from deepthought.util.logging_util import configure_custom configure_custom(debug=False) mne.set_log_level('INFO') ### TODO: change this for each subject subject = 'P01' from deepthought.datasets....
github_jupyter
``` import csv import pandas as pd from collections import Counter from collections import defaultdict from matplotlib import pyplot as plt from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import OneHotEncoder from sklearn.metri...
github_jupyter
This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # Challenge Notebook ## Problem: Add two numbers whose digits are stored in a linked list in reverse order. * [Constraints](#Constraints) * [Test...
github_jupyter
# Keyboard BCI The name "brain-computer interface" suggests that you're using your brain to control a computer. In this notebook, we build a BCI whose `action` is to send keystrokes to the computer. You can probably think of a number of different applications for something like this. One example would be to use your ...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive', force_remount = True) %tensorflow_version 2.x !pip uninstall keras -y !pip uninstall keras-nightly -y !pip uninstall keras-Preprocessing -y !pip uninstall keras-vis -y !pip uninstall tensorflow -y !pip install napari[all] !pip install tensorflow==2.2.0 !p...
github_jupyter
<h1>gcForest Algorithm</h1> <p>The gcForest algorithm was suggested in Zhou and Feng 2017 ( https://arxiv.org/abs/1702.08835 , refer for this paper for technical details) and I provide here a python3 implementation of this algorithm.<br> I chose to adopt the scikit-learn syntax for ease of use and hereafter I present ...
github_jupyter
# 회귀분석 ## 검증하고자 하는 것 : 맛집 프로그램별 SNS채널(네이버 블로그)에 미치는 영향력 ### 분석계획 ### 1. 독립변수에 방송 프로그램 외 변수들을 추가하면서 R^2가 높아지는지 확인 & R^2가 가장 높은 회귀식 도출 ### 2. 방송 프로그램별 회귀식을 만들어 포스팅 증가에 가장 영향을 미치는 요인 찾아보기 ### 3. 2017년 데이터(train set)로 회귀식을 만든 후, 2018년 데이터(test set)로 예측해보고 정확도 확인 ``` import pandas as pd import numpy as np import statsmo...
github_jupyter
# Swedes without any close friends This notebook explores and visualizes the proportion of Swedes stating they have no close friends. - Date: 2019-04-04 - Source: [SCB: Undersökningarna av levnadsförhållanden](http://www.statistikdatabasen.scb.se/pxweb/sv/ssd/START__LE__LE0101__LE0101R/LE0101R07/?rxid=710c09ba-1e21-4...
github_jupyter
#### Copyright 2017 Google LLC. ``` # 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 agreed to in writin...
github_jupyter
# Sampler statistics When checking for convergence or when debugging a badly behaving sampler, it is often helpful to take a closer look at what the sampler is doing. For this purpose some samplers export statistics for each generated sample. ``` import numpy as np import matplotlib.pyplot as plt import seaborn as sb...
github_jupyter
``` # Load Packages import pandas as pd import numpy as np import random import sklearn from sklearn.model_selection import LeaveOneOut from sklearn import preprocessing from matplotlib import pyplot as plt %matplotlib inline # load window methylation data A = pd.read_csv("Window_Meth.csv") # load window methylation da...
github_jupyter
# t-test ___ There may be situations where the standard deviation of the population is unknown, and the sample size is small. In all such cases, we use the T-distribution. This distribution is also called *Student’s T distribution*. The following are the chief characteristics of the T-distribution: + The T-distribut...
github_jupyter
``` import sys # Add the path to system, local or mounted S3 bucket, e.g. /dbfs/mnt/<path_to_bucket> sys.path.append('./secrets.py') import logging import math import os from influxdb import DataFrameClient import numpy as np import matplotlib.mlab as mlab import pandas as pd import matplotlib.pyplot as plt from tabu...
github_jupyter
# Math - Algebra [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rhennig/EMA6938/blob/main/Notebooks/4.Math_Algebra.ipynb) (Based on https://online.stat.psu.edu/stat462/node/132/ and https://www.geeksforgeeks.org/ml-normal-equation-in-linear-regres...
github_jupyter
# An intro to Python & Jupyter notebooks This is a jupyter notebook! It is actually running in your browser and translating it into Python! Super neat. It allows us to write text AND code in the same place. For example, this is a markdown cell where I can write myself notes. First we'll take a tour of jupyter not...
github_jupyter
# N-grams ## Overview An *n-gram* -- in the context of parsing natural languages such as English -- is a sequence of *n* consecutive *tokens* (which we might define as characters separated by whitespace) from some passage of text. Based on the following passage: > I really really like cake. We have the following 2-...
github_jupyter
# Wavelets and sweeps This notebook looks at the convolutional model of a seismic trace — first with an impulse-type wavelet, such as a Ricker — then with a simulated Vibroseis sweep. First, the usual preliminaries. ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ## Load geophysical d...
github_jupyter
``` import syft as sy ``` # Part 1: Launch a Duet Server ``` duet = sy.launch_duet(loopback=True) ``` # Part 2: Upload data to Duet Server ``` import torch as th # Data owner has age data of 6 people age_data = th.tensor([25, 32, 49, 65, 88, 22]) # Data owner names the data with tag "ages" age_data = age_data.tag...
github_jupyter
``` from abc import ABCMeta, abstractmethod, abstractproperty import enum import numpy as np np.set_printoptions(precision=3) np.set_printoptions(suppress=True) import pandas from matplotlib import pyplot as plt %matplotlib inline ``` ## Bernoulli Bandit We are going to implement several exploration strategies for...
github_jupyter
``` from pathlib import Path import numpy as np import pandas as pd from gensim.models import Doc2Vec from gensim.models.doc2vec import TaggedDocument import logging import warnings from random import shuffle import lightgbm as lgb from sklearn.model_selection import train_test_split from sklearn.linear_model import Lo...
github_jupyter
## 02. Multiple Parameters In this tutorial, you will learn how to: * Optimize the Objective Function with Multiple HyperParameters * Define different types of Search Space 在本教程中,您将学习如何: * 优化多超参数的目标函数 * 定义不同类型的搜索空间 ### Optimizing Multi Parameters Objective function ``` # import fmin interface from UltraOpt from u...
github_jupyter
# Comparative analysis ## Imports & Parameters ``` import os, sys import json import numpy as np import matplotlib.pyplot as plt import pandas as pd import rasterio from tqdm import tqdm_notebook as tqdm from sklearn.model_selection import train_test_split from itertools import product from functools import partial f...
github_jupyter
``` #Importing Environment and ImpStates from env_2_stochastic_high import Environment2,StartandGoal,ImportDynamics from SophAgent import SophAgentActions from QlearningAgent import QAgent [startstate,goalstate]=StartandGoal() #Btrue is only used for plotting-model Accuracy Btrue=ImportDynamics() import numpy as np imp...
github_jupyter
##### Copyright 2019 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); ``` #@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.o...
github_jupyter
# Desenhos de Curvas a partir da Curvatura **Autor:** Leonardo Dantas Este trabalho explora o uso da computação simbólica e numérica no estudo da curvatura. Como decorrência do Teorema Fundamental da Teoria Local das Curvas Planas, curvas planas podem ser desenhadas puramente a partir de suas funções de curvatura, des...
github_jupyter
``` # 챗봇, 번역, 이미지 캡셔닝등에 사용되는 시퀀스 학습/생성 모델인 Seq2Seq 을 구현해봅니다. # 영어 단어를 한국어 단어로 번역하는 프로그램을 만들어봅니다. import tensorflow as tf import numpy as np # S: 디코딩 입력의 시작을 나타내는 심볼 # E: 디코딩 출력을 끝을 나타내는 심볼 # P: 현재 배치 데이터의 time step 크기보다 작은 경우 빈 시퀀스를 채우는 심볼 # 예) 현재 배치 데이터의 최대 크기가 4 인 경우 # word -> ['w', 'o', 'r', 'd'] # to...
github_jupyter
# Building Fast Queries on a CSV Skills: Object Oriented Programming, Time and Space Complexity Analysis We will imagine that we own an online laptop store and want to build a way to answer a few different business questions about our inventory. ``` # Open and explore the dataset import csv with open('laptops.csv') ...
github_jupyter
``` from IPython.core.display import display, HTML, Markdown, clear_output, Javascript from string import Template import pandas as pd import json, random import yaml import copy import networkx as nx import math import xml.etree.ElementTree as ET import ipywidgets as widgets import os import time import os.path from o...
github_jupyter
# Sample Hangul RNN ``` # -*- coding: utf-8 -*- # Import Packages import numpy as np import tensorflow as tf import collections import string import argparse import time import os from six.moves import cPickle from TextLoader import * from Hangulpy import * print ("Packages Imported") ``` # Load dataset using TextLoa...
github_jupyter
# Tutorial 2 for Python ## Make a scenario of Dantzig's Transport Problem using the *ix modeling platform* (ixmp) <img style="float: right; height: 80px;" src="_static/python.png"> ### Aim and scope of the tutorial This tutorial uses teh transport problem scenario developed in the first tutorial and illustrates how...
github_jupyter
``` %%writefile morse.py # A lookup dictionary which, given a letter will return the morse code equivalent _letter_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.'...
github_jupyter
# Data Augmentation We'll show you examples of data augmentation with various techniques such as [MixUp](https://openreview.net/pdf?id=r1Ddp1-Rb), [CutMix](http://openaccess.thecvf.com/content_ICCV_2019/papers/Yun_CutMix_Regularization_Strategy_to_Train_Strong_Classifiers_With_Localizable_Features_ICCV_2019_paper.pdf),...
github_jupyter
``` import numpy as np def CSR_to_DNS(data, col, rowptr, shape): A = np.zeros(shape) counter = 0 row = 0 for i in range(len(data)): while counter >= rowptr[row+1]: row += 1 A[row][col[i]] = data[i] counter += 1 return A def DNS_to_CSR(A): data = [] col = [...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np from scipy import stats ``` # Gibbs sampling for a one sample t-test Chapter 3.2.1: Gibbs sampling Assume $Y_i \mid \mu,\sigma^2\sim\mbox{Normal}(\mu,\sigma^2)$ for $i=1,\dots,n$ and let the prior distributions be $\mu\sim\mbox{Normal}\left(0,\frac{\sigma^2}{m}...
github_jupyter
# ***Video da apresentação:*** --- # https://youtu.be/-5xjHpiqnL0 **bold text** ``` from google.colab import drive drive.mount('/gdrive') %cd /gdrive !pip install icc_rt #!pip uninstall icc_rt import pandas as pd import numpy as np import gensim import multiprocessing import sklearn.preprocessing as pp import warn...
github_jupyter
# Classifying Bangla Fake News with HuggingFace Transformers and Fastai - toc: true - branch: master - badges: true - comments: true - categories: [fastpages, jupyter] - image: images/some_folder/your_image.png - hide: false - search_exclude: true - metadata_key1: metadata_value1 - metadata_key2: metadata_value2 ![]...
github_jupyter
# 线性回归的简洁实现 随着深度学习框架的发展,开发深度学习应用变得越来越便利。实践中,我们通常可以用比上一节更简洁的代码来实现同样的模型。在本节中,我们将介绍如何使用tensorflow2.0推荐的keras接口更方便地实现线性回归的训练。 ## 生成数据集 我们生成与上一节中相同的数据集。其中`features`是训练数据特征,`labels`是标签。 ``` import tensorflow as tf num_inputs = 2 num_examples = 1000 true_w = [2, -3.4] true_b = 4.2 features = tf.random.normal(shape=(num_...
github_jupyter
# Getting Started With VerifyML A quickstart guide to documenting your model findings in a VerifyML Model Card. ## Installation ``` !pip install verifyml !pip install seaborn ``` ## Imports ``` import pandas as pd import verifyml.model_card_toolkit as mctlib import verifyml.model_tests.utils as utils import seabor...
github_jupyter
# ARAS Datasets H. Alemdar, H. Ertan, O.D. Incel, C. Ersoy, ARAS Human Activity Datasets in Multiple Homes with Multiple Residents, Pervasive Health, Venice, May 2013. ``` import sys sys.path.append("../..") import pandas as pd import matplotlib.pyplot as plt import pyadlml import requests import plotly plotly.offline...
github_jupyter
## Computer Vision Learner [`vision.learner`](/vision.learner.html#vision.learner) is the module that defines the [`cnn_learner`](/vision.learner.html#cnn_learner) method, to easily get a model suitable for transfer learning. ``` from fastai.gen_doc.nbdoc import * from fastai.vision import * ``` ## Transfer learning...
github_jupyter
##### Copyright 2019 Qiyang Hu ``` #@title Licensed under MIT License (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://huqy.github.io/idre_learning_machine_learning/LICENSE.md # # Unless required by applicable law or agreed to in ...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib notebook ``` # Conditional Entropy: Can Information Theory Beat the L-S Periodogram? **Version 0.1** *** By AA Miller 5 June 2019 In this lecture we will examine alternative methods to search for periodic signals in astronomical ...
github_jupyter
<a href="https://colab.research.google.com/github/ikonushok/My_projects/blob/main/%D0%A0%D0%B0%D0%B7%D0%B1%D0%BE%D1%80_HW4_UltraPro_%D0%A3%D0%B3%D0%BB%D1%83%D0%B1%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_%D0%B2_RNN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a...
github_jupyter
# Ensembling Feature Overview Ensembling is a fancy name for sub-sampling the data and generating $n_\text{models}$ from regressing onto each of these sub-samples. In practice this helps to robustify the regressions against outliers and other issues. We highly recommend checking out the following paper for understandin...
github_jupyter
``` %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt from awave.experimental.filters import gabor_filter, edge_filter, curve_filter from awave.experimental.filters_agg import * import awave.experimental.viz as viz from tqdm import tqdm ``` # look at base filters ``` filter_size = ...
github_jupyter
# Classification on Iris dataset with sklearn and DJL In this notebook, you will try to use a pre-trained sklearn model to run on DJL for a general classification task. The model was trained with [Iris flower dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set). ## Background ### Iris Dataset The dataset c...
github_jupyter