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 |
|---|---|---|---|---|---|
[Volver a la Tabla de Contenido](TOC) Error en la aplicación de la regla trapezoidal Recordando que estos esquemas provienen de la serie truncada de Taylor, el error se puede obtener determinando el primer término truncado en el esquema, que para la regla trapezoidal de aplicación simple corresponde a:\begin{equation*... | from scipy.interpolate import barycentric_interpolate
# usaremos uno de los tantos métodos de interpolación dispobibles en las bibliotecas de Python
n = 3 # puntos a interpolar para un polinomio de grado 2
xp = np.linspace(a,b,n) # generación de n puntos igualmente esp... | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Se observa que hay una gran diferencia entre las áreas que se estarían abarcando en la función llamada "*real*" (que se emplearon $100$ puntos para su generación) y la función *interpolada* (con únicamente $3$ puntos para su generación) que será la empleada en la integración numérica (aproximada) mediante la regla de *... | # se ingresan los valores del intervalo [a,b]
a = float(input('Ingrese el valor del límite inferior: '))
b = float(input('Ingrese el valor del límite superior: '))
# cuerpo del programa por la regla de Simpson 1/3
h = (b-a)/2 # cálculo del valor de h
x0 = a # valor del primer punto para la fórmula de S1/3
x1... | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
[Volver a la Tabla de Contenido](TOC) Error en la regla de Simpson 1/3 de aplicación simple El problema de calcular el error de esta forma es que realmente no conocemos el valor exacto. Para poder calcular el error al usar la regla de *Simpson 1/3*:\begin{equation*}\begin{split}-\frac{h^5}{90}f^{(4)}(\xi)\end{split}\l... | from sympy import *
x = symbols('x') | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Derivamos cuatro veces la función $f(x)$ con respecto a $x$: | deriv4 = diff(4 / (1 + x**2),x,4)
deriv4 | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
y evaluamos esta función de la cuarta derivada en un punto $0 \leq \xi \leq 1$. Como la función $f{^{(4)}}(x)$ es creciente en el intervalo $[0,1]$ (compruébelo gráficamente y/o por las técnicas vistas en cálculo diferencial), entonces, el valor que hace máxima la cuarta derivada en el intervalo dado es: | x0 = 1.0
evald4 = deriv4.evalf(subs={x: x0})
print('El valor de la cuarta derivada de f en x0={0:6.2f} es {1:6.4f}: '.format(x0, evald4)) | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Calculamos el error en la regla de *Simpson$1/3$* | errorS13 = abs(h**5*evald4/90)
print('El error al usar la regla de Simpson 1/3 es: {0:6.6f}'.format(errorS13)) | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Entonces, podemos expresar el valor de la integral de la función $f(x)=e^{x^2}$ en el intervalo $[0,1]$ usando la *Regla de Simpson $1/3$* como:$$\color{blue}{\int_0^1 \frac{4}{1 + x^2}dx} = \color{green}{3,133333} \color{red}{+ 0.004167}$$ Si lo fuéramos a hacer "a mano" $\ldots$ aplicando la fórmula directamente, con... | # usaremos uno de los tantos métodos de interpolación dispobibles en las bibliotecas de Python
n = 4 # puntos a interpolar para un polinomio de grado 2
xp = np.linspace(0,1,n) # generación de n puntos igualmente espaciados para la interpolación
fp = funcion(xp) ... | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Para poder calcular el error al usar la regla de *Simpson 3/8*:$$\color{red}{-\frac{3h^5}{80}f^{(4)}(\xi)}$$será necesario derivar cuatro veces la función original. Para esto, vamos a usar nuevamente el cálculo simbólico (siempre deben verificar que la respuesta obtenida es la correcta!!!): | errorS38 = 3*h**5*evald4/80
print('El error al usar la regla de Simpson 3/8 es: ',errorS38) | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Entonces, podemos expresar el valor de la integral de la función $f(x)=e^{x^2}$ en el intervalo $[0,1]$ usando la *Regla de Simpson $3/8$* como:$$\color{blue}{\int_0^1\frac{4}{1 + x^2}dx} = \color{green}{3.138462} \color{red}{- 0.001852}$$ Aplicando la fórmula directamente, con los siguientes datos:$h = \frac{(1.0 - 0.... | # | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
[Volver a la Tabla de Contenido](TOC) Cuadratura de Gauss Introducción Retomando la idea inicial de los esquemas de [cuadratura](Quadrature), el valor de la integral definida se estima de la siguiente manera:\begin{equation*}\begin{split}I=\int_a^b f(x)dx \approx \sum \limits_{i=0}^n c_if(x_i)\end{split}\label{eq:Ec5... | import numpy as np
import pandas as pd
GaussTable = [[[0], [2]], [[-1/np.sqrt(3), 1/np.sqrt(3)], [1, 1]], [[-np.sqrt(3/5), 0, np.sqrt(3/5)], [5/9, 8/9, 5/9]], [[-0.861136, -0.339981, 0.339981, 0.861136], [0.347855, 0.652145, 0.652145, 0.347855]], [[-0.90618, -0.538469, 0, 0.538469, 0.90618], [0.236927, 0.478629, 0.5688... | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
[Volver a la Tabla de Contenido](TOC) Ejemplo Cuadratura de Gauss Determine el valor aproximado de:$$\int_0^1 \frac{4}{1+x^2}dx$$empleando cuadratura gaussiana de dos puntos.Reemplazando los parámetros requeridos en la ecuación ([5.55](Ec5_55)), donde $a=0$, $b=1$, $x_0=-\sqrt{3}/3$ y $x_1=\sqrt{3}/3$\begin{equation*}... | import numpy as np
def fxG(a, b, x):
xG = ((b + a) + (b - a) * x) / 2
return funcion(xG)
def GQ2(a,b):
c0 = 1.0
c1 = 1.0
x0 = -1.0 / np.sqrt(3)
x1 = 1.0 / np.sqrt(3)
return (b - a) / 2 * (c0 * fxG(a,b,x0) + c1 * fxG(a,b,x1))
print(GQ2(a,b)) | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
[Volver a la Tabla de Contenido](TOC) | from IPython.core.display import HTML
def css_styling():
styles = open('./nb_style.css', 'r').read()
return HTML(styles)
css_styling() | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Deep Learning Assignment 5The goal of this assignment is to train a Word2Vec skip-gram model over Text8 data. Word2vec is a group of related models that are used to produce word embeddings. These models are shallow, two-layer neural networks that are trained to reconstruct linguistic contexts of words. Word2vec takes ... | # These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
%matplotlib inline
from __future__ import print_function
import collections
import math
import numpy as np
import os
import random
import tensorflow as tf
import zipfile
from matplotlib import pylab
from six.mov... | _____no_output_____ | MIT | 5_word2vec_skip-gram.ipynb | ramborra/Udacity-Deep-Learning |
Download the data from the source website if necessary. | url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
if not os.path.exists(filename):
filename, _ = urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
... | Found and verified text8.zip
| MIT | 5_word2vec_skip-gram.ipynb | ramborra/Udacity-Deep-Learning |
Read the data into a string. | def read_data(filename):
"""Extract the first file enclosed in a zip file as a list of words"""
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data(filename)
print('Data size %d' % len(words)) | Data size 17005207
| MIT | 5_word2vec_skip-gram.ipynb | ramborra/Udacity-Deep-Learning |
Build the dictionary and replace rare words with UNK token. (UNK - Unknown Words) | vocabulary_size = 50000
def build_dataset(words):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
... | _____no_output_____ | MIT | 5_word2vec_skip-gram.ipynb | ramborra/Udacity-Deep-Learning |
Function to generate a training batch for the skip-gram model. | data_index = 0
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ sk... | data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first']
with num_skips = 2 and skip_window = 1:
batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term']
labels: ['anarchism', 'as', 'originated', 'a', 'term', 'as', 'a', 'of']
with num_skips = 4 and skip_window = 2:
bat... | MIT | 5_word2vec_skip-gram.ipynb | ramborra/Udacity-Deep-Learning |
Train a skip-gram model. | batch_size = 128
embedding_size = 128 # Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words... | _____no_output_____ | MIT | 5_word2vec_skip-gram.ipynb | ramborra/Udacity-Deep-Learning |
ERROR: type should be string, got " https://towardsdatascience.com/3-basic-steps-of-stock-market-analysis-in-python-917787012143" | %matplotlib inline
!pip install yfinance
!wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
!tar -xzvf ta-lib-0.4.0-src.tar.gz
%cd ta-lib
!./configure --prefix=/usr
!make
!make install
!pip install Ta-Lib
# from yahoofinancials import YahooFinancials
import matplotlib.pyplot as plt
import pandas as... | _____no_output_____ | MIT | Exercise/stocks-analysis.ipynb | JSJeong-me/Machine_Learning |
Analysis notebook comparing scoping vs no-scoping for tower selectionPurpose of this notebook is to categorize and analyze generated towers.Requires:* `.pkl` generated by `stimuli/score_towers.py`See also:* `stimuli/generate_towers.ipynb` for plotting code and a similar analysis in the same place as the tower generati... | # set up imports
import os
import sys
__file__ = os.getcwd()
proj_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(proj_dir)
utils_dir = os.path.join(proj_dir, 'utils')
sys.path.append(utils_dir)
analysis_dir = os.path.join(proj_dir, 'analysis')
analysis_utils_dir = os.path.join(analysis_dir, 'utils')
... | _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Load in data (we might have multiple dfs) | path_to_dfs = [os.path.join(df_dir, f)
for f in ["RLDM_main_experiment.pkl"]]
dfs = [pd.read_pickle(path_to_df) for path_to_df in path_to_dfs]
print("Read {} dataframes: {}".format(len(dfs), path_to_dfs))
# merge dfs
df = pd.concat(dfs)
print("Merged dataframes: {}".format(df.shape))
# do a few things t... | /Users/felixbinder/opt/anaconda3/envs/scoping/lib/python3.9/site-packages/numpy/core/_methods.py:262: RuntimeWarning: Degrees of freedom <= 0 for slice
ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
/Users/felixbinder/opt/anaconda3/envs/scoping/lib/python3.9/site-packages/numpy/core/_methods.py:254: Runtim... | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Let's explore the data a little bit | sum_df
sum_df.groupby([('label', 'first')]).mean()
sum_df.groupby([('label', 'first')]).count()
| _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
What is the rate of success? | display(sum_df.groupby([('label', 'first')]).mean()[('perfect', 'last')])
sum_df.groupby([('label', 'first')]).mean()[('perfect', 'last')].plot(
kind='bar', title='Rate of perfect solutions')
plt.show()
| _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
What is the difference in cost between the two conditions? | display(sum_df.groupby([('label', 'first')]).mean()[('cost', 'sum')])
sum_df.groupby([('label', 'first')]).mean()[('cost', 'sum')].plot(
kind='bar', title='Mean action planning cost (for chosen solution', yerr=sum_df.groupby([('label', 'first')]).mean()[('cost', 'sem')])
plt.yscale('log')
plt.show()
| _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
What about the total cost? | display(sum_df.groupby([('label', 'first')]).mean()[('total_cost', 'sum')])
sum_df.groupby([('label', 'first')]).mean()[('total_cost', 'sum')].plot(
kind='bar', title='Total planning cost', yerr=sum_df.groupby([('label', 'first')]).mean()[('total_cost', 'sem')])
plt.yscale('log')
plt.show()
df[df['label'] == 'Full... | _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Is there a difference between the depth of found solutions? | display(sum_df.groupby([('label', 'first')]).mean()[('action', 'count')])
sum_df.groupby([('label', 'first')]).mean()[('action', 'count')
].plot(kind='bar', title='Mean number of actions')
| _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Tower analysisNow that we have explored the data, let's look at the distribution over towers. Let's make a scatterplot over subgoal and no subgoal costs. | tower_sum_df = df.groupby(['label', 'world']).agg({
'cost': ['sum', 'mean', sem],
'total_cost': ['sum', 'mean', sem],
})
# flatten the index
tower_sum_df.reset_index(inplace=True)
tower_sum_df
# for the scatterplots, we can only show two agents at the same time.
label1 = 'Full Subgoal Planning'
label2 = 'Best... | _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
The same for the total subgoal planning cost | plt.scatter(
x=tower_sum_df[tower_sum_df['label'] == label1]['total_cost']['sum'],
y=tower_sum_df[tower_sum_df['label'] == label2]['total_cost']['sum'],
c=tower_sum_df[tower_sum_df['label'] == label1]['world'])
plt.title("Action planning cost of solving a tower with and without subgoals")
plt.xlabel("Cost o... | _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Can we see a pattern between the relation of the solution and total subgoal planning cost for the subgoal agent? | plt.scatter(
x=tower_sum_df[tower_sum_df['label'] == label1]['cost']['sum'],
y=tower_sum_df[tower_sum_df['label'] == label2]['total_cost']['sum'],
c=tower_sum_df[tower_sum_df['label'] == label1]['world'])
plt.title("Cost of the found solution versus costs of all sequences of subgoals")
plt.xlabel("Cost of t... | _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Looks like there are some **outliers**—let's look at those Do we have towers that can't be solved using a subgoal decomposition? | failed_df = df[(df['perfect'] == False)]
display(failed_df)
bad_ID = list(df[df['world_status'] == 'Fail']['run_ID'])[1]
bad_ID
df[df['run_ID'] == bad_ID]
df[df['run_ID'] == bad_ID]['_chosen_subgoal_sequence'].dropna(
).values[-1].visual_display()
df[df['run_ID'] == bad_ID]['_chosen_subgoal_sequence'].dropna(
).va... | _____no_output_____ | MIT | analysis/tower selection analysis.ipynb | cogtoolslab/projection_block_construction |
Imports | from music21 import converter, instrument, note, chord, stream
import glob
import pickle
import numpy as np
from keras.utils import np_utils | Using TensorFlow backend.
| MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Read a Midi File | midi = converter.parse("midi_songs/EyesOnMePiano.mid")
midi
midi.show('midi')
midi.show('text')
# Flat all the elements
elements_to_parse = midi.flat.notes
len(elements_to_parse)
for e in elements_to_parse:
print(e, e.offset)
notes_demo = []
for ele in elements_to_parse:
# If the element is a Note, then store... | _____no_output_____ | MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Preprocessing all Files | notes = []
for file in glob.glob("midi_songs/*.mid"):
midi = converter.parse(file) # Convert file into stream.Score Object
# print("parsing %s"%file)
elements_to_parse = midi.flat.notes
for ele in elements_to_parse:
# If the element is a Note, then store it's pitch
... | ['1+5+9', 'G#2', '1+5+9', '1+5+9', 'F3', 'F2', 'F2', 'F2', 'F2', 'F2', '4+9', 'E5', '4+9', 'C5', '4+9', 'A5', '4+9', '5+9', 'F5', '5+9', 'C5', '5+9', 'A5', '5+9', '4+9', 'E5', '4+9', 'C5', '4+9', 'A5', '4+9', 'F5', '5+9', 'C5', '5+9', 'E5', '5+9', 'D5', '5+9', 'E5', '4+9', 'E-5', '4+9', 'B5', '4+9', '4+9', 'A5', '5+9',... | MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Prepare Sequential Data for LSTM | # Hoe many elements LSTM input should consider
sequence_length = 100
# All unique classes
pitchnames = sorted(set(notes))
# Mapping between ele to int value
ele_to_int = dict( (ele, num) for num, ele in enumerate(pitchnames) )
network_input = []
network_output = []
for i in range(len(notes) - sequence_length):
seq_... | (60398, 100, 1)
(60398, 359)
| MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Create Model | from keras.models import Sequential, load_model
from keras.layers import *
from keras.callbacks import ModelCheckpoint, EarlyStopping
model = Sequential()
model.add( LSTM(units=512,
input_shape = (normalised_network_input.shape[1], normalised_network_input.shape[2]),
return_sequences = Tru... | _____no_output_____ | MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Predictions | sequence_length = 100
network_input = []
for i in range(len(notes) - sequence_length):
seq_in = notes[i : i+sequence_length] # contains 100 values
network_input.append([ele_to_int[ch] for ch in seq_in])
# Any random start index
start = np.random.randint(len(network_input) - 1)
# Mapping int_to_ele
int_to_ele ... | ['D2', 'D5', 'D3', 'C5', 'B4', 'D2', 'A4', 'D3', 'G#4', 'E5', '4+9', 'C5', 'A4', '0+5', 'C5', 'A4', 'F#5', 'C5', 'A4', '0+5', 'C5', 'A4', 'E5', 'C5', 'B4', 'D5', 'E5', '4+9', 'C5', 'A4', '0+5', '4+9', 'C5', 'A4', 'F#5', 'C5', 'A4', '0+5', 'C5', 'A4', 'E5', 'E3', 'C5', 'B2', 'B4', 'C3', 'D5', 'G#2', 'E5', '4+9', 'C5', '... | MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Create Midi File | offset = 0 # Time
output_notes = []
for pattern in prediction_output:
# if the pattern is a chord
if ('+' in pattern) or pattern.isdigit():
notes_in_chord = pattern.split('+')
temp_notes = []
for current_note in notes_in_chord:
new_note = note.Note(int(current_note)) #... | _____no_output_____ | MIT | Music Generation.ipynb | karandevtyagi/AI-Music-Generator |
Small helper function to read the tokens. | def read_file(filename):
tokens = []
with open(PATH/filename, encoding='utf8') as f:
for line in f:
tokens.append(line.split() + [EOS])
return np.array(tokens)
trn_tok = read_file('wiki.train.tokens')
val_tok = read_file('wiki.valid.tokens')
tst_tok = read_file('wiki.test.tokens')
len(tr... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Give an id to each token and add the pad token (just in case we need it). | itos = [o for o,c in cnt.most_common()]
itos.insert(0,'<pad>')
vocab_size = len(itos); vocab_size | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Creates the mapping from token to id then numericalizing our datasets. | stoi = collections.defaultdict(lambda : 5, {w:i for i,w in enumerate(itos)})
trn_ids = np.array([([stoi[w] for w in s]) for s in trn_tok])
val_ids = np.array([([stoi[w] for w in s]) for s in val_tok])
tst_ids = np.array([([stoi[w] for w in s]) for s in tst_tok]) | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Testing WeightDropout Create a bunch of parameters for deterministic tests. | module = nn.LSTM(20, 20)
tst_input = torch.randn(2,5,20)
tst_output = torch.randint(0,20,(10,)).long()
save_params = {}
for n,p in module._parameters.items(): save_params[n] = p.clone() | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Old WeightDropout | module = nn.LSTM(20, 20)
for n,p in save_params.items(): module._parameters[n] = nn.Parameter(p.clone())
dp_module = WeightDrop(module, 0.5)
opt = optim.SGD(dp_module.parameters(), 10)
dp_module.train()
torch.manual_seed(7)
x = tst_input.clone()
x.requires_grad_(requires_grad=True)
h = (torch.zeros(1,5,20), torch.zeros... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
New WeightDropout | class WeightDropout(nn.Module):
"A module that warps another layer in which some weights will be replaced by 0 during training."
def __init__(self, module, dropout, layer_names=['weight_hh_l0']):
super().__init__()
self.module,self.dropout,self.layer_names = module,dropout,layer_names
... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Testing EmbeddingDropout Create a bunch of parameters for deterministic tests. | enc = nn.Embedding(100,20, padding_idx=0)
tst_input = torch.randint(0,100,(25,)).long()
save_params = enc.weight.clone() | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Old EmbeddingDropout | enc = nn.Embedding(100,20, padding_idx=0)
enc.weight = nn.Parameter(save_params.clone())
enc_dp = EmbeddingDropout(enc)
torch.manual_seed(7)
x = tst_input.clone()
enc_dp(x, dropout=0.5) | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
New EmbeddingDropout | def dropout_mask(x, sz, p):
"Returns a dropout mask of the same type as x, size sz, with probability p to cancel an element."
return x.new(*sz).bernoulli_(1-p)/(1-p)
class EmbeddingDropout1(nn.Module):
"Applies dropout in the embedding layer by zeroing out some elements of the embedding vector."
def __... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Testing RNN model Creating a bunch of parameters for deterministic testing. | tst_model = get_language_model(500, 20, 100, 2, 0, bias=True)
save_parameters = {}
for n,p in tst_model.state_dict().items(): save_parameters[n] = p.clone()
tst_input = torch.randint(0, 500, (10,5)).long()
tst_output = torch.randint(0, 500, (50,)).long() | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Old RNN model | tst_model = get_language_model(500, 20, 100, 2, 0, bias=True, dropout=0.4, dropoute=0.1, dropouth=0.2,
dropouti=0.6, wdrop=0.5)
state_dict = OrderedDict()
for n,p in save_parameters.items(): state_dict[n] = p.clone()
tst_model.load_state_dict(state_dict)
opt = optim.SGD(tst_model.paramet... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
New RNN model | class RNNDropout(nn.Module):
def __init__(self, p=0.5):
super().__init__()
self.p=p
def forward(self, x):
if not self.training or not self.p: return x
m = dropout_mask(x.data, (1, x.size(1), x.size(2)), self.p)
return m * x
def repackage_var1(h):
"Detaches h from its... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
The new model has weights that are organized a bit differently. | save_parameters1 = {}
for n,p in save_parameters.items():
if 'weight_hh_l0' not in n and n!='0.encoder_with_dropout.embed.weight': save_parameters1[n] = p.clone()
elif n=='0.encoder_with_dropout.embed.weight': save_parameters1['0.dp_encoder.emb.weight'] = p.clone()
else:
save_parameters1[n[:-4]] ... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
Regularization We'll keep the same param as before. Old reg | tst_model = get_language_model(500, 20, 100, 2, 0, bias=True, dropout=0.4, dropoute=0.1, dropouth=0.2,
dropouti=0.6, wdrop=0.5)
state_dict = OrderedDict()
for n,p in save_parameters.items(): state_dict[n] = p.clone()
tst_model.load_state_dict(state_dict)
opt = optim.SGD(tst_model.paramet... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
New reg | from dataclasses import dataclass
@dataclass
class RNNTrainer(Callback):
model:nn.Module
bptt:int
clip:float=None
alpha:float=0.
beta:float=0.
def on_loss_begin(self, last_output, **kwargs):
#Save the extra outputs for later and only returns the true output.
self.raw_out,sel... | _____no_output_____ | Apache-2.0 | dev_nb/experiments/lm_checks.ipynb | gurvindersingh/fastai_v1 |
___ ___ Merging, Joining, and ConcatenatingThere are 3 main ways of combining DataFrames together: Merging, Joining and Concatenating. In this lecture we will discuss these 3 methods with examples.____ Example DataFrames | import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 1, 2, 3])
df2 = pd.DataFrame({'A': ['A4', 'A5', '... | _____no_output_____ | Apache-2.0 | 03- General Pandas/06-Merging-Joining-and-Concatenating.ipynb | rikimarutsui/Python-for-Finance-Repo |
ConcatenationConcatenation basically glues together DataFrames. Keep in mind that dimensions should match along the axis you are concatenating on. You can use **pd.concat** and pass in a list of DataFrames to concatenate together: | pd.concat([df1,df2,df3])
pd.concat([df1,df2,df3],axis=1) | _____no_output_____ | Apache-2.0 | 03- General Pandas/06-Merging-Joining-and-Concatenating.ipynb | rikimarutsui/Python-for-Finance-Repo |
_____ Example DataFrames | left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', '... | _____no_output_____ | Apache-2.0 | 03- General Pandas/06-Merging-Joining-and-Concatenating.ipynb | rikimarutsui/Python-for-Finance-Repo |
___ MergingThe **merge** function allows you to merge DataFrames together using a similar logic as merging SQL Tables together. For example: | pd.merge(left,right,how='inner',on='key') | _____no_output_____ | Apache-2.0 | 03- General Pandas/06-Merging-Joining-and-Concatenating.ipynb | rikimarutsui/Python-for-Finance-Repo |
Or to show a more complicated example: | left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2':... | _____no_output_____ | Apache-2.0 | 03- General Pandas/06-Merging-Joining-and-Concatenating.ipynb | rikimarutsui/Python-for-Finance-Repo |
JoiningJoining is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. | left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']},
index=['K0', 'K1', 'K2'])
right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
'D': ['D0', 'D2', 'D3']},
index=['K0', 'K2', 'K3'])
left.join(right)
left.join(right, ho... | _____no_output_____ | Apache-2.0 | 03- General Pandas/06-Merging-Joining-and-Concatenating.ipynb | rikimarutsui/Python-for-Finance-Repo |
2.1 Binary Variables $$Bern(x|\mu) = \mu^x(1-\mu)^{1-x}$$ $$Beta(\mu|a,b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}\mu^{a-1}(1-\mu)^{b-1}$$ | bern = Binary()
X = np.array([1,0,0,0,1,1,1,1,1,1,0,1])
bern.fit(X)
bern.plot() | _____no_output_____ | MIT | short_notebook/chapter02_short_ver.ipynb | hedwig100/PRML |
2.2 Multinomial Variables $$p(\boldsymbol{x}|\boldsymbol{\mu}) = \Pi_{k=1}^K \mu_k^{x_k}$$ $$Dir(\boldsymbol{\mu}|\boldsymbol{\alpha}) = \frac{\Gamma(\alpha_0)}{\Gamma(\alpha_1) \cdots \Gamma(\alpha_K)} \Pi_{k=1}^K \mu_k^{\alpha_k-1}$$ 2.3 The Gaussian Distribution $$\mathcal{N}(x|\mu,\sigma^2) = ... | gauss = Gaussian1D()
X = np.random.randn(100) + 4
gauss.fit(X)
gauss.plot() | _____no_output_____ | MIT | short_notebook/chapter02_short_ver.ipynb | hedwig100/PRML |
Student's t-distribution | plot_student(mu = 0,lamda = 2,nu = 3) | _____no_output_____ | MIT | short_notebook/chapter02_short_ver.ipynb | hedwig100/PRML |
2.5 Nonparametric Methods | hist = Histgram(delta=5e-1)
X = np.random.randn(100)
hist.fit(X)
hist.plot() | _____no_output_____ | MIT | short_notebook/chapter02_short_ver.ipynb | hedwig100/PRML |
Kernel density estimators | parzen_gauss = Parzen()
X = np.random.randn(100)*2 + 4
parzen_gauss.fit(X)
parzen_gauss.plot()
parzen_hist = Parzen(kernel = "hist")
parzen_hist.fit(X)
parzen_hist.plot() | _____no_output_____ | MIT | short_notebook/chapter02_short_ver.ipynb | hedwig100/PRML |
Nearest-neighbor methods | knn5 = KNearestNeighbor(k=5)
knn30 = KNearestNeighbor(k=30)
X = np.random.randn(100)*2.4 + 5.1
knn5.fit(X)
knn5.plot()
knn30.fit(X)
knn30.plot()
def load_iris():
dict = {
"Iris-setosa": 0,
"Iris-versicolor": 1,
"Iris-virginica": 2
}
X = []
y = []
with open("../data/iris.data... | _____no_output_____ | MIT | short_notebook/chapter02_short_ver.ipynb | hedwig100/PRML |
Germany: LK Weißenburg-Gunzenhausen (Bayern)* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Bayern-LK-Weißenburg-Gunzenhausen.ipynb) | import datetime
import time
start = datetime.datetime.now()
print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}")
%config InlineBackend.figure_formats = ['svg']
from oscovida import *
overview(country="Germany", subregion="LK Weißenburg-Gunzenhausen", weeks=5);
overview(c... | _____no_output_____ | CC-BY-4.0 | ipynb/Germany-Bayern-LK-Weißenburg-Gunzenhausen.ipynb | oscovida/oscovida.github.io |
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Bayern-LK-Weißenburg-Gunzenhausen.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://j... | print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and "
f"deaths at {fetch_deaths_last_execution()}.")
# to force a fresh download of data, run "clear_cache()"
print(f"Notebook execution took: {datetime.datetime.now()-start}")
| _____no_output_____ | CC-BY-4.0 | ipynb/Germany-Bayern-LK-Weißenburg-Gunzenhausen.ipynb | oscovida/oscovida.github.io |
Subject Selection Experiments disorder data - Srinivas (handle: thewickedaxe) Initial Data Cleaning | # Standard
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
# Dimensionality reduction and Clustering
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn import manifold, datasets
from i... | (4383, 137)
(2624, 137)
(2981, 137)
| Apache-2.0 | Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb | Upward-Spiral-Science/spect-team |
Extracting the samples we are interested in | # Let's extract ADHd and Bipolar patients (mutually exclusive)
ADHD_men = X.loc[X['ADHD'] == 1]
ADHD_men = ADHD_men.loc[ADHD_men['Bipolar'] == 0]
BP_men = X.loc[X['Bipolar'] == 1]
BP_men = BP_men.loc[BP_men['ADHD'] == 0]
ADHD_cauc = Y.loc[Y['ADHD'] == 1]
ADHD_cauc = ADHD_cauc.loc[ADHD_cauc['Bipolar'] == 0]
BP_cauc ... | (1056, 137)
(257, 137)
(1110, 137)
(323, 137)
| Apache-2.0 | Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb | Upward-Spiral-Science/spect-team |
Dimensionality reduction Manifold Techniques ISOMAP | combined1 = pd.concat([ADHD_men, BP_men])
combined2 = pd.concat([ADHD_cauc, BP_cauc])
print combined1.shape
print combined2.shape
combined1 = preprocessing.scale(combined1)
combined2 = preprocessing.scale(combined2)
combined1 = manifold.Isomap(20, 20).fit_transform(combined1)
ADHD_men_iso = combined1[:1056]
BP_men_is... | _____no_output_____ | Apache-2.0 | Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb | Upward-Spiral-Science/spect-team |
Clustering and other grouping experiments K-Means clustering - iso | data1 = pd.concat([pd.DataFrame(ADHD_men_iso), pd.DataFrame(BP_men_iso)])
data2 = pd.concat([pd.DataFrame(ADHD_cauc_iso), pd.DataFrame(BP_cauc_iso)])
print data1.shape
print data2.shape
kmeans = KMeans(n_clusters=2)
kmeans.fit(data1.get_values())
labels1 = kmeans.labels_
centroids1 = kmeans.cluster_centers_
print('Est... | Estimated number of clusters: 2
| Apache-2.0 | Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb | Upward-Spiral-Science/spect-team |
As is evident from the above 2 experiments, no clear clustering is apparent.But there is some significant overlap and there 2 clear groups Classification Experiments Let's experiment with a bunch of classifiers | ADHD_men_iso = pd.DataFrame(ADHD_men_iso)
BP_men_iso = pd.DataFrame(BP_men_iso)
ADHD_cauc_iso = pd.DataFrame(ADHD_cauc_iso)
BP_cauc_iso = pd.DataFrame(BP_cauc_iso)
BP_men_iso['ADHD-Bipolar'] = 0
ADHD_men_iso['ADHD-Bipolar'] = 1
BP_cauc_iso['ADHD-Bipolar'] = 0
ADHD_cauc_iso['ADHD-Bipolar'] = 1
data1 = pd.concat([ADHD... | Random Forest accuracy is 0.7565 (+/- 0.429)
LDA accuracy is 0.7739 (+/- 0.418)
QDA accuracy is 0.7306 (+/- 0.444)
Gaussian NB accuracy is 0.7558 (+/- 0.430)
| Apache-2.0 | Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb | Upward-Spiral-Science/spect-team |
Riskfolio-Lib Tutorial: __[Financionerioncios](https://financioneroncios.wordpress.com)____[Orenji](https://www.orenj-i.net)____[Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/en/latest/)____[Dany Cajas](https://www.linkedin.com/in/dany-cajas/)__ Part IX: Portfolio Optimization with Risk Factors and Principal Com... | import numpy as np
import pandas as pd
import yfinance as yf
import warnings
warnings.filterwarnings("ignore")
yf.pdr_override()
pd.options.display.float_format = '{:.4%}'.format
# Date range
start = '2016-01-01'
end = '2019-12-30'
# Tickers of assets
assets = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'NBL', 'APA', 'MMC... | _____no_output_____ | BSD-3-Clause | examples/Tutorial 9.ipynb | xiaolongguo/Riskfolio-Lib |
2. Estimating Mean Variance Portfolios with PCR 2.1 Estimating the loadings matrix with PCR.This part is just to visualize how Riskfolio-Lib calculates a loadings matrix using PCR. | import riskfolio.ParamsEstimation as pe
feature_selection = 'PCR' # Method to select best model, could be PCR or Stepwise
n_components = 0.95 # 95% of explained variance. See PCA in scikit learn for more information
loadings = pe.loadings_matrix(X=X, Y=Y, feature_selection=feature_selection,
... | _____no_output_____ | BSD-3-Clause | examples/Tutorial 9.ipynb | xiaolongguo/Riskfolio-Lib |
2.2 Calculating the portfolio that maximizes Sharpe ratio. | import riskfolio.Portfolio as pf
# Building the portfolio object
port = pf.Portfolio(returns=Y)
# Calculating optimum portfolio
# Select method and estimate input parameters:
method_mu='hist' # Method to estimate expected returns based on historical data.
method_cov='hist' # Method to estimate covariance matrix bas... | _____no_output_____ | BSD-3-Clause | examples/Tutorial 9.ipynb | xiaolongguo/Riskfolio-Lib |
2.3 Plotting portfolio composition | import riskfolio.PlotFunctions as plf
# Plotting the composition of the portfolio
ax = plf.plot_pie(w=w, title='Sharpe FM Mean Variance', others=0.05, nrow=25, cmap = "tab20",
height=6, width=10, ax=None) | _____no_output_____ | BSD-3-Clause | examples/Tutorial 9.ipynb | xiaolongguo/Riskfolio-Lib |
2.3 Calculate efficient frontier | points = 50 # Number of points of the frontier
frontier = port.efficient_frontier(model=model, rm=rm, points=points, rf=rf, hist=hist)
display(frontier.T.head())
# Plotting the efficient frontier
label = 'Max Risk Adjusted Return Portfolio' # Title of point
mu = port.mu_fm # Expected returns
cov = port.cov_fm # Cova... | _____no_output_____ | BSD-3-Clause | examples/Tutorial 9.ipynb | xiaolongguo/Riskfolio-Lib |
3. Estimating Portfolios Using Risk Factors with Other Risk Measures and PCRIn this part I will calculate optimal portfolios for several risk measures using a __mean estimate based on PCR__. I will find the portfolios that maximize the risk adjusted return for all available risk measures. 3.1 Calculate Optimal Portfol... | # Risk Measures available:
#
# 'MV': Standard Deviation.
# 'MAD': Mean Absolute Deviation.
# 'MSV': Semi Standard Deviation.
# 'FLPM': First Lower Partial Moment (Omega Ratio).
# 'SLPM': Second Lower Partial Moment (Sortino Ratio).
# 'CVaR': Conditional Value at Risk.
# 'WR': Worst Realization (Minimax)
# 'MDD': Maximu... | _____no_output_____ | BSD-3-Clause | examples/Tutorial 9.ipynb | xiaolongguo/Riskfolio-Lib |
test across all columns (when is it worth running in this system)shrinking encodings of different type (approximate queries)ca_police 6.7GBfull_files 802MBcol_files 802 MBparse time 3min 36sPREDS[5:6] 22161713read_fast 8.66 sread 1min 24sread_chunks 2min 20sread_csv 2min 55sPREDS[4:10] 528503read_fast 6.58sread 2 min ... | indices = []
df_all = []
for i in range(0,num_chunks+1):
df_all.append(feather.read_dataframe(f'{FEATHER_DIR}full{i}.f'))
df = pd.concat(df_all, ignore_index=True)
print('concatted')
print(df.index) | concatted
RangeIndex(start=0, stop=4999999, step=1)
| PSF-2.0 | Column_Storage.ipynb | arjunrawal4/pandas-memdb |
Analyze results for 3D CGANFeb 22, 2021 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import subprocess as sp
import sys
import os
import glob
import pickle
from matplotlib.colors import LogNorm, PowerNorm, Normalize
import seaborn as sns
from functools import reduce
from ipywidgets import *
%matplotlib widget
sys.path.append('/gl... | _____no_output_____ | BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Read validation data | # bins=np.concatenate([np.array([-0.5]),np.arange(0.5,20.5,1),np.arange(20.5,100.5,5),np.arange(100.5,1000.5,50),np.array([2000])]) #bin edges to use
bins=np.concatenate([np.array([-0.5]),np.arange(0.5,100.5,5),np.arange(100.5,300.5,20),np.arange(300.5,1000.5,50),np.array([2000])]) #bin edges to use
bins=f_transform(b... | /global/cfs/cdirs/m3363/vayyar/cosmogan_data/raw_data/3d_data/dataset4_smoothing_4univ_cgan_varying_sigma_128cube/norm_1_sig_0.5_train_val.npy
/global/cfs/cdirs/m3363/vayyar/cosmogan_data/raw_data/3d_data/dataset4_smoothing_4univ_cgan_varying_sigma_128cube/norm_1_sig_0.65_train_val.npy
/global/cfs/cdirs/m3363/vayyar/co... | BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Read data | # main_dir='/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/'
# results_dir=main_dir+'20201002_064327'
dict1={'64':'/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/3d_cGAN/',
'128':'/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results... | /global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/3d_cGAN/20210726_173009_cgan_128_nodes1_lr0.000002_finetune
| BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Plot Losses | df_metrics=pd.read_pickle(result_dir+'/df_metrics.pkle').astype(np.float64)
df_metrics.tail(10)
def f_plot_metrics(df,col_list):
plt.figure()
for key in col_list:
plt.plot(df_metrics[key],label=key,marker='*',linestyle='')
plt.legend()
# col_list=list(col_list)
# df.plot(kind='lin... | _____no_output_____ | BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Read stored chi-squares for images | ## Get sigma list from saved files
flist=glob.glob(result_dir+'/df_processed*')
sigma_lst=[i.split('/')[-1].split('df_processed_')[-1].split('.pkle')[0] for i in flist]
sigma_lst.sort() ### Sorting is important for labels to match !!
labels_lst=np.arange(len(sigma_lst))
sigma_lst,labels_lst
### Create a merged datafra... | _____no_output_____ | BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Slice best steps | def f_slice_merged_df(df,cutoff=0.2,sort_col='chi_1',col_mode='all',label='all',params_lst=[0,1,2],head=10,epoch_range=[0,None],use_sum=True,display_flag=False):
''' View dataframe after slicing
'''
if epoch_range[1]==None: epoch_range[1]=df.max()['epoch']
df=df[(df.epoch<=epoch_range[1])&(df.epoch>=ep... | _____no_output_____ | BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Interactive plot |
def f_plot_hist_spec(df,param_labels,sigma_lst,steps_list,bkg_dict,plot_type,img_size):
assert plot_type in ['hist','spec','grid','spec_relative'],"Invalid mode %s"%(plot_type)
if plot_type in ['hist','spec','spec_relative']: fig=plt.figure(figsize=(6,6))
for par_label in param_labels:
df=df[... | /global/cfs/cdirs/m3363/vayyar/cosmogan_data/raw_data/3d_data/dataset4_smoothing_4univ_cgan_varying_sigma_128cube/norm_1_sig_1.1_train_val.npy
2 4
| BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Delete unwanted stored models(Since deterministic runs aren't working well ) | # # fldr='/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/20210119_134802_cgan_predict_0.65_m2/models'
# fldr=result_dir
# print(fldr)
# flist=glob.glob(fldr+'/models/checkpoint_*.tar')
# len(flist)
# # Delete unwanted stored images
# for i in flist:
# try:
# step=... | _____no_output_____ | BSD-3-Clause-LBNL | code/5_3d_cgan/2_cgan_analysis/1_cgan3d_analyze-results.ipynb | vmos1/cosmogan_pytorch |
Advanced topics in test driven development Introduction- Already seen the basics- Learn some advanced topics The hypothesis package- http://hypothesis.readthedocs.io- `pip install hypothesis`- General idea earlier: - Make test data. - Perform operations - Assert something after operation- Hypothesis automates th... |
from hypothesis import given
from hypothesis import strategies as st
from gcd import gcd
@given(st.integers(min_value=0), st.integers(min_value=0))
def test_gcd(a, b):
result = gcd(a, b)
# Now what?
# assert a%result == 0
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Example: adding a specific case | @given(st.integers(min_value=0), st.integers(min_value=0))
@example(a=44, b=19)
def test_gcd(a, b):
result = gcd(a, b)
# Now what?
# assert a%result == 0
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
More details- `given` generates inputs- `strategies`: provides a strategy for inputs- Different stratiegies - `integers` - `floats` - `text` - `booleans` - `tuples` - `lists` - ...- See: http://hypothesis.readthedocs.io/en/latest/data.html Example exercise- Write a simple run-length encoding func... | def encode(text):
return []
def decode(lst):
return ''
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
The test | from hypothesis import given
from hypothesis import strategies as st
@given(st.text())
def test_decode_inverts_encode(s):
assert decode(encode(s)) == s | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Summary- Much easier to test- hypothesis does the hard work- Can do a lot more!- Read the docs for more- For some detailed articles: http://hypothesis.works/articles/intro/- Here in particular is one interesting article: http://hypothesis.works/articles/calculating-the-mean/---- Unittest module- Basic idea and style... | # gcd.py
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b) | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Writing the test | # test_gcd.py
from gcd import gcd
import unittest
class TestGCD(unittest.TestCase):
def test_gcd_works_for_positive_integers(self):
self.assertEqual(gcd(48, 64), 16)
self.assertEqual(gcd(44, 19), 1)
if __name__ == '__main__':
unittest.main() | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Running it- Just run `python test_gcd.py`- Also works with `nosetests` and `pytest` Notes- Note the name of the method.- Note the use of `self.assertEqual`- Also available: `assertNotEqual, assertTrue, assertFalse, assertIs, assertIsNot`- `assertIsNone, assertIn, assertIsInstance, assertRaises`- `assertAlmostEqual, as... | # test_gcd.py
import gcd
import unittest
class TestGCD(unittest.TestCase):
def setUp(self):
print("setUp")
def tearDown(self):
print("tearDown")
def test_gcd_works_for_positive_integers(self):
self.assertEqual(gcd(48, 64), 16)
self.assertEqual(gcd(44, 19), 1)
if __name__ ==... | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Exercise- Fix bug with negative numbers in gcd.py.- Use TDD. Using hypothesis with unittest | # test_gcd.py
from hypothesis import given
from hypothesis import strategies as st
import gcd
import unittest
class TestGCD(unittest.TestCase):
@given(a=st.integers(min_value=0), b=st.integers(min_value=0))
def test_gcd_works_for_positive_integers(self, a, b):
result = gcd(a, b)
assert a%resul... | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Some notes on style- Use descriptive function names- Intent matters- Segregate the test code into the following | - Given: what is the context of the test?
- When: what action is taken to actually test the problem
- Then: what do we actually ensure. | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
More on intent driven programming- "Programs must be written for people to read, and only incidentally for machines to execute.” Harold Abelson- The code should make the intent clear.For example: | if self.temperature > 600 and self.pressure > 10e5:
message = 'hello you have a problem here!'
message += 'current temp is %s'%(self.temperature)
print(message)
self.valve.close()
self.raise_warning() | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
is totally unclear as to the intent. Instead refactor as follows: | if self.reactor_is_critical():
self.shutdown_with_warning()
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
A more involved testing example- Motivational problem:> Find all the git repositories inside a given directory recursively.> Make this a command line tool supporting command line use.- Write tests for the code- Some rules: 0. The test should be runnable by anyone (even by a computer), almost anywhere. 1. Don't wri... | $ coverage run -m nose.core my_package
$ coverage report -m
$ coverage html | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
mock- Mocking for advanced testing.- Example: reading some twitter data- Example: function to post an update to facebook or twitter- Example: email user when simulation crashes- Can you test it? How? Using mock: the big picture- Do you really want to post something on facebook?- Or do you want to know if the right me... | - `from unittest import mock` | _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
- else `pip install mock` | - `import mock`
| _____no_output_____ | OLDAP-2.5 | slides/test_driven_development/tdd_advanced.ipynb | FOSSEE/sees |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.