markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
TL;DR: A JAX transform inside of a hk.transform is likely to transform a side effecting function, which will result in an UnexpectedTracerError. This page describes two ways to get around this.
Limitations of Nesting JAX Functions and Haiku Modules
Once a Haiku network has been transformed to a pair of pure functions u... | def net(x): # inside of a hk.transform, this is still side-effecting
w = hk.get_parameter("w", (2, 2), init=jnp.ones)
return w @ x
def eval_shape_net(x):
output_shape = jax.eval_shape(net, x) # eval_shape on side-effecting function
return net(x) # UnexpectedTracerError!
init, _ = hk.tr... | docs/notebooks/transforms.ipynb | deepmind/dm-haiku | apache-2.0 |
These examples use jax.eval_shape, but could have used any higher-order JAX function (eg. jax.vmap, jax.scan,
jax.while_loop, ...).
The error points to hk.get_parameter. This is the operation which makes net a side effecting function. The side effect in this case is the creation of a parameter, which gets stored into ... | def net(w, x): # no side effects!
return w @ x
def eval_shape_net(x):
w = hk.get_parameter("w", (3, 2), init=jnp.ones)
output_shape = jax.eval_shape(net, w, x) # net is now side-effect free
return output_shape, net(w, x)
key = jax.random.PRNGKey(777)
x = jnp.ones((2, 3))
init, apply = hk.transform(eval_shape_... | docs/notebooks/transforms.ipynb | deepmind/dm-haiku | apache-2.0 |
However, that's not always possible. Consider the following code which calls a Haiku module (hk.nets.MLP) which we don't own. This module will internally call get_parameter. | def eval_shape_net(x):
net = hk.nets.MLP([300, 100])
output_shape = jax.eval_shape(net, x)
return output_shape, net(x)
init, _ = hk.transform(eval_shape_net)
try:
init(jax.random.PRNGKey(666), jnp.ones((2, 2)))
except jax.errors.UnexpectedTracerError:
print("UnexpectedTracerError: applied JAX transform to si... | docs/notebooks/transforms.ipynb | deepmind/dm-haiku | apache-2.0 |
Using hk.lift
We want a way to get access to our implicit Haiku state, and
get a functionally pure version of hk.nets.MLP. The way to usually achieve this is by using a hk.transform, so all we need is a way to nest an inner hk.tranform inside an outer hk.transform! We'll create another pair of init and apply functions ... | def eval_shape_net(x):
net = hk.nets.MLP([300, 100]) # still side-effecting
init, apply = hk.transform(net) # nested transform
params = hk.lift(init, name="inner")(hk.next_rng_key(), x) # register parameters in outer module scope with name "inner"
output_shape = jax.eval_shape(apply, params, hk.next_rng_key... | docs/notebooks/transforms.ipynb | deepmind/dm-haiku | apache-2.0 |
Using Haiku versions of JAX transforms
Haiku also provides wrapped versions of some of the JAX functions for convenience. For example: hk.grad, hk.vmap, .... See https://dm-haiku.readthedocs.io/en/latest/api.html#jax-fundamentals for a full list of available functions.
These wrappers apply the JAX function to a functio... | def eval_shape_net(x):
net = hk.nets.MLP([300, 100]) # still side-effecting
output_shape = hk.eval_shape(net, x) # hk.eval_shape threads through the Haiku state for you
out = net(x) ... | docs/notebooks/transforms.ipynb | deepmind/dm-haiku | apache-2.0 |
Compute residuals
The GP hyperparameters are fit to the residuals from the ckwn white-noise analysis. | lpf = LPFTM()
pv0 = pd.read_hdf(RFILE_EXT, 'ckwn/fc').median().values
fluxes_m = lpf.compute_transit(pv0)
residuals = [fo-fm for fo,fm in zip(lpf.fluxes, fluxes_m)]
gps = [GPTime(time, res) for time,res in zip(lpf.times, residuals)]
hps = [] | notebooks/01_broadband_analysis/E3_gp_hyperparameter_optimization_1.ipynb | hpparvi/Parviainen-2017-WASP-80b | mit |
Plot the light curves | phases = list(map(lambda t: fold(t, P, TC, 0.5)-0.5, lpf.times))
fig,axs = subplots(4,3, figsize=(14,14),sharey=True, sharex=True)
for iax,ilc in enumerate(lpf.lcorder):
a = axs.flat[iax]
a.plot(phases[ilc], lpf.fluxes[ilc],'.', alpha=0.5)
a.plot(phases[ilc], fluxes_m[ilc],'k')
a.plot(phases[ilc], lpf.f... | notebooks/01_broadband_analysis/E3_gp_hyperparameter_optimization_1.ipynb | hpparvi/Parviainen-2017-WASP-80b | mit |
Fit the Hyperparameters and plot the GP mean with the data | hps = []
for gp in tqdm(gps, desc='Optimising GP hyperparameters'):
gp.fit()
hps.append(gp.hp)
fig,axs = subplots(4,3, figsize=(14,10),sharey=True, sharex=True)
for iax,ilc in enumerate(lpf.lcorder):
axs.flat[iax].plot(phases[ilc], gps[ilc].flux, '.', alpha=0.5)
gps[ilc].compute(hps[ilc])
pr = gps[... | notebooks/01_broadband_analysis/E3_gp_hyperparameter_optimization_1.ipynb | hpparvi/Parviainen-2017-WASP-80b | mit |
Create a Pandas dataframe and save the hyperparameters | with pd.HDFStore(DFILE_EXT) as f:
ntr = [k[3:] for k in f.keys() if 'lc/triaud' in k]
nma = [k[3:] for k in f.keys() if 'lc/mancini' in k]
df = pd.DataFrame(hps, columns=gp.names, index=lpf.passbands)
df['lc_name'] = ntr+nma
df
df.ix[:3].to_hdf(RFILE_EXT, 'gphp/triaud2013')
df.ix[3:].to_hdf(RFILE_EXT, 'gphp/m... | notebooks/01_broadband_analysis/E3_gp_hyperparameter_optimization_1.ipynb | hpparvi/Parviainen-2017-WASP-80b | mit |
Uso de metacaracteres
Se usará <sec> para indicar una secuencia arbitraria, la cual puede ser compuesta de caracteres literales o
metacaracteres.
Las expresiones regulares se dividen en un conjunto BRE (Basic Regular Expression) y ERE (Extended Regular Expression) acorde al soporte definido de los metacaracter... | %%bash
echo ":: non-meta <sec> ::"
grep 'zip' test_regexp
echo ":: meta .<sec> ::"
grep '.zip' test_regexp
echo ":: meta ^<sec> ::"
grep '^zip' test_regexp
echo ":: meta <sec>$ ::"
grep 'zip$' test_regexp
echo ":: meta ^<sec>$ ::"
grep '^zip$' test_regexp
echo ":: meta [<sec>] ::"
grep '[bg]zip' test_regexp
echo ":: me... | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Para los metacaracteres ERE se tiene el siguiente comportamiento.
| Metacaracter | Descripción |
|:---:|:---:|
|<code>sec|sec</code>| Alternación Coincidencia con alguno de los patrones |
|<sec>?| Elemento precedente opcional (cero o una vez) |
|<sec>*| Elemento precedente opcional (cero o multiples ... | %%bash
echo ":: meta <sec>|<sec> ::"
grep -E '^2|.zip$' test_regexp
echo ":: meta <sec>? ::"
grep -E '^[a-z]?zip.' test_regexp
echo ":: meta <sec>* ::"
grep -E '^[a-z]*zip.' test_regexp
echo ":: meta <sec>+ ::"
grep -E '^[a-z]+zip.' test_regexp
echo ":: meta <sec>{n,m} ::"
grep -E '^[a-z]{1,3}zip.' test_regexp | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Otras utilidades para habilitar sus expresiones regulares requieren indicación explicita incluso para el soporte POSIX. Ejemplo locate --regex '<regex>'. En less y vim una vez visualizamos el archivo, habilitamos la búsqueda de expresiones regulares con /.
Manipulación de texto
Concatenación de archivos
Para la... | %%bash
printf "hola\nesto\nes\nuna\nprueba.\n" > prueba1
a=1
echo $a > prueba2
while [ $a -lt 5 ]; do
let a=a+1
echo $a >> prueba2
done
cat prueba1 prueba2 > prueba3
more prueba3 | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Ordenamiento
Es posible ordenar lineas de archivos con los valores definidos en ASCII con la instrucción sort. | !sort prueba3 | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Unicidad
Es posible remover los elementos repetidos de un conjunto con utilidades de linux. Para esto, primero debe ordenarse la lista de elemento (sort) y aplicar uniq. | %%bash
cat prueba3 prueba1 prueba2 prueba3 > repetido
cat repetido
echo ":: uniq sin sort ::"
uniq repetido
echo ":: uniq con sort ::"
sort repetido | uniq | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Cortar
Para extraer secciones especificas de lineas de los archivos usamos la instrucción cut. | %%bash
ls -oh
ls -oh | grep -Ev '[[:alpha:]]+ [[:alnum:]]+\.ipynb|total' | grep -Ev '[a-z]{3} ' > cortar
echo ":: archivo cortar seleccionando lineas ::"
cat cortar
echo ":: Horas enteras de los archivos ::"
cut -d " " -f 7 cortar | cut -c 1-2 > horas
cut -d " " -f 7 cortar | cut -c 4-5 > minutos
echo ":: Horas ::"
ca... | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Pegado
Para pegar columnas usamos la instrucción paste. | %%bash
paste horas minutos | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Comparación de archivos
Es posible comparar archivos con las instrucciones comm y diff. La primera requiere que los archivos sean ordenados. Usando la diferencia de los archivos es posible generar la actualización del archivo base con patch. | %%bash
printf "a\nb\nf\nh" > ordenado1
printf "a\nc\nd\ng\nh" > ordenado2
echo ":: comm ::"
comm ordenado1 ordenado2
echo ":: diff ::"
diff ordenado1 ordenado2
echo ":: patch ::"
diff -Naur ordenado1 ordenado2 > diferencia
cat diferencia
patch < diferencia
cat ordenado1 | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Edición
Es posible hacer "traducciones" con la consola con la instrucción tr. Esto corresponde a substituciones basadas en expresiones regulares. | %%bash
echo "EsCrItUrA TeRrIbLe" | tr [:upper:] [:lower:] | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
Una forma más avanzada es posible con sed. | %%bash
echo "escritura terrible" | sed 'y/esib/3516/'
echo "escritura terrible" | sed 's/terrible/hermosa/' | Presentaciones/Notas/08_Procesamiento_texto.ipynb | cosmoscalibur/herramientas_computacionales | mit |
(1) The histogram and normal probability plot shows that the distribution of body temperatures approximately follows a normal distribution | import numpy as np
import math
import pylab
import scipy.stats as stats
import matplotlib.pyplot as plt
plt.hist(df.temperature)
plt.show()
stats.probplot(df.temperature, dist="norm", plot=pylab)
pylab.show() | JC_inferential_statistics_ex1.ipynb | jo-c-2017/DS_Projects | apache-2.0 |
(2) The sample size is 130, which is large enough (>30) for the assumption of CLT. In addition, 130 people is <10% of the human population, so we can assume that the observations are independent. | sample_size = df.temperature.count()
print('sample size is ' + str(sample_size)) | JC_inferential_statistics_ex1.ipynb | jo-c-2017/DS_Projects | apache-2.0 |
(3) We can use one-sample z test (the sample size is much larger than 30):
$H_0: T = 98.6$
$H_A: T \neq 98.6$
The p value is 4.35e-08, which is much smaller than 0.05. This indicates that the true mean of the human body temperature is not 98.6.
When using t-test instead, the p value is 2.19e-07, which is larger than t... | mean = np.mean(df.temperature)
se = (np.std(df.temperature))/math.sqrt(sample_size)
z = (98.6 - mean)/se
p_z = (1-stats.norm.cdf(z))*2
print('p value for z test is ' + str(p_z))
dgf = sample_size - 1
p_t = 2*(1-stats.t.cdf(z, dgf))
print('p value for t test is ' + str(p_t))
| JC_inferential_statistics_ex1.ipynb | jo-c-2017/DS_Projects | apache-2.0 |
(4) We would consider someone's temperature to be "abnormal" if it doesn't fall within the 95% confidence interval [98.12, 98.37] | ub = mean + 1.96*se
lb = mean - 1.96*se
print('Mean: ' + str(mean))
print('95 % Confidence Interval: [' + str(lb) + ', ' + str(ub) + ']') | JC_inferential_statistics_ex1.ipynb | jo-c-2017/DS_Projects | apache-2.0 |
(5) We can use two-sample z test:
$H_0: T_M = T_F$
$H_A: T_M \neq T_F$
The p value is 0.02, which is smaller than 0.05. This indicates that there is a significant difference between males and females in normal temperature | male_temp = df[df.gender=='M'].temperature
female_temp = df[df.gender=='F'].temperature
mean_diff = abs(np.mean(male_temp) - np.mean(female_temp))
se = math.sqrt(np.var(male_temp)/male_temp.count() + np.var(female_temp)/female_temp.count() )
z = mean_diff/se
p_z = (1-stats.norm.cdf(z))*2
print('mean for male is ' + s... | JC_inferential_statistics_ex1.ipynb | jo-c-2017/DS_Projects | apache-2.0 |
Construct Two Point Sets | # Generate two circles with a small offset
def make_circles(dimension:int=2,offset:list=None):
PointSetType = itk.PointSet[itk.F, dimension]
RADIUS = 100
if not offset or len(offset) != dimension:
offset = [2.0] * dimension
fixed_points = PointSetType.New()
moving_points = PointSetTy... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
Run Gradient Descent Optimization
We will quantify the point set offset with JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4 and minimize the metric value over 10 gradient descent iterations. |
ExhaustiveOptimizerType = itk.ExhaustiveOptimizerv4[itk.D]
dim = 2
# Define translation parameters to update iteratively
TransformType = itk.TranslationTransform[itk.D, dim]
transform = TransformType.New()
transform.SetIdentity()
PointSetType = type(fixed_set)
# Define a metric to reflect the difference between po... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
Resample Moving Point Set | moving_inverse = metric.GetMovingTransform().GetInverseTransform()
fixed_inverse = metric.GetFixedTransform().GetInverseTransform()
transformed_fixed_set = PointSetType.New()
transformed_moving_set = PointSetType.New()
for n in range(0,metric.GetNumberOfComponents()):
transformed_moving_point = moving_inverse.Tra... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
Visualize Gradient Descent
We can use the ITK ExhaustiveOptimizerv4 class to view how the optimizer moved along the surface defined by the transform parameters and metric. | # Set up the new optimizer
# Create a new transform and metric for analysis
transform = TransformType.New()
transform.SetIdentity()
metric = PointSetMetricType.New(
FixedPointSet=fixed_set,
MovingPointSet=moving_set,
MovingTransform=transform,
PointSetSigma=5,
KernelSigma=10.0,... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
We can also view and export the surface as an image using itkwidgets. | x_vals = list(set(x for (x,y) in param_space.keys()))
y_vals = list(set(y for (x,y) in param_space.keys()))
x_vals.sort()
y_vals.sort(reverse=True)
array = np.array([[param_space[(x,y)]
for x in x_vals]
for y in y_vals])
image_view = itk.GetImageViewFromArray(array)
view(image_vi... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
Hyperparameter Search
In order to find adequate results with different transforms, metrics, and optimizers it is often useful to compare results across variations in hyperparameters. In the case of this example it was necessary to evaluate performance for different values of the JensenHavrdaCharvatTsallisPointSetToPoin... | # Index values for gradient descent logging
FINAL_OPT_INDEX = 0
DESCENT_DATA_INDEX = 1
hyper_data = dict()
final_optimizers = dict()
# sigma must be sufficiently large to avoid negative entropy results
point_set_sigmas = (1.0,2.5,5.0,10.0,20.0,50.0)
# Compare performance with repeated or one-time learning rate esti... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
We can use matplotlib subplots and bar graphs to compare gradient descent performance and final metric values for each set of hyperparameters. In this example we see that estimating the learning rate once typically gives the best performance over time, while estimating the learning rate at each iteration can prevent gr... | # Visualize metric over gradient descent iterations as matplotlib subplots.
f, axn = plt.subplots(len(point_set_sigmas),len(estimate_rates),sharex=True)
for (i,j) in [(i,j)
for i in range(0,len(point_set_sigmas))
for j in range(0,len(estimate_rates))]:
axn[i,j].scatter(x=list(hyper_da... | src/Registration/Metricsv4/RegisterTwoPointSets/RegisterTwoPointSets.ipynb | InsightSoftwareConsortium/ITKExamples | apache-2.0 |
Quiz question: Assume an intermediate node has 6 safe loans and 3 risky loans. For each of 4 possible features to split on, the error reduction is 0.0, 0.05, 0.1, and 0.14, respectively. If the minimum gain in error reduction parameter is set to 0.2, what should the tree learning algorithm do next?
Grabbing binary dec... | def intermediate_node_num_mistakes(labels_in_node):
# Corner case: If labels_in_node is empty, return 0
if len(labels_in_node) == 0:
return 0
# Count the number of 1's (safe loans)
## YOUR CODE HERE
num_positive = sum([x == 1 for x in labels_in_node])
# Count the number of -1's... | ml-classification/module-6-decision-tree-practical-assignment-solution.ipynb | dnc1994/MachineLearning-UW | mit |
We then wrote a function best_splitting_feature that finds the best feature to split on given the data and a list of features to consider.
Please copy and paste your best_splitting_feature code here. | def best_splitting_feature(data, features, target):
best_feature = None # Keep track of the best feature
best_error = 10 # Keep track of the best error so far
# Note: Since error is always <= 1, we should intialize it with something larger than 1.
# Convert to float to make sure error gets c... | ml-classification/module-6-decision-tree-practical-assignment-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Incorporating new early stopping conditions in binary decision tree implementation
Now, you will implement a function that builds a decision tree handling the three early stopping conditions described in this assignment. In particular, you will write code to detect early stopping conditions 2 and 3. You implemented a... | def decision_tree_create(data, features, target, current_depth = 0,
max_depth = 10, min_node_size=1,
min_error_reduction=0.0):
remaining_features = features[:] # Make a copy of the features.
target_values = data[target]
print "-------------------... | ml-classification/module-6-decision-tree-practical-assignment-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Quiz question: For my_decision_tree_new trained with max_depth = 6, min_node_size = 100, min_error_reduction=0.0, is the prediction path for validation_set[0] shorter, longer, or the same as for my_decision_tree_old that ignored the early stopping conditions 2 and 3?
Quiz question: For my_decision_tree_new trained with... | def evaluate_classification_error(tree, data):
# Apply the classify(tree, x) to each row in your data
prediction = data.apply(lambda x: classify(tree, x))
# Once you've made the predictions, calculate the classification error and return it
## YOUR CODE HERE
return (prediction != data['safe_loan... | ml-classification/module-6-decision-tree-practical-assignment-solution.ipynb | dnc1994/MachineLearning-UW | mit |
Encoding the labels
Our labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1.
Exercise: Convert labels from positive and negative to 1 and 0, respectively. | labels = labels.split('\n')
labels = np.array([1 if each == 'positive' else 0 for each in labels]) | nanodegrees/deep_learning_foundations/unit_3/lesson_34_sentiment-rnn/Sentiment RNN.ipynb | broundy/udacity | unlicense |
Exercises
Exercise: Maybe the reason the proportional model doesn't work very well is that the growth rate, alpha, is changing over time. So let's try a model with different growth rates before and after 1980 (as an arbitrary choice).
Write an update function that takes pop, t, and system as parameters. The system ob... | # Solution goes here
# Solution goes here | notebooks/chap06.ipynb | AllenDowney/ModSimPy | mit |
Main Program (Takes a while)
Check the pair-wise duration gaps of each funds by Person ID | # Merge back to the main dataset
data_main = data_merged.merge(transformed, how='outer',
left_on='PersonID', right_on='PersonID')
data_main = data_main.sort(columns=['PersonID',
'InceptionDate',
'PerformanceEndDa... | Version 0.2.ipynb | xxPeterxx/RelaunchedFunds | gpl-2.0 |
One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t... | from sklearn.preprocessing import LabelBinarizer
lb = LabelBinarizer()
lb.fit(np.arange(10))
def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
# TODO: ... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest... | import tensorflow as tf
def neural_net_image_input(image_shape):
"""
Return a Tensor for a batch of image input
: image_shape: Shape of the images
: return: Tensor for image input.
"""
# TODO: Implement Function
return tf.placeholder(tf.float32, shape=(None, image_shape[0], image_shape[1], ... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_ksize: kernal size 2-D Tuple fo... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a ch... | def flatten(x_tensor):
"""
Flatten x_tensor to (Batch Size, Flattened Image Size)
: x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
: return: A tensor of size (Batch Size, Flattened Image Size).
"""
# TODO: Implement Function
shape = x_tensor.get_shape().as_... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packag... | def fully_conn(x_tensor, num_outputs):
"""
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_out... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
Note: Act... | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
# TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
... | image-classification/dlnd_image_classification.ipynb | nimish-jose/dlnd | gpl-3.0 |
Loading Reuter corpus from NLTK
Load reuter corpus including 1000 documents with maximum vocabulary size of 10000 from NLTK corpus | n_doc = 1000
voca, doc_ids, doc_cnt = get_reuters_ids_cnt(num_doc=n_doc, max_voca=10000)
docs = convert_cnt_to_list(doc_ids, doc_cnt)
n_voca = len(voca)
print('Vocabulary size:%d' % n_voca) | notebook/LDA_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Inferencen through the Gibbs sampling | max_iter=100
n_topic=10
logger = logging.getLogger('GibbsLDA')
logger.propagate = False
model = GibbsLDA(n_doc, len(voca), n_topic)
model.fit(docs, max_iter=max_iter) | notebook/LDA_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Print top 10 probability words for each topic | for ti in range(n_topic):
top_words = get_top_words(model.TW, voca, ti, n_words=10)
print('Topic', ti ,': ', ','.join(top_words)) | notebook/LDA_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Inferencen through the Variational Bayes | logger = logging.getLogger('vbLDA')
logger.propagate = False
vbmodel = vbLDA(n_doc, n_voca, n_topic)
vbmodel.fit(doc_ids, doc_cnt, max_iter=max_iter) | notebook/LDA_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Print top 10 probability words for each topic | for ti in range(n_topic):
top_words = get_top_words(vbmodel._lambda, voca, ti, n_words=10)
print('Topic', ti ,': ', ','.join(top_words)) | notebook/LDA_example.ipynb | arongdari/python-topic-model | apache-2.0 |
Simpe LSTM model | # data attributes
input_seq_length = X_trn.shape[1]
input_vocabulary_size = len(set(idx2w)) + 1
output_length = 127
#Model parameters
embedding_size=64
num_hidden_lstm = 128
# build the model: Simple LSTM with embedings
from tensorflow.contrib.keras import layers, models, optimizers
print('Build model 1')
seq_inpu... | tensorflow/02-text/03-word_tagging/01_identify_tags_in_airline_database_LSTM - EXERCISE.ipynb | sueiras/training | gpl-3.0 |
Betrachten wir nun Korrelationen zwischen Klassen. Dazu werden die summierten Abstände zwischen den Werten von jeweils zwei Klassen aufgetragen. Blau: Korrelation, Grün: Keine Korrelation, Rot: Antikorrelation. | fig, ax = plt.subplots(figsize=(8, 8))
classes = Tweet.get_all_keys()
y_pos = np.arange(len(classes))
error = np.full((len(classes), len(classes)), 0, dtype=int)
for tweet in tweets[:100]:
for i, class_i in enumerate(classes):
for j, class_j in enumerate(classes):
error[i, j] += abs((tweet[cla... | data_analysis_results/data_analysis.ipynb | Griesbacher/ContentAnalytics | gpl-3.0 |
Basic Aggregation Operations | # Food wise count of likes
food_wise = users_likes_join.groupby('likes')['likes'].count()
food_wise
# Lets sort our data. Default order is ascending
asc_sort = food_wise.sort_values()
asc_sort
# An example for descending
dsc_sort = food_wise.sort_values(ascending=False)
dsc_sort | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
QUICK NOTE ABOUT sort_values
By default sort_values allocates new memory each time it is called. While working with larger production data we can be limited by the available memory on our machines vis-a-vis the dataset size (and really we do not wish to hit the SWAP partition even on SSDs). In such a situation, we can ... | # Using in_place sort for memory efficiency
# Notice there is no left hand side value
food_wise.sort_values(ascending=False, inplace=True)
# food_wise itself has changed
food_wise | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Working with visualisations and charts
We use the python package - matplotlib - to generate visualisations and charts for our analysis. The command %matplotlib inline is a handy option which embeds the charts directly into our ipython/jupyter notebook.
While we can directly configure and call matplotlib functions to ge... | %matplotlib inline
import matplotlib
# ggplot is theme of matplotlib which adds
# some visual asthetics to our charts. It is
# inspired from the eponymous charting package
# of the R programming language
matplotlib.style.use('ggplot')
# Every DataFrame object exposes a plot object
# which can be used to generate diff... | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
matplotlib does provide many more options to generate complex and we will explore more of them as we proceed.
We assemble data and massage it with the sole purpose seeking insights, getting our questions answered - exactly where pandas shines.
Asking questions of our data
Pandas supports boolean indexing using the squa... | # Users who never interact with our data
df_users[~df_users.id.isin(df_likes['user_id'])] | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Since pandas DataFrame is a column based abstraction (as against row) we need to reset_index after an aggregation operation in order retrieve flat DataFrame which is convenient to query. | # Oldest user who has exactly 2 likes
agg_values = (
users_likes_join
.groupby(['user_id', 'name', 'age'])
.agg({ 'likes': 'count' })
.sort_index(level=['age'], sort_remaining=False, ascending=False)
)
agg_values[agg_values['likes'] == 2].head(1) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
In the above we used sort_index instead of sort_values because the groupby operation creates a MultiIndex
on columns user_id, name and age and since age is a part of an index sort_values cannot operate on it.
The head(n) function on a DataFrame returns first n records from the frame and the equivalent function tail(n) ... | # Oldest user who has at least 2 likes
agg_values[agg_values['likes'] >= 2].head(1)
# Lets augment our data a little more
users = users + [
{ 'id': 7, 'name': 'Yeti', 'age': 40 },
{ 'id': 8, 'name': 'Commander', 'age': 31 },
{ 'id': 9, 'name': 'Jonnah', 'age': 26 },
{ 'id': 10, 'name': 'Hex', 'age': 28... | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Eating your own dog food
The above data has been copy-pasted and hand edited. A problem with this approach is the possibility of data containing more than one like for the same product by the same user. While we can manually check the data the approach will be tedious and untractable as the size of the data increases. ... | # DataFrames from native python dictionaries
df_users = pd.DataFrame(users)
df_likes = pd.DataFrame(likes) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Lets figure out where are the duplicates | _duplicate_likes = (
df_likes
.groupby(['user_id', 'likes'])
.agg({ 'likes': 'count' })
)
duplicate_likes = _duplicate_likes[_duplicate_likes['likes'] > 1]
duplicate_likes | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
So there are in all 6 duplicate records. User#2 and Pepsi is recorded twice so that is 1 extra, 2 extra for User#3 and Cola and 1 extra for rest of the three pairs, which equals, 1 + 2 + 1 + 1 + 1 = 6. | # Now remove the duplicates
df_unq_likes = df_likes.drop_duplicates()
# The difference should be 6 since 6 records should be eliminated
len(df_unq_likes), len(df_likes) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
We replay our previous aggregation to verify no more duplicates indeed exist. | # Join the datasets
users_likes_join = df_users.merge(df_unq_likes, left_on='id', right_on='user_id')
users_likes_join.set_index('id')
# We aggregate the likes column and rename it to `Records`
unq_user_likes_group = (
users_likes_join
.groupby(['id', 'name', 'likes'])
.agg({'likes': 'count'})
... | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Lets continue with asking more questions of our data and gloss over some more convenience methods exposed by Pandas for aggregation. | # What percent of audience likes each fruit?
likes_count = (
users_likes_join
.groupby('likes')
.agg({ 'user_id': 'count' })
)
likes_count['percent'] = likes_count['user_id'] * 100 / len(df_users)
likes_count.sort_values('percent', ascending=False) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
In the above code snippet we created a computed column percent in the likes_count DataFrame. Column operations in pandas are vectorized and execute significantly faster than row operations; always a good idea to express computations as column operations as against row operations. | # What do people who like Coconut also like?
coconut_likers = users_likes_join[users_likes_join['likes'] == 'Coconut'].user_id
likes_among_coconut_likers = users_likes_join[(users_likes_join['user_id'].isin(coconut_likers)) & (users_likes_join['likes'] != 'Coconut')]
likes_among_coconut_likers.groupby('likes').agg({ 'u... | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
In our fictitious database, Cola and Pepsi seem to be popular among the users who like Coconut. | # What is the age group distribution of likes?
users_likes_join.groupby('likes').age.plot(kind='hist', legend=True, figsize=(10, 6)) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Most of our audience seem to fall in the 25 - 40 years age group. But this visualisation has one flaw - if records are stacked on top of each other, only one of them will be visible. Lets try an alternative plot. | users_likes_join.groupby('likes').age.plot(kind='kde', legend=True, figsize=(10, 6)) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
Anything surprising? Coconut - gray color - was not represented in the histogram. But from this visualisation, we can notice that coconut is popular among the 25 - 35 years age group only.
On the other hand, if we want to plot a specific "likable" object, we can simply filter our dataframe before groupby operation. | # Age distribution only of people who like Soda
users_likes_join[users_likes_join['likes'] == 'Soda'].groupby('likes').age.plot(kind='hist', legend=True, figsize=(10, 6)) | 1-Working-with-relational-data-using-pandas.ipynb | liquidscorpio/python-data-analysis | gpl-2.0 |
加载模型
HanLP的工作流程是先加载模型,模型的标示符存储在hanlp.pretrained这个包中,按照NLP任务归类。 | import hanlp
hanlp.pretrained.srl.ALL # 语种见名称最后一个字段或相应语料库 | plugins/hanlp_demo/hanlp_demo/zh/srl_stl.ipynb | hankcs/HanLP | apache-2.0 |
调用hanlp.load进行加载,模型会自动下载到本地缓存: | srl = hanlp.load('CPB3_SRL_ELECTRA_SMALL') | plugins/hanlp_demo/hanlp_demo/zh/srl_stl.ipynb | hankcs/HanLP | apache-2.0 |
语义角色分析
为已分词的句子执行语义角色分析: | srl(['2021年', 'HanLPv2.1', '为', '生产', '环境', '带来', '次', '世代', '最', '先进', '的', '多', '语种', 'NLP', '技术', '。']) | plugins/hanlp_demo/hanlp_demo/zh/srl_stl.ipynb | hankcs/HanLP | apache-2.0 |
语义角色标注结果中每个四元组的格式为[论元或谓词, 语义角色标签, 起始下标, 终止下标]。其中,谓词的语义角色标签为PRED,起止下标对应单词数组。
遍历谓词论元结构: | for i, pas in enumerate(srl(['2021年', 'HanLPv2.1', '为', '生产', '环境', '带来', '次', '世代', '最', '先进', '的', '多', '语种', 'NLP', '技术', '。'])):
print(f'第{i+1}个谓词论元结构:')
for form, role, begin, end in pas:
print(f'{form} = {role} at [{begin}, {end}]') | plugins/hanlp_demo/hanlp_demo/zh/srl_stl.ipynb | hankcs/HanLP | apache-2.0 |
Import raw data
The user needs to specify the directories containing the data of interest. Each sample type should have a key which corresponds to the directory path. Additionally, each object should have a list that includes the channels of interest. | # --------------------------------
# -------- User input ------------
# --------------------------------
data = {
# Specify sample type key
'wt': {
# Specify path to data directory
'path': './../yot_experiment/data/Output_wt_01-23-16-06',
# Specify which channels are in the directory an... | experiments/s1a_rescue/landmarks.ipynb | msschwartz21/craniumPy | gpl-3.0 |
Display the numer of samples for each sample type. | len(D['wt']['AT'].keys()),len(D['yot']['AT'].keys()),len(D['hss1a']['AT'].keys()),len(D['hss1ayot']['AT'].keys()) | experiments/s1a_rescue/landmarks.ipynb | msschwartz21/craniumPy | gpl-3.0 |
Landmarks
Calculate landmark bins based on user input parameters and the previously specified control sample. | lm = ds.landmarks(percbins=percbins, rnull=np.nan)
lm.calc_bins(D[s_ctrl][c_ctrl], anum, theta_step)
print('Alpha bins')
print(lm.acbins)
print('Theta bins')
print(lm.tbins)
lmdf = pd.DataFrame()
# Loop through each pair of stype and channels
for s,c in tqdm.tqdm(data_pairs):
print(s,c)
# Calculate landmarks... | experiments/s1a_rescue/landmarks.ipynb | msschwartz21/craniumPy | gpl-3.0 |
Important: Before running, ensure that Accelerate has been configured through either accelerate config in the command line or by running write_basic_config | # from accelerate.utils import write_basic_config
# write_basic_config() | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
Image Classification | path = untar_data(URLs.PETS)/'images'
def train():
dls = ImageDataLoaders.from_name_func(
path, get_image_files(path), valid_pct=0.2,
label_func=lambda x: x[0].isupper(), item_tfms=Resize(224))
learn = vision_learner(dls, resnet34, metrics=error_rate).to_fp16()
with learn.distrib_ctx(in_not... | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
Image Segmentation | path = untar_data(URLs.CAMVID_TINY)
def train():
dls = SegmentationDataLoaders.from_label_func(
path, bs=8, fnames = get_image_files(path/"images"),
label_func = lambda o: path/'labels'/f'{o.stem}_P{o.suffix}',
codes = np.loadtxt(path/'codes.txt', dtype=str)
)
learn = unet_learner(d... | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
Text Classification | path = untar_data(URLs.IMDB_SAMPLE)
df = pd.read_csv(path/'texts.csv')
def train():
imdb_clas = DataBlock(blocks=(TextBlock.from_df('text', seq_len=72), CategoryBlock),
get_x=ColReader('text'), get_y=ColReader('label'), splitter=ColSplitter())
dls = imdb_clas.dataloaders(df, bs=64)
le... | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
Tabular | path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
def train():
dls = TabularDataLoaders.from_csv(path/'adult.csv', path=path, y_names="salary",
cat_names = ['workclass', 'education', 'marital-status', 'occupation',
'relationship', 'race'],
con... | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
Collab Filtering | path = untar_data(URLs.ML_SAMPLE)
df = pd.read_csv(path/'ratings.csv')
def train():
dls = CollabDataLoaders.from_df(df)
learn = collab_learner(dls, y_range=(0.5,5.5))
with learn.distrib_ctx(in_notebook=True):
learn.fine_tune(6)
notebook_launcher(train, num_processes=2) | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
Keypoints | path = untar_data(URLs.BIWI_HEAD_POSE)
def img2pose(x): return Path(f'{str(x)[:-7]}pose.txt')
def get_ctr(f):
ctr = np.genfromtxt(img2pose(f), skip_header=3)
c1 = ctr[0] * cal[0][0]/ctr[2] + cal[0][2]
c2 = ctr[1] * cal[1][1]/ctr[2] + cal[1][2]
return tensor([c1,c2])
img_files = get_image_files(path)
ca... | nbs/examples/distributed_app_examples.ipynb | fastai/fastai | apache-2.0 |
In the previous notebook some hyperparameter exploration was made for the Random Forest Regressor. Let's see which are now the best predictors for each number of "ahead days". | best_raw_params = pd.read_pickle('../../data/best_dataset_params_raw_df.pkl')
def keep_max_r2(record):
return record.loc[np.argmax(record['r2']),:]
best_ini_pred_df = best_raw_params.groupby('ahead_days').apply(keep_max_r2)
best_ini_pred_df | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Those were the best predictors before the hyperparameters tuning | hyper1_df = pd.read_pickle('../../data/hyper_ahead1_random_forest_df.pkl')
hyper1_df
from sklearn.metrics import r2_score
hyper_1_best_series = hyper1_df.iloc[np.argmax(hyper1_df['r2'])].copy()
hyper_1_best_series.name = 1
hyper_1_best_series
ahead_days = [1, 7, 14, 28, 56]
best_hyper_df = pd.DataFrame()
best_hyper_... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Let's compare the new best Random Forest predictors with the old Linear Regressors. | def join_and_compare(df1, df2, column, labels):
tj1 = pd.DataFrame(df1[column].copy())
tj1.rename(columns = {column: labels[0]}, inplace=True)
tj2 = pd.DataFrame(df2[column].copy())
tj2.rename(columns = {column: labels[1]}, inplace=True)
comp_df = tj1.join(tj2)
comp_df['diff'] = comp_df[labels[1... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
First the $r^2$ metrics | comp_r2_df = join_and_compare(best_ini_pred_df, best_hyper_df, 'r2', ['linear', 'random_forest'])
comp_r2_df['best'] = comp_r2_df.apply(lambda x: np.argmax(x), axis=1)
comp_r2_df | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
The values are very similar in both cases. A minor difference can be seen only in the case of 56 days ahead, in which the random forest seems to be a bit better than the linear predictor. In any case, as the linear predictor is much simpler, and faster, it's probably better to keep it as the best predictor. It can be s... | comp_mre_df = join_and_compare(best_ini_pred_df, best_hyper_df, 'mre', ['linear', 'random_forest'])
comp_mre_df['best'] = comp_mre_df.apply(lambda x: np.argmax(x), axis=1)
comp_mre_df | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
The values for the MRE metrics are almost the same for both predictors.
Conlcusion: The linear predictor will be chosen for all the predictions. In the case of the 56 ahead days prediction, a better $r^2$ metric could be achieved by the random forest predictor, but the linear predictor is still far simpler and faster.
... | data_test_df = pd.read_pickle('../../data/data_test_df.pkl')
data_test_df.head() | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
When generating the datasets, some symbols were removed from the training set (because they contained too many missing points). The same symbols should be removed from the test set.
Let's generate datasets for the test set, with the best parameters found. | best_ini_pred_df
best_ini_pred_df.to_pickle('../../data/best_params_final_df.pkl') | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Some playing with the data to remove the same symbols as in the training set | params = best_ini_pred_df.loc[1]
train_val_time = int(params['train_val_time'])
base_days = int(params['base_days'])
step_days = int(params['step_days'])
ahead_days = int(params['ahead_days'])
print('Generating: base{}_ahead{}'.format(base_days, ahead_days))
pid = 'base{}_ahead{}'.format(base_days, ahead_days)
y... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
OK, let's create a function to generate one test dataset | def generate_one_test_set(params, data_df):
# print(('-'*70 + '\n {}, {} \n' + '-'*70).format(params['base_days'].values, params['ahead_days'].values))
tic = time()
train_val_time = int(params['train_val_time'])
base_days = int(params['base_days'])
step_days = int(params['step_days'])
ahead... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
The datasets were successfully generated
There will be two types of test. One is retraining at every step, and the other is without retraining. The first one is good enough to confirm that there was no overfitting on the hyperparameters. The second can show how "valid" is the model for periods outside the training peri... | best_params_df = pd.read_pickle('../../data/best_params_final_df.pkl')
best_params_df | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Ahead 1
Without retraining
Warning: The dates that appear on the samples are the initial dates (there are 112 days ahead after the marked date). | from predictor.linear_predictor import LinearPredictor
import utils.misc as misc
import predictor.evaluation as ev
ahead_days = 1
# Get some parameters
train_days = int(best_params_df.loc[ahead_days, 'train_days'])
GOOD_DATA_RATIO, \
train_val_time, \
base_days, \
step_days, \
ahead_days, \
SAMPLES_GOOD_DATA_RATIO, \... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Ahead 7 | from predictor.linear_predictor import LinearPredictor
import utils.misc as misc
import predictor.evaluation as ev
ahead_days = 7
# Get some parameters
train_days = int(best_params_df.loc[ahead_days, 'train_days'])
GOOD_DATA_RATIO, \
train_val_time, \
base_days, \
step_days, \
ahead_days, \
SAMPLES_GOOD_DATA_RATIO, \... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Ahead 14 | from predictor.linear_predictor import LinearPredictor
import utils.misc as misc
import predictor.evaluation as ev
ahead_days = 14
# Get some parameters
train_days = int(best_params_df.loc[ahead_days, 'train_days'])
GOOD_DATA_RATIO, \
train_val_time, \
base_days, \
step_days, \
ahead_days, \
SAMPLES_GOOD_DATA_RATIO, ... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Ahead 28 | from predictor.linear_predictor import LinearPredictor
import utils.misc as misc
import predictor.evaluation as ev
ahead_days = 28
# Get some parameters
train_days = int(best_params_df.loc[ahead_days, 'train_days'])
GOOD_DATA_RATIO, \
train_val_time, \
base_days, \
step_days, \
ahead_days, \
SAMPLES_GOOD_DATA_RATIO, ... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Ahead 56 | from predictor.linear_predictor import LinearPredictor
import utils.misc as misc
import predictor.evaluation as ev
ahead_days = 56
# Get some parameters
train_days = int(best_params_df.loc[ahead_days, 'train_days'])
GOOD_DATA_RATIO, \
train_val_time, \
base_days, \
step_days, \
ahead_days, \
SAMPLES_GOOD_DATA_RATIO, ... | notebooks/prod/n07_testing_and_time_validity.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
<h2> Non-linear supply functions </h2>
When thinking about supply it helps to start with the following considerations...
<ol>
<li> ...when prices are low, the quantity supplied increases slowly because of fixed costs of production (think startup costs, etc).
<li> ...when prices are high, supply also increases ... | def quantity_supply(expected_price, gamma, p_bar, **params):
"""The quantity of goods supplied in period t given the epxected price."""
return -np.arctan(-gamma * p_bar) + np.arctan(gamma * (expected_price - p_bar)) | notebooks/cobweb-models.ipynb | davidrpugh/sfi-complexity-mooc | mit |
<h3> Exploring supply shocks </h3>
Interactively change the value of $\gamma$ to see the impact on the shape of the supply function. | ipywidgets.interact?
interactive_quantity_supply_plot = ipywidgets.interact(cobweb.quantity_supply_plot,
S=ipywidgets.fixed(quantity_supply),
gamma=cobweb.gamma_float_slider,
... | notebooks/cobweb-models.ipynb | davidrpugh/sfi-complexity-mooc | mit |
<h2> Special case: Linear demand functions </h2>
Suppose the the quantity demanded of goods is a simple, decresing linear function of the observed price.
$$ q_t^d = D(p_t) = a - b p_t \implies p_t = D^{-1}(q_t^d) = \frac{a}{b} - \frac{1}{b}q_t^d \tag{11} $$
...where $-\infty < a < \infty$ and $0 < b < \infty$. | def quantity_demand(observed_price, a, b):
"""The quantity demand of goods in period t given the price."""
quantity = a - b * observed_price
return quantity
def inverse_demand(quantity_demand, a, b, **params):
"""The price of goods in period t given the quantity demanded."""
price = (a / b) - (1 /... | notebooks/cobweb-models.ipynb | davidrpugh/sfi-complexity-mooc | mit |
<h3> Exploring demand shocks </h3>
Interactively change the values of $a$ and $b$ to get a feel for how they impact demand. Shocks to $a$ shift the entire demand curve; shocks to $b$ change the slope of the demand curve (higher $b$ implies greater sensitivity to price; lower $b$ implies less sensitivity to price). | interactive_quantity_demand_plot = ipywidgets.interact(cobweb.quantity_demand_plot,
D=ipywidgets.fixed(quantity_demand),
a=cobweb.a_float_slider,
b=cobweb.... | notebooks/cobweb-models.ipynb | davidrpugh/sfi-complexity-mooc | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.