markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Let's try to understand what's going wrong.
A Brief Review: Batch and Event Shape
In TFP, an ordinary (not a JointDistribution) probability distribution has an event shape and a batch shape, and understanding the difference is crucial to effective use of TFP:
Event shape describes the shape of a single draw from the d... | sample | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
And here are our distributions: | dists | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
The log probability is computed by summing the log probabilities of the sub-distributions at the (matched) elements of the parts: | log_prob_parts = [dist.log_prob(s) for (dist, s) in zip(dists, sample)]
log_prob_parts
np.sum(log_prob_parts) - jds.log_prob(sample) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
So, one level of explanation is that the log probability calculation is returning a 7-Tensor because the third subcomponent of log_prob_parts is a 7-Tensor. But why?
Well, we see that the last element of dists, which corresponds to our distribution over Y in the mathematial formulation, has a batch_shape of [7]. In oth... | dists[2] | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
By using TFP's Independent metadistribution, which converts batch dimensions to event dimensions, we can convert this into a distribution with event_shape=[7] and batch_shape=[] (we'll rename it y_dist_i because it's a distribution on Y, with the _i standing in for our Independent wrapping): | y_dist_i = tfd.Independent(dists[2], reinterpreted_batch_ndims=1)
y_dist_i | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Now, the log_prob of a 7-vector is a scalar: | y_dist_i.log_prob(sample[2]) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Under the covers, Independent sums over the batch: | y_dist_i.log_prob(sample[2]) - tf.reduce_sum(dists[2].log_prob(sample[2])) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
And indeed, we can use this to construct a new jds_i (the i again stands for Independent) where log_prob returns a scalar: | jds_i = tfd.JointDistributionSequential([
tfd.Normal(loc=0., scale=1.), # m
tfd.Normal(loc=0., scale=1.), # b
lambda b, m: tfd.Independent( # Y
tfd.Normal(loc=m*X + b, scale=1.),
reinterpreted_batch_ndims=1)
])
jds_i.log_prob(sample) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
A couple notes:
- jds_i.log_prob(s) is not the same as tf.reduce_sum(jds.log_prob(s)). The former produces the "correct" log probability of the joint distribution. The latter sums over a 7-Tensor, each element of which is the sum of the log probability of m, b, and a single element of the log probability of Y, so it ov... | try:
jds_i.sample([5, 3])
except tf.errors.InvalidArgumentError as e:
print(e) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Let's think about why. When we call jds_i.sample([5, 3]), we'll first draw samples for m and b, each with shape (5, 3). Next, we're going to try to construct a Normal distribution via:
tfd.Normal(loc=m*X + b, scale=1.)
But if m has shape (5, 3) and X has shape 7, we can't multiply them together, and indeed this is the ... | m = tfd.Normal(0., 1.).sample([5, 3])
try:
m * X
except tf.errors.InvalidArgumentError as e:
print(e) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
To resolve this issue, let's think about what properties the distribution over Y has to have. If we've called jds_i.sample([5, 3]), then we know m and b will both have shape (5, 3). What shape should a call to sample on the Y distribution produce? The obvious answer is (5, 3, 7): for each batch point, we want a sample ... | m[..., tf.newaxis].shape
(m[..., tf.newaxis] * X).shape | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Adding an axis to both m and b, we can define a new JDS that supports multiple samples: | jds_ia = tfd.JointDistributionSequential([
tfd.Normal(loc=0., scale=1.), # m
tfd.Normal(loc=0., scale=1.), # b
lambda b, m: tfd.Independent( # Y
tfd.Normal(loc=m[..., tf.newaxis]*X + b[..., tf.newaxis], scale=1.),
reinterpreted_batch_ndims=1)
])
shaped_sample = jds_ia.sample([5, 3])
s... | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
As an extra check, we'll verify that the log probability for a single batch point matches what we had before: | (jds_ia.log_prob(shaped_sample)[3, 1] -
jds_i.log_prob([shaped_sample[0][3, 1],
shaped_sample[1][3, 1],
shaped_sample[2][3, 1, :]])) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a id='AutoBatching-For-The-Win'></a>
AutoBatching For The Win
Excellent! We now have a version of JointDistribution that handles all our desiderata: log_prob returns a scalar thanks to the use of tfd.Independent, and multiple samples work now that we fixed broadcasting by adding extra axes.
What if I told you there wa... | jds_ab = tfd.JointDistributionSequentialAutoBatched([
tfd.Normal(loc=0., scale=1.), # m
tfd.Normal(loc=0., scale=1.), # b
lambda b, m: tfd.Normal(loc=m*X + b, scale=1.) # Y
])
jds_ab.log_prob(jds.sample())
shaped_sample = jds_ab.sample([5, 3])
jds_ab.log_prob(shaped_sample)
jds_ab.log_prob(shaped_sam... | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
How does this work? While you could attempt to read the code for a deep understanding, we'll give a brief overview which is sufficient for most use cases:
- Recall that our first problem was that our distribution for Y had batch_shape=[7] and event_shape=[], and we used Independent to convert the batch dimension to an ... | jds.batch_shape
jds_i.batch_shape
jds_ia.batch_shape
jds_ab.batch_shape | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
We see that the original jds has subdistributions with different batch shapes. jds_i and jds_ia fix this by creating subdistributions with the same (empty) batch shape. jds_ab has only a single (empty) batch shape.
It's worth noting that JointDistributionSequentialAutoBatched offers some additional generality for free.... | X = np.arange(14).reshape((2, 7))
X | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Our JointDistributionSequentialAutoBatched works with no changes (we need to redefine the model because the shape of X is cached by jds_ab.log_prob): | jds_ab = tfd.JointDistributionSequentialAutoBatched([
tfd.Normal(loc=0., scale=1.), # m
tfd.Normal(loc=0., scale=1.), # b
lambda b, m: tfd.Normal(loc=m*X + b, scale=1.) # Y
])
shaped_sample = jds_ab.sample([5, 3])
shaped_sample
jds_ab.log_prob(shaped_sample) | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
On the other hand, our carefully crafted JointDistributionSequential no longer works: | jds_ia = tfd.JointDistributionSequential([
tfd.Normal(loc=0., scale=1.), # m
tfd.Normal(loc=0., scale=1.), # b
lambda b, m: tfd.Independent( # Y
tfd.Normal(loc=m[..., tf.newaxis]*X + b[..., tf.newaxis], scale=1.),
reinterpreted_batch_ndims=1)
])
try:
jds_ia.sample([5, 3])
except tf.... | site/en-snapshot/probability/examples/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
The values returned are:
The least-squares solution
The sum of squared residuals
The rank of the independent variables
The singular values of the independent variables
Exercise
Calculate the predictions our model would make
Calculate the sum of squared residuals from our predictions. Does this match the value return... | coeff, residuals, rank, sing_vals = np.linalg.lstsq(intercept_x,y)
predictions = | Wk03-Numpy-model-package-survey.ipynb | streety/biof509 | mit |
Least squares refers to the cost function for this algorithm. The objective is to minimize the residual sum of squares. The difference between the actual and predicted values is calculated, it is squared and then summed over all records. The function is as follows:
$$RSS(\beta) = \sum_{i=1}^{N}(y_i - x_i^T\beta)^2$$
Ma... | our_coeff = np.dot(np.dot(np.linalg.inv(np.dot(intercept_x.T, intercept_x)), intercept_x.T), y)
print(coeff, '\n', our_coeff)
our_predictions = np.dot(intercept_x, our_coeff)
np.hstack((predictions,
our_predictions
))
plt.plot(x, y, 'ko', label='True values')
plt.plot(x, our_predictions, 'ro',... | Wk03-Numpy-model-package-survey.ipynb | streety/biof509 | mit |
Exercise
Plot the residuals. The x axis will be the independent variable (x) and the y axis the residual between our prediction and the true value.
Plot the predictions generated for our model over the entire range of 0-1. One approach is to use the np.linspace method to create equally spaced values over a specified r... | x_expanded = np.hstack((x**i for i in range(1,20)))
b, residuals, rank, s = np.linalg.lstsq(x_expanded, y)
print(b)
plt.plot(x, y, 'ko', label='True values')
plt.plot(x, np.dot(x_expanded, b), 'ro', label='Predictions')
plt.legend(numpoints=1, loc=4)
plt.show() | Wk03-Numpy-model-package-survey.ipynb | streety/biof509 | mit |
Take samples from population | #Take sample of size n=20
sampler=fp.PopSampler(len(pops),20,rng)
fp.evolve_regions_sampler(rng,pops,sampler,
nlist[:N], #Evolve for N generations
mutrate_neutral,
mutrate_sel,
recrate,
... | docs/examples/temporalSampling.ipynb | molpopgen/fwdpy | gpl-3.0 |
The output from this particular sampler type is a generator. Let's look at the first element of the first sample: | data=sampler[0]
print data[0] | docs/examples/temporalSampling.ipynb | molpopgen/fwdpy | gpl-3.0 |
These "genotypes" blocks can be used to caculate summary statistics. See the example on using pylibseq for that task. | print data[1] | docs/examples/temporalSampling.ipynb | molpopgen/fwdpy | gpl-3.0 |
Each element in d[0] is a tuple: | #The first element are the genotypes
data[0][0]
#The first element in the genotypes are the neutral variants.
#The first value is the position. The second value is a string
#of genotypes for chromosomes 1 through n. 0 = ancestral/1=derived
data[0][0][0]
#Same format for selected variants
data[0][0][1]
#This is a d... | docs/examples/temporalSampling.ipynb | molpopgen/fwdpy | gpl-3.0 |
To define the physics problem, we write a function to simulate the forward physics. This function takes the initial position, height, speed and angle of a thrown object and computes where the object will land, assuming the object follows a parabolic trajectory. Neglecting friction, can compute this by solving a quadrat... | def simulate_hit(pos, height, vel, angle, gravity=1.):
vel_x, vel_y = math.cos(angle) * vel, math.sin(angle) * vel
height = math.maximum(height, .5)
hit_time = (vel_y + math.sqrt(vel_y**2 + 2 * gravity * height)) / gravity
return pos + vel_x * hit_time, hit_time, height, vel_x, vel_y
simulate_hit(10, 1... | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Let's plot the trajectory! We define y(x) and sample it on a grid. We have to drop invalid values, such as negative flight times and below-ground points. | def sample_trajectory(pos, height, vel, angle, gravity=1.):
hit, hit_time, height, vel_x, vel_y = simulate_hit(pos, height, vel, angle, gravity)
def y(x):
t = (x.vector[0] - pos) / vel_x
y_ = height + vel_y * t - gravity / 2 * t ** 2
return math.where((y_ > 0) & (t > 0), y_, NAN)
ret... | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Before we train neural networks on this problem, let's perform a classical optimization using gradient descent in the initial velocity vel. We need to define a loss function to optimize. Here we desire the object to hit at x=0. | vel = 1
def loss_function(vel):
return math.l2_loss(simulate_hit(10, 1, vel, 0)[0] - 0)
loss_function(0) | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Φ<sub>Flow</sub> uses the selected library (PyTorch/TensorFlow/Jax) to derive analytic derivatives.
By default, the gradient function also returns the function value. | gradient = math.functional_gradient(loss_function)
gradient(0) | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Now we can just subtract the gradient times a learning rate $\eta = 0.2$ until we converge. | trj = [vel]
for i in range(10):
loss, (grad,) = gradient(vel)
vel = vel - .2 * grad
trj.append(vel)
print(f"vel={vel} - loss={loss}")
trj = math.stack(trj, channel('opt'))
vis.plot(sample_trajectory(tensor(10), 1, trj, 0)) | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Next, we generate a training set and test by sampling random values. | def generate_data(shape):
pos = math.random_normal(shape)
height = math.random_uniform(shape) + .5
vel = math.random_uniform(shape)
angle = math.random_uniform(shape) * PI/2
return math.stack(dict(pos=pos, height=height, vel=vel, angle=angle), channel('vector'))
x_train = generate_data(batch(examples=1000))
... | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Now, let's create a fully-connected neural network with three hidden layers. We can reset the seed to make the weight initialization predictable. | math.seed(0)
net_sup = dense_net(1, 4, [32, 64, 32])
net_sup
# net_sup.trainable_weights[0] # TensorFlow
net_sup.state_dict()['linear0.weight'].flatten() # PyTorch
# net_sup.parameters[0][0] # Stax | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
For the differentiable physics network we do the same thing again. | math.seed(0)
net_dp = dense_net(1, 4, [32, 64, 32])
# net_dp.trainable_weights[0] # TensorFlow
net_dp.state_dict()['linear0.weight'].flatten() # PyTorch
# net_dp.parameters[0][0] # Stax | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Indeed, the We see that the networks were initialized identically! Alternatively, we could have saved and loaded the state.
Supervised Training
Now we can train the network. We feed the desired hit position into the network and predict a possible initial state.
For supervised training, we compare the network prediction... | opt_sup = adam(net_sup)
def supervised_loss(x, y, net=net_sup):
prediction = math.native_call(net, y)
return math.l2_loss(prediction - x)
print(f"Supervised loss (training set): {supervised_loss(x_train, y_train)}")
print(f"Supervised loss (test set): {supervised_loss(x_test, y_test)}")
for i in range(100):
up... | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
What? That's almost no progress! Feel free to run more iterations but there is a deeper problem at work here. Before we get into that, let's train a the network again but with a differentiable physics loss function.
Training with Differentiable Physics
For the differentiable physics loss, we simulate the trajectory giv... | def physics_loss(y, net=net_dp):
prediction = math.native_call(net, y)
y_sim = simulate_hit(*prediction.vector)[0]
return math.l2_loss(y_sim - y)
opt_dp = adam(net_dp)
for i in range(100):
update_weights(net_dp, opt_dp, physics_loss, y_train)
print(f"Supervised loss (training set): {supervised_loss(x_train, ... | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
This looks even worse! The differentiable physics network seems to stray even further from the ground truth.
Well, we're not trying to match the ground truth, though. Let's instead measure how close to the desired location the network threw the object. | print(f"Supervised network (test set): {physics_loss(y_test, net=net_sup)}")
print(f"Diff.Phys. network (test set): {physics_loss(y_test, net=net_dp)}") | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
Now this is much more promissing. The diff.phys. network seems to hit the desired location very accurately considering it was only trained for 100 iterations. With more training steps, this loss will go down even further, unlike the supervised network.
So what is going on here? Why does the supervised network perform s... | predictions = math.stack({
"Ground Truth": x_test.examples[:4],
"Supervised": math.native_call(net_sup, y_test.examples[:4]),
"Diff.Phys": math.native_call(net_dp, y_test.examples[:4]),
}, channel('curves'))
vis.plot(sample_trajectory(*predictions.vector), size=(16, 4)) | demos/Learn_to_Throw_Tutorial.ipynb | tum-pbs/PhiFlow | mit |
3. Affine Decomposition
For this problem the affine decomposition is straightforward. | class EllipticOptimalControl(EllipticOptimalControlProblem):
# Default initialization of members
def __init__(self, V, **kwargs):
# Call the standard initialization
EllipticOptimalControlProblem.__init__(self, V, **kwargs)
# ... and also store FEniCS data structures for assembly
... | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4. Main program
4.1. Read the mesh for this problem
The mesh was generated by the data/generate_mesh_2.ipynb notebook. | mesh = Mesh("data/mesh2.xml")
subdomains = MeshFunction("size_t", mesh, "data/mesh2_physical_region.xml")
boundaries = MeshFunction("size_t", mesh, "data/mesh2_facet_region.xml") | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.2. Create Finite Element space (Lagrange P1) | scalar_element = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
element = MixedElement(scalar_element, scalar_element, scalar_element)
V = FunctionSpace(mesh, element, components=["y", "u", "p"]) | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.3. Allocate an object of the EllipticOptimalControl class | problem = EllipticOptimalControl(V, subdomains=subdomains, boundaries=boundaries)
mu_range = [(3.0, 20.0), (0.5, 1.5), (1.5, 2.5)]
problem.set_mu_range(mu_range) | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.4. Prepare reduction with a reduced basis method | reduced_basis_method = ReducedBasis(problem)
reduced_basis_method.set_Nmax(40) | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.5. Perform the offline phase | lifting_mu = (3.0, 1.0, 2.0)
problem.set_mu(lifting_mu)
reduced_basis_method.initialize_training_set(100)
reduced_problem = reduced_basis_method.offline() | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.6. Perform an online solve | online_mu = (15.0, 0.6, 1.8)
reduced_problem.set_mu(online_mu)
reduced_solution = reduced_problem.solve()
print("Reduced output for mu =", online_mu, "is", reduced_problem.compute_output())
plot(reduced_solution, reduced_problem=reduced_problem, component="y")
plot(reduced_solution, reduced_problem=reduced_problem, c... | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.7. Perform an error analysis | reduced_basis_method.initialize_testing_set(100)
reduced_basis_method.error_analysis() | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.8. Perform a speedup analysis | reduced_basis_method.speedup_analysis() | tutorials/13_elliptic_optimal_control/tutorial_elliptic_optimal_control_2_rb.ipynb | mathLab/RBniCS | lgpl-3.0 |
Classifier comparison
A comparison of a several classifiers in scikit-learn on synthetic datasets.
The point of this example is to illustrate the nature of decision boundaries
of different classifiers.
This should be taken with a grain of salt, as the intuition conveyed by
these examples does not necessarily carry over... | print(__doc__)
# Code source: Gaël Varoquaux
# Andreas Müller
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preproces... | DataScienceProgramming/08-Machine-Learning-I/HW5_orig.ipynb | squishbug/DataScienceProgramming | cc0-1.0 |
Standard Scaler
http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler
Standardize features by removing the mean and scaling to unit variance
Centering and scaling happen independently on each feature by computing the relevant statistics on the sa... | datset
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can... | DataScienceProgramming/08-Machine-Learning-I/HW5_orig.ipynb | squishbug/DataScienceProgramming | cc0-1.0 |
Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of target_text. Th... | def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
"""
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionar... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Build the Neural Network
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:
- model_inputs
- process_decoder_input
- encoding_layer
- decoding_layer_train
- decoding_layer_infer
- decoding_layer
- seq2seq_model
Input
Implement the model_inputs() fu... | def model_inputs():
"""
Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences.
:return: Tuple (input, targets, learning rate, keep probability, target sequence length,
max target sequence length, source sequence length)
"""
input_text = tf.placehol... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Process Decoder Input
Implement process_decoder_input by removing the last word id from each batch in target_data and concat the GO ID to the begining of each batch. | def process_decoder_input(target_data, target_vocab_to_int, batch_size):
"""
Preprocess target data for encoding
:param target_data: Target Placehoder
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param batch_size: Batch Size
:return: Preprocessed target data
"... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Encoding
Implement encoding_layer() to create a Encoder RNN layer:
* Embed the encoder input using tf.contrib.layers.embed_sequence
* Construct a stacked tf.contrib.rnn.LSTMCell wrapped in a tf.contrib.rnn.DropoutWrapper
* Pass cell and embedded input to tf.nn.dynamic_rnn() | from imp import reload
reload(tests)
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob,
source_sequence_length, source_vocab_size,
encoding_embedding_size):
"""
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Decoding - Training
Create a training decoding layer:
* Create a tf.contrib.seq2seq.TrainingHelper
* Create a tf.contrib.seq2seq.BasicDecoder
* Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode |
def decoding_layer_train(encoder_state, dec_cell, dec_embed_input,
target_sequence_length, max_summary_length,
output_layer, keep_prob):
"""
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Decoding - Inference
Create inference decoder:
* Create a tf.contrib.seq2seq.GreedyEmbeddingHelper
* Create a tf.contrib.seq2seq.BasicDecoder
* Obtain the decoder outputs from tf.contrib.seq2seq.dynamic_decode | def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,
end_of_sequence_id, max_target_sequence_length,
vocab_size, output_layer, batch_size, keep_prob):
"""
Create a decoding layer for inference
:param encoder_state: Encoder ... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Embed the target sequences
Construct the decoder LSTM cell (just like you constructed the encoder cell above)
Create an output layer to map the outputs of the decoder to the elements of our vocabulary
Use the your decoding_layer_train(e... | def decoding_layer(dec_input, encoder_state,
target_sequence_length, max_target_sequence_length,
rnn_size,
num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, decoding_embedding_size):
"""
Create decoding layer
... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size).
Process target data using your process_decoder_input(target_data, target_vocab_to_int, bat... | def seq2seq_model(input_data, target_data, keep_prob, batch_size,
source_sequence_length, target_sequence_length,
max_target_sentence_length,
source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size,
rnn_size, ... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set num_layers to the number of layers.
Set encoding_embedding_size to the size of the embedding for the encoder.
Set decoding_embedding_siz... | # Number of Epochs
epochs = 5
# Batch Size
batch_size = 64
# RNN Size
rnn_size = 128
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 128
decoding_embedding_size = 128
# Learning Rate
learning_rate = 0.001
# Dropout Keep Probability
keep_probability = 0.5
display_step = 100 | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
Sentence to Sequence
To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.
Convert the sentence to lowercase
Convert words into ids using vocab_to_int
Convert words not in the vocabulary, to the <UNK> word id. | def sentence_to_seq(sentence, vocab_to_int):
"""
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
"""
unk_id = vocab_to_int["<UNK>"]
return [vocab_to_int.get(word, unk_id) for word in s... | language-translation/dlnd_language_translation.ipynb | msanterre/deep_learning | mit |
From Stack Overflow | def stft(x, fs, framesz, hop):
framesamp = int(framesz*fs)
hopsamp = int(hop*fs)
w = scipy.signal.hann(framesamp)
X = np.array([fft(w*x[i:i+framesamp]) for i in range(0, len(x)-framesamp, hopsamp)])
return X
def istft(X, fs, T, hop):
x = np.zeros(T*fs)
framesamp = X.shape[1]
hopsamp = i... | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
Benchmark signals | # Let's make a function to plot a signal and its specgram
def tf(signal, fs, w=256, wtime=False, poverlap=None, xlim=None, ylim=None, colorbar=False, vmin=None, vmax=None, filename=None, interpolation="bicubic"):
dt = 1./fs
n = signal.size
t = np.arange(0.0, n*dt, dt)
if wtime:
# Then... | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
Complex display | import colorsys
fm = np.amax(np.abs(SYN))
np.amin(np.angle(SYN))
timesteps = []
for t in SYN.T:
freqs = []
for f in t:
# This is not right, need phase angle and mag:
#rgb = colorsys.hsv_to_rgb(f.imag, f.real, f.real)
hue = 0.5 + (np.angle(f) / (2*np.pi))
rgb = colorsys.hsv_to_... | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
The matplotlib function imshow interprets arrays like this as 3-channel colour images, so we can just display this array directly. We'll chop off the negative frequencies again. | plt.figure(figsize=(12,4))
plt.imshow(rgb_arr[:rgb_arr.shape[0]/2.,...], aspect="auto", origin="lower", interpolation="none")
plt.savefig('/Users/matt/Pictures/stft_complex.png')
plt.show() | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
Inverse STFT | SYN.shape
8192/800.
fs=800
T = 8192/800.
hop = 0.010
syn = istft(SYN, fs, T, hop)
plt.figure(figsize=(12,4))
plt.plot(syn)
plt.show() | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
PyTFD implementation
I found a lightweight library for doing all sorts of time-frequency stuff: pytfd. https://github.com/endolith/pytfd | import pytfd.stft
N = 256
t_max = 10
t = np.linspace(0, t_max, N)
fs = N/t_max
f = np.linspace(0, fs, N)
plt.figure(figsize=(15,6))
for i, T in enumerate([32, 64, 128]):
w = scipy.signal.boxcar(T) # Rectangular window
delta1 = np.zeros(N)
delta1[N/4] = 5
delta2 = np.zeros(N)
delta2[-N/4]... | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
Nice! But no inverse STFT.
Uncertainty principle
The time and frequency localication of the window determine the localization of the result. | w = scipy.signal.hann(256)
plt.plot(w)
plt.show()
W = rfft(w)
plt.plot(np.absolute(W)[:10])
plt.show()
1/0.256 | stft.ipynb | kwinkunks/timefreak | apache-2.0 |
1.1 Importamos las librerias que vamos a necesitar | # Realizamos la lectura del fichero y incluimos en el fichero el nombre de las columnas
names_features = [
'age', # Edad del individuo: [17 - 90] media 38,
'type_employer', # Tipo de trabajo : [ State-gov, Self-emp-not-inc, Private, Federal-gov, Local-gov, ?, Self-emp-inc, Without-pay, Never-worked ]
'fn... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Agrupa los países en grupos
Agrupamos las personas por ciudad, Las que son de EEUU en uno y los que no son de EEUU en otro |
def isEEUU(x):
if x == ' United-States':
return 1
else :
return 0
# Aplicamos una funcion a la columna, para convertir los valores en enumerados
enum_isEEUU = df["native-country"].apply(isEEUU)
# Cramos la nueva columna enum_isEEUU con los datos anteriores
df["enum_isEEUU"] = enum_isE... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapeamos las razas | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
# Mapea los valores unicos de type_employer a enumerados
le.fit(df["race"].unique())
# Muestra como lo ha mapeado
print(list(le.classes_))
# Aplicamos una funcion a la columna, para convertir los valores en enumerados
enum_razas = le.transform( df["... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapea el tipo de trabajo | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
# Mapea los valores unicos de type_employer a enumerados
le.fit(df["type_employer"].unique())
# Transformamos la columna type_employer con 'labelEncoder' en enumerados
enum_type_employer = le.transform( df["type_employer"])
# Cramos la nueva col... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapea el tipo de familia | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df["relationship"].unique())
enum_relationship = le.transform( df["relationship"])
df["enum_relationship"] = enum_relationship
#muestra la inversa
#list(le.inverse_transform(df["enum_rel"].head()))
print('ok') | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapea la ocupacion | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df["occupation"].unique())
df["enum_occupation"] = le.transform( df["occupation"])
print('ok') | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapea las ganancias (>50k o <=50k) | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df["income"].unique())
# Muestra como lo ha mapeado
print(list(le.classes_))
df["enum_income"] = le.transform( df["income"])
print('ok') | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapea el sexo | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df["sex"].unique())
# Muestra como lo ha mapeado
print(list(le.classes_))
df["enum_sex"] = le.transform( df["sex"])
print('ok') | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
• Mapea el estado civil de cada persona | from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(df["marital-status"].unique())
# Muestra como lo ha mapeado
print(list(le.classes_))
df["enum_marital-status"] = le.transform( df["marital-status"])
print('ok') | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
2. Haz visualizaciones de diferentes valores con seaborn.
Describe lo que ves en las visualizaciones | plt.title('Personas que ganan mas de 50 o lo contrario', y=1.1, size=15)
sns.countplot('income', data=df)
plt.title('Numero de personas que ganan mas o menos de 50k diferenciadas por sexos', size=20, y=1.1)
sns.countplot(x = 'income', hue='sex', data=df)
plt.title('media de las que ganan mas o menos de 50k diferencia... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
En esta grafica podemos ver que hay menos mujeres que ganan mas de 50k. | plt.title('Media de las ganancias diferenciadas por el tipo de trabajador', size=10, y=1.1)
sns.barplot(x = 'enum_type_employer', y='enum_income', data=df, hue="type_employer") | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Esta grafica nos muestra que los que mas ganan son los trabajadores con los puestos:
Self-emp-not-inc
Federal-gov
Local-gov | plt.title('Numero de personas que ganan mas o menos de 50k diferenciadas por la raza', size=20, y=1.1)
sns.countplot(x = 'income', hue='race', data=df) | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Aqui podemos ver que las personas de raza blanca son las mas numerosas.
Del mismo modo se ve que los blancos son los que ganan mas de 50k. | plt.title('Media de las ganancias diferenciadas por la raza', size=20, y=1.1)
sns.barplot(x = 'enum_race', y='enum_income', data=df, hue="race") | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
En cambio al hacer la media de las personas nos da como resultado que que los que mas ganan son los asiaticos. | plt.title('Numero de personas que ganan mas de 50k diferenciadas por la relacion familiar', size=20, y=1.1)
sns.countplot(x = 'income', hue='relationship', data=df) | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
En esta grafica se aprecia que el numero de personas que ganan mas de 50k son los 'maridos' | plt.title('Media de las ganancias diferenciadas por la relacion familiar', size=20, y=1.1)
sns.barplot(x = 'enum_relationship', y='enum_income', data=df, hue="relationship") | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Aqui podemos ver las 'esposas' tienen la mayor media de ganancias (> 50k) | plt.title('Numero de personas que ganan mas de 50k diferenciadas por la ocupacion', size=20, y=1.1)
sns.countplot(x = 'income', hue='occupation', data=df)
plt.title('Media de las ganancias diferenciadas por la relacion familiar', size=20, y=1.1)
sns.barplot(x = 'enum_occupation', y='enum_income', data=df, hue="occupat... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Podemos observar que la mayoria de las personas trabajan 40h a la semana
Correlacion | colormap = plt.cm.viridis
plt.figure(figsize=(12, 12))
plt.title("Correlacion entre todas las features", y=1.05, size=20)
sns.heatmap(df.corr(), linewidths=0.1, square=True, vmax=1.0, annot=True, cmap=colormap)
features = ["hours-per-week","enum_sex","enum_type_employer","enum_race","enum_income","age","education-num"... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
4. Utiliza random forest con diferentes parámetros, diferentes features, y cross_validation para conseguir el mejor modelo posible. | from sklearn import svm
from sklearn.model_selection import cross_val_score
import pandas as pd
import numpy as np
# modelo
modelo = RandomForestClassifier(n_estimators=9, min_samples_split=2 ,min_samples_leaf =1, n_jobs = 49)
# Seleccionamos las features con las que vamos a usar el algoritmo
features = ["education-n... | ejercicio 2/Ejercicio_2.ipynb | cristhro/Machine-Learning | gpl-3.0 |
Read in the trajectory file (.dcd) and the topology file (.psf) | traj = pt.Trajectory('step5_production.dcd', '../step3_pbcsetup.xplor.ext.psf')
print(traj) | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Calculate the water-water radial distribution function. In statistical mechanics, the radial distribution function, (or pair correlation function) g(r) in a system of particles (atoms, molecules, colloids, etc.), describes how density varies as a function of distance from a reference particle.
$$g(r)=\frac{1}{N\rho}\su... | goo = pt.rdf(traj, solvent_mask=':TIP3@OH2', solute_mask=':TIP3@OH2', bin_spacing=0.05, maximum=8.)
goh1 = pt.rdf(traj, solvent_mask=':TIP3@OH2', solute_mask=':TIP3@H1', bin_spacing=0.05, maximum=8.)
goh2 = pt.rdf(traj, solvent_mask=':TIP3@OH2', solute_mask=':TIP3@H2', bin_spacing=0.05, maximum=8.) | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Plot the g(r) versus r for O-O and O-H | plt.plot(goo[0],goo[1])
plt.plot(goo[0],goh1[1])
plt.plot((0, 8), (1, 1), 'k--')
plt.xlim([1.5,8])
plt.ylim([0,3])
plt.xlabel('$r_{ox} / \AA$', fontsize=14)
plt.ylabel('$g(r_{ox})$', fontsize=14)
plt.show() | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Calculate molecule - water rdf | gon = pt.rdf(traj, solvent_mask=':TIP3@OH2', solute_mask=':DOP@N23', bin_spacing=0.05, maximum=8.)
goh231 = pt.rdf(traj, solvent_mask=':TIP3@OH2', solute_mask=':DOP@H231', bin_spacing=0.05, maximum=8.)
goo1 = pt.rdf(traj, solvent_mask=':TIP3@OH2', solute_mask=':DOP@O1', bin_spacing=0.05, maximum=8.)
goh4 = p... | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Plot the g(r) versus r for Ow-x | plt.plot(gon[0],gon[1],label='OW...NH$_{3}$')
plt.plot(goh231[0],goh231[1],label='OW...HN')
plt.plot(goo1[0],goo1[1],label='OW...O1')
plt.plot(goh4[0],goh4[1],label='OW...HO1')
plt.plot((0, 8), (1, 1), 'k--')
plt.xlim([1.5,8])
plt.ylim([0,0.0015])
plt.xlabel('$r_{ox} / \AA$', fontsize=14)
plt.ylabel('$g(r_{ox})$', font... | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Plot the g(r) versus r for Hw-x | plt.plot(ghwn23[0],ghwn23[1],label='HW...NH$_{3}$')
plt.plot(ghwh231[0],ghwh231[1],label='HW...HN')
plt.plot(ghwo1[0],ghwo1[1],label='HW...O1')
plt.plot(ghwh4[0],ghwh4[1],label='HW...HO1')
plt.plot((0, 8), (1, 1), 'k--')
plt.xlim([1.5,8])
plt.ylim([0,0.0008])
plt.xlabel('$r_{hwx} / \AA$', fontsize=14)
plt.ylabel('$g(r_... | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Print the distance between dop (residue 0) and residue 1 (H2O) | data = pt.calc_pairdist(traj, mask=':TIP3@OH2', mask2=':DOP@N23')
print(data[:,0][:1])
atom_indices = pt.select(':DOP@N23', traj.top)
print(atom_indices) | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Calculate a dihedral angle as a function of time | dataset = pt.dihedral(traj, ':DOP@N23 :DOP@C2 :DOP@C3 :DOP@C1') | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Plot the results | time = [i*0.002 for i in range(len(dataset))]
plt.plot(time,dataset, 'ro', label='$\phi$')
plt.xlabel('Time / ns', fontsize=14)
plt.ylabel('Angle / $\circ$', fontsize=14)
plt.legend(loc='upper right',frameon=False, bbox_to_anchor=(1.2, 0.95),numpoints=1)
plt.show()
hist0 = plt.hist(dataset,25)
tmp = plt.setp(hist0[2],... | pytraj_users/pytraj_md.ipynb | hainm/bag_of_tips | bsd-2-clause |
Examples
One more time, I'll load the data from the NSFG. | import first
live, firsts, others = first.MakeFrames() | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
And compute the distribution of birth weight for first babies and others. | first_wgt = firsts.totalwgt_lb
first_wgt_dropna = first_wgt.dropna()
print('Firsts', len(first_wgt), len(first_wgt_dropna))
other_wgt = others.totalwgt_lb
other_wgt_dropna = other_wgt.dropna()
print('Others', len(other_wgt), len(other_wgt_dropna))
first_pmf = thinkstats2.Pmf(first_wgt_dropna, label='first')
other_pm... | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
We can plot the PMFs on the same scale, but it is hard to see if there is a difference. | width = 0.4 / 16
# plot PMFs of birth weights for first babies and others
thinkplot.PrePlot(2)
thinkplot.Hist(first_pmf, align='right', width=width)
thinkplot.Hist(other_pmf, align='left', width=width)
thinkplot.Config(xlabel='Weight (pounds)', ylabel='PMF') | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
PercentileRank computes the fraction of scores less than or equal to your_score. | def PercentileRank(scores, your_score):
count = 0
for score in scores:
if score <= your_score:
count += 1
percentile_rank = 100.0 * count / len(scores)
return percentile_rank | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
If this is the list of scores. | t = [55, 66, 77, 88, 99] | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
If you got the 88, your percentile rank is 80. | PercentileRank(t, 88) | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Percentile takes a percentile rank and computes the corresponding percentile. | def Percentile(scores, percentile_rank):
scores.sort()
for score in scores:
if PercentileRank(scores, score) >= percentile_rank:
return score | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
The median is the 50th percentile, which is 77. | Percentile(t, 50) | solutions/chap04soln.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.