markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Backtest Get ModelsIn cases where `BackTester` doesn't cut it or for more custom use-cases, there's an interface to export the `TimeSeriesSplitter` and predicted data, as shown earlier. It's also possible to get each of the fitted models for deeper diving
fitted_models = bt.get_fitted_models() model_1 = fitted_models[0] model_1.get_regression_coefs()
_____no_output_____
Apache-2.0
docs/tutorials/backtest.ipynb
goncaloperes/orbit
BackTester composes a TimeSeriesSplitter within it, but TimeSeriesSplitter can also be created on its own as a standalone object. See section below on TimeSeriesSplitter for more details on how to use the splitter.All of the additional TimeSeriesSplitter args can also be passed into BackTester on instantiation
ts_splitter = bt.get_splitter() _ = ts_splitter.plot()
_____no_output_____
Apache-2.0
docs/tutorials/backtest.ipynb
goncaloperes/orbit
Hyperparameter TunningAfter seeing the results fromt the backtest, users may wish to fine tune the hyperparmeters. Orbit also provide a `grid_search_orbit` utilities for parameter searching. It uses `Backtester` under the hood so users can compare backtest metrics for different paramters combination.
from orbit.utils.params_tuning import grid_search_orbit # defining the search space for level smoothing paramter and seasonality smooth paramter param_grid = { 'level_sm_input': [0.3, 0.5, 0.8], 'seasonality_sm_input': [0.3, 0.5, 0.8], } # configs min_train_len = 380 # in case of rolling window, this specify ...
_____no_output_____
Apache-2.0
docs/tutorials/backtest.ipynb
goncaloperes/orbit
Gemetric Test of Reciprocity Moment Tensors Step 0Load packages
#load all packages import datetime import pickle import copy import os from sys import argv from pathlib import Path import numpy as np import pandas as pd import pyvista as pv import matplotlib.pyplot as plt from matplotlib.colors import Normalize from pyaspect.project import * from pyaspect.model.gridmod3d impor...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Step 1 Extract the ndarray of the subsampled, smoothed NAM model and instantiate a new GriddedModel3D object for QC'ing
data_in_dir = 'data/output/' data_out_dir = data_in_dir !ls {data_in_dir} !ls data/groningen
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Step 6 Decompress the ndarray of the sliced, subsampled, smoothed NAM model and instantiate a new GriddedModel3D object for QC'ing
# set filename then used it to decompress model ifqn = f'{data_out_dir}/vsliced_subsmp_smth_nam_2017_vp_vs_rho_Q_model_dx100_dy100_dz100_maxdepth5850_sig250.npz' vslice_gm3d, other_pars = decompress_gm3d_from_file(ifqn) print() print('decompressed gridded model\n:',vslice_gm3d) print() print('other parameters:\n',oth...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
create virtual recievers (CMT solutions in forwards sense)
#coords = vslice_gm3d.getGlobalCoordsPointsXYZ() coords = vslice_gm3d.getLocalCoordsPointsXYZ() coords[:,2] = -coords[:,2] xc = np.unique(coords.T[0,:]) yc = np.unique(coords.T[1,:]) zc = np.unique(coords.T[2,:]) #n_rand_p = 1000 n_rand_p = 3 np.random.seed(n_rand_p) #nothing special about using n_rand_p just want ...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make Moment Tensors and CMTSolutionHeaders for each tensor
def CMTtoM0(CMTsol): A = np.array(([CMTsol[0],CMTsol[3],CMTsol[4]], [CMTsol[3],CMTsol[1],CMTsol[5]], [CMTsol[4],CMTsol[5],CMTsol[2]])) M0 = ((1/np.sqrt(2))*np.sqrt(np.sum(A*A))) return(M0) def aki_from_sdr(strike,dip,rake,M0): from math import sin,cos p...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
this is the path to the project dir on the clustermy_proj_dir = '/scratch/seismology/tcullison/test_mesh/FWD_Batch_Src_Test'm0 = 1mW = (np.log10(m0)-9.1)/1.5print(f'mW = {mW}')(mnn, mee, mdd, mne, mnd, med, magnitude)((mnn, mne, mnd), (mne, mee, med), (mnd, med, mdd))Mnn = MomentTensor.from_values((0,0,0, 1, 0, 0, m...
# this is the path to the project dir on the cluster my_proj_dir = '/scratch/seismology/tcullison/test_mesh/FWD_Batch_Src_Test' m0 = 1 mW = (np.log10(m0)-9.1)/1.5 #(mnn, mee, mdd, mne, mnd, med, magnitude) #((mnn, mne, mnd), (mne, mee, med), (mnd, med, mdd)) h_mat_xy = np.array([[0, 0,0],[ 0,0,-1],[0,-1,0]]) h_mat_...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make Corresponding "Virtual" Recievers (including cross membors for derivatives) for the CMT's
m_delta = 25.0 # distance between cross stations for derivatives assert m_delta < xy_pad #see cells above this is padding #l_grp_vrecs = make_grouped_half_cross_reciprocal_station_headers_from_cmt_list(l_cmt_srcs,m_delta) l_grp_vrecs = make_grouped_cross_reciprocal_station_headers_from_cmt_list(l_cmt_srcs,m_delta) ig ...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Plot Virtual Receiver Groups
all_g_xyz = get_xyz_coords_from_station_list(flatten_grouped_headers(l_grp_vrecs)) all_g_xyz[:,2] *= -1 #pyview z-up positive and oposize sign of standard geophysics pv_all_points = pv.wrap(all_g_xyz) p = pv.Plotter() p.add_mesh(grid,cmap=cmap,opacity=0.5) #p.add_mesh(slices,cmap=cmap,opacity=1.0) p.add_mesh(pv_all_po...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make real-receivers/virtual-sources
h = 3000 rec_z = -200 vsrc_rec_xyz = np.zeros((9,3)) for i in range(vsrc_rec_xyz.shape[0]): vsrc_rec_xyz[i,:] = vrec_cmt_xyz[0,:] vsrc_rec_xyz[i,2] = rec_z # x-h, y-y vsrc_rec_xyz[0,0] = vrec_cmt_xyz[0,0] - h vsrc_rec_xyz[0,1] = vrec_cmt_xyz[0,1] - h # x, y-y vsrc_rec_xyz[1,1] = vrec_cmt_xyz[0,1] -...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Plot virtual sources (red) with virtual receivers (white)
pv_spoints = pv.wrap(vsrc_rec_xyz) p = pv.Plotter() #p.add_mesh(slices,cmap=cmap,opacity=0.50) p.add_mesh(grid,cmap=cmap,opacity=0.3) p.add_mesh(pv_spoints, render_points_as_spheres=True, point_size=8,opacity=1,color='red') #p.add_mesh(pv_rpoints, render_points_as_spheres=True, point_size=5,opacity=0.5) p.add_mesh(all_...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make StationHeaders (real recievers/virtual sources)
l_real_recs = [] for i in range(len(vsrc_rec_xyz)): tr_bname = 'tr' new_r = StationHeader(name=tr_bname, network='NL', #FIXME lon_xc=vsrc_rec_xyz[i,0], lat_yc=vsrc_rec_xyz[i,1], depth=-vsrc_rec_xyz[i,2],...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make ForceSolutionHeaders for the above virtual sources (including force-triplets for calculation derivatives)
l_grp_vsrcs = make_grouped_reciprocal_force_solution_triplet_headers_from_rec_list(l_real_recs)
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make replicates of each virtual receiver list: one for each force-triplet
l_grp_vrecs_by_vsrcs = make_replicated_reciprocal_station_headers_from_src_triplet_list(l_grp_vsrcs, l_grp_vrecs)
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Plot virtual sources (red) and virtual receivers (white) FROM headers
grp_s_xyz = get_unique_xyz_coords_from_solution_list(flatten_grouped_headers(l_grp_vsrcs)) grp_s_xyz[:,2] *= -1 #pyvista z-up is positive flat_recs = flatten_grouped_headers(flatten_grouped_headers(l_grp_vrecs_by_vsrcs)) grp_r_xyz = get_unique_xyz_coords_from_station_list(flat_recs) grp_r_xyz[:,2] *= -1 #pyvista z-up ...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make replicates of each "real" receiver list: for each CMT source
l_grp_recs_by_srcs = make_replicated_station_headers_from_src_list(l_cmt_srcs,l_real_recs) for i in range(len(l_cmt_srcs)): print(f'***** SRC Records for Source: {i} *****\n') for j in range(len(l_real_recs)): print(f'*** REC Header for Receiver: {j} ***\n{l_grp_recs_by_srcs[i][j]}')
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Plot "real" sources (red) and virtual receivers (white) FROM headers
grp_s_xyz = get_unique_xyz_coords_from_solution_list(l_cmt_srcs) grp_s_xyz[:,2] *= -1 #pyvista z-up is positive flat_recs = flatten_grouped_headers(l_grp_recs_by_srcs) #real! grp_r_xyz = get_unique_xyz_coords_from_station_list(flat_recs) grp_r_xyz[:,2] *= -1 #pyvista z-up is positive print(len(grp_s_xyz)) print(len(g...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make reciprical RecordHeader
l_flat_vsrcs = flatten_grouped_headers(l_grp_vsrcs) l_flat_vrecs = flatten_grouped_headers(flatten_grouped_headers(l_grp_vrecs_by_vsrcs)) vrecord_h = RecordHeader(name='Reciprocal-Record',solutions_h=l_flat_vsrcs,stations_h=l_flat_vrecs) print(vrecord_h) # save the header to disc vrec_fqp = os.path.join(data_out_dir,...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make reciprocal project
test_proj_name = 'ReciprocalGeometricTestProject' test_proj_root_fqp = os.path.join(data_out_dir, 'tmp/TestProjects/NewMKProj') test_parfile_fqp = os.path.join(data_out_dir, 'Par_file') test_mesh_fqp = '/scratch/seismology/tcullison/test_mesh/MESH-default_batch_force_src' test_spec_fqp = '/quanta1/home/tcullison/DevG...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make Forward/Real RecordHeader
l_flat_srcs = l_cmt_srcs #NOTE: we don't need to flatten CMT list because they are not grouped l_flat_recs = flatten_grouped_headers(l_grp_recs_by_srcs) #Note: only one level of flattening record_h = RecordHeader(name='Forward-Record',solutions_h=l_flat_srcs,stations_h=l_flat_recs) print(f'Forward Record:\n{record_h}'...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Make "real" project
test_real_proj_name = 'ForwardGeometricTestProject' test_proj_root_fqp = os.path.join(data_out_dir, 'tmp/TestProjects/NewMKProj') test_parfile_fqp = os.path.join(data_out_dir, 'Par_file') test_mesh_fqp = '/scratch/seismology/tcullison/test_mesh/MESH-default_batch_force_src' test_spec_fqp = '/quanta1/home/tcullison/De...
_____no_output_____
Apache-2.0
notebooks/Make_Project_Geometric_Elementary_Moment_Tensor_Reciprocity.ipynb
code-cullison/pyaspect
Diagnosing Loss
import torch from torch.utils.data import DataLoader trainloader = DataLoader(train) for idx, (data, label) in enumerate(trainloader): logits = model(data) losses = [] print(label) for i in range(len(label[0])): print(i) loss = F.cross_entropy(logits[i], torch.tensor((label[:,i],))) ...
_____no_output_____
MIT
notebooks/example_script.ipynb
jacobhinkle/bayescache
Shape of Things to Come:
data, labels = train.load_data() len(labels) len(labels[:,0]) import numpy as np unq, counts = np.unique(labels[:,0], return_counts=True) unq counts data[0].shape sum(counts) data.shape labels data
_____no_output_____
MIT
notebooks/example_script.ipynb
jacobhinkle/bayescache
Representação numérica de palavras e textos Neste notebook iremos apresentação formas de representar valores textuais por meio de representação numérica. Iremos usar pandas, caso queira entender um pouco sobre pandas, [veja este notebook](pandas.ipynb). Por isso, não esqueça de instalar o módulo pandas:``pip3 install ...
import pandas as pd df_jogos = pd.DataFrame([ ["boa","nublado","não"], ["boa","chuvoso","não"], ["média","nublado","sim"], ["fraca","chuvoso","não"]], columns=["disposição","tempo","jogar volei?"]) df_jogos
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Caso quisermos maperar cada coluna (agora chamada de atributo) para um valor, forma mais simples de se fazer a transformação é simplesmente mapear esse atributo para um valor numérico. Veja o exemplo abaixo: Nesse exemplo, temos dois atributos disposição do jogador e tempo e queremos prever se o jogar irá jogar volei ...
from typing import Dict def mapeia_atributo_para_int(df_data:pd.DataFrame, coluna:str, dic_nom_to_int: Dict[int,str]): for i,valor in enumerate(df_data[coluna]): valor_int = dic_nom_to_int[valor] df_data[coluna].iat[i] = valor_int df_jogos = pd.DataFrame([ ["boa","nublado","sim"], ...
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Binarização dos atributos categóricos Podemos fazer a binarização dos atributos categóricos em que, cada valor de atributo transforma-se em uma coluna que recebe `0` caso esse atributo não exista e `1`, caso contrário. Em nosso exemplo:
from preprocessamento_atributos import BagOfItems df_jogos = pd.DataFrame([ [4, "boa","nublado","sim"], [3,"boa","chuvoso","não"], [2,"média","ensolarado","sim"], [1,"fraca","chuvoso","não"]], columns=["id","dispos...
0/4
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Como existem vários valores no teste que você desconhece, se fizermos dessa forma, atributos que estão no teste poderiam estar completamente zerados no treino, sendo desnecessário, por exemplo:
df_jogos_treino = df_jogos[:2] df_jogos_treino df_jogos_teste = df_jogos[2:] df_jogos_teste
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Exemplo Real Considere este exemplo real de filmes e seus atores ([obtidos no kaggle](https://www.kaggle.com/rounakbanik/the-movies-dataset)):
import pandas as pd df_amostra = pd.read_csv("movies_amostra.csv") df_amostra
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Nesse exemplo, as colunas que representam os atores principais podem ser binarizadas. Em nosso caso, podemos colocar os atores todos em um "Bag of Items". Os atores são representados por as colunas `ator_1`, `ator_2`,..., `ator_5`. Abaixo, veja um sugestão de como fazer em dataset:
import pandas as pd from preprocessamento_atributos import BagOfItems obj_bag_of_actors = BagOfItems(min_occur=3) #boa=bag of actors ;) df_amostra_boa = obj_bag_of_actors.cria_bag_of_items(df_amostra,["ator_1","ator_2","ator_3","ator_4","ator_5"]) df_amostra_boa
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Veja que temos bastante atributos um para cada ator. Mesmo sendo melhor possuirmos poucos atributos e mais informativos, um método de aprendizado de máquina pode ser capaz de usar essa quantidade de forma eficaz. Particularmente, o [SVM linear](https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.htm...
#supondo que 80% da amostra é treino df_treino_amostra = df_amostra.sample(frac=0.8, random_state = 2) df_teste_amostra = df_amostra.drop(df_treino_amostra.index) #min_occur=3 definie o minimo de ocorrencias desse ator para ser considerado #pois, um ator que apareceu em poucos filmes, pode ser menos relevante para a p...
0/2400 1000/2400 2000/2400 0/600
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Representação Bag of Words Muitas vezes, temos textos que podem ser relevantes para uma determinada tarefa de aprendizado d máquina. Por isso, temos que representar tais elementos para nosso método de aprendizado de máquina. A forma mais usual para isso, é a `Bag of Words` em que cada palavra é um atributo e, o valor ...
dic_bow = {"a":[1,1], "casa":[1,1], "é":[1,1], "verde":[0,2] } df_bow = pd.DataFrame.from_dict(dic_bow) df_bow
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Da forma que fizemos acima, usamos a frequencia de um termo para definir sua importancia no texto, porém, existem termos que possuem uma frequencia muito alta e importancia baixa: são os casos dos artigos e preposições por exemplo, pois, eles não discriminam o texto. Uma forma de mensurar o porder discriminativo das pa...
import math N = 1000 n_de = 900 n_bebida = 500 n_cerveja = 100 IDF_de = math.log(N/n_de) IDF_bebida = math.log(N/n_bebida) IDF_cerveja = math.log(N/n_cerveja) print(f"IDF_de: {IDF_de}\tIDF_bebida:{IDF_bebida}\tIDF_cerveja:{IDF_cerveja}")
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
A biblioteca `scikitlearn`também já possui uma classe [TFIDFVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) que transforma um texto em um vetor de atributos usando o TF-IDF para o valor referente a relevancia deste termo. Veja um exemplo na coluna `res...
import pandas as pd from preprocessamento_atributos import BagOfWords df_amostra = pd.read_csv("datasets/movies_amostra.csv") bow_amostra = BagOfWords() df_bow_amostra = bow_amostra.cria_bow(df_amostra,"resumo") df_bow_amostra
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
Como são muitos atributos, pode parecer que não ficou corretamente gerado. Mas, filtrando as palavras de um determinado resumo você verificará que está ok:
df_bow_amostra[["in","lake", "high"]]
_____no_output_____
CC-BY-4.0
pln/binarizacao_e_tf_idf.ipynb
IagorSs/roteiro-projetos
""" author: Dominik Stec, index: s12623, email: s12623@pja.edu.pl To run module: import module into Google Colaboratory notebook and run. This module recognize type of clothes according to given image of clothe. Keras model is build as classification type and contains two types of classification neural network a...
%tensorflow_version 2.x import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.datasets.fashion_mnist import load_data from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense, Dropout from keras.utils import ...
real value: Sneaker
MIT
Neural_Networks/classification/3_neural_net_NAI_MNIST_clothes.ipynb
dccstcc/NAI_PJATK_2020
**Second model**
model = Sequential() model.add(Flatten(input_shape=(28, 28))) model.add(Dense(units=1024, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(units=512, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(units=512, activation='relu')) model.add(Dense(units=10, activation='softmax')) model.c...
real value: Trouser
MIT
Neural_Networks/classification/3_neural_net_NAI_MNIST_clothes.ipynb
dccstcc/NAI_PJATK_2020
Callback for RNN training> Callback that uses the outputs of language models to add AR and TAR regularization
#export @docs class RNNTrainer(Callback): "`Callback` that adds AR and TAR regularization in RNN training" def __init__(self, alpha=0., beta=0.): self.alpha,self.beta = alpha,beta def begin_train(self): self.model.reset() def begin_validate(self): self.model.reset() def after_pred(self): ...
_____no_output_____
Apache-2.0
dev/34_callback_rnn.ipynb
anhquan0412/fastai_dev
Export -
#hide from nbdev.export import notebook2script notebook2script()
Converted 00_test.ipynb. Converted 01_core.ipynb. Converted 01a_dataloader.ipynb. Converted 01a_script.ipynb. Converted 02_transforms.ipynb. Converted 03_pipeline.ipynb. Converted 04_data_external.ipynb. Converted 05_data_core.ipynb. Converted 06_data_source.ipynb. Converted 07_vision_core.ipynb. Converted 08_pets_tuto...
Apache-2.0
dev/34_callback_rnn.ipynb
anhquan0412/fastai_dev
Machine Learning Engineer Nanodegree Reinforcement Learning Project: Train a Smartcab to DriveWelcome to the fourth project of the Machine Learning Engineer Nanodegree! In this notebook, template code has already been provided for you to aid in your analysis of the *Smartcab* and your implemented learning algorithm. Y...
# Import the visualization code import visuals as vs # Pretty display for notebooks %matplotlib inline
_____no_output_____
MIT
P4-Training-a-Smart-Cab/smartcab.ipynb
yatingupta10/Machine-Learning-Nanodegree
Understand the WorldBefore starting to work on implementing your driving agent, it's necessary to first understand the world (environment) which the *Smartcab* and driving agent work in. One of the major components to building a self-learning agent is understanding the characteristics about the agent, which includes h...
# Load the 'sim_no-learning' log file from the initial simulation results vs.plot_trials('sim_no-learning.csv')
_____no_output_____
MIT
P4-Training-a-Smart-Cab/smartcab.ipynb
yatingupta10/Machine-Learning-Nanodegree
Question 3Using the visualization above that was produced from your initial simulation, provide an analysis and make several observations about the driving agent. Be sure that you are making at least one observation about each panel present in the visualization. Some things you could consider:- *How frequently is the ...
# Load the 'sim_default-learning' file from the default Q-Learning simulation vs.plot_trials('sim_default-learning.csv')
_____no_output_____
MIT
P4-Training-a-Smart-Cab/smartcab.ipynb
yatingupta10/Machine-Learning-Nanodegree
Question 6Using the visualization above that was produced from your default Q-Learning simulation, provide an analysis and make observations about the driving agent like in **Question 3**. Note that the simulation should have also produced the Q-table in a text file which can help you make observations about the agent...
# Load the 'sim_improved-learning' file from the improved Q-Learning simulation vs.plot_trials('sim_improved-learning.csv')
_____no_output_____
MIT
P4-Training-a-Smart-Cab/smartcab.ipynb
yatingupta10/Machine-Learning-Nanodegree
Hash CodesConsider the challenges associated with the 16-bit hashcode for a character string `s` that sums the Unicode values of the characters in `s`.For example, let `s = "stop"`. It's unicode character representation is:
for char in "stop": print(char + ': ' + str(ord(char))) sum([ord(x) for x in "stop"])
_____no_output_____
MIT
notebooks/computer_science/Algorithms_and_data_structures_in_python/maps_and_dictionaries/example_1.ipynb
NathanielDake/NathanielDake.github.io
If we then sum these unicode values, we arrive as the following hash code:```stop -----------> 454```The problem is, the following strings will all map to the same value!```stop -----------> 454pots -----------> 454tops -----------> 454spot -----------> 454```A better hash code would take into account the _position_ of...
1 << 32 2**32 2 << 2
_____no_output_____
MIT
notebooks/computer_science/Algorithms_and_data_structures_in_python/maps_and_dictionaries/example_1.ipynb
NathanielDake/NathanielDake.github.io
Investigate hash map uniformity
import random import numpy as np import matplotlib.pyplot as plt %config InlineBackend.figure_format='retina' n = 0 prime = 109345121 scale = 1 + random.randrange(prime - 1) shift = random.randrange(prime) def my_hash_func(k, upper): table = upper * [None] hash_code = hash(k) compressed_co...
CPU times: user 6.33 ms, sys: 413 µs, total: 6.74 ms Wall time: 6.4 ms
MIT
notebooks/computer_science/Algorithms_and_data_structures_in_python/maps_and_dictionaries/example_1.ipynb
NathanielDake/NathanielDake.github.io
The deAlmeida Overland Flow Component For more Landlab tutorials, click here: https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html This notebook illustrates running the deAlmeida overland flow component in an extremely simple-minded way on a real topography, then shows it creating a flood sequence alon...
from landlab.components.overland_flow import OverlandFlow from landlab.plot.imshow import imshow_grid from landlab.plot.colors import water_colormap from landlab import RasterModelGrid from landlab.io.esri_ascii import read_esri_ascii from matplotlib.pyplot import figure import numpy as np from time import time %matplo...
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Pick the initial and run conditions
run_time = 100 # duration of run, (s) h_init = 0.1 # initial thin layer of water (m) n = 0.01 # roughness coefficient, (s/m^(1/3)) g = 9.8 # gravity (m/s^2) alpha = 0.7 # time-step factor (nondimensional; from Bates et al., 2010) u = 0.4 # constant velocity (m/s, de Almeida et al., 2012) run_time_slices = (10, 50...
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Elapsed time starts at 1 second. This prevents errors when setting our boundary conditions.
elapsed_time = 1.0
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Use Landlab methods to import an ARC ascii grid, and load the data into the field that the component needs to look at to get the data. This loads the elevation data, z, into a "field" in the grid itself, defined on the nodes.
rmg, z = read_esri_ascii('Square_TestBasin.asc', name='topographic__elevation') rmg.set_closed_boundaries_at_grid_edges(True, True, True, True) # un-comment these two lines for a "real" DEM #rmg, z = read_esri_ascii('hugo_site.asc', name='topographic__elevation') #rmg.status_at_node[z<0.0] = rmg.BC_NODE_IS_CLOSED
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
We can get at this data with this syntax:
np.all(rmg.at_node['topographic__elevation'] == z)
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Note that the boundary conditions for this grid mainly got handled with the final line of those three, but for the sake of completeness, we should probably manually "open" the outlet. We can find and set the outlet like this:
my_outlet_node = 100 # This DEM was generated using Landlab and the outlet node ID was known rmg.status_at_node[my_outlet_node] = rmg.BC_NODE_IS_FIXED_VALUE
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Now initialize a couple more grid fields that the component is going to need:
rmg.add_zeros('surface_water__depth', at='node') # water depth (m) rmg.at_node['surface_water__depth'] += h_init
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Let's look at our watershed topography
imshow_grid(rmg, 'topographic__elevation') #, vmin=1650.0)
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Now instantiate the component itself
of = OverlandFlow( rmg, steep_slopes=True ) #for stability in steeper environments, we set the steep_slopes flag to True
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Now we're going to run the loop that drives the component:
while elapsed_time < run_time: # First, we calculate our time step. dt = of.calc_time_step() # Now, we can generate overland flow. of.overland_flow() # Increased elapsed time print('Elapsed time: ', elapsed_time) elapsed_time += dt imshow_grid(rmg, 'surface_water__depth', cmap='Blues')
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Now let's get clever, and run a set of time slices:
elapsed_time = 1. for t in run_time_slices: while elapsed_time < t: # First, we calculate our time step. dt = of.calc_time_step() # Now, we can generate overland flow. of.overland_flow() # Increased elapsed time elapsed_time += dt figure(t) imshow_grid(rmg, 's...
_____no_output_____
MIT
lessons/landlab/overland_flow_driver_for_espin.ipynb
BCampforts/espin
Predicting Boston Housing Prices Using XGBoost in SageMaker (Deploy)_Deep Learning Nanodegree Program | Deployment_---As an introduction to using SageMaker's Low Level Python API we will look at a relatively simple problem. Namely, we will use the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/data/boston/...
%matplotlib inline import os import time from time import gmtime, strftime import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_boston import sklearn.model_selection
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
In addition to the modules above, we need to import the various bits of SageMaker that we will be using.
import sagemaker from sagemaker import get_execution_role from sagemaker.amazon.amazon_estimator import get_image_uri # This is an object that represents the SageMaker session that we are currently operating in. This # object contains some useful information that we will need to access later such as our region. sessio...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Step 1: Downloading the dataFortunately, this dataset can be retrieved using sklearn and so this step is relatively straightforward.
boston = load_boston()
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Step 2: Preparing and splitting the dataGiven that this is clean tabular data, we don't need to do any processing. However, we do need to split the rows in the dataset up into train, test and validation sets.
# First we package up the input data and the target variable (the median value) as pandas dataframes. This # will make saving the data to a file a little easier later on. X_bos_pd = pd.DataFrame(boston.data, columns=boston.feature_names) Y_bos_pd = pd.DataFrame(boston.target) # We split the dataset into 2/3 training ...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Step 3: Uploading the training and validation files to S3When a training job is constructed using SageMaker, a container is executed which performs the training operation. This container is given access to data that is stored in S3. This means that we need to upload the data we want to use for training to S3. We can u...
# This is our local data directory. We need to make sure that it exists. data_dir = '../data/boston' if not os.path.exists(data_dir): os.makedirs(data_dir) # We use pandas to save our train and validation data to csv files. Note that we make sure not to include header # information or an index as this is required b...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Upload to S3Since we are currently running inside of a SageMaker session, we can use the object which represents this session to upload our data to the 'default' S3 bucket. Note that it is good practice to provide a custom prefix (essentially an S3 folder) to make sure that you don't accidentally interfere with data u...
prefix = 'boston-xgboost-deploy-ll' val_location = session.upload_data(os.path.join(data_dir, 'validation.csv'), key_prefix=prefix) train_location = session.upload_data(os.path.join(data_dir, 'train.csv'), key_prefix=prefix)
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Step 4: Train and construct the XGBoost modelNow that we have the training and validation data uploaded to S3, we can construct a training job for our XGBoost model and build the model itself. Set up the training jobFirst, we will set up and execute a training job for our model. To do this we need to specify some info...
# We will need to know the name of the container that we want to use for training. SageMaker provides # a nice utility method to construct this for us. container = get_image_uri(session.boto_region_name, 'xgboost', '0.90-1') # We now specify the parameters we wish to use for our training job training_params = {} # We...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Execute the training jobNow that we've built the dict containing the training job parameters, we can ask SageMaker to execute the job.
# First we need to choose a training job name. This is useful for if we want to recall information about our # training job at a later date. Note that SageMaker requires a training job name and that the name needs to # be unique, which we accomplish by appending the current timestamp. training_job_name = "boston-xgboos...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
The training job has now been created by SageMaker and is currently running. Since we need the output of the training job, we may wish to wait until it has finished. We can do so by asking SageMaker to output the logs generated by the training job and continue doing so until the training job terminates.
session.logs_for_job(training_job_name, wait=True)
2020-06-24 14:07:15 Starting - Launching requested ML instances......... 2020-06-24 14:08:20 Starting - Preparing the instances for training... 2020-06-24 14:09:10 Downloading - Downloading input data... 2020-06-24 14:09:27 Training - Downloading the training image..INFO:sagemaker-containers:Imported framework sag...
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Build the modelNow that the training job has completed, we have some model artifacts which we can use to build a model. Note that here we mean SageMaker's definition of a model, which is a collection of information about a specific algorithm along with the artifacts which result from a training job.
# We begin by asking SageMaker to describe for us the results of the training job. The data structure # returned contains a lot more information than we currently need, try checking it out yourself in # more detail. training_job_info = session.sagemaker_client.describe_training_job(TrainingJobName=training_job_name) m...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Step 5: Test the trained modelWe will be skipping this step for now. We will still test our trained model but we are going to do it by using the deployed model, rather than setting up a batch transform job. Step 6: Create and deploy the endpointNow that we have trained and constructed a model it is time to build the a...
# As before, we need to give our endpoint configuration a name which should be unique endpoint_config_name = "boston-xgboost-endpoint-config-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) # And then we ask SageMaker to construct the endpoint configuration endpoint_config_info = session.sagemaker_client.create_endpoint_co...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
And now that the endpoint configuration has been created we can deploy the endpoint itself.**NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important...
# Again, we need a unique name for our endpoint endpoint_name = "boston-xgboost-endpoint-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) # And then we can deploy our endpoint endpoint_info = session.sagemaker_client.create_endpoint( EndpointName = endpoint_name, EndpointConfigName =...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Just like when we created a training job, SageMaker is now requisitioning and launching our endpoint. Since we can't do much until the endpoint has been completely deployed we can wait for it to finish.
endpoint_dec = session.wait_for_endpoint(endpoint_name)
---------------!
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Step 7: Use the modelNow that our model is trained and deployed we can send test data to it and evaluate the results. Here, because our test data is so small, we can send it all using a single call to our endpoint. If our test dataset was larger we would need to split it up and send the data in chunks, making sure to ...
# First we need to serialize the input data. In this case we want to send the test data as a csv and # so we manually do this. Of course, there are many other ways to do this. payload = [[str(entry) for entry in row] for row in X_test.values] payload = '\n'.join([','.join(row) for row in payload]) # This time we use th...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
To see how well our model works we can create a simple scatter plot between the predicted and actual values. If the model was completely accurate the resulting scatter plot would look like the line $x=y$. As we can see, our model seems to have done okay but there is room for improvement.
plt.scatter(Y_test, Y_pred) plt.xlabel("Median Price") plt.ylabel("Predicted Price") plt.title("Median Price vs Predicted Price")
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Delete the endpointSince we are no longer using the deployed model we need to make sure to shut it down. Remember that you have to pay for the length of time that your endpoint is deployed so the longer it is left running, the more it costs.
session.sagemaker_client.delete_endpoint(EndpointName = endpoint_name)
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Optional: Clean upThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a ...
# First we will remove all of the files contained in the data_dir directory #!rm $data_dir/* # And then we delete the directory itself #!rmdir $data_dir
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Deploy) - Low Level.ipynb
karimhamdi/sagemaker-deployment
Машинное обучение Семинар 13. ЕМ-алгоритм9 декабря 2021 Будем решать задачу восставновления картинки лица по набору зашумленных картинок (взято с курса deep bayes 2018 https://github.com/bayesgroup/deepbayes-2018).У вас есть $K$ фотографий, поврежденных электромагнитным шумом. Известно, что на каждом фото есть лицо в...
from matplotlib import pyplot as plt import numpy as np import zipfile with zipfile.ZipFile('data_em.zip', 'r') as zip_ref: zip_ref.extractall('.') DATA_FILE = "data_em" w = 73 # face_width X = np.load(DATA_FILE) X.shape # H, W, K plt.imshow(X[:, :, 7], cmap="Greys_r") plt.axis("off") tH, tW, tw, tK = 2, 3, 1, 2 tX...
_____no_output_____
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
1. **Реализуйте calculate_log_probability**Для $k$-й картини $X_k$ и некоторой позиции $d_k$: $$ p(X_k \mid d_k,\,F,\,B,\, std) = \prod\limits_{ij}\begin{cases} \mathcal{N}(X_k[i,j]\mid F[i,\,j-d_k],\, std^2), & \text{if}\, (i,j)\in faceArea(d_k)\\ \mathcal{N}(X_k[i,j]\mid B[i,j],\, std^2), ...
import scipy.stats def calculate_log_probability(X, F, B, s): """ Calculates log p(X_k|d_k, F, B, s) for all images X_k in X and all possible face position d_k. Parameters ---------- X : array, shape (H, W, K) K images of size H x W. F : array, shape (H, w) Estimate of prank...
OK
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
2. **Реализуйте calculate_lower_bound**\begin{equation}\mathscr{L}(q, \,F, \,B,\, s,\, a) = \sum_k \biggl (\mathbb{E} _ {q( d_k)}\bigl ( \log p( X_{k} \mid {d}_{k} , \,F,\,B,\,s) + \log p( d_k \mid a)\bigr) - \mathbb{E} _ {q( d_k)} \log q( d_k)\biggr) \end{equation}Замечания * Используйте calculate_log_probabil...
def calculate_lower_bound(X, F, B, s, a, q): """ Calculates the lower bound L(q, F, B, s, a) for the marginal log likelihood. Parameters ---------- X : array, shape (H, W, K) K images of size H x W. F : array, shape (H, w) Estimate of prankster's face. B : array, shape ...
OK
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
3. **Реализуем E шаг**$$q(d_k) = p(d_k \mid X_k, \,F, \,B, \,s,\, a) = \frac {p( X_{k} \mid {d}_{k} , \,F,\,B,\,s)\, p(d_k \mid a)}{\sum_{d'_k} p( X_{k} \mid d'_k , \,F,\,B,\,s) \,p(d'_k \mid a)}$$Замечания * Используйте calculate_log_probability! * Считайте в логарифмах, возведите в экспоненту в конце. * Рекоменд...
def run_e_step(X, F, B, s, a): """ Given the current esitmate of the parameters, for each image Xk esitmates the probability p(d_k|X_k, F, B, s, a). Parameters ---------- X : array, shape(H, W, K) K images of size H x W. F : array_like, shape(H, w) Estimate of prankster's f...
OK
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
4. **Реализуйте M шаг**Надо\begin{equation}\mathscr{L}(q, \,F, \,B,\, s,\, a) = \sum_k \biggl (\mathbb{E} _ {q( d_k)}\bigl ( \log p( X_{k} \mid {d}_{k} , \,F,\,B,\,s) + \log p( d_k \mid a)\bigr) - \mathbb{E} _ {q( d_k)} \log q( d_k)\biggr)\rightarrow \max\limits_{\theta, a} \end{equation}После долгих вычислений ...
def run_m_step(X, q, w): """ Estimates F, B, s, a given esitmate of posteriors defined by q. Parameters ---------- X : array, shape (H, W, K) K images of size H x W. q : q[dw, k] - estimate of posterior of position dw of prankster's face given image Xk w ...
OK
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
5. **Реализуйте EM алгоритм**
def run_EM(X, w, F=None, B=None, s=None, a=None, tolerance=0.001, max_iter=50): """ Runs EM loop until the likelihood of observing X given current estimate of parameters is idempotent as defined by a fixed tolerance. Parameters ---------- X : array, shape (H, W, K) K imag...
_____no_output_____
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
Расшифровываем картинку:
def show(F, i=1, n=1): """ shows face F at subplot i out of n """ plt.subplot(1, n, i) plt.imshow(F, cmap="Greys_r") plt.axis("off") %%time F, B, s, a = [None] * 4 lens = [50, 100, 300, 500, 1000] iters = [5, 1, 1, 1, 1] plt.figure(figsize=(20, 5)) for i, (l, it) in enumerate(zip(lens, iters)): ...
iteration = 0 e m 114.93555180113619 iteration = 1 e m 113.77686133696521 iteration = 2 e m 113.43816994843172
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
И фон:
show(B)
_____no_output_____
MIT
2021-fall-part-1/seminars/13_em_algo/13_em_algo_practice.ipynb
bagrorg/ml-course
Near real-time HF-Radar currents in the proximity of the Deepwater Horizon site The explosion on the Deepwater Horizon (DWH) tragically killed 11 people, and resulted in one of the largest marine oil spills in history. One of the first questions when there is such a tragedy is: where will the oil go?In order the help ...
from IPython.display import HTML url = ( 'https://cordc.ucsd.edu/projects/mapping/maps/fullpage.php?' 'll=29.061888,-87.373643&' 'zm=7&' 'mt=&' 'rng=0.00,50.00&' 'us=1&' 'cs=4&' 'res=6km_h&' 'ol=3&' 'cp=1' ) iframe = '<iframe src="{src}" width="750" height="450" style="border:...
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
The interactive interface is handy for exploration but we usually need to download "mechanically" in order to use them in our analysis, plots, or for downloading time-series.One way to achieve that is to use an OPeNDAP client, here Python's `xarray`, and explore the endpoint directly. (We'll use the same 6 km resolutio...
import xarray as xr url = ( 'http://hfrnet-tds.ucsd.edu/thredds/dodsC/HFR/USEGC/6km/hourly/RTV/' 'HFRADAR_US_East_and_Gulf_Coast_6km_Resolution_Hourly_RTV_best.ncd' ) ds = xr.open_dataset(url) ds
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
How about extracting a week time-series from the dataset averaged around the area of interest?
dx = dy = 2.25 # Area around the point of interest. center = -87.373643, 29.061888 # Point of interest. dsw = ds.sel(time=slice('2017-07-20', '2017-07-27')) dsw = dsw.sel( lon=(dsw.lon < center[0]+dx) & (dsw.lon > center[0]-dx), lat=(dsw.lat < center[1]+dy) & (dsw.lat > center[1]-dy), )
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
With `xarray` we can average hourly (`resample`) the whole dataset with one method call.
dsw = dsw.resample(freq='1H', dim='time', how='mean')
/home/filipe/miniconda3/envs/IOOS/lib/python3.6/site-packages/ipykernel/__main__.py:1: DeprecationWarning: .resample() has been modified to defer calculations. Instead of passing 'dim' and 'how="mean", instead consider using .resample(time="1H").mean() if __name__ == '__main__':
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
Now all we have to do is mask the missing data with `NaN`s and average over the area.
import numpy.ma as ma v = dsw['v'].data u = dsw['u'].data time = dsw['time'].to_index().to_pydatetime() u = ma.masked_invalid(u) v = ma.masked_invalid(v) i, j, k = u.shape u = u.reshape(i, j*k).mean(axis=1) v = v.reshape(i, j*k).mean(axis=1) %matplotlib inline import matplotlib.pyplot as plt from oceans import stick...
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
To close this post let's us reproduce the HF radar DAC image from above but using yesterday's data.
from datetime import date, timedelta yesterday = date.today() - timedelta(days=1) dsy = ds.sel(time=yesterday)
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
Now that we singled out the date and and time we want the data, we trigger the download by accessing the data with `xarray`'s `.data` property.
u = dsy['u'].data v = dsy['v'].data lon = dsy.coords['lon'].data lat = dsy.coords['lat'].data time = dsy.coords['time'].data
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
The cell below computes the speed from the velocity. We can use the speed computation to color code the vectors. Note that we re-create the vector velocity preserving the direction but using intensity of `1`. (The same visualization technique used in the HF radar DAC.)
import numpy as np from oceans import uv2spdir, spdir2uv angle, speed = uv2spdir(u, v) us, vs = spdir2uv(np.ones_like(speed), angle, deg=True)
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
Now we can create a `matplotlib` figure displaying the data.
import cartopy.crs as ccrs from cartopy import feature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER LAND = feature.NaturalEarthFeature( 'physical', 'land', '10m', edgecolor='face', facecolor='lightgray' ) sub = 2 bbox = lon.min(), lon.max(), lat.min(), lat.max() fig, ax = pl...
_____no_output_____
MIT
notebooks/2017-07-25-HFRadar_currents.ipynb
kellydesent/notebooks_demos
define what to clusterThis document contains part of the codes in -lfcdataset = 0.6 (July 2015)minimum number of studies = 80mask = bilateral ATL
%matplotlib inline from neurosynth.base.dataset import Dataset dataset = Dataset.load("data/neurosynth_0.6_400_4.pkl") from neurosynth.analysis.cluster import Clusterable mask = 'masks/Xu_ATLp2.nii' roi = Clusterable(dataset, mask=mask,min_studies=80,feature_threshold=0.05) reference = Clusterable(dataset, min_studies=...
For n_clusters = 2 The average silhouette_score is : 0.190294163513 For n_clusters = 3 The average silhouette_score is : 0.167182073533 For n_clusters = 4 The average silhouette_score is : 0.184467016516 For n_clusters = 5 The average silhouette_score is : 0.154431718383 For n_clusters = 6 The average silhouette_score ...
MIT
0.2 Silhouette.ipynb
jinyihung/ATL_neurosynth
DeRT analysis using Iris dataset
from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from kitchen.dert.dert_models import FeatureDrivenModel, CombinedModel import numpy as np from nltk.translate.bleu_score import sentence_bleu iris = load_iris() X = iris['data'] y = iris['target'] scaler = StandardScaler() scaler.f...
actual vs predicted: ['S', '4L', '3R', '3L', '4L', 'E'] vs S 4L 3R 3L 4L E labels: 1 1 actual vs predicted: ['S', '4R', 'E'] vs S 4R E labels: 2 2 actual vs predicted: ['S', '4L', '3L', 'E'] vs S 4L 3L E labels: 0 0 actual vs predicted: ['S', '4L', '3R', '3L', '4L', 'E'] vs S 4L 3R 3L 4L E labels: 1 1 a...
MIT
notebooks/dert/1.0-sa-dert-demo.ipynb
anujstam/kitchen
--- Trials
actual_path = trial_2.df.iloc[1, 8] actual_path_tok = [trial_2.char_indices[char] for char in actual_path] actual_path_tok trial_2.char_indices trial_2.get_j_coeff(actual_path_tok, [0,9,6,1]) import distance distance.levenshtein(['S', 'L', 'E'],['S', 'L', 'E']) ## Extracting failure paths a = ['S', '4R', '4L', '3L', '...
_____no_output_____
MIT
notebooks/dert/1.0-sa-dert-demo.ipynb
anujstam/kitchen
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 athttps://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under...
#@title Setup Environment #@test {"output": "ignore"} import glob print 'Copying checkpoints and example MIDI from GCS. This will take a few minutes...' !gsutil -q -m cp -R gs://download.magenta.tensorflow.org/models/music_vae/colab2/* /content/ print 'Installing dependencies...' !apt-get update -qq && apt-get insta...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
2-Bar Drums ModelBelow are 4 pre-trained models to experiment with. The first 3 map the 61 MIDI drum "pitches" to a reduced set of 9 classes (bass, snare, closed hi-hat, open hi-hat, low tom, mid tom, high tom, crash cymbal, ride cymbal) for a simplified but less expressive output space. The last model uses a [NADE](h...
#@title Load Pretrained Models drums_models = {} # One-hot encoded. drums_config = configs.CONFIG_MAP['cat-drums_2bar_small'] drums_models['drums_2bar_oh_lokl'] = TrainedModel(drums_config, batch_size=4, checkpoint_dir_or_path='/content/checkpoints/drums_2bar_small.lokl.ckpt') drums_models['drums_2bar_oh_hikl'] = Trai...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Samples
#@title Generate 4 samples from the prior of one of the models listed above. drums_sample_model = "drums_2bar_oh_lokl" #@param ["drums_2bar_oh_lokl", "drums_2bar_oh_hikl", "drums_2bar_nade_reduced", "drums_2bar_nade_full"] temperature = 0.5 #@param {type:"slider", min:0.1, max:1.5, step:0.1} drums_samples = drums_model...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
Generate Interpolations
#@title Option 1: Use example MIDI files for interpolation endpoints. input_drums_midi_data = [ tf.gfile.Open(fn).read() for fn in sorted(tf.gfile.Glob('/content/midi/drums_2bar*.mid'))] #@title Option 2: upload your own MIDI files to use for interpolation endpoints instead of those provided. input_drums_midi_d...
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta
2-Bar Melody ModelThe pre-trained model consists of a single-layer bidirectional LSTM encoder with 2048 nodes in each direction, a 3-layer LSTM decoder with 2048 nodes in each layer, and Z with 512 dimensions. The model was given 0 free bits, and had its beta valued annealed at an exponential rate of 0.99999 from 0 to...
#@title Load the pre-trained model. mel_2bar_config = configs.CONFIG_MAP['cat-mel_2bar_big'] mel_2bar = TrainedModel(mel_2bar_config, batch_size=4, checkpoint_dir_or_path='/content/checkpoints/mel_2bar_big.ckpt')
_____no_output_____
Apache-2.0
colab/MusicVAE.ipynb
hwangsog/magenta