markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Now we need to create a dataset, a dataset needs to be able to be indexable, and at that index we expect a tuple (data, label). Here we are using the python `zip` function to take the `train_x` and `train_y` varibles and combine them into a tuple at each index as described | dset = list(zip(train_x,train_y))
x,y = dset[0]
x.shape,y | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
We need to do the same operations above for our validation set as well- Concatinate the images and reshape- Create labels and unsqueeze- Zip data and label into dataset | valid_x = torch.cat([valid_3_tens, valid_7_tens]).view(-1, 28*28)
valid_y = tensor([1]*len(valid_3_tens) + [0]*len(valid_7_tens)).unsqueeze(1)
valid_dset = list(zip(valid_x,valid_y)) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Here is a simple function that will initialize our parameters with random values. PyTorch `randn` returns a tensor the shape and size of its argument with normalized values between 0 and 1. We can use a variance argument here to scale the random values if necessary, but not in this example. We want to be able to calcul... | def init_params(size, std=1.0): return (torch.randn(size)*std).requires_grad_() | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
We create and initialize our weights and bias variables | weights = init_params((28*28,1))
bias = init_params(1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
In neural networks, the w in the equation y=w*x+b is called the weights, and the b is called the bias. Together, the weights and bias make up the parameters. We can now calculate a prediction for one image: | (train_x[0]*weights.T).sum() + bias | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
While we could use a Python for loop to calculate the prediction for each image, that would be very slow. Because Python loops don't run on the GPU, and because Python is a slow language for loops in general, we need to represent as much of the computation in a model as possible using higher-level functions.In this cas... | def linear1(xb): return xb@weights + bias
preds = linear1(train_x)
preds | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Lets check how good our random initialization is. Here is make a determination that if a prediction is over 0 it's a **3** else its a **7** and we compare it against our labels | corrects = (preds>0.0).float() == train_y
corrects | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
As you can see, and could have predicted, a random initilization is correct roughly 50% of the time. | corrects.float().mean().item() | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
So lets change one of our parameters a little bit and see if that changes our result | weights[0] *= 1.0001
preds = linear1(train_x)
((preds>0.0).float() == train_y).float().mean().item() | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
As we can see above changing one parameter a little has absolutely no affect on the results of our network. What does this mean practically?By changing this pixel by some small amount is not sufficient in itself to change the prediction of an image from a **3** to a **7**Becaue there is no change we cannot calculate a ... | trgts = tensor([1,0,1])
prds = tensor([0.9, 0.4, 0.2]) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Here's a first try at a loss function that measures the distance between predictions and targets: | def mnist_loss(predictions, targets):
return torch.where(targets==1, 1-predictions, predictions).mean() | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
**Read the Docs: It's important to learn about PyTorch functions like this, because looping over tensors in Python performs at Python speed, not C/CUDA speed! Try running help(torch.where) now to read the docs for this function, or, better still, look it up on the PyTorch documentation site.** | torch.where(trgts==1, 1-prds, prds) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
You can see that this function returns a lower number when predictions are more accurate, when accurate predictions are more confident (higher absolute values), and when inaccurate predictions are less confident. In PyTorch, we always assume that a lower value of a loss function is better. Since we need a scalar for th... | mnist_loss(prds,trgts) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
For instance, if we change our prediction for the one "false" target from 0.2 to 0.8 the loss will go down, indicating that this is a better prediction: | mnist_loss(tensor([0.9, 0.4, 0.8]),trgts) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
One problem with mnist_loss as currently defined is that it assumes that predictions are always between 0 and 1. We need to ensure, then, that this is actually the case! As it happens, there is a function that does exactly that—let's take a look. Sigmoid The sigmoid function always outputs a number between 0 and 1. It... | def sigmoid(x): return 1/(1+torch.exp(-x))
plot_function(torch.sigmoid, title='Sigmoid', min=-4, max=4) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
As you can see, it takes any input value, positive or negative, and smooshes it onto an output value between 0 and 1. It's also a smooth curve that only goes up, which makes it easier for SGD to find meaningful gradients.Let's update mnist_loss to first apply sigmoid to the inputs: | def mnist_loss(predictions, targets):
predictions = predictions.sigmoid()
return torch.where(targets==1, 1-predictions, predictions).mean() | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
SGD and Mini-Batches In the context of SGD, "Minibatch" means that the gradient is calculated across the entire batch before updating weights. If you are not using a "minibatch", every training example in a "batch" updates the learning algorithm's parameters independently. | coll = range(15)
dl = DataLoader(coll, batch_size=5, shuffle=True)
list(dl)
ds = L(enumerate(string.ascii_lowercase))
ds
dl = DataLoader(ds, batch_size=6, shuffle=True)
list(dl) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Putting It All Together First, let's re-initialize our parameters: | weights = init_params((28*28,1))
bias = init_params(1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
A DataLoader can be created from a Dataset and we can set our bacth size here: | dl = DataLoader(dset, batch_size=256)
xb,yb = first(dl)
xb.shape,yb.shape | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
We'll do the same for the validation set: | valid_dl = DataLoader(valid_dset, batch_size=256) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Let's create a mini-batch of size 4 for testing: | batch = train_x[:4]
batch.shape
preds = linear1(batch)
preds
loss = mnist_loss(preds, train_y[:4])
loss | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Now we can calculate the gradients: | loss.backward()
weights.grad.shape,weights.grad.mean(),bias.grad | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Let's put this into a function: | def calc_grad(xb, yb, model):
preds = model(xb)
loss = mnist_loss(preds, yb)
loss.backward()
calc_grad(batch, train_y[:4], linear1)
weights.grad.mean(),bias.grad | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
But look what happens if we call it twice: | calc_grad(batch, train_y[:4], linear1)
weights.grad.mean(),bias.grad | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
The gradients have changed! The reason for this is that loss.backward actually adds the gradients of loss to any gradients that are currently stored. So, we have to set the current gradients to 0 first: | weights.grad.zero_()
bias.grad.zero_(); | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
**Inplace Operations: Methods in PyTorch whose names end in an underscore modify their objects in place. For instance, bias.zero_() sets all elements of the tensor bias to 0.** Our only remaining step is to update the weights and biases based on the gradient and learning rate. When we do so, we have to tell PyTorch not... | def train_epoch(model, lr, params):
for xb,yb in dl:
calc_grad(xb, yb, model)
for p in params:
p.data -= p.grad*lr
p.grad.zero_() | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
We also want to check how we're doing, by looking at the accuracy of the validation set. To decide if an output represents a 3 or a 7, we can just check whether it's greater than 0. So our accuracy for each item can be calculated (using broadcasting, so no loops!) with: | (preds>0.0).float() == train_y[:4] | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
That gives us this function to calculate our validation accuracy: | def batch_accuracy(xb, yb):
preds = xb.sigmoid()
correct = (preds>0.5) == yb
return correct.float().mean()
batch_accuracy(linear1(batch), train_y[:4]) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
and then put the batches together: | def validate_epoch(model):
accs = [batch_accuracy(model(xb), yb) for xb,yb in valid_dl]
return round(torch.stack(accs).mean().item(), 4)
validate_epoch(linear1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
That's our starting point. Let's train for one epoch, and see if the accuracy improves: | lr = 1.
params = weights,bias
train_epoch(linear1, lr, params)
validate_epoch(linear1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Then do a few more: | for i in range(20):
train_epoch(linear1, lr, params)
print(validate_epoch(linear1), end=' ') | 0.8265 0.89 0.9183 0.9276 0.9398 0.9467 0.9506 0.9525 0.9559 0.9579 0.9598 0.9608 0.9613 0.9618 0.9633 0.9637 0.9647 0.9657 0.9672 0.9677 | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Looking good! We're already about at the same accuracy as our "pixel similarity" approach, and we've created a general-purpose foundation we can build on. Our next step will be to create an object that will handle the SGD step for us. In PyTorch, it's called an optimizer. Creating an Optimizer PyTorch's `nn.Linear` do... | linear_model = nn.Linear(28*28,1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Every PyTorch module knows what parameters it has that can be trained; they are available through the parameters method: | w,b = linear_model.parameters()
w.shape,b.shape | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Now, let's create an optimizer: | class BasicOptim:
def __init__(self,params,lr): self.params,self.lr = list(params),lr
def step(self, *args, **kwargs):
for p in self.params: p.data -= p.grad.data * self.lr
def zero_grad(self, *args, **kwargs):
for p in self.params: p.grad = None | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
We can create our optimizer by passing in the model's parameters: | opt = BasicOptim(linear_model.parameters(), lr)
def train_epoch(model):
for xb,yb in dl:
calc_grad(xb, yb, model)
opt.step()
opt.zero_grad()
validate_epoch(linear_model)
def train_model(model, epochs):
for i in range(epochs):
train_epoch(model)
print(validate_epoch(model)... | 0.4932 0.7685 0.8554 0.9136 0.9346 0.9482 0.957 0.9634 0.9658 0.9678 0.9697 0.9717 0.9736 0.9746 0.9761 0.977 0.9775 0.9775 0.978 0.9785 | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
fastai provides the SGD class which, by default, does the same thing as our BasicOptim: | linear_model = nn.Linear(28*28,1)
opt = SGD(linear_model.parameters(), lr)
train_model(linear_model, 20) | 0.4932 0.8179 0.8496 0.914 0.9346 0.9482 0.957 0.9619 0.9658 0.9673 0.9692 0.9712 0.9741 0.9751 0.9761 0.9775 0.9775 0.978 0.9785 0.979 | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
fastai also provides Learner.fit, which we can use instead of train_model. To create a Learner we first need to create a DataLoaders, by passing in our training and validation DataLoaders: | dls = DataLoaders(dl, valid_dl) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
To create a Learner without using an application (such as cnn_learner) we need to pass in all the elements that we've created in this chapter: the DataLoaders, the model, the optimization function (which will be passed the parameters), the loss function, and optionally any metrics to print: | learn = Learner(dls, nn.Linear(28*28,1), opt_func=SGD,
loss_func=mnist_loss, metrics=batch_accuracy)
learn.fit(10, lr=lr) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Adding a Nonlinearity So far we have a general procedure for optimizing the parameters of a function, and we have tried it out on a very boring function: a simple linear classifier. A linear classifier is very constrained in terms of what it can do. To make it a bit more complex (and able to handle more tasks), we nee... | def simple_net(xb):
res = xb@w1 + b1
res = res.max(tensor(0.0))
res = res@w2 + b2
return res | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
That's it! All we have in simple_net is two linear classifiers with a max function between them.Here, w1 and w2 are weight tensors, and b1 and b2 are bias tensors; that is, parameters that are initially randomly initialized, just like we did in the previous section: | w1 = init_params((28*28,30))
b1 = init_params(30)
w2 = init_params((30,1))
b2 = init_params(1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
The key point about this is that w1 has 30 output activations (which means that w2 must have 30 input activations, so they match). That means that the first layer can construct 30 different features, each representing some different mix of pixels. You can change that 30 to anything you like, to make the model more or l... | plot_function(F.relu) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
**Mathematically, we say the composition of two linear functions is another linear function. So, we can stack as many linear classifiers as we want on top of each other, and without nonlinear functions between them, it will just be the same as one linear classifier.** | simple_net = nn.Sequential(
nn.Linear(28*28,30),
nn.ReLU(),
nn.Linear(30,1)
) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
nn.Sequential creates a module that will call each of the listed layers or functions in turn.nn.ReLU is a PyTorch module that does exactly the same thing as the F.relu function. Most functions that can appear in a model also have identical forms that are modules. Generally, it's just a case of replacing F with nn and c... | learn = Learner(dls, simple_net, opt_func=SGD,
loss_func=mnist_loss, metrics=batch_accuracy)
learn.fit(40, 0.1)
plt.plot(L(learn.recorder.values).itemgot(2)); | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
And we can view the final accuracy: | learn.recorder.values[-1][2] | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
At this point we have something that is rather magical:A function that can solve any problem to any level of accuracy (the neural network) given the correct set of parametersA way to find the best set of parameters for any function (stochastic gradient descent) Going Deeper Here what happens when we train an 18-layer ... | dls = ImageDataLoaders.from_folder(path)
learn = cnn_learner(dls, resnet18, pretrained=False,
loss_func=F.cross_entropy, metrics=accuracy)
learn.fit_one_cycle(1, 0.1) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
Almost 100% accuracy! Jargon Recap - **ReLU :** Function that returns 0 for negative numbers and doesn't change positive numbers.- **Mini-batch :** A small group of inputs and labels gathered together in two arrays. A gradient descent step is updated on this batch (rather than a whole epoch).- **Forward pass :** Apply... | lst_in = range(10)
lst_out = [2*el for el in lst_in if el%2==1]
# is equivalent to:
lst_out = []
for el in lst_in:
if el%2==1:
lst_out.append(2*el) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
**What is a "rank-3 tensor"?** The rank of a tensor is the number of dimensions it has. An easy way to identify the rank is the number of indices you would need to reference a number within a tensor. A scalar can be represented as a tensor of rank 0 (no index), a vector can be represented as a tensor of rank 1 (one ind... | stacked_threes.shape | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
torch.Size([6131, 28, 28])We just need to find its length to know its rank. This is done as follows. | len(stacked_threes.shape) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
3You can also get a tensor’s rank directly with ndim . | stacked_threes.ndim | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
3 **What are RMSE and L1 norm?** Root mean square error (RMSE), also called the L2 norm, and mean absolute difference (MAE), also called the L1 norm, are two commonly used methods of measuring “distance”. Simple differences do not work because some difference are positive and others are negative, canceling each other ... | a = torch.Tensor(list(range(1,10))).view(3,3); print(a) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) | b = 2*a;
print(b) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
tensor([[ 2., 4., 6.], [ 8., 10., 12.], [14., 16., 18.]]) | b[1:,1:] | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
tensor([[10., 12.], [16., 18.]]) **What is broadcasting?** Scientific/numerical Python packages like NumPy and PyTorch will often implement broadcasting that often makes code easier to write. In the case of PyTorch, tensors with smaller rank are expanded to have the same size as the larger rank tenso... | for x,y in dl:
pred = model(x)
loss = loss_func(pred, y)
loss.backward()
parameters -= parameters.grad * lr | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
**Create a function that, if passed two arguments `[1,2,3,4]` and `'abcd'`, returns `[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]`. What is special about that output data structure?** | def func(a,b): return list(zip(a,b)) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
This data structure is useful for machine learning models when you need lists of tuples where each tuple would contain input data and a label. **What does `view` do in PyTorch?** It changes the shape of a Tensor without changing its contents. **What are the "bias" parameters in a neural network? Why do we need them?** ... | def train_epoch(model, lr, params):
for xb,yb in dl:
calc_grad(xb, yb, model)
for p in params:
p.data -= p.grad*lr
p.grad.zero_()
for i in range(20):
train_epoch(model, lr, params) | _____no_output_____ | Apache-2.0 | _notebooks/2020-12-10-Tears-In-Rain.ipynb | bailey-deep-learning/im_sorry_dave |
08 - Common problems & bad data situationsIn this notebook, we will revise common problems that might come up when dealing with real-world data.Maintainers: [@thempel](https://github.com/thempel), [@cwehmeyer](https://github.com/cwehmeyer), [@marscher](https://github.com/marscher), [@psolsson](https://github.com/psols... | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import mdshare
import pyemma | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Case 1: preprocessed, two-dimensional data (toy model) well-sampled double-well potentialLet's again have a look at the double-well potential.Since we are only interested in the problematic situations here,we will simplify our data a bit and work with a 1D projection. | file = mdshare.fetch('hmm-doublewell-2d-100k.npz', working_directory='data')
with np.load(file) as fh:
data = [fh['trajectory'][:, 1]] | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Since this particular example is simple enough, we can define a plotting function that combines histograms with trajectory data: | def plot_1D_histogram_trajectories(data, cluster=None, max_traj_length=200, ax=None):
if ax is None:
fig, ax = plt.subplots()
for n, _traj in enumerate(data):
ax.hist(_traj, bins=30, alpha=.33, density=True, color='C{}'.format(n));
ylims = ax.get_ylim()
xlims = ax.get_xlim()
for n, _... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
As a reference, we visualize the histogram of this well-sampled trajectory along with the first $200$ steps (left panel) and the MSM implied timescales (right panel): | fig, axes = plt.subplots(1, 2, figsize=(10, 4))
cluster = pyemma.coordinates.cluster_regspace(data, dmin=0.05)
plot_1D_histogram_trajectories(data, cluster=cluster, ax=axes[0])
lags = [i + 1 for i in range(10)]
its = pyemma.msm.its(cluster.dtrajs, lags=lags)
pyemma.plots.plot_implied_timescales(its, marker='o', ax=a... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We see a nice, reversibly connected trajectory.That means we have sampled transitions between the basins in both directions that are correctly resolved by the discretization.As we see from the almost perfect overlay of discrete and continuous trajectory, nearly no discretization error is made. irreversibly connected ... | file = mdshare.fetch('doublewell_oneway.npy', working_directory='data')
data = [trj for trj in np.load(file)]
plot_1D_histogram_trajectories(data, max_traj_length=data[0].shape[0]) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We note that the orange trajectory does not leave its potential well while the blue trajectory does overcome the barrier exactly once.⚠️ Even though we have sampled one direction of the process,we do not sample the way out of one of the potential wells, thus effectively finding a sink state in our data. Let's have a lo... | cluster_fine = pyemma.coordinates.cluster_regspace(data, dmin=0.1)
cluster_poor = pyemma.coordinates.cluster_regspace(data, dmin=0.7)
print(cluster_fine.n_clusters, cluster_poor.n_clusters)
fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharey='col')
for cluster, ax in zip([cluster_poor, cluster_fine], axes):
plot... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
What do we see? 1) We observe implied timescales that even look converged in the fine discretization case. 2) With poor clustering, the process cannot be resolved any more, i.e., the ITS does not convergence before the lag time exceeds the implied time scale. The obvious question is, what is the process that can be ob... | msm = pyemma.msm.estimate_markov_model(cluster_fine.dtrajs, 200)
fig, ax = plt.subplots()
ax.plot(
cluster_fine.clustercenters[msm.active_set, 0],
msm.eigenvectors_right()[:, 1],
'o:',
label='first eigvec')
tx = ax.twinx()
tx.hist(np.concatenate(data), bins=30, alpha=0.33)
tx.set_yticklabels([])
tx.set_... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We observe a process which is entirely taking place in the left potential well.How come?PyEMMA estimates MSMs only on the largest connected set because they are only defined on connected sets.In this particular example, the largest connected set is the microstates in the left potential well.That means that we find a tr... | print('Active set: {}'.format(msm.active_set))
print('Active state fraction: {:.2}'.format(msm.active_state_fraction)) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
In this example we clearly see that some states are missing. disconnected double-well trajectories with cross-oversThis example covers the worst-case scenario.We have two trajectories that live in two separated wells and never transition to the other one.Due to a very bad clustering, we believe that the data is connect... | file = mdshare.fetch('doublewell_disconnected.npy', working_directory='data')
data = [trj for trj in np.load(file)]
plot_1D_histogram_trajectories(data, max_traj_length=data[0].shape[0]) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We, again, compare a reasonable to a deliberately poor discretization: | cluster_fine = pyemma.coordinates.cluster_regspace(data, dmin=0.1)
cluster_poor = pyemma.coordinates.cluster_regspace(data, dmin=0.7)
print(cluster_fine.n_clusters, cluster_poor.n_clusters)
fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharey='col')
for cluster, ax in zip([cluster_poor, cluster_fine], axes):
plot... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
What do we see?1) With the fine discretization, we observe some timescales that are converged. These are most probably processes within one of the wells, similar to the ones we saw before.2) The poor discretization induces a large error and describes artificial short visits to the other basin.3) The timescales in the ... | msm = pyemma.msm.estimate_markov_model(cluster_poor.dtrajs, 200)
nstates = 2
msm.pcca(nstates)
index_order = np.argsort(cluster_poor.clustercenters[:, 0])
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
axes[0].plot(
cluster_poor.clustercenters[index_order, 0],
msm.eigenvectors_right()[index_order, 1],
'... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We observe that the first eigenvector represents a process that does not exist, i.e., is an artifact.Nevertheless, the PCCA++ algorithm can separate metastable states in a way we would expect.It finds the two disconnected states. However, the stationary distribution yields arbitrary results. How to detect disconnectiv... | hmm = pyemma.msm.estimate_hidden_markov_model(cluster_poor.dtrajs, nstates, msm.lag) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We are getting an error message which already explains what is going wrong, i.e.,that the (macro-) states are not connected and thus no unique stationary distribution can be estimated.This is equivalent to having two eigenvalues of magnitude 1 or an implied timescale of infinity which is what we observe in the implied ... | its = pyemma.msm.timescales_hmsm(cluster_poor.dtrajs, nstates, lags=[1, 3, 4, 10, 100])
pyemma.plots.plot_implied_timescales(its, marker='o', ylog=True); | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
As we see, the requested timescales above $4$ steps could not be computed because the underlying HMM is disconnected,i.e., the corresponding timescales are infinity.The implied timescales that could be computed are most likely the same process that we observed from the fine clustering before, i.e., jumps within one bas... | file = mdshare.fetch('hmm-doublewell-2d-100k.npz', working_directory='data')
with np.load(file) as fh:
data = [fh['trajectory'][:, 1]]
cluster = pyemma.coordinates.cluster_regspace(data, dmin=0.05) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We want to simulate a process that happens on a timescale that is on the order of magnitude of the trajectory length.To do so, we choose `n_trajs` chunks from the full data set that contain `traj_length` steps by splitting the original trajectory: | traj_length = 10
n_trajs = 50
data_short_trajs = list(data[0].reshape((data[0].shape[0] // traj_length, traj_length)))[:n_trajs]
dtrajs_short = list(cluster.dtrajs[0].reshape((data[0].shape[0] // traj_length, traj_length)))[:n_trajs] | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Now, let's plot the trajectories (left panel) and estimate implied timescales (right panel) as above.Since we know the true ITS of this process, we visualize it as a dotted line. | fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for n, _traj in enumerate(data_short_trajs):
axes[0].plot(_traj, np.linspace(0, 1, _traj.shape[0]) + n)
lags = [i + 1 for i in range(9)]
its = pyemma.msm.its(dtrajs_short, lags=lags)
pyemma.plots.plot_implied_timescales(its, marker='o', ax=axes[1], nits=1)
its_refe... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We note that the slowest process is clearly contained in the data chunks and is reversibly sampled (left panel, short trajectory pieces color coded and stacked).Due to very short trajectories, we find that this process can only be captured at a very short MSM lag time (right panel).Above that interval, the slowest time... | msm_short_trajectories = pyemma.msm.estimate_markov_model(dtrajs_short, 1) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Let's now have a look at the CK-test: | pyemma.plots.plot_cktest(msm_short_trajectories.cktest(2), marker='.'); | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
As already discussed, we cannot expect new estimates above a certain lag time to agree with the model prediction due to too short trajectories.Indeed, we find that new estimates and model predictions diverge at very high lag times.This does not necessarily mean that the model at $\tau=1$ is wrong and in this particular... | pdb = mdshare.fetch('alanine-dipeptide-nowater.pdb', working_directory='data')
files = mdshare.fetch('alanine-dipeptide-*-250ns-nowater.xtc', working_directory='data')
feat = pyemma.coordinates.featurizer(pdb)
feat.add_all()
data = pyemma.coordinates.load(files, features=feat) | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
TICA analysis is conducted with an extremely high lag time of almost $249.9$ ns. We map down to two dimensions. | tica = pyemma.coordinates.tica(data, lag=data[0].shape[0] - 100, dim=2)
tica_output = tica.get_output()
pyemma.plots.plot_free_energy(*np.concatenate(tica_output).T, legacy=False); | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
In the free energy plot, we recognize two defined basins that are nicely separated by the first TICA component. We thus continue with a discretization of this space and estimate MSM implied timescales. | cluster = pyemma.coordinates.cluster_kmeans(tica_output, k=200, max_iter=30, stride=100)
its = pyemma.msm.its(cluster.dtrajs, lags=[1, 5, 10, 20, 30, 50])
pyemma.plots.plot_implied_timescales(its, marker='o', units='ps', nits=3); | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Indeed, we observe a converged implied timescale.In this example we already know that it is way lower than expected,but in the general case we are unaware of the real dynamics of the system. Thus, we estimate an MSM at lag time $20 $ ps.Coarse graining and validation will be done with $2$ metastable states since we fou... | msm = pyemma.msm.estimate_markov_model(cluster.dtrajs, 20)
nstates = 2
msm.pcca(nstates);
stride = 10
metastable_trajs_strided = [msm.metastable_assignments[dtrj[::stride]] for dtrj in cluster.dtrajs]
tica_output_strided = [i[::stride] for i in tica_output]
_, _, misc = pyemma.plots.plot_state_map(*np.concatenate(tica... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
As we see, the PCCA++ algorithm is perfectly able to separate the two basins.Let's go on with a Chapman-Kolmogorow validation. | pyemma.plots.plot_cktest(msm.cktest(nstates), units='ps'); | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Congratulations, we have estimated a well-validated MSM.The only question remaining is: What does it actually describe?For this, we usually extract representative structures as described in [Notebook 00 ➜ 📓](00-pentapeptide-showcase.ipynb).We will not do this here but look at the metastable trajectories instead. What ... | fig, ax = plt.subplots(1, 1, figsize=(15, 6), sharey=True, sharex=True)
ax_yticks_labels = []
for n, pcca_traj in enumerate(metastable_trajs_strided):
ax.plot(range(len(pcca_traj)), msm.n_metastable * n + pcca_traj, color='k', linewidth=0.3)
ax.scatter(range(len(pcca_traj)), msm.n_metastable * n + pcca_traj, c=... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
What do we see?The above figure shows the metastable states visited by the trajectory over time.Each metastable state is color-coded, the trajectory is shown by the black line.This is clearly not a metastable trajectory as we would have expected. What did we do wrong?Let's have a look at the TICA trajectories, not onl... | fig, axes = plt.subplots(2, 3, figsize=(12, 6), sharex=True, sharey='row')
for n, trj in enumerate(tica_output):
for dim, traj1d in enumerate(trj.T):
axes[dim, n].plot(traj1d[::stride], linewidth=.5)
for ax in axes[1]:
ax.set_xlabel('time / {} ps'.format(stride))
for dim, ax in enumerate(axes[:, 0]):
... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
This is essentially noise, so it is not surprising that the metastable trajectories do not show significant metastability.The MSM nevertheless found a process in the above TICA components which, however,does not seem to describe any of the slow dynamics.Thus, the model is not wrong, it is just not informative. As we se... | tica = pyemma.coordinates.tica(data, lag=10, dim=2)
tica_output = tica.get_output()
cluster = pyemma.coordinates.cluster_kmeans(tica_output, k=200, max_iter=30, stride=100)
pyemma.plots.plot_free_energy(*np.concatenate(tica_output).T, legacy=False); | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
As wee see, TICA yields a very nice state separation.We will see that these states are in fact metastable. | msm = pyemma.msm.estimate_markov_model(cluster.dtrajs, lag=20)
msm.pcca(nstates);
metastable_trajs_strided = [msm.metastable_assignments[dtrj[::stride]] for dtrj in cluster.dtrajs]
stride = 10
tica_output_strided = [i[::stride] for i in tica_output]
_, _, misc = pyemma.plots.plot_state_map(*np.concatenate(tica_output_s... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
We note that PCCA++ separates the two basins of the free energy plot.Let's have a look at the metastable trajectories: | fig, ax = plt.subplots(1, 1, figsize=(12, 6), sharey=True, sharex=True)
ax_yticks_labels = []
for n, pcca_traj in enumerate(metastable_trajs_strided):
ax.plot(range(len(pcca_traj)), msm.n_metastable * n + pcca_traj, color='k', linewidth=0.3)
ax.scatter(range(len(pcca_traj)), msm.n_metastable * n + pcca_traj, c=... | _____no_output_____ | CC-BY-4.0 | notebooks/08-common-problems.ipynb | markovmodel/pyemma_tutorials |
Define the Convolutional Neural NetworkAfter you've looked at the data you're working with and, in this case, know the shapes of the images and of the keypoints, you are ready to define a convolutional neural network that can *learn* from this data.In this notebook and in `models.py`, you will:1. Define a CNN with ima... | # import the usual resources
import matplotlib.pyplot as plt
import numpy as np
# watch for any changes in model.py, if itchanges, re-load it automatically
%load_ext autoreload
%autoreload 2
## TODO: Define the Net in models.py
import torch
import torch.nn as nn
import torch.nn.functional as F
## TODO: Once you've d... | Net(
(conv1): Conv2d(1, 32, kernel_size=(4, 4), stride=(1, 1))
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(conv3): Conv2d(64, 128, kernel_size=(2, 2), stride=(1, 1))
(conv4): Conv2d(128, 256, kernel_size=(2, 2), stride=(1, 1))
(drop_out1): Dropout(p=0.1)
(drop_out2): Dropout(p=0.1)
(drop_o... | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Transform the dataset To prepare for training, create a transformed dataset of images and keypoints. TODO: Define a data transformIn PyTorch, a convolutional neural network expects a torch image of a consistent size as input. For efficient training, and so your model's loss does not blow up during training, it is also... | from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# the dataset we created in Notebook 1 is copied in the helper file `data_load.py`
from data_load import FacialKeypointsDataset
# the transforms we defined in Notebook 1 are in the helper file `data_load.py`
from data_load impor... | Number of images: 3462
0 torch.Size([1, 224, 224]) torch.Size([68, 2])
1 torch.Size([1, 224, 224]) torch.Size([68, 2])
2 torch.Size([1, 224, 224]) torch.Size([68, 2])
3 torch.Size([1, 224, 224]) torch.Size([68, 2])
| MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Batching and loading dataNext, having defined the transformed dataset, we can use PyTorch's DataLoader class to load the training data in batches of whatever size as well as to shuffle the data for training the model. You can read more about the parameters of the DataLoader, in [this documentation](http://pytorch.org/... | # load training data in batches
batch_size = 128
train_loader = DataLoader(transformed_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=4)
| _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Before trainingTake a look at how this model performs before it trains. You should see that the keypoints it predicts start off in one spot and don't match the keypoints on a face at all! It's interesting to visualize this behavior so that you can compare it to the model after training and see how the model has improv... | # load in the test data, using the dataset class
# AND apply the data_transform you defined above
# create the test dataset
test_dataset = FacialKeypointsDataset(csv_file='data/test_frames_keypoints.csv',
root_dir='data/test/',
t... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Apply the model on a test sampleTo test the model on a test sample of data, you have to follow these steps:1. Extract the image and ground truth keypoints from a sample2. Make sure the image is a FloatTensor, which the model expects.3. Forward pass the image through the net to get the predicted, output keypoints.This ... | # test the model on a batch of test images
def net_sample_output():
# iterate through the test dataset
for i, sample in enumerate(test_loader):
# get sample data: images and ground truth keypoints
images = sample['image']
key_pts = sample['keypoints']
# convert im... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Debugging tipsIf you get a size or dimension error here, make sure that your network outputs the expected number of keypoints! Or if you get a Tensor type error, look into changing the above code that casts the data into float types: `images = images.type(torch.FloatTensor)`. | # call the above function
# returns: test images, test predicted keypoints, test ground truth keypoints
test_images, test_outputs, gt_pts = net_sample_output()
# print out the dimensions of the data to see if they make sense
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size()) | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Visualize the predicted keypointsOnce we've had the model produce some predicted output keypoints, we can visualize these points in a way that's similar to how we've displayed this data before, only this time, we have to "un-transform" the image/keypoint data to display it.Note that I've defined a *new* function, `sho... | def show_all_keypoints(image, predicted_key_pts, gt_pts=None):
"""Show image with predicted keypoints"""
# image is grayscale
plt.imshow(image, cmap='gray')
plt.scatter(predicted_key_pts[:, 0], predicted_key_pts[:, 1], s=20, marker='.', c='m')
# plot ground truth points as green pts
if gt_pts is... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Un-transformationNext, you'll see a helper function. `visualize_output` that takes in a batch of images, predicted keypoints, and ground truth keypoints and displays a set of those images and their true/predicted keypoints.This function's main role is to take batches of image and keypoint data (the input and output of... | # visualize the output
# by default this shows a batch of 10 images
def visualize_output(test_images, test_outputs, gt_pts=None, batch_size=10):
for i in range(batch_size):
plt.figure(figsize=(20,10))
ax = plt.subplot(1, batch_size, i+1)
# un-transform the image data
image = test_i... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Training Loss functionTraining a network to predict keypoints is different than training a network to predict a class; instead of outputting a distribution of classes and using cross entropy loss, you may want to choose a loss function that is suited for regression, which directly compares a predicted value and target... | ## TODO: Define the loss and optimization
import torch.optim as optim
#criterion = nn.MSELoss()
criterion = nn.SmoothL1Loss()
optimizer = optim.Adam(net.parameters(), lr=1e-3, betas=(0.9, 0.999))
#optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Training and Initial ObservationNow, you'll train on your batched training data from `train_loader` for a number of epochs. To quickly observe how your model is training and decide on whether or not you should modify it's structure or hyperparameters, you're encouraged to start off with just one or two epochs at first... | from livelossplot import PlotLosses
def train_net(n_epochs):
# prepare the net for training
net.train()
liveloss = PlotLosses()
for epoch in range(n_epochs): # loop over the dataset multiple times
epoch_loss = 0.0
epoch_correct = 0
epoch_loss_val = 0.0
epoch_correct... | Epoch: 1, Batch: 10, Avg. Loss: 0.0005024574361741543
Epoch: 1, Batch: 20, Avg. Loss: 0.00045902186259627343
Epoch: 2, Batch: 10, Avg. Loss: 0.0004713563397526741
Epoch: 2, Batch: 20, Avg. Loss: 0.000502167847007513
Epoch: 3, Batch: 10, Avg. Loss: 0.0005260687507688999
Epoch: 3, Batch: 20, Avg. Loss: 0.0004413062520325... | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Test dataSee how your model performs on previously unseen, test data. We've already loaded and transformed this data, similar to the training data. Next, run your trained model on these images to see what kind of keypoints are produced. You should be able to see if your model is fitting each new face it sees, if the p... | # get a sample of test data again
test_images, test_outputs, gt_pts = net_sample_output()
torch.cuda.get_device_name(0)
print(test_images.data.size())
print(test_outputs.data.size())
print(gt_pts.size())
visualize_output(test_images, test_outputs, gt_pts)
## TODO: visualize your test output
# you can use the same func... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Once you've found a good model (or two), save your model so you can load it and use it later! | ## TODO: change the name to something uniqe for each new model
model_dir = 'saved_models/'
model_name = 'model_3200_1600_smoothL1.pt'
# after training, save your model parameters in the dir 'saved_models'
torch.save(net.state_dict(), model_dir+model_name) | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
After you've trained a well-performing model, answer the following questions so that we have some insight into your training and architecture selection process. Answering all questions is required to pass this project. Question 1: What optimization and loss functions did you choose and why? **Answer**: write your answ... | # Get the weights in the first conv layer, "conv1"
# if necessary, change this to reflect the name of your first conv layer
weights1 = net.conv1.weight.data
w = weights1.numpy()
filter_index = 0
print(w[filter_index][0])
print(w[filter_index][0].shape)
# display the filter weights
plt.imshow(w[filter_index][0], cma... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Feature mapsEach CNN has at least one convolutional layer that is composed of stacked filters (also known as convolutional kernels). As a CNN trains, it learns what weights to include in it's convolutional kernels and when these kernels are applied to some input image, they produce a set of **feature maps**. So, featu... | ##TODO: load in and display any image from the transformed test dataset
## TODO: Using cv's filter2D function,
## apply a specific set of filter weights (like the one displayed above) to the test image
fig = plt.figure(figsize=(120, 4))
for idx in np.arange(4):
ax = fig.add_subplot(2, 128/2, idx+1, xticks=[], yt... | _____no_output_____ | MIT | 2. Define the Network Architecture.ipynb | thanhthtran/Facial_keypoint_cnv |
Knight Lab Amplicon Sample Sheet and Mapping (preparation) File Generator What is it?This Jupyter Notebook allows you to automatically generate sample sheets for amplicon sequencing. Here's how it should work.You'll start out with a **basic plate map** (platemap.tsv) , which just links each sample to it's approprite... | seq_type = '16S'
#options are ['16S', '18S', 'ITS'] | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Step 1: read in plate map**Enter the correct path to the plate map file**. This will serve as the plate map for relating all subsequent information. | plate_map_fp = './test_data/amplicon/compressed-map.tsv'
if not exists(plate_map_fp):
print("Error: %s is not a path to a valid file" % plate_map_fp) | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
**Read in the plate map**. It should look something like this:```Sample Row Col BlankGLY_01_012 A 1 FalseGLY_14_034 B 1 FalseGLY_11_007 C 1 FalseGLY_28_018 D 1 FalseGLY_25_003 E 1 FalseGLY_06_106 F 1 FalseGLY_07_011 G 1 FalseGLY_18_043 H 1 FalseGLY_28_004 I 1 False```**Make sure there a no duplicate IDs.** If each samp... | plate_df = read_plate_map_csv(open(plate_map_fp,'r'))
plate_df.head() | _____no_output_____ | MIT | notebooks/amplicon_samplesheet_generator.ipynb | antgonza/metagenomics_pooling_notebook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.